Technical Documentation: ianstormtaylor/editor
ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference
Overview (`Readme.md`)
Slate lets you build rich, intuitive editors like those in Medium, Dropbox Paper or Google Docs—which are becoming table stakes for applications on the web—without your codebase getting mired in complexity.
It can do this because all of its logic is implemented with a series of plugins, so you aren't ever constrained by what is or isn't in "core". You can think of it like a pluggable implementation of contenteditable built on top of React. It was inspired by libraries like Draft.js, Prosemirror and Quill.
🤖 Slate is currently in beta. Its core API is useable right now, but you might need to pull request improvements for advanced use cases, or fixes for some bugs. Some of its APIs are not "finalized" and will have breaking changes over time as we discover better solutions. There isn't currently a
1.0release schedule, we're still getting the architecture right.
🤖 Slate is also contributor-driven. It is not backed by any huge company, which means that all contributions are voluntary and done by the people who need them. If you need something improved, added, or fixed, please contribute it yourself or no one will. And if you want to become a more active maintainer, let us know in the Slack channel.
Why?
Why create Slate? Well... (Beware: this section has a few of my opinions!)
Before creating Slate, I tried a lot of the other rich text libraries out there—Draft.js, Prosemirror, Quill, etc. What I found was that while getting simple examples to work was easy enough, once you started trying to build something like Medium, Dropbox Paper or Google Docs, you ran into deeper issues...
The editor's "schema" was hardcoded and hard to customize. Things like bold and italic were supported out of the box, but what about comments, or embeds, or even more domain-specific needs?
Transforming the documents programmatically was very convoluted. Writing as a user may have worked, but making programmatic changes, which is critical for building advanced behaviors, was needlessly complex.
Serializing to HTML, Markdown, etc. seemed like an afterthought. Simple things like transforming a document to HTML or Markdown involved writing lots of boilerplate code, for what seemed like very common use cases.
Re-inventing the view layer seemed inefficient and limiting. Most editors rolled their own views, instead of using existing technologies like React, so you have to learn a whole new system with new "gotchas".
Collaborative editing wasn't designed for in advance. Often the editor's internal representation of data made it impossible to use to for a realtime, collaborative editing use case without basically rewriting the editor.
The repositories were monolithic, not small and reusable. The code bases for many of the editors often didn't expose the internal tooling that could have been re-used by developers, leading to having to reinvent the wheel.
Building complex, nested documents was impossible. Many editors were designed around simplistic "flat" documents, making things like tables, embeds and captions difficult to reason about and sometimes impossible.
Of course not every editor exhibits all of these issues, but if you've tried using another editor you might have run into similar problems. To get around the limitations of their API's and achieve the user experience you're after, you have to resort to very hacky things. And some experiences are just plain impossible to achieve.
If that sounds familiar, you might like Slate.
Which brings me to how Slate solves all of that...
Principles
Slate tries to solve the question of "Why?" with a few principles:
First-class plugins. The most important part of Slate is that plugins are first-class entities. That means you can completely customize the editing experience, to build complex editors like Medium's or Dropbox's, without having to fight against the library's assumptions.
Schema-less core. Slate's core logic assumes very little about the schema of the data you'll be editing, which means that there are no assumptions baked into the library that'll trip you up when you need to go beyond the most basic use cases.
Nested document model. The document model used for Slate is a nested, recursive tree, just like the DOM itself. This means that creating complex components like tables or nested block quotes are possible for advanced use cases. But it's also easy to keep it simple by only using a single level of hierarchy.
Parallel to the DOM. Slate's data model is based on the DOM—the document is a nested tree, it uses selections and ranges, and it exposes all the standard event handlers. This means that advanced behaviors like tables or nested block quotes are possible. Pretty much anything you can do in the DOM, you can do in Slate.
Intuitive commands. Slate documents are edited using "commands", that are designed to be high-level and extremely intuitive to write and read, so that custom functionality is as expressive as possible. This greatly increases your ability to reason about your code.
Collaboration-ready data model. The data model Slate uses—specifically how operations are applied to the document—has been designed to allow for collaborative editing to be layered on top, so you won't need to rethink everything if you decide to make your editor collaborative.
Clear "core" boundaries. With a plugin-first architecture, and a schema-less core, it becomes a lot clearer where the boundary is between "core" and "custom", which means that the core experience doesn't get bogged down in edge cases.
Demo
Check out the live demo of all of the examples!
Examples
To get a sense for how you might use Slate, check out a few of the examples:
- Plain text — showing the most basic case: a glorified
<textarea>. - Rich text — showing the features you'd expect from a basic editor.
- Markdown preview — showing how to add key handlers for Markdown-like shortcuts.
- Inlines — showing how wrap text in inline nodes with associated data.
- Images — showing how to use void (text-less) nodes to add images.
- Hovering toolbar — showing how a hovering toolbar can be implemented.
- Tables — showing how to nest blocks to render more advanced components.
- Paste HTML — showing how to use an HTML serializer to handle pasted HTML.
- Mentions — showing how to use inline void nodes for simple @-mentions.
- See all the examples...
If you have an idea for an example that shows a common use case, pull request it!
Documentation
If you're using Slate for the first time, check out the Getting Started walkthroughs and the Concepts to familiarize yourself with Slate's architecture and mental models.
If even that's not enough, you can always read the source itself, which is heavily commented.
There are also translations of the documentation into other languages:
If you're maintaining a translation, feel free to pull request it here!
Packages
Slate's codebase is a monorepo of Yarn workspaces, released with Changesets. It consists of a handful of packages—although you won't always use all of them. They are:
| Package | Version | Size | Description |
|---|---|---|---|
slate |
Slate's core data model logic. | ||
slate-history |
A plugin that adds undo/redo history to Slate. | ||
slate-hyperscript |
A hyperscript tool to write JSX Slate documents! | ||
slate-react |
React components for rendering Slate editors. |
Contributing!
All contributions are super welcome! Check out the Contributing instructions for more info!
Slate is MIT-licensed.
Overview (`.changeset/README.md`)
Changesets
Hello and welcome! This folder has been automatically generated by @changesets/cli, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it in our repository
We have a quick list of common questions to get you started engaging with this project in
our documentation
Overview (`packages/slate-history/Readme.md`)
This package contains the core logic of Slate. Feel free to poke around to learn more!
Overview (`packages/slate-hyperscript/Readme.md`)
This package contains a hyperscript helper for creating Slate documents with JSX!
Overview (`packages/slate-react/Readme.md`)
This package contains the React-specific logic for Slate. It's separated further into a series of directories:
- Components — containing the React components for rendering Slate editors.
- Hooks — containing a few React hooks for Slate editors.
- Plugins — containing the React-specific plugins for Slate editors.
- Utils — containing a few private convenience modules.
Feel free to poke around in each of them to learn more!
Overview (`packages/slate/Readme.md`)
This package contains the core logic of Slate. Feel free to poke around to learn more!
Note: A number of source files contain extracted types for Interfaces or Transforms. This is done currently to enable custom type extensions as found in packages/src/interfaces/custom-types.ts.
Overview (`playwright/devices/README.md`)
Device and IME checks
These scripts drive the real input layer, where synthetic Playwright key events don't reach: OS input methods on macOS, and soft keyboards on Android. Each scenario opens an example, sends input through the OS, and compares the DOM, the Slate model and the selection after each step.
macOS input methods
macos/run.cjs opens headed Chromium and Firefox and types through real macOS input sources (Pinyin, Japanese, Korean, Russian, dead keys) with macos/ime-key.swift. The OS input method does the composing.
Setup:
- Give your terminal Accessibility access (System Settings > Privacy & Security > Accessibility).
ime-key trustedprintstruewhen it's set. - Start the examples:
yarn serve.
Run:
yarn node playwright/devices/macos/run.cjs [--browsers chromium,firefox] [scenario-or-issue ...]While it runs, the browser takes keyboard and mouse focus. Every key checks that the test browser is the frontmost app first, so switching to another app stops the run instead of typing into it. The original input source is restored afterwards.
Output is one line per scenario and browser: PASS, FAIL with the problems found, or SKIP when the input method didn't start composing after three tries. The control-* scenarios type into a plain textarea to confirm the input method works before blaming Slate.
Playwright's WebKit build runs as a background app that macOS won't give keyboard focus, so input methods can't reach it. Safari coverage needs real Safari instead.
Android soft keyboards
android/run.cjs drives Chrome on an Android emulator or a USB-connected phone. Input goes through android/ime, a small test keyboard app that makes the same Android input calls a keyboard like Gboard makes: set composing text, commit text, delete around the cursor, set the composing region, and key events. Chrome turns those into the same composition and beforeinput events a real keyboard produces.
Setup:
- An emulator with Chrome (a Google Play system image) or a phone with USB debugging on.
adb devicesshould list it. - Start the examples:
yarn serve.
Run:
yarn node playwright/devices/android/run.cjs [--serial emulator-5554] [scenario-or-issue ...]The script builds and installs the test keyboard on first use (needs the Android SDK build tools and a JDK), selects it, opens the example through adb reverse, and connects Playwright to Chrome's DevTools socket. It selects Gboard again when it finishes; set KEEP_TEST_IME=1 to leave the test keyboard on.
The test keyboard sends the calls a scenario lists. Real keyboards differ in which calls they make and in what order, so a passing scenario shows Slate handles that sequence, not that every keyboard works.
Use separate emulator, example-server and DevTools ports for concurrent runs:
SLATE_PORT=3200 DEVTOOLS_PORT=9335 yarn node playwright/devices/android/run.cjs --serial emulator-5556 second-composing-character-new-lineScenarios cover touch selection, suggestion replacement, sending during composition, paragraph formatting, scroll containers, Enter in headings, deleting a selection before accepting a suggestion, repeated identical composition updates, onChange per Backspace during composition, and Backspace across blocks. Letter/digit, text/void, composing/committed and keyboard/touch controls distinguish input setup failures from the reported editing behavior. The image-tap cases substitute a local SVG for the example's remote image requests so they do not depend on the image host.
tap sends an Android adb input tap by default and checks that a trusted touch reached the requested element, then waits for its click before the scenario continues. It reads Chrome’s toolbar_hairline bounds from uiautomator, then chooses a visible, hit-tested client rectangle and converts it using the current visual viewport and device scale. Set CDP_TAPS=1 to use Chrome DevTools touch dispatch for scenario taps instead. The initial editor tap remains native so Android establishes the keyboard input connection. Text still goes through Android InputConnection. keyboardShown reads Android's mInputShown state. hideKeyboard sends Android's Back key to establish a hidden-keyboard precondition before comparing text and mention taps. composeSequence sends composing prefixes without the usual per-step pause; adb transport still adds latency, so this does not model every fast physical keyboard.
Firefox for Android can be driven by geckodriver using moz:firefoxOptions.androidPackage and androidDeviceSerial. Complete its first-run screens and open a web page before waiting for a WebDriver session; the native home screen does not create a Marionette content window. WebDriver touch actions alone did not establish a test-keyboard input connection in the probe, while an adb touchscreen tap did. The Chrome runner is not a Firefox runner; verify both model and DOM when probing Firefox separately.
The Gboard probes use the keyboard’s accessibility key bounds from a fresh uiautomator dump --windows; they do not assume a screen size or fixed key coordinates. They require an English Gboard layout with the requested key labels exposed. A missing key stops the probe rather than guessing its location.
ANDROID_SERIAL=emulator-5556 SLATE_PORT=3200 DEVTOOLS_PORT=9335 yarn node playwright/devices/gboard-6022.cjs
ANDROID_SERIAL=emulator-5556 SLATE_PORT=3200 DEVTOOLS_PORT=9335 yarn node playwright/devices/gboard-5099.cjsThe first probe toggles bold and types bold; the second clears the editor, presses Backspace three times, then types asd. Both keep the model/keyboard diagnostics and exit non-zero when an assertion fails. The bold probe checks the inserted mark, caret preservation and surrounding document. The empty-editor probe checks the model, placeholder and keyboard before and after Backspace and typing; it accepts Gboard’s automatic capitalization of the first letter. Reading a fresh key dump adds time between Gboard keystrokes, so these probes establish the recorded sequence rather than rapid typing behavior.
The touch geometry check runs without a device:
yarn node --test playwright/devices/android/touch.test.cjstap-mention-composing records the native failure after composing pending, selecting a mention, pressing Backspace and composing after. The finished-composition and visible-keyboard controls exercise the same selection and deletion without an active composition. These are device regressions, so the composing case is expected to fail until the library handles the missing composition end. No synthetic composition event is used in the regression.
Run scenarios by issue number as above, or by their full names. They use the test keyboard's InputConnection calls and do not reproduce a specific vendor's candidate UI, a held Gboard key, or Keyman Mozhi transliteration. A failed platform-specific report still needs its keyboard and browser identified separately from these sequence checks.
Overview (`site/examples/Readme.md`)
Examples
This directory contains a set of examples that give you an idea for how you might use Slate to implement your own editor. Take a look around!
- Plain text — showing the most basic case: a glorified
<textarea>. - Rich text — showing the features you'd expect from a basic editor.
- Forced Layout - showing how to use constraints to enforce a document structure.
- Markdown Shortcuts — showing how to add key handlers for Markdown-like shortcuts.
- Inlines — showing how wrap text in inline nodes with associated data.
- Images — showing how to use void (text-less) nodes to add images.
- Hovering toolbar — showing how a hovering toolbar can be implemented.
- Tables — showing how to nest blocks to render more advanced components.
- Paste HTML — showing how to use an HTML serializer to handle pasted HTML.
- Code Highlighting — showing how to use decorations to dynamically format text.
- ...and more!
If you have an idea for an example that shows a common use case, pull request it!
Running the Examples
To get the examples running on your machine, you need to have the Slate repository cloned to your computer. After that, you need to cd into the directory where you cloned it, and install the dependencies with yarn and build the monorepo:
yarn install
yarn buildThen start the watcher and examples server:
yarn startNow you can open up http://localhost:3000 in your browser and you'll see the examples site. Any changes you make to the source code will be immediately reflected when you refresh the page. You can open the examples URL quickly with:
yarn openOverview (`docs/api/locations/README.md`)
Location Types APIs
The Location interface is a union of the ways to refer to a specific location in a Slate document: paths, points or ranges. Methods will often accept a Location instead of requiring only a Path, Point or Range.
type Location = Path | Point | RangeOverview (`docs/api/nodes/README.md`)
Node Types APIs
The Node union type represents all of the different types of nodes that occur in a Slate document tree.
type Node = Editor | Element | Text
type Descendant = Element | Text
type Ancestor = Editor | ElementOverview (`docs/api/operations/README.md`)
Operation Types
Operation objects define the low-level instructions that Slate editors use to apply changes to their internal state. Representing all changes as operations is what allows Slate editors to easily implement history, collaboration, and other features.
- Operation object
- Operation subtypes
Node Operations
Node operations operate on Node objects.
// insert a new `Node`
type InsertNodeOperation = {
type: 'insert_node'
path: Path
node: Node
}
// merge two `Node` objects
type MergeNodeOperation = {
type: 'merge_node'
path: Path
position: number
properties: Partial<Node>
}
// move `Node` from one path to another
type MoveNodeOperation = {
type: 'move_node'
path: Path
newPath: Path
}
// Remove a `Node`
type RemoveNodeOperation = {
type: 'remove_node'
path: Path
node: Node
}
// Set properties of a `Node`
type SetNodeOperation = {
type: 'set_node'
path: Path
properties: Partial<Node>
newProperties: Partial<Node>
}
// Split a node into two separate `Node` objects
type SplitNodeOperation = {
type: 'split_node'
path: Path
position: number
properties: Partial<Node>
}
export type NodeOperation =
| InsertNodeOperation
| MergeNodeOperation
| MoveNodeOperation
| RemoveNodeOperation
| SetNodeOperation
| SplitNodeOperationText Operations
Text operations operate on Text objects only.
Note: Text objects are Node objects so you can use Node operations on Text objects.
// insert text into an existing `Text` node
type InsertTextOperation = {
type: 'insert_text'
path: Path
offset: number
text: string
}
// remove text from an existing `Text` node
type RemoveTextOperation = {
type: 'remove_text'
path: Path
offset: number
text: string
}
export type TextOperation = InsertTextOperation | RemoveTextOperationSelection Operation
Operation to set or unset a selection Range.
type SetSelectionOperation =
| {
type: 'set_selection'
properties: null
newProperties: Range
}
| {
type: 'set_selection'
properties: Partial<Range>
newProperties: Partial<Range>
}
| {
type: 'set_selection'
properties: Range
newProperties: null
}
export type SelectionOperation = SetSelectionOperationBase Operation
The combination of all operation types.
export type BaseOperation = NodeOperation | SelectionOperation | TextOperationOverview (`docs/libraries/slate-history/README.md`)
Slate History
This sub-library tracks changes to the Slate value state over time, and enables undo and redo functionality.
Overview (`docs/libraries/slate-react/README.md`)
Slate React
This sub-library contains the React-specific logic for Slate.
Overview (`packages/slate/test/properties/README.md`)
Core property tests
yarn test includes this suite with seed 20261014 and 100 runs per property. yarn test:fuzz runs the same 41 properties 5,000 times each, with a longer Mocha timeout. fast-check shrinks failures and prints the seed, replay path and counterexample.
To replay a failure, select its property and pass the reported seed and path:
SLATE_FUZZ_SEED=20261014 SLATE_FUZZ_PATH='0:1' yarn test:fuzz --grep 'normalization is idempotent'For a different run count or seed:
SLATE_FUZZ_RUNS=10000 SLATE_FUZZ_SEED=42 yarn test:fuzzDomains and contracts
Default documents are bounded to four top-level blocks, a container level, inline elements and voids. The fuzz profile raises those limits to six root blocks and three container levels. Text includes ASCII, accented characters, a surrogate pair and a combining sequence. Text marks include optional booleans, IDs and nested JSON data. The normalization generator also supplies empty elements, adjacent text nodes and mixed block/inline content, including invalid top-level text.
Each of the nine operation types has its own document-and-selection inverse property. Operation payloads come from the current tree: removed text and nodes match their source, merge positions and properties match the preceding node, split properties match the source, and moves cannot target their own descendants. Separate generated sequences recompute valid operations after each step.
Raw operation and ref checks disable automatic normalization. An inverse cannot undo extra operations performed by a normalizer. The separate normalization property checks idempotence, no changes on a second pass, nonempty elements, compatible inline/block children, text around inline elements, and no adjacent empty or equal-mark texts.
Selection inverse properties use surviving, unambiguous points. Removing text or a node destroys position information inside it; re-inserting it cannot recover an old selection. The closed removed-text interval and both representations of a text merge seam are excluded from inverse assertions. Merged node paths also lose their separate node identities, so the path inverse check excludes those two exact paths. These exclusions are computed from the original operation, never by filtering for a successful transform result. Refs still test all these cases, including null affinities and removal, and must release their registrations.
Character positions are grapheme positions, not every UTF-16 offset. The string/position property compares against independently segmented block strings using Intl.Segmenter, checks strictly increasing points and their exact offsets, and checks reverse traversal by text-prefix positions. Distinct leaf endpoints can represent the same block offset when walking in opposite directions. It uses voids: true so hidden void text is included consistently by both string APIs.
Loose text equality is checked against Lodash's deep comparison of independently extracted marks. Generators never produce explicit undefined property values. Slate's equality treats them as missing keys, and merge_node and set_node inverses can drop them, so the strict round-trip checks would report differences JSON cannot represent. Equal nested values are cloned to avoid checking only shared object identities.
High-level transforms and history
Fifteen properties apply normalized high-level transforms with valid generated points, ranges and paths: delete, insertText, insertFragment, insertNodes, splitNodes, mergeNodes, inline/block wrap and unwrap, liftNodes, moveNodes, setNodes, unsetNodes and removeNodes. Deletion varies character/word/line/block units, distance and direction. Expanded deletion uses hanging: true; collapsed ranges use point deletion rather than an empty-range string oracle. String checks preserve the unaffected prefix/suffix, or all text for structural transforms. Point deletion protects root blocks outside the target and its immediate neighbors to allow void and empty-inline behavior.
Three history properties execute one to ten transforms under default history, withNewBatch, or withoutMerging. Empty documents are repaired with one root insertion before subsequent commands.
Documents must match the starting and ending snapshots after undoing and redoing every batch. Undo restores the first saved batch's selection. Redo starts from the final batch's selectionBefore and transforms it through its saved operations with forward affinity, checking equality when those points survive; standalone selection changes are not history entries. Every final selection must resolve to valid text offsets. This selection oracle tests history wiring, not an independent implementation of point transformation.
Seven position properties cover word, line and block with both void modes, plus character with voids: false. Each direction is strictly ordered and agrees with after or before for consecutive positions. Forward and reverse word boundaries need not coincide. A sample custom normalizer converts paragraphs containing exactly "x" into x-para, then checks termination, structural invariants and an operation-free second normalization.
Regressions and deferred contracts
regressions.spec.ts retains plain regressions for fragment replacement through voids and block-leading inlines, history restoring saved selections from null, and directional traversal through inline voids. The leading-inline cases cover both range directions and whether a preceding block exists; insertion must remain in its own block. A deep-container case also covers the trailing inline while the document temporarily ends in emptied containers.
Text-conserving generated merges use adjacent sibling elements with compatible child modes: both have block children, or both have text/inline children. An additional generated property constructs incompatible sibling pairs in both directions and checks that they throw without changing the document, selection, operations or registered refs. Plain regressions also cover inline children, a non-sibling target, empty sides, text-node merging and the previous-node removal policy.
The withoutMerging property covers issue #6302: before the fix, a transform's normalization operations became separate undo steps, and undoing them could throw or restore an invalid selection.
Scope
The fixed seed is a reproducible regression sample, not exhaustive coverage. Documents and sequences are deliberately small; sequences contain at most ten operations. Platform input and concurrent-operation convergence remain outside this suite; Slate operation transformation is not a convergent OT. History is the only plugin exercised here.
Introduction (`docs/Introduction.md`)
Introduction
Slate is a completely customizable framework for building rich text editors.
Slate lets you build rich, intuitive editors like those in Medium, Dropbox Paper or Google Docs—which are becoming table stakes for applications on the web—without your codebase getting mired in complexity.
It can do this because all of its logic is implemented with a series of plugins, so you aren't ever constrained by what is or isn't in "core". You can think of it like a pluggable implementation of contenteditable built on top of React. It was inspired by libraries like Draft.js, Prosemirror and Quill.
🤖 Slate is currently in beta. Its core API is usable now, but you might need to pull request fixes for advanced use cases. Some of its APIs are not "finalized" and will (breaking) change over time as we find better solutions.
Why?
Why create Slate? Well... (Beware: this section has a few of my opinions!)
Before creating Slate, I tried a lot of the other rich text libraries out there—Draft.js, Prosemirror, Quill, etc. What I found was that while getting simple examples to work was easy enough, once you started trying to build something like Medium, Dropbox Paper or Google Docs, you ran into deeper issues...
- The editor's "schema" was hardcoded and hard to customize. Things like bold and italic were supported out of the box, but what about comments, or embeds, or even more domain-specific needs?
- Transforming the documents programmatically was very convoluted. Writing as a user may have worked, but making programmatic changes, which is critical for building advanced behaviors, was needlessly complex.
- Serializing to HTML, Markdown, etc. seemed like an afterthought. Simple things like transforming a document to HTML or Markdown involved writing lots of boilerplate code, for what seemed like very common use cases.
- Re-inventing the view layer seemed inefficient and limiting. Most editors rolled their own views, instead of using existing technologies like React, so you had to learn a whole new system with new "gotchas".
- Collaborative editing wasn't designed for in advance. Often the editor's internal representation of data made it impossible to use for a realtime, collaborative editing use case without basically rewriting the editor.
- The repositories were monolithic, not small and reusable. The code bases for many of the editors often didn't expose the internal tooling that could have been re-used by developers, leading to having to reinvent the wheel.
- Building complex, nested documents was impossible. Many editors were designed around simplistic "flat" documents, making things like tables, embeds and captions difficult to reason about and sometimes impossible.
Of course not every editor exhibits all of these issues, but if you've tried using another editor you might have run into similar problems. To get around the limitations of their APIs and achieve the user experience you're after, you have to resort to very hacky things. And some experiences are just plain impossible to achieve.
If that sounds familiar, you might like Slate.
Which brings me to how Slate solves all of that...
Principles
Slate tries to solve the question of "Why?" with a few principles:
- First-class plugins. The most important part of Slate is that plugins are first-class entities. That means you can completely customize the editing experience, to build complex editors like Medium's or Dropbox's, without having to fight against the library's assumptions.
- Schema-less core. Slate's core logic assumes very little about the schema of the data you'll be editing, which means that there are no assumptions baked into the library that'll trip you up when you need to go beyond the most basic use cases.
- Nested document model. The document model used for Slate is a nested, recursive tree, just like the DOM itself. This means that creating complex components like tables or nested block quotes are possible for advanced use cases. But it's also easy to keep it simple by only using a single level of hierarchy.
- Parallel to the DOM. Slate's data model is based on the DOM—the document is a nested tree, it uses selections and ranges, and it exposes all the standard event handlers. This means that advanced behaviors like tables or nested block quotes are possible. Pretty much anything you can do in the DOM, you can do in Slate.
- Intuitive commands. Slate documents are edited using "commands", that are designed to be high-level and extremely intuitive to write and read, so that custom functionality is as expressive as possible. This greatly increases your ability to reason about your code.
- Collaboration-ready data model. The data model Slate uses—specifically how operations are applied to the document—has been designed to allow for collaborative editing to be layered on top, so you won't need to rethink everything if you decide to make your editor collaborative.
- Clear "core" boundaries. With a plugin-first architecture, and a schema-less core, it becomes a lot clearer where the boundary is between "core" and "custom", which means that the core experience doesn't get bogged down in edge cases.
Demo
Check out the live demo of all of the examples!
Examples
To get a sense for how you might use Slate, check out a few of the examples:
- Plain text — showing the most basic case: a glorified
<textarea>. - Rich text — showing the features you'd expect from a basic editor.
- Markdown preview — showing how to add key handlers for Markdown-like shortcuts.
- Inlines — showing how to wrap text in inline nodes with associated data.
- Images — showing how to use void (text-less) nodes to add images.
- Hovering toolbar — showing how a contextual hovering menu can be implemented.
- Tables — showing how to nest blocks to render more advanced components.
- Paste HTML — showing how to use an HTML serializer to handle pasted HTML.
- Mentions — showing how to use inline void nodes for simple @-mentions.
Each example includes a View Source link to the code that implements it. And we have other examples too.
If you have an idea for an example that shows a common use case, pull request it!
Documentation
If you're using Slate for the first time, check out the Getting Started walkthroughs and the Concepts to familiarize yourself with Slate's architecture and mental models.
If even that's not enough, you can always read the source itself, which is heavily commented.
There are also translations of the documentation into other languages:
If you're maintaining a translation, feel free to pull request it here!
Contributing!
All contributions are super welcome! Check out the Contributing instructions for more info!
Slate is MIT-licensed.
Summary (`docs/Summary.md`)
Table of contents
Walkthroughs
- Installing Slate
- Adding Event Handlers
- Defining Custom Elements
- Applying Custom Formatting
- Executing Commands
- Saving to a Database
- Enabling Collaborative Editing
- Using the Bundled Source
- Improving Performance
- Collaboration with Yjs
- Accessibility
Concepts
- Interfaces
- Nodes
- Locations
- Transforms
- Operations
- Commands
- Editor
- Plugins
- Rendering
- Serializing
- Normalizing
- TypeScript
- Migrating
API
Libraries
General
Api Scrubber (`docs/api/scrubber.md`)
Scrubber API
When Slate throws an exception, it includes a stringified representation of the
relevant data. For example, if your application makes an API call to access the
child of a text Node (an impossible operation), Slate will throw an exception
like this:
Cannot get the child of a text node: {"text": "This is my text node."}If your rich text editor can include sensitive customer data, you may want to
scrub or obfuscate that text. To help with that, you can use the Scrubber API.
Here's an example of recursively scrubbing the 'text' fields of any entity
that gets logged.
import { Scrubber } from 'slate'
Scrubber.setScrubber((key, value) => {
if (key === 'text') return '... scrubbed ...'
return value
})By setting the scrubber in this way, the error example given above will be
printed as:
Cannot get the child of a text node: {"text": "... scrubbed ..."}Text Randomizer Example
Here's an example "textRandomizer" scrubber, which randomizes particular fields
of Nodes, preserving their length, but replacing their contents with randomly
chosen alphanumeric characters.
import { Scrubber } from 'slate'
const textRandomizer = (fieldNames: string[]) => (key, value) => {
if (fieldNames.includes(key)) {
if (typeof value === 'string') {
return value.split('').map(generateRandomCharacter).join('')
} else {
return '... scrubbed ...'
}
}
return value
}
const generateRandomCharacter = (): string => {
const chars =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890'
return chars.charAt(Math.floor(Math.random() * chars.length))
}
// randomize the 'text' and 'src' fields of any Node that is included in an
// exception thrown by Slate
Scrubber.setScrubber(Scrubber.textRandomizer(['text', 'src']))In this example, a Node that looked like:
{ "text": "My test input string", "count": 5 }will be logged by Slate in an exception as (the random string will differ):
{ "text": "rSIvEzKe39l6rqQSCfyv", "count": 5 }Api Transforms (`docs/api/transforms.md`)
Transforms API
Transforms are helper functions operating on the document. They can be used in defining your own commands.
Node options
Transforms that target a location support a parameter options. This includes options specific to the transform and general NodeOptions to specify which Nodes in the document the transform is applied to.
interface NodeOptions {
at?: Location
match?: (node: Node, path: Location) => boolean
mode?: 'highest' | 'lowest'
voids?: boolean
}The
atoption selects a Location in the editor. It defaults to the user's current selection. Learn more about theatoptionThe
matchoption filters the set of Nodes with a custom function. Learn more about thematchoptionThe
modeoption also filters the set of nodes.When
voidsis false, void Elements are filtered out.
Static methods
Node transforms
These transforms operate on nodes.
`Transforms.setChildren(editor: Editor, children: Descendant[])`
Apply an external document through Slate operations. Delegates to editor.setChildren, so plugins can override the transform. Unchanged child prefixes and suffixes are retained, matched by identity or by deep equality, so a refetched copy of the document with one new block emits a single insert_node. Compatible nodes are updated recursively; text edits replace only the changed string middle. Deep-equal cloned values emit no operations.
Nodes shared by object identity can move within or across parents with a move_node, preserving selections inside them. Cloned moves are treated as content edits or replacements. Normalization is held until the diff is complete, and selection and refs follow the emitted operations through their normal rules.
With withHistory, each external change forms one undo step and is separate from typing before and after it.
To clear an editable document, pass a schema-valid empty block, for example [{ type: 'paragraph', children: [{ text: '' }] }]. setChildren itself accepts an empty root; it does not invent a block or reset history.
`Transforms.insertFragment(editor: Editor, fragment: Node[], options?)`
Insert a fragment of nodes at the specified location or (if not defined) the current selection or (if not defined) the end of the document.
Options: {at?: Location, hanging?: boolean, voids?: boolean}
With voids: true, replacing an expanded range also deletes within void content instead of removing the void nodes as atomic units. At an inline boundary, insertion uses the surrounding text in that block, adding the empty text required by normalization if replacement temporarily removes it.
`Transforms.insertNodes(editor: Editor, nodes: Node | Node[], options?)`
Atomically insert nodes at the specified location or (if not defined) the current selection or (if not defined) the end of the document.
Options supported: NodeOptions & {hanging?: boolean, select?: boolean}.
For example, to insert at the very end, without replacing the current selection and regardless of block nesting, use
Transforms.insertNodes(
editor,
{ type: targetType, children: [{ text: '' }] },
{ at: [editor.children.length] }
)`Transforms.removeNodes(editor: Editor, options?)`
Remove nodes at the specified location in the document. If no location is specified, remove the nodes in the selection.
Options supported: NodeOptions & {hanging?: boolean}
`Transforms.mergeNodes(editor: Editor, options?)`
Merge a node at the specified location with the previous node at the same depth. If no location is specified, use the selection. Resulting empty container nodes are removed.
Merging elements throws if both have children and one contains blocks while the other contains text or inline nodes, unless shouldMergeNodesRemovePrevNode removes the previous node instead. The error names both paths and is raised before moving or removing the merge targets. An expanded at range can be deleted before this check.
Options supported: NodeOptions & {hanging?: boolean}
`Transforms.splitNodes(editor: Editor, options?)`
Split nodes at the specified location. If no location is specified, split the selection.
Options supported: NodeOptions & {height?: number, always?: boolean}
`Transforms.wrapNodes(editor: Editor, element: Element, options?)`
Wrap nodes at the specified location in the element container. If no location is specified, wrap the selection.
Options supported: NodeOptions & {hanging?: boolean, split?: boolean}.
options.mode:'all'is also supported.options.splitindicates that it's okay to split a node in order to wrap the location. For example, ifipsumwas selected in aTextnode withlorem ipsum dolar,split: truewould wrap the wordipsumonly, resulting in splitting theTextnode. Ifsplit: false, the entireTextnodelorem ipsum dolarwould be wrapped.
`Transforms.unwrapNodes(editor: Editor, options?)`
Unwrap nodes at the specified location. If necessary, the parent node is split. If no location is specified, use the selection.
Options supported: NodeOptions & {hanging?: boolean, split?: boolean}. For options.mode, 'all' is also supported.
`Transforms.setNodes(editor: Editor, props: Partial> | ((node: Node, path: Path) => Partial>), options?)`
Set properties of nodes at the specified location. If no location is specified, use the selection. Optional node properties can be set to null to unset them.
If props contains undefined values, the node's corresponding property will also be set to undefined as opposed to ignored.
props can also be a function that receives each matched node and its path and returns the properties for that node, so new values can depend on old ones. Each node still gets one set_node operation, so undo works per node:
Transforms.setNodes(editor, node => ({ indent: (node.indent ?? 0) + 1 }), {
match: n => Element.isElement(n) && n.type === 'paragraph',
})children and text in props are ignored, since they hold a node's content rather than its properties. To change content, use insertNodes, removeNodes or the text transforms.
With replace: true, every other property of each matched node is removed in the same operation, so the node ends up with exactly props (plus its children or text). Use it to change a node into a different type without carrying over properties that only made sense for the old type, such as turning { type: 'callout', color: 'blue' } into { type: 'paragraph' }. Undo restores the removed properties.
Options supported: NodeOptions & {hanging?: boolean, split?: boolean, replace?: boolean}. For options.mode, 'all' is also supported.
`Transforms.unsetNodes(editor: Editor, props: string | string[], options?)`
Unset properties of nodes at the specified location. If no location is specified, use the selection.
Options supported: NodeOptions & {hanging?: boolean, split?: boolean}. For options.mode, 'all' is also supported.
`Transforms.liftNodes(editor: Editor, options?)`
Lift nodes at the specified location upwards in the document tree. If necessary, the parent node is split. If no location is specified, use the selection.
Options supported: NodeOptions & {height?: number}. height defaults to 1 and must be a non-negative integer. A height of 0 does nothing; larger heights lift each matched node through that many ancestors, stopping at the top level. A node that is already at the top level cannot be lifted. For options.mode, 'all' is also supported.
`Transforms.moveNodes(editor: Editor, options)`
Move the nodes from an origin to a destination. A destination must be specified in the options. If no origin is specified, move the selection.
to is the path the node ends up at once the move is done, not the path it is inserted before. For example, with four blocks 1 2 3 4, moving [0] to [2] gives 2 3 1 4. When match selects several nodes, they are moved one at a time, each to to.
Options supported: NodeOptions & {to: Path}. For options.mode, 'all' is also supported.
Selection transforms
Transforms that operate on the document's selection.
`Transforms.collapse(editor: Editor, options?)`
Collapse the selection to a single point.
Options: {edge?: 'anchor' | 'focus' | 'start' | 'end'}
`Transforms.select(editor: Editor, target: Location)`
Set the selection to a new value specified by target. When a selection already exists, this method is just a proxy for setSelection and will update the existing value.
For example, to set the selection to the entire contents of the editor:
Transforms.select(editor, {
anchor: Editor.start(editor, []),
focus: Editor.end(editor, []),
})`Transforms.deselect(editor: Editor)`
Unset the selection.
`Transforms.move(editor: Editor, options?)`
Move the selection's point forward or backward.
Options: {distance?: number, unit?: 'offset' | 'character' | 'word' | 'line', reverse?: boolean, edge?: 'anchor' | 'focus' | 'start' | 'end'}
`Transforms.setPoint(editor: Editor, props: Partial, options?)`
Set new properties on one of the selection's points.
Options: {edge?: 'anchor' | 'focus' | 'start' | 'end'}
`Transforms.setSelection(editor: Editor, props: Partial)`
Set new properties on an active selection. Since the value is a Partial<Range>, this method can only handle updates to an existing selection. If there is no active selection the operation will be void. Use select if you'd like to create a selection when there is none.
Text transforms
Transforms that operate on text.
`Transforms.delete(editor: Editor, options?)`
Delete text in the document.
Options: {at?: Location, distance?: number, unit?: 'character' | 'word' | 'line' | 'block', reverse?: boolean, hanging?: boolean, voids?: boolean}
`Transforms.insertText(editor: Editor, text: string, options?)`
Insert a string of text at the specified location or (if not defined) the current selection or (if not defined) the end of the document.
Options: {at?: Location, voids?: boolean}
Editor transforms
`Transforms.transform(editor: Editor, transform: Transform)`
Transform the editor by an operation.
Selecting transform results
insertNodes, insertFragment, insertText, splitNodes, moveNodes and liftNodes accept select?: boolean. Use select: true to move the caret to the result even when supplying an explicit at:
Transforms.insertText(editor, 'hello', {
at: { path: [1, 0], offset: 0 },
select: true,
})Insertions select the end of the inserted content. Splitting selects the start of the new content after the split. Moving or lifting selects the end of the last moved node. Insertion and splitting select by default only when at is omitted. moveNodes and liftNodes preserve their existing default: the selection follows moved content, keeping its offsets and direction, without explicitly selecting the end.
With select: false, these transforms do not explicitly select their result. The existing selection is still transformed by operations, so its paths and offsets can change when content moves or text is inserted. An explicit at without select: true leaves an unrelated selection in place.
Other transforms retain their existing selection behavior; property changes and wrapping, unwrapping, merging or removing nodes do not gain a new result-selection option.
insertText preserves a null selection by default; use select: true to create a caret after inserting into an unfocused document.
Concepts 01 Interfaces (`docs/concepts/01-interfaces.md`)
Interfaces
Slate works with pure JSON objects. All it requires is that those JSON objects conform to certain interfaces. For example, a text node in Slate must obey the Text interface:
interface Text {
text: string
}Which means it must have a text property with a string of content.
But any other custom properties are also allowed, and completely up to you. This lets you tailor your data to your specific domain and use case, adding whatever formatting logic you'd like, without Slate getting in the way.
This interface-based approach separates Slate from most other rich text editors which require you to work with their hand-rolled "model" classes and makes it much easier to reason about. It also means that it avoids startup time penalties related to "initializing" the data model.
Custom Properties
To take another example, the Element node interface in Slate is:
interface Element {
children: Node[]
}This is a very permissive interface. All it requires is that the children property gets defined containing the element's child nodes.
But you can extend elements (or any other interface) with your custom properties that are specific to your domain. For example, you might have "paragraph" and "link" elements:
const paragraph = {
type: 'paragraph',
children: [...],
}
const link = {
type: 'link',
url: 'https://example.com',
children: [...]
}The type and url properties are your custom API. Slate sees that they exist, but doesn't use them. However, when Slate renders a link element, you'll receive an object with the custom properties attached so that you can render it as:
<a href={element.url}>{element.children}</a>When getting started with Slate, it's important to understand all of the interfaces it defines. There are a handful of interfaces that are discussed in each of the guides.
Helper Functions
In addition to the typing information, each interface in Slate also exposes a series of helper functions that make them easier to work with.
For example, when working with nodes:
import { Node } from 'slate'
// Get the string content of an element node.
const string = Node.string(element)
// Get the node at a specific path inside a root node.
const descendant = Node.get(value, path)Or, when working with ranges:
import { Range } from 'slate'
// Get the start and end points of a range in order.
const [start, end] = Range.edges(range)
// Check if a range is collapsed to a single point.
if (Range.isCollapsed(range)) {
// ...
}There are many helper functions available for all common use cases when working with different interfaces. When getting started it helps to read through all of them so you can often simplify complex logic into just a handful of lines of code.
Custom Helpers
In addition to the built-in helper functions, you might want to define your custom helper functions and expose them on your custom namespaces.
For example, if your editor supports images, you might want a helper that determines if an element is an image element:
const isImageElement = element => {
return element.type === 'image' && typeof element.url === 'string'
}You can define these as one-off functions easily. But you might also bundle them up into namespaces, just like the core interfaces do, and use them instead.
For example:
import { Element } from 'slate'
// You can use `MyElement` everywhere to have access to your extensions.
export const MyElement = {
...Element,
isImageElement,
isParagraphElement,
isQuoteElement,
}This makes it easy to reuse domain-specific logic alongside the built-in Slate helpers.
Concepts 02 Nodes (`docs/concepts/02-nodes.md`)
Nodes
The most important types are the Node objects:
- A root-level
Editornode that contains the entire document's content. - Container
Elementnodes that have semantic meaning in your domain. - And leaf-level
Textnodes which contain the document's text.
These three interfaces are combined to form a tree—just like the DOM. For example, here's a simple plaintext value:
const editor = {
children: [
{
type: 'paragraph',
children: [
{
text: 'A line of text!',
},
],
},
],
// ...the editor has other properties too.
}Mirroring the DOM as much as possible is one of Slate's principles. People use the DOM to represent documents with rich text-like structures all the time. Mirroring the DOM helps make the library familiar for new users, and it lets us reuse battle-tested patterns without having to reinvent them ourselves.
🤖 The following content on Mozilla's Developer Network may help you learn more about the corresponding DOM concepts:
A Slate document is a nested and recursive structure. In a document, elements can have children nodes—all of which may have children nodes without limit. The nested and recursive structure enables you to model simple behaviors such as user mentions and hashtags or complex behaviors such as tables and figures with captions.
`Editor`
The top-level node in a Slate document is the Editor itself. It encapsulates all of the rich text "content" of the document. Its interface is:
interface Editor {
children: Node[]
...
}We'll cover its functionality later, but the important part as far as nodes are concerned is its children property which contains a tree of Node objects.
`Element`
Elements make up the middle layers of a rich text document. They are the nodes that are custom to your domain. Their interface is:
interface Element {
children: Node[]
}You can define custom elements for any type of content you want. For example, you might have paragraphs and quotes in your data model which are differentiated by a type property:
const paragraph = {
type: 'paragraph',
children: [...],
}
const quote = {
type: 'quote',
children: [...],
}It's important to note that you can use any custom properties you want. The type property in that example isn't something Slate knows or cares about. If you were defining your own "link" nodes, you might have a url property:
const link = {
type: 'link',
url: 'https://example.com',
children: [...],
}Or maybe you want to give all of your nodes an ID property:
const paragraph = {
id: 1,
type: 'paragraph',
children: [...],
}All that matters is that elements always have a children property.
Node IDs
IDs are custom properties. Slate does not assign them or enforce their uniqueness. By default, splitting a node copies its properties onto the new right-hand node, including its id. The left-hand node keeps its original properties.
Override editor.getSplitProperties to choose the new node's properties. This example gives each new element a fresh ID while keeping text marks and other split policies:
import { Element } from 'slate'
const withNodeIds = (editor, createId) => {
const { getSplitProperties } = editor
editor.getSplitProperties = (node, path) => {
const properties = getSplitProperties(node, path)
if (!Element.isElement(node)) return properties
const { id, ...rest } = properties
return { ...rest, id: createId() }
}
return editor
}Pass an ID generator that produces unique values. Return rest instead if another part of your application assigns missing IDs. Return the other properties too: the hook supplies the new node's complete property set, rather than a patch. Do not include children or text in the returned properties.
The hook receives the node and its current path for every node actually split by Transforms.splitNodes, including text nodes and multiple ancestor levels. It also covers commands that use that transform, such as Enter, fragment insertion and setNodes with split: true, and inline elements split by Transforms.wrapNodes. Keep text properties when overriding it so formatting survives these operations.
With slate-history, undo restores the original node and its ID; redo reuses the properties recorded in the split operation. The hook does not assign or deduplicate IDs on incoming content that is inserted without a split. Apply your ID policy to initial and pasted content separately.
Blocks vs. Inlines
Depending on your use case, you might want to define another behavior for Element nodes which determines their editing "flow".
All elements default to being "block" elements. They each appear separated by vertical space, and they never run into each other.
But in certain cases, like for links, you might want to make them "inline" flowing elements instead. That way they live at the same level as text nodes, and flow.
🤖 This is a concept borrowed from the DOM's behavior, see Block Elements and Inline Elements.
You can define which nodes are treated as inline nodes by overriding the editor.isInline function. (By default it always returns false.) Note that inline nodes cannot be the first or last child of a parent block, nor can they be next to another inline node in the children array. Slate will automatically space these with { text: '' } children by default with normalizeNode.
Elements can either contain block elements or inline elements intermingled with text nodes as children. But elements cannot contain some children that are blocks and some that are inlined.
Voids
Similar to blocks and inlines, there is another element-specific behavior you can define depending on your use case: their "void"-ness.
Elements default to being non-void, meaning that their children are fully editable as text. But in some cases, like for images, you want to ensure that Slate doesn't treat their content as editable text, but instead as a black box.
🤖 This is a concept borrowed from the HTML spec, see Void Elements.
You can define which elements are treated as void by overriding the editor.isVoid function. (By default it always returns false.) See Rendering Void Elements for implementation details.
`Text`
Text nodes are the lowest-level nodes in the tree, containing the text content of the document, along with any formatting. Their interface is:
interface Text {
text: string
}For example, a string of bold text:
const text = {
text: 'A string of bold text',
bold: true,
}Text nodes too can contain any custom properties you want, and that's how you implement custom formatting like bold, italic, code, etc.
These custom properties are sometimes called marks.
Concepts 03 Locations (`docs/concepts/03-locations.md`)
Locations
Locations are how you refer to specific places in the document when inserting, deleting, or doing anything else with a Slate editor. There are a few different kinds of location interfaces, each for different use cases.
`Path`
Paths are the lowest-level way to refer to a location. Each path is a simple array of numbers that refers to a node in the document tree by its indexes in each of its ancestor nodes down the tree:
type Path = number[]For example, in this document:
const editor = {
children: [
{
type: 'paragraph',
children: [
{
text: 'A line of text!',
},
],
},
],
}The leaf text node would have a path of: [0, 0].
The Editor itself has a path of []. For example, to select the whole contents of the editor, callTransforms.select(editor, [])
`Point`
Points are slightly more specific than paths, and contain an offset into a specific text node. Their interface is:
interface Point {
path: Path
offset: number
}For example, with that same document, if you wanted to refer to the very first place you could put your cursor it would be:
const start = {
path: [0, 0],
offset: 0,
}Or, if you wanted to refer to the end of the sentence:
const end = {
path: [0, 0],
offset: 15,
}It can be helpful to think of points as being "cursors" (or "carets") of a selection.
🤖 Points always refer to text nodes! Since they are the only ones with strings that can have cursors.
`Range`
Ranges are a way to refer not just to a single point in the document, but to a wider span of content between two points. (An example of a range is when you make a selection.) Their interface is:
interface Range {
anchor: Point
focus: Point
}🤖 The terms "anchor" and "focus" are borrowed from the DOM, see Anchor and Focus.
An anchor and focus are established by a user interaction. The anchor point isn't always before the focus point in the document. Just like in the DOM, the ordering of an anchor and selection point depend on whether the range is backwards or forwards.
Here's how Mozilla Developer Network explains it:
A user may make a selection from left to right (in document order) or right to left (reverse of document order). The anchor is where the user began the selection and the focus is where the user ends the selection. If you make a selection with a desktop mouse, the anchor is placed where you pressed the mouse button and the focus is placed where you released the mouse button. Anchor and focus should not be confused with the start and end positions of a selection, since anchor can be placed before the focus or vice versa, depending on the direction you made your selection. —
Selection, MDN
One important distinction is that the anchor and focus points of ranges always reference the leaf-level text nodes in a document and never reference elements. This behavior is different than the DOM, but it simplifies working with ranges as there are fewer edge cases for you to handle.
🤖 For more info, check out the Range API reference.
Selection
Ranges are used in many places in Slate's API when you need to refer to a span of content between two points. One of the most common, though, is the user's current "selection".
The selection is a special range that is a property of the top-level Editor. For example, say someone has the whole sentence currently selected:
const editor = {
selection: {
anchor: { path: [0, 0], offset: 0 },
focus: { path: [0, 0], offset: 15 },
},
children: [
{
type: 'paragraph',
children: [
{
text: 'A line of text!',
},
],
},
],
}🤖 The selection concept is also borrowed from the DOM, see
Selection, MDN, although in a greatly-simplified form because Slate doesn't allow for multiple ranges inside a single selection, which makes things a lot easier to work with.
There isn't a special Selection interface. It's just an object that happens to respect the more general-purpose Range interface instead.
For example, to find the lowest block that contains all of the current selection:
function getCommonBlock(editor) {
const range = Editor.unhangRange(editor, editor.selection, { voids: true })
let [common, path] = SlateNode.common(
editor,
range.anchor.path,
range.focus.path
)
if (Editor.isBlock(editor, common) || Editor.isEditor(common)) {
return [common, path]
} else {
return Editor.above(editor, {
at: path,
match: n => Editor.isBlock(editor, n) || Editor.isEditor(n),
})
}
}Concepts 04 Transforms (`docs/concepts/04-transforms.md`)
Transforms
Slate's data structure is immutable, so you can't modify or delete nodes directly. Instead, Slate comes with a collection of "transform" functions that let you change your editor's value.
Slate's transform functions are designed to be very flexible, to make it possible to represent all kinds of changes you might need to make to your editor. However, that flexibility can be hard to understand at first.
Typically, you'll apply a single operation to zero or more Nodes. For example, here's how you flatten the syntax tree,
by applying unwrapNodes to every parent of block Elements:
Transforms.unwrapNodes(editor, {
at: [], // Path of Editor
match: node =>
!Editor.isEditor(node) &&
node.children?.every(child => Editor.isBlock(editor, child)),
mode: 'all', // also the Editor's children
})Non-standard operations (or debugging/tracing which Nodes will be affected by a set of NodeOptions) may require usingEditor.nodes to create a JavaScript Iterator of NodeEntries and a for..of loop to act.
For example, to replace all image elements with their alt text:
const imageElements = Editor.nodes(editor, {
at: [], // Path of Editor
match: (node, path) => 'image' === node.type,
// mode defaults to "all", so this also searches the Editor's children
})
for (const nodeEntry of imageElements) {
const altText =
nodeEntry[0].alt ||
nodeEntry[0].title ||
/\/([^/]+)$/.exec(nodeEntry[0].url)?.[1] ||
'☹︎'
Transforms.select(editor, nodeEntry[1])
Editor.insertFragment(editor, [{ text: altText }])
}🤖 Check out the Transforms reference for a full list of Slate's transforms.
Selection Transforms
Selection-related transforms are some of the simpler ones. For example, here's how you set the selection to a new range:
Transforms.select(editor, {
anchor: { path: [0, 0], offset: 0 },
focus: { path: [1, 0], offset: 2 },
})But they can be more complex too.
For example, it's common to need to move a cursor forwards or backwards by varying distances—by character, by word, by line. Here's how you'd move the cursor backwards by three words:
Transforms.move(editor, {
distance: 3,
unit: 'word',
reverse: true,
})🤖 For more info, check out the Selection Transforms API Reference
Text Transforms
Text transforms act on the text content of the editor. For example, here's how you'd insert a string of text as a specific point:
Transforms.insertText(editor, 'some words', {
at: { path: [0, 0], offset: 3 },
})Or you could delete all of the content in an entire range from the editor:
Transforms.delete(editor, {
at: {
anchor: { path: [0, 0], offset: 0 },
focus: { path: [1, 0], offset: 2 },
},
})🤖 For more info, check out the Text Transforms API Reference
Node Transforms
Node transforms act on the individual element and text nodes that make up the editor's value. For example you could insert a new text node at a specific path:
Transforms.insertNodes(
editor,
{
text: 'A new string of text.',
},
{
at: [0, 1],
}
)Or you could move nodes from one path to another:
Transforms.moveNodes(editor, {
at: [0, 0],
to: [0, 1],
})🤖 For more info, check out the Node Transforms API Reference
The `at` Option
Many transforms act on a specific location in the document. By default, they will use the user's current selection. But this can be overridden with the at option.
For example when inserting text, this would insert the string at the user's current cursor:
Transforms.insertText(editor, 'some words')Whereas this would insert it at a specific point:
Transforms.insertText(editor, 'some words', {
at: { path: [0, 0], offset: 3 },
})The at option is very versatile, and can be used to implement more complex transforms very easily. Since it is a Location it can always be either a Path, Point, or Range. And each of those types of locations will result in slightly different transformations.
For example, in the case of inserting text, if you specify a Range location, the range will first be deleted, collapsing to a single point where your text is then inserted.
So to replace a range of text with a new string you can do:
Transforms.insertText(editor, 'some words', {
at: {
anchor: { path: [0, 0], offset: 0 },
focus: { path: [0, 0], offset: 3 },
},
})Or, if you specify a Path location, it will expand to a range that covers the entire node at that path. Then, using the range-based behavior it will delete all of the content of the node, and replace it with your text.
So to replace the text of an entire node with a new string you can do:
Transforms.insertText(editor, 'some words', {
at: [0, 0],
})These location-based behaviors work for all the transforms that take an at option. It can be hard to wrap your head around at first, but it makes the API very powerful and capable of expressing many subtly different transforms.
The `match` Option
Many of the node-based transforms take a match function option, which restricts the transform to only apply to nodes for which the function returns true. When combined with at, match can also be very powerful.
For example, consider a basic transform that moves a node from one path to another:
Transforms.moveNodes(editor, {
at: [2],
to: [5],
})Although it looks like it simply takes a path and moves it to another place. Under the hood two things are happening…
First, the at option is expanded to be a range representing all of the content inside the node at [2]. Which might look something like:
at: {
anchor: { path: [2, 0], offset: 0 },
focus: { path: [2, 2], offset: 19 }
}Second, the match option is defaulted to a function that only matches the specific path, in this case [2]:
match: (node, path) => Path.equals(path, [2])Then Slate iterates over the range and moves any nodes that pass the matcher function to the new location. In this case, since match is defaulted to only match the exact [2] path, that node is moved.
But what if you wanted to move the children of the node at [2] instead?
You might consider looping over the node's children and moving them one at a time, but this gets very complex to manage because as you move the nodes the paths you're referring to become outdated.
Instead, you can take advantage of the at and match options to match all of the children:
Transforms.moveNodes(editor, {
// This will again be expanded to a range of the entire node at `[2]`.
at: [2],
// Matches nodes with a longer path, which are the children.
match: (node, path) => path.length === 2,
to: [5],
})Here we're using the same at path (which is expanded to a range), but instead of letting it match just that path by default, we're supplying our own match function which happens to match only the children of the node.
Using match can make representing complex logic a lot simpler.
For example, consider wanting to add a bold mark to any text nodes that aren't already italic:
Transforms.setNodes(
editor,
{ bold: true },
{
// This path references the editor, and is expanded to a range that
// will encompass all the content of the editor.
at: [],
// This only matches text nodes that are not already italic.
match: (node, path) => Text.isText(node) && node.italic !== true,
}
)When performing transforms, if you're ever looping over nodes and transforming them one at a time, consider seeing if match can solve your use case, and offload the complexity of managing loops to Slate instead.
The match function can examine the children of a node, in node.children, or use Node.parent to examine its parent.
Transforms and Normalization
Sequences of Transforms may need to be wrapped in Editor.withoutNormalizing if the node tree should not be normalized between Transforms.
See Normalization - Implications for Other Code;
Concepts 05 Operations (`docs/concepts/05-operations.md`)
Operations
Operations are the granular, low-level actions that occur while invoking transforms. A single transform could result in many low-level operations being applied to the editor.
Slate's core defines all of the possible operations that can occur on a richtext document. For example:
editor.apply({
type: 'insert_text',
path: [0, 0],
offset: 15,
text: 'A new string of text to be inserted.',
})
editor.apply({
type: 'remove_node',
path: [0, 0],
node: {
text: 'A line of text!',
},
})
editor.apply({
type: 'set_selection',
properties: {
anchor: { path: [0, 0], offset: 0 },
},
newProperties: {
anchor: { path: [0, 0], offset: 15 },
},
})Under the covers Slate converts complex transforms into the low-level operations and applies them to the editor automatically. So you rarely have to think about operations unless you're implementing collaborative editing.
🤖 Slate's editing behaviors being defined as operations is what makes things like collaborative editing possible, because each change is easily define-able, apply-able, compose-able and even undo-able!
Concepts 06 Commands (`docs/concepts/06-commands.md`)
Commands
While editing richtext content, your users will be doing things like inserting text, deleting text, splitting paragraphs, adding formatting, etc. Under the cover these edits are expressed using transforms and operations. But at a high level we talk about them as "commands".
Commands are the high-level actions that represent a specific intent of the user. They are represented as helper functions on the Editor interface. A handful of helpers are included in core for common richtext behaviors, but you are encouraged to write your own that model your specific domain.
For example, here are some of the built-in commands:
Editor.insertText(editor, 'A new string of text to be inserted.')
Editor.deleteBackward(editor, { unit: 'word' })
Editor.insertBreak(editor)But you can (and will!) also define your own custom commands that model your domain. For example, you might want to define a formatQuote command, or an insertImage command, or a toggleBold command depending on what types of content you allow.
Commands always describe an action to be taken as if the user was performing the action. For that reason, they never need to define a location to perform the command, because they always act on the user's current selection.
🤖 The concept of commands is loosely based on the DOM's built-in
execCommandAPIs. However Slate defines its own simpler (and extendable!) version of the API, because the DOM's version is too opinionated and inconsistent.
Under the covers, Slate takes care of converting each command into a set of low-level "operations" that are applied to produce a new value. This is what makes collaborative editing implementations possible. But you don't have to worry about that, because it happens automatically.
Custom Commands
When defining custom commands, you can create your own namespace:
const MyEditor = {
...Editor,
insertParagraph(editor) {
// ...
},
}When writing your own commands, you'll often make use of the Transforms helpers that ship with Slate.
Transforms
Transforms are a specific set of helpers that allow you to perform a wide variety of specific changes to the document, for example:
// Set a "bold" format on all of the text nodes in a range.
// Normally you would apply a style like bold using the Editor.addMark() command.
// The addMark() command performs a similar setNodes transform, but it uses a more
// complicated match function in order to apply marks within markableVoid elements.
Transforms.setNodes(
editor,
{ bold: true },
{
at: range,
match: node => Text.isText(node),
split: true,
}
)
// Wrap the lowest block at a point in the document in a quote block.
Transforms.wrapNodes(
editor,
{ type: 'quote', children: [] },
{
at: point,
match: node => Editor.isBlock(editor, node),
mode: 'lowest',
}
)
// Insert new text to replace the text in a node at a specific path.
Transforms.insertText(editor, 'A new string of text.', { at: path })
// ...there are many more transforms!The transform helpers are designed to be composed together. So you might use a handful of them for each command.
Concepts 07 Editor (`docs/concepts/07-editor.md`)
Editor
All of the behaviors, content and state of a Slate editor is rolled up into a single, top-level Editor object. It has an interface of:
interface Editor {
// Current editor state
children: Node[]
selection: Range | null
operations: Operation[]
marks: Omit<Text, 'text'> | null
// Schema-specific node behaviors.
isInline: (element: Element) => boolean
isVoid: (element: Element) => boolean
markableVoid: (element: Element) => boolean
normalizeNode: (entry: NodeEntry) => void
onChange: (options?: { operation?: Operation }) => void
// Overrideable core actions.
addMark: (key: string, value: any) => void
apply: (operation: Operation) => void
deleteBackward: (unit: 'character' | 'word' | 'line' | 'block') => void
deleteForward: (unit: 'character' | 'word' | 'line' | 'block') => void
deleteFragment: () => void
insertBreak: () => void
insertSoftBreak: () => void
insertFragment: (fragment: Node[]) => void
insertNode: (node: Node) => void
insertText: (text: string) => void
removeMark: (key: string) => void
}It is slightly more complex than the others, because it contains all of the top-level functions that define your custom, domain-specific behaviors.
The children property contains the document tree of nodes that make up the editor's content.
The selection property contains the user's current selection, if any.
Don't set it directly; use Transforms.select
The operations property contains all of the operations that have been applied since the last "change" was flushed. (Since Slate batches operations up into ticks of the event loop.)
The marks property stores formatting to be applied when the editor inserts text. If marks is null, the formatting will be taken from the current selection.
Don't set it directly; use Editor.addMark and Editor.removeMark.
Overriding Behaviors
In previous guides we've already hinted at this, but you can override any of the behaviors of an editor by overriding its function properties.
For example, if you want to define link elements that are inline nodes:
const { isInline } = editor
editor.isInline = element => {
return element.type === 'link' ? true : isInline(element)
}Or maybe you want to override the insertText behavior to "linkify" URLs:
const { insertText } = editor
editor.insertText = text => {
if (isUrl(text)) {
// ...
return
}
insertText(text)
}If you have void "mention" elements that can accept marks like bold or italic:
const { isVoid, markableVoid } = editor
editor.isVoid = element => {
return element.type === 'mention' ? true : isVoid(element)
}
editor.markableVoid = element => {
return element.type === 'mention' || markableVoid(element)
}Or you can even define custom "normalizations" that take place to ensure that links obey certain constraints:
const { normalizeNode } = editor
editor.normalizeNode = (entry, options) => {
const [node, path] = entry
if (Element.isElement(node) && node.type === 'link') {
// ...
return
}
normalizeNode(entry, options)
}Whenever you override behaviors, be sure to call the existing functions as a fallback mechanism for the default behavior. Unless you really do want to completely remove the default behaviors (which is rarely a good idea).
🤖 For more info, check out the Editor Instance Methods to Override API Reference
Helper Functions
The Editor interface, like all Slate interfaces, exposes helper functions that are useful when implementing certain behaviors. There are many, many editor-related helpers. For example:
// Get the start point of a specific node at path.
const point = Editor.start(editor, [0, 0])
// Get the fragment (a slice of the document) at a range.
const fragment = Editor.fragment(editor, range)There are also many iterator-based helpers, for example:
// Iterate over every node in a range.
for (const [node, path] of Editor.nodes(editor, { at: range })) {
// ...
}
// Iterate over every point in every text node in the current selection.
for (const point of Editor.positions(editor)) {
// ...
}🤖 For more info, check out the Editor Static Methods API Reference
Insertion at inline and mark edges
A visual caret can name either side of an inline or formatting boundary. Keep typing outside links by overriding inlineEdgeAffinity:
const { inlineEdgeAffinity } = editor
editor.inlineEdgeAffinity = (element, edge) =>
element.type === 'link' ? 'outside' : inlineEdgeAffinity(element, edge)For marks, use leafEdgeAffinity. This example exits code at its end and otherwise prefers the preceding leaf:
editor.leafEdgeAffinity = (before, after) =>
before.code && !after.code ? 'forward' : 'backward'The same receiving leaf determines Editor.marks, keeping toolbar state and typed text in agreement. Explicitly toggled editor.marks still win. Both hooks default to null, preserving existing behavior until you opt in.
For placement based on movement direction, record your application’s last movement and return that direction. This does not add an extra arrow-key stop:
let direction = 'backward'
const { move } = editor
editor.move = (options = {}) => {
direction = options.reverse ? 'forward' : 'backward'
move(options)
}
editor.leafEdgeAffinity = () => directionA forward movement enters the boundary from the preceding leaf, so subsequent insertion uses 'backward'; a reverse movement uses 'forward'. Route your movement commands through editor.move (or update the stored direction in your own keyboard handler).
Editor.insertionPoint(editor, point) lets plugins resolve the same point without changing selection. Core applies it only for implicit insertion at a collapsed caret: typed text, fragments, and inline nodes. Explicit at and expanded selections keep their existing behavior. Native IME composition is unchanged.
Concepts 08 Plugins (`docs/concepts/08-plugins.md`)
Plugins
You've already seen how the behaviors of Slate editors can be overridden. These overrides can also be packaged up into "plugins" to be reused, tested and shared. This is one of the most powerful aspects of Slate's architecture.
A plugin is simply a function that takes an Editor object and returns it after it has augmented it in some way.
For example, a plugin that marks image nodes as "void":
const withImages = editor => {
const { isVoid } = editor
editor.isVoid = element => {
return element.type === 'image' ? true : isVoid(element)
}
return editor
}And then to use the plugin, simply:
import { createEditor } from 'slate'
const editor = withImages(createEditor())This plugin composition model makes Slate extremely easy to extend!
Helper Functions
In addition to the plugin functions, you might want to expose helper functions that are used alongside your plugins. For example:
import { Editor, Element } from 'slate'
const MyEditor = {
...Editor,
insertImage(editor, url) {
const element = { type: 'image', url, children: [{ text: '' }] }
Transforms.insertNodes(editor, element)
},
}
const MyElement = {
...Element,
isImageElement(value) {
return Element.isElement(element) && element.type === 'image'
},
}Then you can use MyEditor and MyElement everywhere and have access to all your helpers in one place.
Concepts 09 Rendering (`docs/concepts/09-rendering.md`)
Rendering
One of the best parts of Slate is that it's built with React, so it fits right into your existing application. It doesn't re-invent its own view layer that you have to learn. It tries to keep everything as React-y as possible.
To that end, Slate gives you control over the rendering behavior of your custom nodes and properties in your richtext domain.
You can define these behaviors by passing "render props" to the top-level <Editable> component.
For example if you wanted to render custom element components, you'd pass in the renderElement prop:
import { createEditor } from 'slate'
import { Slate, Editable, withReact } from 'slate-react'
const MyEditor = () => {
const [editor] = useState(() => withReact(createEditor()))
const renderElement = useCallback(({ attributes, children, element }) => {
switch (element.type) {
case 'quote':
return <blockquote {...attributes}>{children}</blockquote>
case 'link':
return (
<a {...attributes} href={element.url}>
{children}
</a>
)
default:
return <p {...attributes}>{children}</p>
}
}, [])
return (
<Slate editor={editor}>
<Editable renderElement={renderElement} />
</Slate>
)
}🤖 Be sure to mix in
props.attributesand renderprops.childrenin your custom components! The attributes must be added to the top-level DOM element inside the component, as they are required for Slate's DOM helper functions to work. And the children are the "leaves" holding text content and inline elements.
You don't have to use simple HTML elements, you can use your own custom React components too:
const renderElement = useCallback(props => {
switch (props.element.type) {
case 'quote':
return <QuoteElement {...props} />
case 'link':
return <LinkElement {...props} />
default:
return <DefaultElement {...props} />
}
}, [])Leaves
When text-level formatting is rendered, the characters are grouped into "leaves" of text that each contain the same formatting (marks) applied to them.
To customize the rendering of each leaf, you use a custom renderLeaf prop:
const renderLeaf = useCallback(({ attributes, children, leaf }) => {
return (
<span
{...attributes}
style={{
fontWeight: leaf.bold ? 'bold' : 'normal',
fontStyle: leaf.italic ? 'italic' : 'normal',
}}
>
{children}
</span>
)
}, [])Notice though how we've handled it slightly differently than renderElement. Since text formatting tends to be fairly simple, we've opted to ditch the switch statement and just toggle on/off a few styles instead. (But there's nothing preventing you from using custom components if you'd like!)
🤖 As with the Element renderer, be sure to mix in
props.attributesand renderprops.childrenin your leaf renderer! The attributes must be added to the top-level DOM element inside the component, as they are required for Slate's DOM helper functions to work. And the children are the actual text content of your document which Slate manages for you automatically.
When decorations split a single text node, the renderLeaf function will receive an additional leafPosition property. This object contains the start and end offsets of the leaf within the original text node, along with optional isFirst and isLast booleans. This leafPosition property is only added when a text node is actually split by decorations.
One disadvantage of text-level formatting is that you cannot guarantee that any given format is "contiguous"—meaning that it stays as a single leaf. This limitation with respect to leaves is similar to the DOM, where this is invalid:
<em>t<strong>e</em>x</strong>tBecause the elements in the above example do not properly close themselves they are invalid. Instead, you would write the above HTML as follows:
<em>t</em><strong><em>e</em>x</strong>tIf you happened to add another overlapping section of <strike> to that text, you might have to rearrange the closing tags yet again. Rendering leaves in Slate is similar—you can't guarantee that even though a word has one type of formatting applied to it that that leaf will be contiguous, because it depends on how it overlaps with other formatting.
Of course, this leaf stuff sounds pretty complex. But, you do not have to think about it much, as long as you use text-level formatting and element-level formatting for their intended purposes:
- Text properties are for non-contiguous, character-level formatting.
- Element properties are for contiguous, semantic elements in the document.
Texts
While renderLeaf allows you to customize the rendering of individual leaves based on their formatting (marks and decorations), sometimes you need to customize the rendering for an entire text node, regardless of how decorations might split it into multiple leaves.
This is where the renderText prop comes in. It allows you to render a component that wraps all the leaves generated for a single Text node.
const renderText = useCallback(({ attributes, children, text }) => {
return (
<span {...attributes} className="custom-text">
{children}
{/* Render anything you want here */}
</span>
)
}, [])
// In your editor component:
<Editable
renderText={renderText}
renderLeaf={renderLeaf}
/>When to use renderLeaf vs renderText:
renderLeaf: Use this when you need to apply styles or rendering logic based on the specific properties of each individual leaf (e.g., applying bold style ifleaf.boldis true, or highlighting based on a decoration). This function might be called multiple times for a single text node if decorations split it. You can use the optionalleafPositionprop (available when a text node is split) to conditionally render something based on the position of the leaf within the text node.renderText: Use this when you need to render something exactly once for a given text node, regardless of how many leaves it's split into. It's ideal for wrapping the entire text node's content or adding elements associated with the text node as a whole without worrying about duplication caused by decorations.
You can use both renderText and renderLeaf together. renderLeaf renders the individual marks and decorations within a text node (leaves), and renderText renders the container of those leaves.
Decorations
Decorations are another type of text-level formatting. They are similar to regular old custom properties, except each one applies to a Range of the document instead of being associated with a given text node.
However, decorations are computed at render-time based on the content itself. This is helpful for dynamic formatting like syntax highlighting or search keywords, where changes to the content (or some external data) has the potential to change the formatting.
Decorations are different from Marks in that they are not stored on editor state.
Toolbars, Menus, Overlays, and more!
In addition to controlling the rendering of nodes inside Slate, you can also retrieve the current editor context from inside other components using the useSlate hook.
That way other components can execute commands, query the editor state, or anything else.
A common use case for this is rendering a toolbar with formatting buttons that are highlighted based on the current selection:
const MyEditor = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate editor={editor}>
<Toolbar />
<Editable />
</Slate>
)
}
const Toolbar = () => {
const editor = useSlate()
return (
<div>
<Button active={isBoldActive(editor)}>B</Button>
<Button active={isItalicActive(editor)}>I</Button>
</div>
)
}Because the <Toolbar> uses the useSlate hook to retrieve the context, it will re-render whenever the editor changes, so that the active state of the buttons stays in sync.
Editor Styling
Custom styles can be applied to the editor itself by using the style prop on the <Editable> component.
const MyEditor = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate editor={editor}>
<Editable style={{ minHeight: '200px', backgroundColor: 'lime' }} />
</Slate>
)
}It is also possible to apply custom styles with a stylesheet and className. However, Slate uses inline styles to provide some default styles for the editor. Because inline styles take precedence over stylesheets, styles you provide using stylesheets will not override the default styles. If you are trying to use a stylesheet and your rules are not taking effect, do one of the following:
- Provide your styles using the
styleprop instead of a stylesheet, which overrides the default inline styles. - Pass the
disableDefaultStylesprop to the<Editable>component. - Use
!importantin your stylesheet declarations to make them override the inline styles.
Performance
See Improving Performance for ways to improve the rendering performance of the editor.
Concepts 10 Serializing (`docs/concepts/10-serializing.md`)
Serializing
Slate's data model has been built with serialization in mind. Specifically, its text nodes are defined in a way that makes them easier to read at a glance, but also easy to serialize to common formats like HTML and Markdown.
And, because Slate uses plain JSON for its data, you can write serialization logic very easily.
Plaintext
For example, taking the value of an editor and returning plaintext:
import { Node } from 'slate'
const serialize = nodes => {
return nodes.map(n => Node.string(n)).join('\n')
}Here we're taking the children nodes of an Editor as a nodes argument, and returning a plaintext representation where each top-level node is separated by a single \n new line character.
For an input of:
const nodes = [
{
type: 'paragraph',
children: [{ text: 'An opening paragraph...' }],
},
{
type: 'quote',
children: [{ text: 'A wise quote.' }],
},
{
type: 'paragraph',
children: [{ text: 'A closing paragraph!' }],
},
]You'd end up with:
An opening paragraph...
A wise quote.
A closing paragraph!Notice how the quote block isn't distinguishable in any way, that's because we're talking about plaintext. But you can serialize the data to anything you want—it's just JSON after all.
HTML
For example, here's a similar serialize function for HTML:
import escapeHtml from 'escape-html'
import { Text } from 'slate'
const serialize = node => {
if (Text.isText(node)) {
let string = escapeHtml(node.text)
if (node.bold) {
string = `<strong>${string}</strong>`
}
return string
}
const children = node.children.map(n => serialize(n)).join('')
switch (node.type) {
case 'quote':
return `<blockquote><p>${children}</p></blockquote>`
case 'paragraph':
return `<p>${children}</p>`
case 'link':
return `<a href="${escapeHtml(node.url)}">${children}</a>`
default:
return children
}
}This one is a bit more aware than the plaintext serializer above. It's actually recursive so that it can keep iterating deeper through a node's children until it gets to the leaf text nodes. And for each node it receives, it converts it to an HTML string.
It also takes a single node as input instead of an array, so if you passed in an editor like:
const editor = {
children: [
{
type: 'paragraph',
children: [
{ text: 'An opening paragraph with a ' },
{
type: 'link',
url: 'https://example.com',
children: [{ text: 'link' }],
},
{ text: ' in it.' },
],
},
{
type: 'quote',
children: [{ text: 'A wise quote.' }],
},
{
type: 'paragraph',
children: [{ text: 'A closing paragraph!' }],
},
],
// `Editor` objects also have other properties that are omitted here...
}You'd receive back (line breaks added for legibility):
<p>An opening paragraph with a <a href="https://example.com">link</a> in it.</p>
<blockquote><p>A wise quote.</p></blockquote>
<p>A closing paragraph!</p>It's really that easy!
Deserializing
Another common use case in Slate is doing the reverse—deserializing. This is when you have some arbitrary input and want to convert it into a Slate-compatible JSON structure. For example, when someone pastes HTML into your editor and you want to ensure it gets parsed with the proper formatting for your editor.
Slate has a built-in helper for this: the slate-hyperscript package.
The most common way to use slate-hyperscript is for writing JSX documents, for example when writing tests. You might use it like so:
/** @jsx jsx */
import { jsx } from 'slate-hyperscript'
const input = (
<fragment>
<element type="paragraph">A line of text.</element>
</fragment>
)And the JSX feature of your compiler (Babel, TypeScript, etc.) would turn that input variable into:
const input = [
{
type: 'paragraph',
children: [{ text: 'A line of text.' }],
},
]This is great for test cases, or places where you want to be able to write a lot of Slate objects in a very readable form.
However! This doesn't help with deserialization.
But slate-hyperscript isn't only for JSX. It's just a way to build trees of Slate content. Which happens to be exactly what you want to do when you're deserializing something like HTML.
For example, here's a deserialize function for HTML:
import { jsx } from 'slate-hyperscript'
const deserialize = (el, markAttributes = {}) => {
if (el.nodeType === window.Node.TEXT_NODE) {
return jsx('text', markAttributes, el.textContent)
} else if (el.nodeType !== window.Node.ELEMENT_NODE) {
return null
}
const nodeAttributes = { ...markAttributes }
// define attributes for text nodes
switch (el.nodeName) {
case 'STRONG':
nodeAttributes.bold = true
}
const children = Array.from(el.childNodes)
.map(node => deserialize(node, nodeAttributes))
.flat()
if (children.length === 0) {
children.push(jsx('text', nodeAttributes, ''))
}
switch (el.nodeName) {
case 'BODY':
return jsx('fragment', {}, children)
case 'BR':
return '\n'
case 'BLOCKQUOTE':
return jsx('element', { type: 'quote' }, children)
case 'P':
return jsx('element', { type: 'paragraph' }, children)
case 'A':
return jsx(
'element',
{ type: 'link', url: el.getAttribute('href') },
children
)
default:
return children
}
}The node type constants come from the DOM's window.Node, not Slate's Node, which shadows the DOM global wherever it's imported.
It takes in an el HTML element object and returns a Slate fragment. So if you have an HTML string, you can parse and deserialize it like so:
const html = '...'
const document = new DOMParser().parseFromString(html, 'text/html')
deserialize(document.body)With this input:
<p>An opening paragraph with a <a href="https://example.com">link</a> in it.</p>
<blockquote><p>A wise quote.</p></blockquote>
<p>A closing paragraph!</p>You'd end up with this output:
const fragment = [
{
type: 'paragraph',
children: [
{ text: 'An opening paragraph with a ' },
{
type: 'link',
url: 'https://example.com',
children: [{ text: 'link' }],
},
{ text: ' in it.' },
],
},
{
type: 'quote',
children: [
{
type: 'paragraph',
children: [{ text: 'A wise quote.' }],
},
],
},
{
type: 'paragraph',
children: [{ text: 'A closing paragraph!' }],
},
]And just like the serializing function, you can extend it to fit your exact domain model's needs.
Concepts 11 Normalizing (`docs/concepts/11-normalizing.md`)
Normalizing
Slate editors can edit complex, nested data structures. And for the most part this is great. But in certain cases inconsistencies in the data structure can be introduced—most often when allowing a user to paste arbitrary richtext content.
"Normalizing" is how you can ensure that your editor's content is always of a certain shape. It's similar to "validating", except instead of just determining whether the content is valid or invalid, its job is to fix the content to make it valid again.
Built-in Constraints
Slate editors come with a few built-in constraints out of the box. These constraints are there to make working with content much more predictable than standard contenteditable. All of the built-in logic in Slate depends on these constraints, so unfortunately you cannot omit them. They are...
- All
Elementnodes must contain at least oneTextdescendant — even Void Elements. If an element node does not contain any children, an empty text node will be added as its only child. This constraint exists to ensure that the selection's anchor and focus points (which rely on referencing text nodes) can always be placed inside any node. Without this, empty elements (or void elements) wouldn't be selectable. - Two adjacent texts with the same custom properties will be merged. If two adjacent text nodes have the same formatting, they're merged into a single text node with a combined text string of the two. This exists to prevent the text nodes from only ever expanding in count in the document, since both adding and removing formatting results in splitting text nodes.
- Block nodes can only contain other blocks, or inline and text nodes. For example, a
paragraphblock cannot have anotherparagraphblock element and alinkinline element as children at the same time. The type of children allowed is determined by the first child. Any other non-conforming children are tried to be converted (if possible) or removed. This ensures that common richtext behaviors like "splitting a block in two" function consistently. Conversion of block nodes is done by unwrapping the block node; conversion of inline/text nodes is performed by wrapping such nodes into afallbackElementif specified in thenormalizeNodeoptions. ThefallbackElementcan be specified by editors overriding thenormalizeNodefunction. - Inline nodes cannot be the first or last child of a parent block, nor can it be next to another inline node in the children array. If this is the case, an empty text node will be added to correct this to be in compliance with the constraint.
- The top-level editor node can only contain block nodes. If any of the top-level children are inline or text nodes they will be removed. This ensures that there are always block nodes in the editor so that behaviors like "splitting a block in two" work as expected.
- Nodes must be JSON-serializable. For example, avoid using
undefinedin your data model. This ensures that operations are also JSON-serializable, a property which is assumed by collaboration libraries. - Property values must not be
null. Instead, you should use an optional property, e.g.foo?: stringinstead offoo: string | null. This limitation is due tonullbeing used in operations to represent the absence of a property.
These default constraints are all mandated because they make working with Slate documents much more predictable.
🤖 Although these constraints are the best we've come up with now, we're always looking for ways to have Slate's built-in constraints be less constraining if possible—as long as it keeps standard behaviors easy to reason about. If you come up with a way to reduce or remove a built-in constraint with a different approach, we're all ears!
Adding Constraints
The built-in constraints are fairly generic. But you can also add your own constraints on top of the built-in ones that are specific to your domain.
To do this, you extend the normalizeNode function on the editor. The normalizeNode function gets called every time an operation is applied that inserts or updates a node (or its descendants), giving you the opportunity to ensure that the changes didn't leave it in an invalid state, and correcting the node if so.
For example here's a plugin that ensures paragraph blocks only have text or inline elements as children:
import { Transforms, Element, Node } from 'slate'
const withParagraphs = editor => {
const { normalizeNode } = editor
editor.normalizeNode = (entry, options) => {
const [node, path] = entry
// If the element is a paragraph, ensure its children are valid.
if (Element.isElement(node) && node.type === 'paragraph') {
for (const [child, childPath] of Node.children(editor, path)) {
if (Element.isElement(child) && !editor.isInline(child)) {
Transforms.unwrapNodes(editor, { at: childPath })
return
}
}
}
// Fall back to the original `normalizeNode` to enforce other constraints.
normalizeNode(entry, options)
}
return editor
}This example is fairly simple. Whenever normalizeNode gets called on a paragraph element, it loops through each of its children ensuring that none of them are block elements. And if one is a block element, it gets unwrapped, so that the block is removed and its children take its place. The node is "fixed".
But what if the child has nested blocks?
Resetting a Cleared Document
Deleting a selection preserves the surviving block's properties. Slate does not know which element type your application uses for a default block, so deleting every character can leave an empty heading or list.
If deleting the whole document should create a fresh paragraph, override deleteFragment. Check the selection before deleting, and use transforms so undo can restore the original document. This is the policy used by the richtext example:
import { Editor, Element as SlateElement, Range, Transforms } from 'slate'
const withRichText = editor => {
const { deleteFragment } = editor
editor.deleteFragment = direction => {
const { selection } = editor
if (selection && Range.isExpanded(selection)) {
const [start, end] = Range.edges(selection)
if (Editor.isStart(editor, start, []) && Editor.isEnd(editor, end, [])) {
Editor.withoutNormalizing(editor, () => {
Transforms.removeNodes(editor, {
at: [],
match: node => SlateElement.isElement(node),
mode: 'highest',
})
Transforms.insertNodes(
editor,
{ type: 'paragraph', children: [{ text: '' }] },
{ at: [0], select: true }
)
})
return
}
}
deleteFragment(direction)
}
return editor
}This override handles an expanded selection covering the whole document in either direction. Partial deletions use the original method. Inserting text or a fragment over a selection uses separate commands; choose their replacement behavior independently.
Use normalizeNode for structural constraints, such as inserting a default block when the editor has no children. Do not reset every single empty heading in a normalizer: that would also undo a user's deliberate choice to create an empty heading. For example, an empty-root constraint can be added to your plugin as follows:
const { normalizeNode } = editor
editor.normalizeNode = (entry, options) => {
const [node] = entry
if (Editor.isEditor(node) && node.children.length === 0) {
Transforms.insertNodes(
editor,
{ type: 'paragraph', children: [{ text: '' }] },
{ at: [0] }
)
return
}
normalizeNode(entry, options)
}Multi-pass Normalizing
One thing to understand about normalizeNode constraints is that they are multi-pass.
If you check the example above again, you'll notice the return statement:
if (Element.isElement(child) && !editor.isInline(child)) {
Transforms.unwrapNodes(editor, { at: childPath })
return
}You might at first think this is odd, because with the return there, the original normalizeNodes will never be called, and the built-in constraints won't get a chance to run their own normalizations.
But, there's a slight "trick" to normalizing.
When you do call Transforms.unwrapNodes, you're actually changing the content of the node that is currently being normalized. So even though you're ending the current normalization pass, by making a change to the node you're kicking off a new normalization pass. This results in a sort of recursive normalizing.
This multi-pass characteristic makes it much easier to write normalizations, because you only ever have to worry about fixing a single issue at once, and not fixing every possible issue that could be putting a node in an invalid state.
To see how this works in practice, let's start with this invalid document:
<editor>
<paragraph a>
<paragraph b>
<paragraph c>word</paragraph>
</paragraph>
</paragraph>
</editor>The editor starts by running normalizeNode on ``. And it is valid, because it contains only text nodes as children.
But then, it moves up the tree, and runs normalizeNode on . This paragraph is invalid, since it contains a block element \(). So that child block gets unwrapped, resulting in a new document of:
<editor>
<paragraph a>
<paragraph b>word</paragraph>
</paragraph>
</editor>And in performing that fix, the top-level changed. It gets normalized, and it is invalid, so gets unwrapped, resulting in:
<editor>
<paragraph a>word</paragraph>
</editor>And now when normalizeNode runs, no changes are made, so the document is valid!
🤖 For the most part you don't need to think about these internals. You can just know that anytime
normalizeNodeis called and you spot an invalid state, you can fix that single invalid state and trust thatnormalizeNodewill be called again until the node becomes valid.
Empty Children Early Constraint Execution
One special normalization executes before all other normalizations and this can be important to keep in mind when writing your normalizers.
Before any of the other normalizations can execute, Slate iterates through all Element nodes and makes sure they have at least one child. If it does not, an empty Text descendant is created.
This can trip you up when you have custom handling when an Element has no children. For example, if a table element has no rows, you may wish to remove the table; however, this will never happen because a Text node would automatically be created before that normalization could run.
Incorrect Fixes
One pitfall to avoid is creating an infinite normalization loop. This can happen if you check for a specific invalid structure, but then don't actually fix that structure with the change you make to the node. This results in an infinite loop because the node continues to be flagged as invalid, but it is never fixed properly.
For example, consider a normalization that ensured link elements have a valid url property:
// WARNING: this is an example of incorrect behavior!
const withLinks = editor => {
const { normalizeNode } = editor
editor.normalizeNode = (entry, options) => {
const [node, path] = entry
if (
Element.isElement(node) &&
node.type === 'link' &&
typeof node.url !== 'string'
) {
// ERROR: null is not a valid value for a url
Transforms.setNodes(editor, { url: null }, { at: path })
return
}
normalizeNode(entry, options)
}
return editor
}This fix is incorrectly written. It wants to ensure that all link elements have a url property string. But to fix invalid links it sets the url to null, which is still not a string!
In this case you'd either want to unwrap the link, removing it entirely. Or expand your validation to accept an "empty" url == null as well.
Implications for Other Code
Sequences of Transforms may need to be wrapped in Editor.withoutNormalizing if the node tree should not be normalized between Transforms.
This is frequently the case when you unwrapNodes followed by wrapNodes.
For example, you might write a function to change the type of a block as follows:
const LIST_TYPES = ['numbered-list', 'bulleted-list']
function changeBlockType(editor, type) {
Editor.withoutNormalizing(editor, () => {
const isActive = isBlockActive(editor, type)
const isList = LIST_TYPES.includes(type)
Transforms.unwrapNodes(editor, {
match: n =>
LIST_TYPES.includes(
!Editor.isEditor(n) && SlateElement.isElement(n) && n.type
),
split: true,
})
const newProperties = {
type: isActive ? 'paragraph' : isList ? 'list-item' : type,
}
Transforms.setNodes(editor, newProperties)
if (!isActive && isList) {
const block = { type: type, children: [] }
Transforms.wrapNodes(editor, block)
}
})
}Concepts 12 Typescript (`docs/concepts/12-typescript.md`)
Using TypeScript
Slate supports typing of one Slate document model (ie. one set of custom Editor, Element and Text types). If you need to support more than one document model, see the section Multiple Document Models.
Warning: You must define CustomTypes, annotate useState, and annotate the editor's initial state when using TypeScript or Slate will display typing errors.
Migrating from 0.47.x
When migrating from 0.47.x, read the guide below first. Also keep in mind these common migration issues:
- When referring to
node.type, you may see the errorProperty 'type' does not exist on type 'Node'. To fix this, you need to add code likeElement.isElement(node) && node.type === 'paragraph'. This is necessary because aNodecan be anElementorTextandTextdoes not have atypeproperty. - Be careful when you define the CustomType for
Editor. Make sure to define the CustomType forEditorasBaseEditor & .... It should not beEditor & ...
Defining `Editor`, `Element` and `Text` Types
To define a custom Element or Text type, extend the CustomTypes interface in the slate module like this.
// This example is for an Editor with `ReactEditor` and `HistoryEditor`
import { BaseEditor } from 'slate'
import { ReactEditor } from 'slate-react'
import { HistoryEditor } from 'slate-history'
type CustomElement = { type: 'paragraph'; children: CustomText[] }
type CustomText = { text: string; bold?: true }
declare module 'slate' {
interface CustomTypes {
Editor: BaseEditor & ReactEditor & HistoryEditor
Element: CustomElement
Text: CustomText
}
}Annotations in the Editor
Annotate the editor's initial value w/ Descendant[].
import React, { useState } from 'react'
import { createEditor, Descendant } from 'slate'
import { Slate, Editable, withReact } from 'slate-react'
const initialValue: Descendant[] = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable />
</Slate>
)
}Type-Checking Plugin Order
createEditor() returns Editor, the fully extended type from CustomTypes, so a plugin that requires another plugin's fields type-checks even when that plugin wasn't applied. To check the chain against the plugins actually applied, start from BaseEditor:
const editor = withPlugin2(withPlugin1(createEditor<BaseEditor>()))Best Practices for `Element` and `Text` Types
While you can define types directly in the CustomTypes interface, best practice is to define and export each type separately so that you can reference individual types like a ParagraphElement.
Using best practices, the custom types might look something like:
// This example is for an Editor with `ReactEditor` and `HistoryEditor`
import { BaseEditor } from 'slate'
import { ReactEditor } from 'slate-react'
import { HistoryEditor } from 'slate-history'
export type CustomEditor = BaseEditor & ReactEditor & HistoryEditor
export type ParagraphElement = {
type: 'paragraph'
children: CustomText[]
}
export type HeadingElement = {
type: 'heading'
level: number
children: CustomText[]
}
export type CustomElement = ParagraphElement | HeadingElement
export type FormattedText = { text: string; bold?: true }
export type CustomText = FormattedText
declare module 'slate' {
interface CustomTypes {
Editor: CustomEditor
Element: CustomElement
Text: CustomText
}
}In this example, CustomText is equal to FormattedText but in a real editor, there can be more types of text like text in a code block which may not allow formatting for example.
Why Is The Type Definition Unusual
Because it gets asked often, this section explains why Slate's type definition is atypical.
Slate needs to support a feature called type discrimination which is available when using union types (e.g. ParagraphElement | HeadingElement). This allows a user to narrow a type. If presented with code like if (node.type === 'paragraph') { ... } the inside of the block, will narrow the type of node to ParagraphElement.
Slate also needs a way to allow developers to get their custom types into Slate. This is done through declaration merging which is a feature of an interface.
Slate combines a union type and an interface in order to use both features.
For more information see Proposal: Add Custom TypeScript Types to Slate
Multiple Document Models
At the moment, Slate supports types for a single document model at a time. For example, it cannot support two different Rich Text Editor with different document schemas.
Slate's TypeScript support was designed this way because typing for one document schema was better than none. The goal is to eventually support typing for multiple editor definitions and there is currently an in progress PR built by the creator of Slate.
One workaround for supporting multiple document models is to create each editor in a separate package and then import them. This hasn't been tested but should work.
Extending Other Types
Currently there is also support for extending other types but these haven't been tested as thoroughly as the ones documented above:
SelectionRangePoint
Feel free to extend these types but extending these types should be considered experimental. Please report bugs on GitHub issues.
TypeScript Examples
For some examples of how to use types, see packages/slate-react/src/custom-types.ts in the slate repository.
Concepts Xx Migrating (`docs/concepts/xx-migrating.md`)
Migrating
Migrating from earlier versions of Slate to the 0.50.x versions is not a simple task. The entire framework was re-considered from the ground up. This has resulted in a much better set of abstractions, which will result in you writing less code. But the migration process is not simple.
It's highly recommended that after reading this guide you read through the original Walkthroughs and the other Concepts to see how all of the new concepts get applied.
Major Differences
Here's an overview of the major differences in the 0.50.x version of Slate from an architectural point of view.
JSON!
The data model is now comprised of simple JSON objects. Previously, it used Immutable.js data structures. This is a huge change, and one that unlocks many other things. Hopefully it will also increase the average performance when using Slate. It also makes it much easier to get started for newcomers. This will be a large change to migrate from, but it will be worth it.
Interfaces
The data model is interface-based. Previously each model was an instance of a class. Now, not only is the data plain objects, but Slate only expects that the objects implement an interface. So custom properties that used to live in node.data can now live at the top-level of the nodes.
Namespaces
A lot of helper functions are exposed as a collection of helper functions on a namespace. For example, Node.get(root, path) or Range.isCollapsed(range). This ends up making code much clearer because you can always quickly see what interface you're working with.
TypeScript
The codebase now uses TypeScript. Working with pure JSON as a data model, and using an interface-based API are two things that have been made easier by migrating to TypeScript. You don't need to use it yourself, but if you do you'll get a lot more security when using the APIs. (And if you use VS Code you'll get nice autocompletion regardless!)
Fewer Concepts
The number of interfaces and commands has been reduced. Previously Selection, Annotation, and Decoration used to all be separate classes. Now they are simply objects that implement the Range interface. Previously Block and Inline were separate; now they are objects that implement the Element interface. Previously there was a Document and Value, but now the top-level Editor contains the children nodes of the document itself.
The number of commands has been reduced too. Previously we had commands for every type of input, like insertText, insertTextAtRange, insertTextAtPath. These have been merged into a smaller set of more customizable commands, eg. insertText which can take at: Path | Range | Point.
Fewer Packages
In an attempt to decrease the maintenance burden, and because the new abstraction and APIs in Slate's core packages make things much easier, the total number of packages has been reduced. Things like slate-plain-serializer, slate-base64-serializer, etc. have been removed and can be implemented in userland easily if needed. Even the slate-html-deserializer can now be implemented in userland (in ~10 LOC leveraging slate-hyperscript). And internal packages like slate-dev-environment, slate-dev-test-utils, etc. are no longer exposed because they are implementation details.
Commands
A new "command" concept has been introduced. (The old "commands" are now called "transforms".) This new concept expresses the semantic intent of a user editing the document. And they allow for the right abstraction to tap into user behaviors—for example to change what happens when a user presses enter, or backspace, etc. Instead of using keydown events you should likely override command behaviors instead.
Commands are triggered by calling the editor.* core functions. And they travel through a middleware-like stack, but built from composed functions. Any plugin can override the behaviors to augment an editor.
Plugins
Plugins are now plain functions that augment the Editor object they receive and return it again. For example, they can augment the command execution by composing the editor.exec function or listen to operations by composing editor.apply. Previously they relied on a custom middleware stack, and they were just bags of handlers that got merged onto an editor. Now we're using plain old function composition (aka wrapping) instead.
Elements
Block-ness and inline-ness is now a runtime choice. Previously it was baked into the data model with the object: 'block' or object: 'inline' attributes. Now, it checks whether an "element" is inline or not at runtime. For example, you might check to see that element.type === 'link' and treat it as inline.
More React-ish
Rendering and event-handling are no longer a plugin's concern. Previously plugins had full control over the rendering and event-handling logic in the editor. This creates a bad incentive to start putting all rendering logic in plugins, which puts Slate in a position of being a wrapper around all of React, which is very hard to do well. Instead, the new architecture has plugins focused purely on the richtext aspects, and leaves the rendering and event handling aspects to React.
Context
Previously the <Editor> component was doing double duty as a sort of "controller" object and also the contenteditable DOM element. This led to a lot of awkwardness in how other components worked with Slate. In the new version, there is a new <Slate> context provider and a simpler <Editable> contenteditable-like component. By putting the <Slate> provider higher up in your component tree, you can share the editor directly with toolbars, buttons, etc. using the useSlate hook.
Hooks
In addition to the useSlate hook, there are a handful of other hooks. For example the useSelected and useFocused hooks help with knowing when to render selected states (often for void nodes). And since they use React's Context API they will automatically re-render when their state changes.
`beforeinput`
We now use the beforeinput event almost exclusively. Instead of relying on a series of shims and the quirks of React synthetic events, we're now using the standardized beforeinput event as our baseline. It is fully supported in Safari and Chrome, will soon be supported in the new Chromium-based Edge, and is currently being worked on in Firefox. In the meantime there are a few patches to make Firefox work. Internet Explorer is no longer supported in core out of the box.
History-less
The core history logic has now finally been extracted into a standalone plugin. This makes it much easier for people to implement their own custom history behaviors. And it ensures that plugins have enough control to augment the editor in complex ways, because the history requires it.
Mark-less
Marks have been removed from the Slate data model. Now that we have the ability to define custom properties right on the nodes themselves, you can model marks as custom properties of text nodes. For example bold can be modelled simply as a bold: true property.
Annotation-less
Similarly, annotations have been removed from Slate's core. They can be fully implemented now in userland by defining custom operations and rendering annotated ranges using decorations. But most cases should be using custom text node properties or decorations anyways. There were not that many use cases that benefited from annotations.
Reductions
One of the goals was to dramatically simplify a lot of the logic in Slate to make it easier to maintain and iterate on. This was done by refactoring to better base abstractions that can be built on, by leveraging modern DOM APIs, and by migrating to simpler React patterns.
To give you a sense for the change in total lines of code:
slate 8,436 -> 3,958 (47%)
slate-react 3,905 -> 1,954 (50%)
slate-base64-serializer 38 -> 0
slate-dev-benchmark 340 -> 0
slate-dev-environment 102 -> 0
slate-dev-test-utils 44 -> 0
slate-history 0 -> 211
slate-hotkeys 62 -> 0
slate-html-serializer 253 -> 0
slate-hyperscript 447 -> 345
slate-plain-serializer 56 -> 0
slate-prop-types 62 -> 0
slate-react-placeholder 62 -> 0
total 13,807 -> 6,468 (47%)It's quite a big difference! And that doesn't even include the dependencies that were shed in the process too.
General Changelog (`docs/general/changelog.md`)
Changelog
This is a list of changes to Slate with each new release. Until 1.0 is released, breaking changes will be added as minor version bumps, and smaller, patch-level changes won't be noted since the library is moving quickly while in beta.
⚠️ Until https://github.com/atlassian/changesets/issues/264 is solved, each package will maintain its own individual changelog, which you can find here:
`0.61` — March 29, 2021
BREAKING
New CustomTypes for Editor, Element, Text and other implementation specific objects. Improved typing with TypeScript lets you add CustomTypes for the Slate Editor. This change requires you to set up your types at the start. It's a new concept so please read the new TypeScript documentation here: https://docs.slatejs.org/concepts/11-typescript
`0.60` — November 24, 2020
BREAKING
Introduced new customizable TypeScript typings. You can override the built-in types to extend them for your own editor's domain model. However the changes to make this possible likely resulted in some changes to the existing type contracts.
The useEditor hook was renamed to useSlateStatic. This was done to better differentiate between the useSlate hook and to make it clear that the static version will not re-render when changes occur.
`0.59` — September 24, 2020
There were no breaking changes or new additions in this release.
`0.58` — May 5th, 2020
BREAKING
User properties on Elements and Texts now have an unknown type instead of any. Previously, the arbitrary user defined keys on the Text and Element interface had a type of any which effectively removed any potential type checking on those properties. Now these have a type of unknown so that type checking can be done by consumers of the API when they are applying their own custom properties to the Texts and Elements.
`0.57` — December 18, 2019
BREAKING
Overridable commands now live directly on the editor object. Previously the Command concept was implemented as an interface that was passed into the editor.exec function, allowing the "core" commands to be overridden in one place. But this introduced a lot of Redux-like indirection when implementing custom commands that wasn't necessary because they are never overridden. Instead, now the core actions that can be overridden are implemented as individual functions on the editor (eg. editor.insertText) and they can be overridden just like any other function (eg. isVoid).
Previously to override a command you'd do:
const withPlugin = editor => {
const { exec } = editor
editor.exec = command => {
if (command.type === 'insert_text') {
const { text } = command
if (myCustomLogic) {
// ...
return
}
}
exec(command)
}
return editor
}Now, you'd override the specific function directly:
const withPlugin = editor => {
const { insertText } = editor
editor.insertText = text => {
if (myCustomLogic) {
// ...
return
}
insertText(text)
}
return editor
}You shouldn't ever need to call these functions directly! They are there for plugins to tap into, but there are higher level helpers for you to call whenever you actually need to invoke them. Read on…
Transforms now live in a separate namespace of helpers. Previously the document and selection transformation helpers were available directly on the Editor interface as Editor.*. But these helpers are fairly low level, and not something that you'd use in your own codebase all over the place, usually only inside specific custom helpers of your own. To make room for custom userland commands, these helpers have been moved to a new Transforms namespace.
Previously you'd write:
Editor.unwrapNodes(editor, ...)Now you'd write:
Transforms.unwrapNodes(editor, ...)The Command interfaces were removed. As part of those changes, the existing Command, CoreCommand, HistoryCommand, and ReactCommand interfaces were all removed. You no longer need to define these "command objects", because you can just call the functions directly. Plugins can still define their own overridable commands by extending the Editor interface with new functions. The slate-react plugin does this with insertData and the slate-history plugin does this with undo and redo.
NEW
User action helpers now live directly on the Editor.* interface. These are taking the place of the existing Transforms.* helpers that were moved. These helpers are equivalent to user actions, and they always operate on the existing selection. There are some defined by core, but you are likely to define your own custom helpers that are specific to your domain as well.
For example, here are some of the built-in actions:
Editor.insertText(editor, 'a string of text')
Editor.deleteForward(editor)
Editor.deleteBackward(editor, { unit: 'word' })
Editor.addMark(editor, 'bold', true)
Editor.insertBreak(editor)
...Every one of the old "core commands" has an equivalent Editor.* helper exposed now. However, you can easily define your own custom helpers and place them in a namespace as well:
const MyEditor = {
...Editor,
insertParagraph(editor) { ... },
toggleBoldMark(editor) { ... },
formatLink(editor, url) { ... },
...
}Whatever makes sense for your specific use case!
`0.56` — December 17, 2019
BREAKING
The format_text command is split into add_mark and remove_mark. Although the goal is to keep the number of commands in core to a minimum, having this as a combined command made it very hard to write logic that wanted to guarantee to only ever add or remove a mark from a text node. Now you can be guaranteed that the add_mark command will only ever add custom properties to text nodes, and the remove_mark command will only ever remove them.
Previously you would write:
editor.exec({
type: 'format_text',
properties: { bold: true },
})Now you would write:
if (isActive) {
editor.exec({ type: 'remove_mark', key: 'bold' })
} else {
editor.exec({ type: 'add_mark', key: 'bold', value: true })
}🤖 Note that the "mark" term does not mean what it meant in
0.47and earlier. It simply means formatting that is applied at the text level—bold, italic, etc. We need a term for it because it's such a common pattern in richtext editors, and "mark" is often the term that is used. For example the<mark>tag in HTML.
The Node.text helper was renamed to Node.string. This was simply to reduce the confusion between "the text string" and "text nodes". The helper still just returns the concatenated string content of a node.
`0.55` — December 15, 2019
BREAKING
The match option must now be a function. Previously there were a few shorthands, like passing in a plain object. This behavior was removed because it made it harder to reason about exactly what was being matched, it made debugging harder, and it made it hard to type well. Now the match option must be a function that receives the Node object to match. If you're using TypeScript, and the function you pass in is a type guard, that will be taken into account in the return value!
Previously you might write:
Editor.nodes(editor, {
at: range,
match: 'text',
})
Editor.nodes(editor, {
at: range,
match: { type: 'paragraph' },
})Now you'd write:
Editor.nodes(editor, {
at: range,
match: Text.isText,
})
Editor.nodes(editor, {
at: range,
match: node => node.type === 'paragraph',
})The mode option now defaults to 'lowest'. Previously the default varied depending on where in the codebase it was used. Now it defaults to 'lowest' everywhere, and you can always pass in 'highest' to change the behavior. The one exception is the Editor.nodes helper which defaults to 'all' since that's the expected behavior most of the time.
The Editor.match helper was renamed to Editor.above. This was just to make it clear how it searched in the tree—it looks through all of the nodes directly above a location in the document.
The Editor.above/previous/next helpers now take all options in a dictionary. Previously their APIs did not exactly match the Editor.nodes helper which they are shorthand for, but now this is no longer the case. The at, match and mode options are all passed in the options argument.
Previously you would use:
Editor.previous(editor, path, n => Text.isText(n), {
mode: 'lowest',
})Now you'd use:
Editor.previous(editor, {
at: path,
match: n => Text.isText(n),
mode: 'lowest',
...
})The Editor.elements and Editor.texts helpers were removed. These were simple convenience helpers that were rarely used. You can now achieve the same thing by using the Editor.nodes helper directly along with the match option. For example:
Editor.nodes(editor, {
at: range,
match: Element.isElement,
})`0.54` — December 12, 2019
BREAKING
The <Slate> onChange handler no longer receives the selection argument. Previously it received (value, selection), now it receives simply (value). Instead, you can access any property of the editor directly (including the value as editor.children). The value/onChange convention is provided purely for form-related use cases that expect it. This is along with the change to how extra props are "controlled". By default they are uncontrolled, but you can pass in any of the other top-level editor properties to take control of them.
The Command and CoreCommand interfaces have been split apart. Previously you could access Command.isCoreCommand, however now this helper lives directly on the core command interface as CoreCommand.isCoreCommand. This makes it more symmetrical with userland commands.
Command checkers have been simplified. Previously Slate exposed command-checking helpers like Command.isInsertTextCommand. However these were verbose and not useful most of the time. Instead, you can now check for CoreCommand.isCoreCommand and then use the command.type property to narrow further. This keeps core more symmetrical with how userland will implement custom commands.
NEW
The <Slate> component is now pseudo-controlled. It requires a value= prop to be passed in which is controlled. However, the selection, marks, history, or any other props are not required to be controlled. They default to being uncontrolled. If your use case requires controlling these extra props you can pass them in and they will start being controlled again. This change was made to make using Slate easier, while still allowing for more complex state to be controlled by core or plugins going forward—state that users don't need to concern themselves with most of time.
The Editor now has a marks property. This property represents text-level formatting that will be applied to the next character that is inserted. This is a common richtext editor behavior, where pressing a Bold button with a collapsed selection turns on "bold" formatting mode, and then typing a character becomes bold. This state isn't stored in the document, and is instead stored as an extra property on the editor itself.
`0.53` — December 10, 2019
BREAKING
The slate-schema package has been removed! This decision was made because with the new helpers on the Editor.* interface, and with the changes to normalizeNode in the latest version of Slate, adding constraints using normalizeNode actually leads to more maintainable code than using slate-schema. Previously it was required to keep things from getting too unreadable, but that always came at a large cost of indirection and learning additional APIs. Everything you could do with slate-schema you can do with normalizeNode, and more.
Node matching functions now receive just a Node. Previously they received a NodeEntry tuple, which consisted of [node, path]. However now they receive only a node argument, which makes it easier to write one-off node-checking helpers and pass them in directly as arguments. If you need to ensure a path, lookup the node first.
A few unnecessary helpers were removed. There were a handful of leftovers helpers that were not used anywhere in Slate's core logic, and were very unlikely to be used in userland, so they've been removed to reduce bundle size. You are always free to re-implement them if you truly need them. The list of helpers removed is:
Editor.ancestorNode.closestNode.furthestRange.existsRange.isRangeListRange.isRangeMap
`0.52` — December 5, 2019
BREAKING
The slate-schema package now exports a factory. Previously you imported the withSchema function directly from the package, and passed in your schema rules when you called it. However, now you import the defineSchema factory instead which takes your schema rules and returns a custom withSchema plugin function. This way you can still use helpers like compose with the plugin, while pre-defining your custom rules.
The properties validation in the schema is now exhaustive. Previously a properties validation would check any properties you defined, and leave any unknown ones as is. This made it hard to be certain about which properties would end up on a node. Now any non-defined properties are considered invalid. And using an empty {} validation would ensure that there are no custom properties at all.
NEW
The leaves schema validation ensures text-level formatting. You can use it from any higher up element node in the tree, to guarantee that it only contains certain types of text-level formatting on its inner text nodes. For example you could use it to ensure that a code block doesn't allow any of its text to be bolded or italicized.
`0.51` — December 5, 2019
BREAKING
The Mark interface has been removed! Previously text-level formatting was stored in an array of unique marks. Now that same formatting is stored directly on the Text nodes themselves. For example instead of:
{
text: 'A line of text.',
marks: [{ type: 'bold' }],
}You now have:
{
text: 'A line of text.',
bold: true,
}And the marks are added and removed from the text nodes using the same Editor.setNodes transform that you use for toggling formatting on block and inline nodes. This greatly simplifies things and makes Slate's core even smaller.
The <Slate> component is now a "controlled" component. This makes things a bit more React-ish, and makes it easier to update the editor's value when new data is received after the initial render. To arrive at the previous "uncontrolled" behavior you'll need to implement it in userland using React's built-in hooks.
Whereas previously you would do:
<Slate defaultValue={initialValue}>...</Slate>Now you must manage the value and selection yourself, like:
const [value, setValue] = useState(initialValue)
const [selection, setSelection] = useState(null)
<Slate
initialValue={initialValue}
selection={selection}
onChange={(value, selection) => {
setValue(value)
setSelection(selection)
}}
>
...
</Slate>`0.50` — November 27, 2019
BREAKING
A complete overhaul. The Slate codebase has had a complete overhaul and many pieces of its core architecture have been reconsidered from the ground up. There are lots of changes. We recommend re-reading the Walkthroughs and Concepts documentation and the Examples to get a sense for everything that has changed. As well as the Migration writeup for what the major changes are.
⚠ Warning: Changes past this point refer to the older Slate architecture, based on Immutable.js and without TypeScript. Many things are different in the older architecture and may not apply to the newer one.
`0.47` — May 8, 2019
NEW
Introducing the Annotation model. This is very similar to what used to be stored in value.decorations, except they also contain a unique "key" to be identified by. They can be used for things like comments, suggestions, collaborative cursors, etc.
{
object: 'annotation',
key: String,
type: String,
data: Map,
anchor: Point,
focus: Point,
}There are three new *_annotation operations. The set of operations now includes add_annotation, remove_annotation and set_annotation. They are similar to the existing *_mark operations.
Introducing "iterable" model methods. This introduces several iteratable-producing methods on the Element interface, which Document, Block and Inline all implement. There are iterables for traversing the entire tree:
element.blocks(options)
element.descendants(options)
element.inlines(options)
element.texts(options)
element.ancestors(path, options)
element.siblings(path, options)You can use them just like the native JavaScript iterables. For example, you can loop through the text nodes after a specific node:
for (const next of document.texts({ path: start.path })) {
const [node, path] = next
// do something with the text node or its path
}Or you can traverse all of the "leaf" blocks:
for (const [block] of document.blocks({ onlyLeaves: true })) {
// ...
}And because these iterations use native for/of loops, you can easily break or return out of the loops directly—a much nicer DX than remembering to return false.
BREAKING
The value.decorations property is now value.annotations. Following with the split of decorations into annotations, this property was also renamed. They must now contain unique key properties, as they are stored as a Map instead of a List. This allows for much more performant updates.
The Decoration model no longer has a nested mark property. Previously a real Mark object was used as a property on decorations, but now the type and data properties are first class properties instead.
{
object: 'decoration',
type: String,
data: Map,
anchor: Point,
focus: Point,
}`0.46` — May 1, 2019
BREAKING
Mark operations no longer have offset or length properties. Since text nodes now contain a unique set of marks, it wouldn't make sense for a single mark-related operation to result in a splitting of nodes. Instead, when a mark is added to only part of a text node, it will result in a split_node operation as well as an add_mark operation.
Text operations no longer have a marks property. Previously it was used to add text with a specific set of marks. However this is no longer necessary, and when text is added with marks it will result in an insert_text operation as well as an add_mark operation.
Using Text.create or Text.createList with a leaves property will error. Now that text nodes no longer have leaves, you will need to pass in the text string and marks directly when creating a new text node. (However, you can still create entire values using Value.create in a backwards compatible way for convenience while migrating.)
// This works, although deprecated, which is the common case...
Value.create(oldValueJson)
// ...but this will error!
Text.create(oldTextJson)Value.toJSON returns the new data model format, without leaves. Although Value.fromJSON and Value.create allow the old format in deprecated mode, calling Value.toJSON will return the new data format. If you still need the old one you'll need to iterate the document tree converting text nodes yourself.
The low-level Value.* and Node.* mutation methods have changed. These changes follow the operation signature changes, since the methods take the same arguments as the operations themselves. For example:
// Previously...
value.addMark(path, offset, length, mark)
// ...is now:
value.addMark(path, mark)These are low-level methods, so this change shouldn't affect the majority of use cases.
DEPRECATED
Initializing editors with Text nodes with a leaves property is deprecated. In this new version of Slate, creating a new value with Value.create with the old leaf data model is still allowed for convenience in migration, but it will be removed in a coming version. (However, using the low-level Text.create will throw an error!)
// This works, although deprecated, which is the common case...
Value.create(oldValueJson)
// ...but this will error!
Text.create(oldTextJson)`0.45` — April 2, 2019
BREAKING
A few properties of Operation objects have changed. In an effort to standardize and streamline operations, their properties have changed. This won't affect 90% of use cases, since operations are usually low-level concerns. However, if you are using operational transform or some other low-level parts of Slate, this may affect you. The value, selection, node, and mark properties—which contained references to Immutable.js objects—have all been removed. In their place, we have standardized a properties and newProperties pair. This will greatly reduce the size of operations stored in memory, and makes dealing with them easier when serialized as well.
`0.44` — November 8, 2018
NEW
Introducing the child_min_invalid and child_max_invalid schema errors. These new schema errors map directly to the mix and max schema rule definitions, and make it easier to determine exactly what your normalization logic needs to do to fix the document.
Added new node retrieval methods. There are three new methdos for node retrieval. The first is getNodesAtRange which will retrieve all of the nodes in the tree in a given range. And the second two are getRootBlocksAtRange and getRootInlinesAtRange for retrieving the top-most blocks or inlines in a given range. These should be helpful in defining your own command logic.
BREAKING
Schema errors for min and max rules have changed. Previously they would result in errors of child_required, child_object_invalid, child_type_invalid and child_unknown. Now that we have the new child_min_invalid and child_max_invalid errors, these schema rules will return them instead, making it much easier to determine exactly which rule is causing a schema error.
DEPRECATED
The getBlocksAtRange and getInlinesAtRange methods have been renamed. To clear up confusion about which blocks and inlines are retrieve in the case of nesting, these two methods have been renamed to getLeafBlocksAtRange and getLeafInlinesAtRange to clarify that they retrieve the bottom-most nodes. And now there are two additional methods called getRootBlocksAtRange and getRootInlinesAtRange for cases where you want the top-most nodes instead.
`0.43` — October 27, 2018
NEW
The editor.command and editor.query methods can take functions. Previously they only accepted a type string and would look up the command or query by type. Now, they also accept a custom function. This is helpful for plugin authors, who want to accept a "command option", since it gives users more flexibility to write one-off commands or queries. For example a plugin could be passed either:
Hotkey({
hotkey: 'cmd+b',
command: 'addBoldMark',
})Or a custom command function:
Hotkey({
hotkey: 'cmd+b',
command: editor => editor.addBoldMark().moveToEnd(),
})BREAKING
The Change object has been removed. The Change object as we know it previously has been removed, and all of its behaviors have been folded into the Editor controller. This includes the top-level commands and queries methods, as well as methods like applyOperation and normalize. All places that used to receive change now receive editor, which is API equivalent.
Changes are now flushed to onChange asynchronously. Previously this was done synchronously, which resulted in some strange race conditions in React environments. Now they will always be flushed asynchronously, just like setState.
The normalize* and validate* middleware signatures have changed! Previously the normalize* and validate* middleware was passed (node, next). However now, for consistency with the other middleware they are all passed (node, editor, next). This way, all middleware always receive editor and next as their final two arguments.
The editor.event method has been removed. Previously this is what you'd use when writing tests to simulate events being fired—which were slightly different to other running other middleware. With the simplification to the editor and to the newly-consistent middleware signatures, you can now use editor.run directly to simulate events:
editor.run('onKeyDown', { key: 'Tab', ... })DEPRECATED
The editor.change method is deprecated. With the removal of the Change object, there's no need anymore to create the small closures with editor.change(). Instead you can directly invoke commands on the editor in series, and all of the changes will be emitted asynchronously on the next tick.
editor.insertText('word').moveFocusForward(10).addMark('bold')The applyOperations method is deprecated. Instead you can loop a set of operations and apply each one using applyOperation. This is to reduce the number of methods exposed on the Editor to keep it simpler.
The change.call method is deprecated. Previously this was used to call a one-off function as a change method. Now this behavior is equivalent to calling editor.command(fn) instead.
`0.42` — October 9, 2018
NEW
Introducing the Editor controller. Previously there was a vague editor concept, that was the React component itself. This was helpful, but because it was tightly coupled to React and the browser, it didn't lend itself to non-browser use cases well. This meant that the line between "model" and "controller/view" was blurred, and some concepts lived in both places at once, in inconsistent ways.
A new Editor controller now makes this relationship clear. It borrows many of its behaviors from the React <Editor> component. And the component actually just instantiates its own plain JavaScript Editor under the covers to delegate the work to.
This new concept powers a lot of the thinking in this new version, unlocking a lot of changes that bring a clearer separation of responsibilities to Slate. It allows us to create editors in any environment, which makes server-side use cases easier, brings parity to testing, and even opens us up to supporting other view layers like React Native or Vue.js in the future.
It has a familiar API, based on the existing editor concept:
const editor = new Editor({ plugins, value, onChange })
editor.change(change => {
...
})However it also introduces imperative methods to make testing easier:
editor.run('renderNode', props)
editor.event('onKeyDown', event)
editor.command('addMark', 'bold')
editor.query('isVoid', node)I'm very excited about it, so I hope you like it!
Introducing the "commands" concept. Previously, "change methods" were treated in a first-class way, but plugins had no easy way to add their own change methods that were reusable elsewhere. And they had no way to override the built-in logic for certain commands, for example splitBlock or insertText. However, now this is all customizable by plugins, with the core Slate plugin providing all of the previous default commands.
const plugin = {
commands: {
wrapQuote(change) {
change.wrapBlock('quote')
},
},
}Those commands are then available directly on the change objects, which are now editor-specific:
change.wrapQuote()This allows you to define all of your commands in a single, easily-testable place. And then "behavioral" plugins can simply take command names as options, so that you have full control over the logic they trigger.
Introducing the "queries" concept. Similarly to the commands, queries allow plugins to define specific behaviors that the editor can be queried for in a reusable way, to be used when rendering buttons, or deciding on command behaviors, etc.
For example, you might define an getActiveList query:
const plugin = {
queries: {
getActiveList(editor) {},
},
}And then be able to re-use that logic easily in different places in your codebase, or pass in the query name to a plugin that can use your custom logic itself:
const list = change.getActiveList()
if (list) {
...
} else {
...
}Taken together, commands and queries offer a better way for plugins to manage their inter-dependencies. They can take in command or query names as options to change their behaviors, or they can export new commands and queries that you can reuse in your codebase.
The middleware stack is now deferrable. With the introduction of the Editor controller, the middleware stack in Slate has also been upgraded. Each middleware now receives a next function (similar to Express or Koa) that allows you to choose whether to iterating the stack or not.
// Previously, you'd return `undefined` to continue.
function onKeyDown(event, editor, next) {
if (event.key !== 'Enter') return
...
}
// Now, you call `next()` to continue...
function onKeyDown(event, editor, next) {
if (event.key !== 'Enter') return next()
...
}While that may seem inconvenient, it opens up an entire new behavior, which is deferring to the plugins later in the stack to see if they "handle" a specific case, and if not, handling it yourself:
function onKeyDown(event, editor, next) {
if (event.key === 'Enter') {
const handled = next()
if (handled) return handled
// Otherwise, handle `Enter` yourself...
}
}This is how all of the core logic in slate-react is now implemented, eliminating the need for a "before" and an "after" plugin that duplicate logic.
Under the covers, the schema, commands and queries concept are all implemented as plugins that attach varying middleware as well. For example, commands are processed using the onCommand middleware under the covers:
const plugin = {
onCommand(command, editor, next) {
...
}
}This allows you to actually listen in to all commands, and override individual behaviors if you choose to do so, without having to override the command itself. This is a very advanced feature, which most people won't need, but it shows the flexibility provided by migrating all of the previously custom internal logic to be based on the new middleware stack.
Plugins can now be defined in nested arrays. This is a small addition, but it means that you no longer need to differentiate between individual plugins and multiple plugins in an array. This allows plugins to be more easily composed up from multiple other plugins themselves, without the end user having to change how they use them. Small, but encourages reuse just a little bit more.
DEPRECATED
The slate-simulator is deprecated. Previously this was used as a pseudo-controller for testing purposes. However, now with the new Editor controller as a first-class concept, everything the simulator could do can now be done directly in the library. This should make testing in non-browser environments much easier to do.
BREAKING
The Value object is no longer tied to changes. Previously, you could create a new Change by calling value.change() and retrieve a new value. With the re-architecture to properly decouple the schema, commands, queries and plugins from the core Slate data models, this is no longer possible. Instead, changes are always created via an Editor instance, where those concepts live.
// Instead of...
const { value } = this.state
const change = value.change()
...
this.onChange(change)
// You now would do...
this.editor.change(change => {
const { value } = change
...
})Sometimes this means you will need to store the React ref of the editor to be able to access its editor.change method in your React components.
Remove the Stack "model", in favor of the new Editor. Previously there was a pseudo-model called the Stack that was very low level, and not really a model. This concept has now been rolled into the new Editor controller, which can be used in any environment because it's just plain JavaScript. There was almost no need to directly use a Stack instance previously, so this change shouldn't affect almost anyone.
Remove the Schema "model", in favor of the new Editor. Previously there was another pseudo-model called the Schema, that was used to contain validation logic. All of the same validation features are still available, but the old Schema model is now rolled into the Editor controller as well, in the form of an internal SchemaPlugin that isn't exposed.
Remove the schema.isVoid and schema.isAtomic in favor of queries. Previously these two methods were used to query the schema about the behavior of a specific node or decoration. Now these same queries as possible using the "queries" concept, and are available directly on the change object:
if (change.isVoid(node)) {
...
}The middleware stack must now be explicitly continued, using next. Previously returning undefined from a middleware would (usually) continue the stack onto the next middleware. Now, with middleware taking a next function argument you must explicitly decide to continue the stack by call next() yourself.
Remove the History model, in favor of commands. Previously there was a History model that stored the undo/redo stacks, and managing saving new operations to those stacks. All of this logic has been folded into the new "commands" concept, and the undo/redo stacks now live in value.data. This has the benefit of allowing the history behavior to be completely overridable by userland plugins, which was not an easy feat to manage before.
Values can no longer be normalized on creation. With the decoupling of the data model and the plugin layer, the schema rules are no longer available inside the Value model. This means that you can no longer receive a "normalized" value without having access to the Editor and its plugins.
// While previously you could attach a `schema` to a value...
const normalized = Value.create({ ..., schema })
// Now you'd need to do that with the `editor`...
const value = Value.create({ ... })
const editor = new Editor({ value, plugins: [{ schema }] })
const normalized = editor.valueWhile this seems inconvenient, it makes the boundaries in the API much more clear, and keeps the immutable and mutable concepts separated. This specific code sample gets longer, but the complexities elsewhere in the library are removed.
The Change class is no longer exported. Changes are now editor-specific, so exporting the Change class no longer makes sense. Instead, you can use the editor.change() API to receive a new change object with the commands and queries specific to your editor's plugins.
The getClosestVoid, getDecorations and hasVoidParent method now take an editor. Previously these Node methods took a schema argument, but this has been replaced with the new editor controller instead now that the Schema model has been removed.
`0.41` — September 21, 2018
DEPRECATED
The withoutNormalization helper has been renamed to withoutNormalizing. This is to stay consistent with the new helpers for withoutSaving and withoutMerging.
BREAKING
The the "operation flags" concept was removed. This was a confusing concept that was implemented in multiple different ways and led to the logic around normalizing, saving, and merging operations being more complex than it needed to be. These flags have been replaced with three simpler helper functions: withoutNormalizing, withoutSaving and withoutMerging.
change.withoutNormalizing(() => {
nodes.forEach(node => change.removeNodeByKey(node.key))
})change.withoutSaving(() => {
change.setValue({ decorations })
})This means that you no longer use the { normalize: false } or { save: false } options as arguments to individual change methods, and instead use these new helper methods to apply these behaviors to groups of changes at once.
The "normalize" change methods have been removed. Previously there were a handful of different normalization change methods like normalizeNodeByPath, normalizeParentByKey, etc. These were confusing because it put the onus on the implemented to know exact which nodes needed to be normalized. They have been removed, and implementers no longer ever need to worry about which specific nodes to normalize, as Slate will handle that for them.
The internal refindNode and refindPath methods were removed. These should never have been exposed in the first place, and are now no longer present on the Element interface. These were only used internally during the normalization process.
`0.40` — August 22, 2018
BREAKING
Remove all previously deprecated code paths. This helps to reduce some of the complexity in Slate by not having to handle these code paths anymore. And it helps to reduce file size. When upgrading, it's highly recommended that you upgrade to the previous version first and ensure there are no deprecation warnings being logged, then upgrade to this version.
`0.39` — August 22, 2018
NEW
Introducing the Range model and interface. Previously the "range" concept was used in multiple different places, for the selection, for decorations, and for acting on ranges of the document. This worked okay, but it was hiding the underlying system which is that Range is really an interface that other models can choose to implement. Now, we still use the Range model for referencing parts of the document, but it can also be implemented by other models that need to attach more semantic meaning...
Introducing the Decoration and Selection models. These two new models both implement the new Range interface. Where previously they had to mis-use the Range model itself with added semantics. This just cleans up some of the confusion around overlapping properties, and allows us to add even more domain-specific methods and properties in the future without trouble.
BREAKING
Decorations have changed! Previously, decorations piggybacked on the Range model, using the existing marks property, and introducing their own isAtomic property. However, they have now been split out into their own Decoration model with a single mark and with the isAtomic property controlled by the schema. What previously would have looked like:
Range.create({
anchor: { ... },
focus: { ... },
marks: [{ type: 'highlight' }],
isAtomic: true,
})Is now:
Decoration.create({
anchor: { ... },
focus: { ... },
mark: { type: 'highlight' },
})Each decoration maps to a single mark object. And the atomicity of the mark controlled in the schema instead, for example:
const schema = {
marks: {
highlight: {
isAtomic: true,
},
},
}The Range model has reduced semantics. Previously, since all decorations and selections were ranges, you could create ranges with an isFocused, isAtomic or marks properties. Now Range objects are much simpler, offering only an anchor and a focus, and can be extended by other models implementing the range interface. However, this means that using Range.create or document.createRange might not be what you want anymore. For example, for creating a new selection, you used to use:
const selection = document.createRange({
isFocused: true,
anchor: { ... },
focus: { ... },
})But now, you'll need to use document.createSelection instead:
const selection = document.createSelection({
isFocused: true,
anchor: { ... },
focus: { ... },
})The value.decorations property is no longer nullable. Previously when no decorations were applied to the value, the decorations property would be set to null. Now it will be an empty List object, so that the interface is more consistent.
DEPRECATED
The Node.createChildren static method is deprecated. This was just an alias for Node.createList and wasn't necessary. You can use Node.createList going forward for the same effect.
The renderPortal property of plugins is deprecated. This allows slate-react to be slightly slimmer, since this behavior can be handled in React 16 with the new <React.Fragment> using the renderEditor property instead, in a way that offers more control over the portal behavior.
The data property of plugins is deprecated. This property wasn't well designed and circumvented the core tenet that all changes to the value object will flow through operations inside Change objects. It was mostly used for view-layer state which should be handled with React-specific conventions for state management instead.
`0.38` — August 21, 2018
DEPRECATED
Node.isVoid access is deprecated. Previously the "voidness" of a node was hardcoded in the data model. Soon it will be determined at runtime based on your editor's schema. This deprecation just ensures that you aren't using the node.isVoid property which will not work in future verisons. What previously would have been:
if (node.isVoid) {
...
}Now becomes:
if (schema.isVoid(node)) {
...
}This requires you to have a reference to the schema object, which can be access as value.schema.
Value.isFocused/isBlurred and Value.hasUndos/hasRedos are deprecated. These properties are easily available via value.selection and value.history instead, and are now deprecated to reduce the complexity and number of different ways of doing things.
`0.37` — August 3, 2018
NEW
Introducing the Point model. Ranges are now built up of two Point models—an anchor and a focus—instead of having the properties set directly on the range itself. This makes the "point" concept first-class in Slate and better API's can be built around point objects.
Point.create({
key: 'a',
path: [0, 0],
offset: 31,
})These points are exposed on Range objects via the anchor, focus, start and end properties:
const { anchor, focus } = range
change.removeNodeByKey(anchor.key)These replace the earlier anchorKey, anchorOffset, etc. properties.
Document.createRange creates a relative range. Previously you'd have to use Range.create and make sure that you passed valid arguments, and ensure that you "normalized" the range to sync its keys and paths. This is no longer the case, since the createRange method will do it for you.
const range = document.createRange({
anchor: {
key: 'a',
offset: 1,
},
focus: {
key: 'a',
offset: 4,
},
})This will automatically ensure that the range references leaf text nodes, and that its anchor and focus paths are set.
Document.createPoint creates a relative point. Just like the createRange method, createPoint will create a point that is guaranteed to be relative to the document itself. This is often a lot easier than using Point.create directly.
const anchor = document.createPoint({
key: 'a',
offset: 1,
})BREAKING
The Range.focus method was removed. (Not Change.focus!) This was necessary to make way for the new range.focus point property. Usually this would have been done in a migration-friendly way like the rest of the method changes in this release, but this was an exception. However the change.focus() method is still available and works as expected.
Range.set and Range.merge are dangerous. If you were previously using the super low-level Immutable.js methods range.set or range.merge with any of the now-removed properties of ranges, these invocations will fail. Instead, you should use the range.set* helpers going forward which can be migrated with deprecations warnings instead of failing outright.
The offset property of points defaults to null. Previously it would default to 0 but that could be confusing because it made no distinction from a "set" or "unset" offset. Now they default to null instead. This shouldn't really affect any real-world usage of Slate.
The Range.toJSON() structure has changed. With the introduction of points, the range now returns its anchor and focus properties as nested point JSON objects instead of directly as properties. For example:
{
"object": "range",
"anchor": {
"object": "point",
"key": "a",
"offset": 1,
"path": [0, 0]
},
"focus": {
"object": "point",
"key": "a",
"offset": 3,
"path": [0, 0]
},
"isAtomic": false,
"isFocused": false,
"marks": []
}DEPRECATED
The selection-based shorts on Value were deprecated. Previously you could access things like anchorKey, startOffset and isCollapsed directly on Value objects. This results in extra duplication that is hard to maintain over time, and hard for newcomers to understand, without much benefit. All of these properties are deprecated and should be accessed on the value.selection object directly instead.
The Range methods were standardized, with many deprecated. The methods on Range objects had grown drastically in size. Many of them weren't consistently named, or overlapped in unnecessary ways. With the introduction of Point objects a lot of these methods could be cleaned up and their logic delegated to the points directly. All of these methods remain available but will raise deprecation warnings, making it easier to upgrade.
There's a very good chance you're only using a handful of them in your codebase. Either way, all of them will log warnings. For an example of migrating see this commit.
Here's a full list of the newly deprecated methods and properties, and their new alternative if one exists:
/* Detailed source-code truncated for AI context efficiency. */The selection-based changes were standardized, with many deprecated. Similarly to the Range method deprecations, the same confusion and poor naming choices existed in the Change methods that dealt with selections. Many of them have been renamed for consistency, or deprecated when alternatives existed. All of these methods remain available but will raise deprecation warnings, making it easier to upgrade.
There's a very good chance you're only using a handful of these change methods in your codebase. Either way, all of them will log warnings. For an example of migrating see this commit.
Here's a full list of the newly deprecated changed methods, and their new alternative if one exists:
/* Detailed source-code truncated for AI context efficiency. */`0.36` — July 27, 2018
BREAKING
Schema rules have changed! To make them able to be used in more cases (so you don't have to dip down to the slower validateNode/normalizeNode function), the matching syntax for schema rules has changed. Previously multiples types/objects would be expressed as:
{
parent: { types: ['ordered_list', 'unordered_list'] },
}Now there is a new match object concept, which looks like:
{
parent: { object: 'block', type: 'list' },
}Match objects can be objects, or an array of objects which acts as OR:
{
parent: [{ type: 'ordered_list' }, { type: 'unordered_list' }],
}Additionally, schema rules can now be defined using a schema.rules array of objects with top-level match properties. This allows for matching nodes in ways that were previously impossible. For example:
{
schema: {
rules: [{
// Match all blocks, regardless of type!
match: { object: 'block' },
text: /.../g,
normalize: () => { ... },
}]
}
}All of the shorthands like schema.blocks and schema.inlines are still available, and are simply rewritten to the more flexible rules syntax under the covers. These changes are just a small way of making Slate more flexible for advanced use cases when you run into them.
Schema rule normalize functions now receive SlateError objects. Previously they would be called with a signature of (change, violation, context). They are now called with (change, error). This new error is a SlateError object with an error.code and all of the same context properties.
A normalizer that previously looked like:
{
normalize: (change, violation, context) {
if (violation === 'child_type_invalid') {
const type = index === 0 ? 'title' : 'paragraph'
return change.setNodeByKey(context.child.key, type)
}
}
}Would now look like:
{
normalize: (change, error) {
if (error.code === 'child_type_invalid') {
const type = index === 0 ? 'title' : 'paragraph'
return change.setNodeByKey(error.child.key, type)
}
}
}This is just an attempt to make dealing with normalization errors slightly more idiomatic with how errors are represented in most libraries, in order to not reinvent the wheel unnecessarily.
`0.35` — July 27, 2018
NEW
Range objects now keep track of paths, in addition to keys. Previously ranges only stored their points as keys. Now both paths and keys are used, which allows you to choose which one is the most convenient or most performant for your use case. They are kept in sync my Slate under the covers.
A new set of *ByPath change methods have been added. All of the changes you could previously do with a *ByKey change are now also supported with a *ByPath change of the same name. The path-based changes are often more performant than the key-based ones.
Paths are now of type List instead of array. See the documentation of List for its differences to array (get method instead of array indexing, size instead of length, etc).
BREAKING
Internal-yet-public Node methods have been changed. There were a handful of internal methods that shouldn't be used in 99% of Slate implementations that updated or removed. This was done in the process of streamlining many of the Node methods to make them more consistent and easier to use. For a list of those affected:
Node.assertPathwas changed. It was previously confusingly named because the equivalentNode.getPathdid something completely different. You should now useNode.assertNode(path)if you need this behavior.Node.removeDescendantwas removed. There's no reason you should have been using this, since it was an undocumented and unused method that was left over from a previous version.Node.updateNode,Node.insertNode,Node.removeNode,Node.splitNodeandNode.mergeNodemutating methods were changed. All of your changes should be done with operations, so you likely weren't using these internal methods. They have been changed internally to use paths.
DEPRECATED
The setKeyGenerator and resetKeyGenerator helpers are deprecated. These were previously used to change the default key generation logic. Now you can use the equivalent KeyUtils.setGenerator and KeyUtils.resetGenerator helpers instead. This follows the new pattern of grouping related utilities into single namespaces, as is the case with the new PathUtils and TextUtils.
Internal-yet-public Node methods have been deprecated. There were a handful of internal methods that shouldn't be used in 99% of Slate implementations that were deprecated. For a list of those affected:
Node.getKeysandNode.getKeysAsArraywere deprecated. If you really need to check the presence of a key, use the newNode.getKeysToPathsObjectinstead.Node.areDescendantsSortedandNode.isInRangewere deprecated. These were used to check whether a node was in a range, but this can be done more performantly and more easily with paths now.Node.getNodeAtPathandNode.getDescendantAtPathwere deprecated. These were probably not in use by anyone, but if you were using them you can use the existingNode.getNodeandNode.getDescendantmethods instead which now take either paths or keys.
`0.34` — June 14, 2018
NEW
Decorations can now be "atomic". If you set a decoration as atomic, it will be removed when changed, preventing it from entering a "partial" state, which can be useful for some use cases.
BREAKING
Text nodes now represent their content as "leaves". Previously their immutable representation used individual Character instance for each character. Now they have changed to group characters into Leaf models, which more closely resembles how they are used, and results in a lot fewer immutable object instances floating around. For most people this shouldn't cause any issues, since this is a low-level aspect of Slate.
DEPRECATED
The Character model is deprecated. Although the character concept is still in the repository for now, it is deprecated and will be removed in a future release. Everything it solves can be solved with leaves instead.
`0.33` — February 21, 2018
BREAKING
Void nodes no longer prescribe their text content. Previously void nodes would automatically normalize their text content to be a single text node containing ' ' an empty string of content. This restriction was removed, so that void nodes can have arbitrary content. You can use this to store information in void nodes in a way that is more consistent with non-void nodes.
DEPRECATED
The setBlock method has been renamed to setBlocks. This is to make it more clear that it operates on any of the current blocks in the selection, not just a single blocks.
The setInline method has been renamed to setInlines. For the same reason as setBlocks, to be clear and stay consistent.
`0.32` — January 4, 2018
BREAKING
The kind property of Slate objects has been renamed to object. This is to reduce the confusion over the difference between "kind" and "type" which are practically synonyms. The "object" name was chosen to match the Stripe API, since it seems like a sensible choice and reads much more nicely when looking through JSON.
All normalization reasons containing kind have been renamed too. Previously there were normalization reason strings like child_kind_invalid. These types of strings have been renamed to child_object_invalid to stay consistent.
`0.31` — November 16, 2017
NEW
Added a new Operation model. This model is used to store operations for the history stack, and (de)serializes them in a consistent way for collaborative editing use cases.
BREAKING
Operation objects in Slate are now immutable records. Previously they were native, mutable JavaScript objects. Now, there's a new immutable Operation model in Slate, ensuring that all of the data inside Value objects are immutable. And it allows for easy serialization of operations using operation.toJSON() for when sending them between editors. This should not affect most users, unless you are relying on changing the values of the low-level Slate operations (simply reading them is fine).
Operation lists in Slate are now immutable lists. Previously they were native, mutable JavaScript arrays. Now, to keep consistent with other immutable uses, they are immutable lists. This should not affect most users.
`0.30` — October 27, 2017
BREAKING
Remove all previously deprecated code paths. This helps to reduce some of the complexity in Slate by not having to handle these code paths anymore. And it helps to reduce file size. When upgrading, it's highly recommended that you upgrade to the previous version first and ensure there are no deprecation warnings being logged, then upgrade to this version.
`0.29` — October 27, 2017
NEW
Added the new Value model to replace State. The new model is exactly the same, but with a new name. There is also a shimmed State model exported that warns when used, to ease migration.
BREAKING
The set_state operation has been renamed set_value. This shouldn't affect almost anyone, but in the event that you were relying on the low-level operation types you'll need to update this.
DEPRECATED
The "state" has been renamed to "value" everywhere. All of the current references are maintained as deprecations, so you should be able to upgrade and see warnings logged instead of being greeted with a broken editor. This is to reduce the confusion between React's "state" and Slate's editor value, and in an effort to further mimic the native DOM APIs.
`0.28` — October 25, 2017
NEW
State objects now have an embedded state.schema property. This new schema property is used to automatically normalize the state as it changes, according to the editor's current schema. This makes normalization much easier.
BREAKING
The Schema objects in Slate have changed! Previously, they used to be where you could define normalization rules, define rendering rules, and define decoration rules. This was overloaded, and made other improvements hard. Now, rendering and decorating is done via the newly added plugin functions (renderNode, renderMark, decorateNode). And validation is done either via the lower-level validateNode plugin function, or via the new schema objects.
The normalize* change methods no longer take a schema argument. Previously you had to maintain a reference to your schema, and pass it into the normalize methods when you called them. Since State objects now have an embedded state.schema property, this is no longer needed.
`0.27` — October 14, 2017
BREAKING
The Range model is now called Leaf. This is to disambiguate with the concept of "ranges" that is used throughout the codebase to be synonymous to selections. For example in methods like getBlocksAtRange(selection).
The text.ranges property in the JSON representation is now text.leaves. When passing in JSON with text.ranges you'll now receive a deprecation warning in the console in development.
DEPRECATED
The Selection model is now called Range. This is to make it more clear what a "selection" really is, to make many of the other methods that act on "ranges" make sense, and to more closely parallel the native DOM API for selections and ranges. A mock Selection object is still exported with deprecated static methods, to make the transition to the new API easier.
The Text.getRanges() method is now Text.getLeaves(). It will still work, and it will return a list of leaves, but you will see a deprecation warning in the console in development.
`0.26` — October 13, 2017
BREAKING
The decorate function of schema rules has changed. Previously, in decorate you would receive a text node and the matched node, and you'd need to manually add any marks you wanted to the text node's characters. Now, "decorations" have changed to just be Selection objects with marks in the selection.marks property. Instead of applying the marks yourself, you simply return selection ranges with the marks to be applied, and Slate will apply them internally. This makes it possible to write much more complex decoration behaviors. Check out the revamped code-highlighting example and the new search-highlighting example to see this in action.
The set_data operation type has been replaced by set_state. With the new state.decorations property, it doesn't make sense to have a new operation type for every property of State objects. Instead, the new set_state operation more closely mimics the existing set_mark and set_node operations.
DEPRECATED
NEW
You can now set decorations based on external information. Previously, the "decoration" logic in Slate was always based off of the text of a node, and would only re-render when that text changed. Now, there is a new state.decorations property that you can set via change.setState({ decorations }). You can use this to add presentation-only marks to arbitrary ranges of text in the document. Check out the new search-highlighting example to see this in action.
The setData change method has been replaced by setState. Previously you would call change.setData(data). But as new State properties are introduced it doesn't make sense to need to add new change methods each time. Instead, the new change.setState(properties) more closesely mimics the existing setMarkByKey and setNodeByKey. To achieve the old behavior, you can do change.setState({ data }).
The preserveStateData option of state.toJSON has changed. The same behavior is now called preserveData instead. This makes it consistent with all of the existing options, and the new preserveDecorations option as well.
`0.25` — September 21, 2017
BREAKING
The insertBlock change method no longer replaces empty blocks. Previously if you used insertBlock and the selection was in an empty block, it would replace it. Now you'll need to perform that check yourself and use the new replaceNodeByKey method instead.
The Block.create and Inline.create methods no longer normalize. Previously if you used one of them to create a block or inline with zero nodes in it, they would automatically add a single empty text node as the only child. This was unexpected in certain situations, and if you were relying on this you'll need to handle it manually instead now.
`0.24` — September 11, 2017
NEW
Slate is now a "monorepo". Instead of a single package, Slate has been divided up into individual packages so that you can only require what you need, cutting down on file size. In the process, some helpful modules that used to be internal-only are now exposed.
There's a new slate-hyperscript helper. This was possible thanks to the work on slate-sugar, which paved the way.
The slate-prop-types package is now exposed. Previously this was an internal module, but now you can use it for adding prop types to any components or plugins you create.
The slate-simulator package is now exposed. Previously this was an internal testing utility, but now you can use it in your own tests as well. It's currently pretty bare bones, but we can add to it over time.
BREAKING
immutable is now a peer dependency of Slate. Previously it was a regular dependency, but this prevented you from bringing your own version, or you'd have duplication. You'll need to ensure you install it!
The Html, Plain and Raw serializers are broken into new packages. Previously you'd import them from slate. But now you'll import them from slate-html-serializer and slate-plain-serializer. And the Raw serializer that was deprecated is now removed.
The Editor and Placeholder components are broken into a new React-specific package. Previously you'd import them from slate. But now you import { Editor } from 'slate-react' instead.
`0.23` — September 10, 2017
NEW
Slate models now have Model.fromJSON(object) and model.toJSON() methods. These methods operate with the canonical JSON form (which used to be called "raw"). This way you don't need to import a serializer to retrieve JSON, if you have the model you can serialize/deserialize.
Models also have toJS and fromJS aliases. This is just to match Immutable.js objects, which have both methods. For Slate though, the methods are equivalent.
BREAKING
The isNative property of State has been removed. Previously this was used for performance reasons to avoid re-rendering, but it is no longer needed. This shouldn't really affect most people because it's rare that you'd be relying on this property to exist.
DEPRECATED
The Raw serializer is now deprecated. The entire "raw" concept is being removed, in favor of allowing all models to be able to serialize and deserialize to JSON themselves. Instead of using the Raw serializer, you can now use the fromJSON and toJSON on the models directly.
The toRaw options for the Plain and Html serializers are now called toJSON. This is to stay symmetrical with the removal of the "raw" concept everywhere.
The terse option for JSON serialization has been deprecated! This option causes lots of abstraction leakiness because it means there is no one canonical JSON representation of objects. You had to work with either terse or not terse data.
The Html serializer no longer uses the terse representation. This shouldn't actually be an issue for anyone because the main manifestation of this has a deprecation notice with a patch in place for now.
The defaultBlockType of the Html serializer is now called defaultBlock. This is just to make it more clear that it supports not only setting the default type but also data and isVoid.
`0.22` — September 5, 2017
NEW
The state.activeMarks returns the intersection of marks in the selection. Previously there was only state.marks which returns marks that appeared on any character in the selection. But state.activeMarks returns marks that appear on every character in the selection, which is often more useful for implementing standard richtext editor behaviors.
BREAKING
The Plain serializer now adds line breaks between blocks. Previously between blocks the text would be joined without any space whatsoever, but this wasn't really that useful or what you'd expect.
The toggleMark transform now checks the intersection of marks. Previously, toggling would remove the mark from the range if any of the characters in a range didn't have it. However, this wasn't what all other richtext editors did, so the behavior has changed to mimic the standard behavior. Now, if any characters in the selection have the mark applied, it will first be added when toggling.
The .length property of nodes has been removed. This property caused issues with code like in Lodash that checked for "array-likeness" by simply looking for a .length property that was a number.
onChange now receives a Change object (previously named Transform) instead of a State. This is needed because it enforces that all changes are represented by a single set of operations. Otherwise right now it's possible to do things like state.transform()....apply({ save: false }).transform()....apply() and result in losing the operation information in the history. With OT, we need all transforms that may happen to be exposed and emitted by the editor. The new syntax looks like:
onChange(change) {
this.setState({ state: change.state })
}
onChange({ state }) {
this.setState({ state })
}Similarly, handlers now receive e, data, change instead of e, data, state. Instead of doing return state.transform()....apply() the plugins can now act on the change object directly. Plugins can still return change... if they want to break the stack from continuing on to other plugins. (Any != null value will break out.) But they can also now not return anything, and the stack will apply their changes and continue onwards. This was previously impossible. The new syntax looks like:
function onKeyDown(e, data, change) {
if (data.key == 'enter') {
return change.splitBlock()
}
}The onChange and on[Before]Change handlers now receive Change objects. Previously they would also receive a state object, but now they receive change objects like the rest of the plugin API.
The .apply({ save }) option is now state.change({ save }) instead. This is the easiest way to use it, but requires that you know whether to save or not up front. If you want to use it inline after already saving some changes, you can use the change.setOperationFlag('save', true) flag instead. This shouldn't be necessary for 99% of use cases though.
The .undo() and .redo() transforms don't save by default. Previously you had to specifically tell these transforms not to save into the history, which was awkward. Now they won't save the operations they're undoing/redoing by default.
onBeforeChange is no longer called from componentWillReceiveProps, when a new state is passed in as props to the <Editor> component. This caused lots of state-management issues and was weird in the first place because passing in props would result in changes firing. It is now the parent component's responsibility to not pass in improperly formatted State objects.
The splitNodeByKey change method has changed to be shallow. Previously, it would deeply split to an offset. But now it is shallow and another splitDescendantsByKey change method has been added (with a different signature) for the deep splitting behavior. This is needed because splitting and joining operations have been changed to all be shallow, which is required so that operational transforms can be written against them.
Blocks cannot have mixed "inline" and "block" children anymore. Blocks were implicitly expected to either contain "text" and "inline" nodes only, or to contain "block" nodes only. Invalid case are now normalized by the core schema.
The shape of many operations has changed. This was needed to make operations completely invertible without any extra context. The operations were never really exposed in a consumable way, so I won't detail all of the changes here, but feel free to look at the source to see the details.
All references to "joining" nodes is now called "merging". This is to be slightly clearer, since merging can only happen with adjacent nodes already, and to have a nicer parallel with "splitting", as in cells. The operation is now called merge_node, and the transforms are now merge*.
DEPRECATED
The transform.apply() method is deprecated. Previously this is where the saving into the history would happen, but it created an awkward convention that wasn't necessary. Now operations are saved into the history as they are created with change methods, instead of waiting until the end. You can access the new State of a change at any time via change.state.
`0.21` — July 20, 2017
BREAKING
The Html serializer now uses DOMParser instead of cheerio. Previously, the Html serializer used the cheerio library for representing elements in the serialization rule logic, but cheerio was a very large dependency. It has been removed, and the native browser DOMParser is now used instead. All HTML serialization rules will need to be updated. If you are working with Slate on the server, you can now pass in a custom serializer to the Html constructor, using the parse5 library.
`0.20` — May 17, 2017
BREAKING
Returning null from the Html serializer skips the element. Previously, null and undefined had the same behavior of skipping the rule and trying the rest of the rules. Now if you explicitly return null it will skip the element itself.
`0.19` — March 3, 2017
BREAKING
The filterDescendants and findDescendants methods are now depth-first. This shouldn't affect almost anyone, since they are usually not the best things to be using for performance reasons. If you happen to have a very specific use case that needs breadth-first, (or even likely something better), you'll need to implement it yourself.
DEPRECATED
Some Node methods have been deprecated! There were a few methods that had been added over time that were either poorly named that have been deprecated and renamed, and a handful of methods that are no longer useful for the core library that have been deprecated. Here's a full list:
areDescendantSorted->areDescendantsSortedgetHighestChild->getFurthestAncestorgetHighestOnlyChildParent->getFurthestOnlyChildAncestorconcatChildrendecorateTextsfilterDescendantsDeepfindDescendantDeepgetChildrenBetweengetChildrenBetweenIncludingisInlineSplitAtRange
`0.18` — March 2, 2017
BREAKING
The plugin.render property is now called plugin.renderPortal. This is to make way for the new plugin.render property that offers HOC-like behavior, so that plugins can augment the editor however they choose.
`0.17` — February 27, 2017
DEPRECATED
Some Selection methods have been deprecated! Previously there were many inconsistencies in the naming and handling of selection changes. This has all been cleaned up, but in the process some methods have been deprecated. Here is a full list of the deprecated methods and their new alternatives:
moveToOffsets->moveOffsetsTomoveForward->movemoveBackward->movemoveAnchorOffset->moveAnchormoveFocusOffset->moveFocusmoveStartOffset->moveStartmoveEndOffset->moveEndextendForward->extendextendBackward->extendunset->deselect
Some selection transforms have been deprecated! Along with the methods, the selection-based transforms have also been refactored, resulting in deprecations. Here is a full list of the deprecated transforms and their new alternatives:
moveTo->selectmoveToOffsets->moveOffsetsTomoveForward->movemoveBackward->movemoveStartOffset->moveStartmoveEndOffset->moveEndextendForward->extendextendBackward->extendflipSelection->flipunsetSelection->deselectunsetMarks
`0.16` — December 2, 2016
BREAKING
Inline nodes are now always surrounded by text nodes. Previously this behavior only occured for inline nodes with isVoid: true. Now, all inline nodes will always be surrounded by text nodes. If text nodes don't exist, empty ones will be created. This allows for more consistent behavior across Slate, and parity with other editing experiences.
`0.15` — November 17, 2016
BREAKING
The unique key generated values have changed. Previously, Slate generated unique keys that looked like '9dk3'. But they were not very conflict-resistant. Now the keys are simple string of auto-incrementing numbers, like '0', '1', '2'. This makes more clear that keys are simply a convenient way to uniquely reference nodes in the short-term lifespan of a single in-memory instance of Slate. They are not designed to be used for long-term uniqueness. A new setKeyGenerator function has been exported that allows you to pass in your own key generating mechanism if you want to ensure uniqueness.
The Raw serializer doesn't preserve keys by default. Previously, the Raw serializer would omit keys when passed the terse: true option, but preserve them without it. Now it will always omit keys, unless you pass the new preserveKeys: true option. This better reflects that keys are temporary, in-memory IDs.
Operations on the document now update the selection when needed. This won't affect you unless you were doing some very specific things with transforms and updating selections. Overall, this makes it much easier to write transforms, since in most cases, the underlying operations will update the selection as you would expect without you doing anything.
DEPRECATED
Node accessor methods no longer accept being passed another node! Previously, node accessor methods like node.getParent could be passed either a key string or a node object. For performance reasons, passing in a node object is being deprecated. So if you have any calls that look like: node.getParent(descendant), they will now need to be written as node.getParent(descendant.key). They will throw a warning for now, and will throw an error in a later version of Slate.
`0.14` — September 10, 2016
BREAKING
The undo and redo transforms need to be applied! Previously, undo and redo were special cased such that they did not require an .apply() call, and instead would return a new State directly. Now this is no longer the case, and they are just like every other transform.
Transforms are no longer exposed on State or Node. The transforms API has been completely refactored to be built up of "operations" for collaborative editing support. As part of this refactor, the transforms are now only available via the state.transform() API, and aren't exposed on the State or Node objects as they were before.
Transform objects are now mutable. Previously Transform was an Immutable.js Record, but now it is a simple constructor. This is because transforms are inherently mutating their representation of a state, but this decision is up for discussion.
The selection can now be "unset". Previously, a selection could never be in an "unset" state where the anchorKey or focusKey was null. This is no longer technically true, although this shouldn't really affect anyone in practice.
`0.13` — August 15, 2016
BREAKING
The renderNode and renderMark properties are gone! Previously, rendering nodes and marks happened via these two properties of the <Editor>, but this has been replaced by the new schema property. Check out the updated examples to see how to define a schema! There's a good chance this eliminates extra code for most use cases! :smile:
The renderDecorations property is gone! Decoration rendering has also been replaced by the new schema property of the <Editor>.
`0.12` — August 9, 2016
BREAKING
The data.files property is now an Array. Previously it was a native FileList object, but needed to be changed to add full support for pasting an dropping files in all browsers. This shouldn't affect you unless you were specifically depending on it being array-like instead of a true Array.
`0.11` — August 4, 2016
BREAKING
Void nodes are renderered implicitly again! Previously Slate had required that you wrap void node renderers yourself with the exposed <Void> wrapping component. This was to allow for selection styling, but a change was made to make selection styling able to handled in JavaScript. Now the <Void> wrapper will be implicitly rendered by Slate, so you do not need to worry about it, and "voidness" only needs to toggled in one place, the isVoid: true property of a node.
`0.10` — July 29, 2016
BREAKING
Marks are now renderable as components. Previously the only supported way to render marks was by returning a style object. Now you can return a style object, a class name string, or a full React component. Because of this, the DOM will be renderered slightly differently than before, resulting in an extra `` when rendering non-component marks. This won't affect you unless you were depending on the DOM output by Slate for some reason.
`0.9` — July 28, 2016
BREAKING
The wrap and unwrap method signatures have changed! Previously, you would pass type and data as separate parameters, for example: wrapBlock('code', { src: true }). This was inconsistent with other transforms, and has been updated such that a single argument of properties is passed instead. So that example could now be: wrapBlock({ type: 'code', { data: { src: true }}). You can still pass a type string as shorthand, which will be the most frequent use case, for example: wrapBlock('code').
`0.8` — July 27, 2016
BREAKING
The onKeyDown and onBeforeInput handlers signatures have changed! Previously, some Slate handlers had a signature of (e, state, editor) and others had a signature of (e, data, state, editor). Now all handlers will be passed a data object—which contains Slate-specific data related to the event—even if it is empty. This is helpful for future compatibility where we might need to add data to a handler that previously didn't have any, and is nicer for consistency. The onKeyDown handler's new data object contains the key name, code and a series of is* properties to make working with hotkeys easier. The onBeforeInput handler's new data object is empty.
The Utils export has been removed. Previously, a Key utility and the findDOMNode utility were exposed under the Utils object. The Key has been removed in favor of the data object passed to onKeyDown. And then findDOMNode utility has been upgraded to a top-level named export, so you'll now need to access it via import { findDOMNode } from 'slate'.
Void nodes now permanently have " " as content. Previously, they contained an empty string, but this isn't technically correct, since they have content and shouldn't be considered "empty". Now they will have a single space of content. This shouldn't really affect anyone, unless you happened to be accessing that string for serialization.
Empty inline nodes are now impossible. This is to stay consistent with native contenteditable behavior, where although technically the elements can exist, they have odd behavior and can never be selected.
`0.7` — July 24, 2016
BREAKING
The Raw serializer is no longer terse by default! Previously, the Raw serializer would return a "terse" representation of the document, omitting information that wasn't strictly necessary to deserialize later, like the key of nodes. By default this no longer happens. You have to opt-in to the behavior by passing { terse: true } as the second options argument of the deserialize and serialize methods.
`0.6` — July 22, 2016
BREAKING
Void components are no longer rendered implicity! Previously, Slate would automatically wrap any node with isVoid: true in a <Void> component. But doing this prevented you from customizing the wrapper, like adding a className or style property. So you must now render the wrapper yourself, and it has been exported as Slate.Void. This, combined with a small change to the <Void> component's structure allows the "selected" state of void nodes to be rendered purely with CSS based on the :focus property of a <Void> element, which previously had to be handled in JavaScript. This allows us to streamline selection-handling logic, improving performance and reducing complexity.
data-offset-key is now <key>- instead of <key>:<start>-<end>. This shouldn't actually affect anyone, unless you were specifically relying on that attribute in the DOM. This change greatly reduces the number of re-renders needed, since previously any additional characters would cause a cascading change in the <start> and <end> offsets of latter text ranges.
`0.5` — July 20, 2016
BREAKING
node.getTextNodes() is now node.getTexts(). This is just for consistency with the other existing Node methods like getBlocks(), getInlines(), etc. And it's nicely shorter. :wink:
Node methods now throw earlier during unexpected states. This shouldn't break anything for most folks, unless a strange edge-case was going undetected previously.
`0.4` — July 20, 2016
BREAKING
renderMark(mark, state, editor) is now renderMark(mark, marks, state, editor). This change allows you to render marks based on multiple marks presence at once on a given range of text, for example using a custom BoldItalic.otf font when text has both bold and italic marks.
`0.3` — July 20, 2016
BREAKING
transform.unwrapBlock() now unwraps selectively. Previously, calling unwrapBlock with a range representing a middle sibling would unwrap all of the siblings, removing the wrapping block entirely. Now, calling it with those same arguments will only move the middle sibling up a layer in the hierarchy, preserving the nesting on any of its siblings. This changes makes it much simpler to implement functionality like unwrapping a single list item, which previously would unwrap the entire list.
`0.2` — July 18, 2016
BREAKING
transform.mark() is now transform.addMark() and transform.unmark() is now transform.removeMark(). The new names make it clearer that the transforms are actions being performed, and it paves the way for adding a toggleMark convenience as well.
`0.1` — July 13, 2016
:tada:
General Contributing (`docs/general/contributing.md`)
Contributing
Want to contribute to Slate? That would be awesome!
Reporting Bugs
If you run into any weird behavior while using Slate, feel free to open a new issue in this repository! Please run a search before opening a new issue, to make sure that someone else hasn't already reported or solved the bug you've found.
Any issue you open must include:
- A JSFiddle that reproduces the bug with a minimal setup.
- A GIF showing the issue in action. (Using something like RecordIt.)
- A clear explanation of what the issue is.
Here's a JSFiddle template for Slate to get you started:
Asking Questions
ℹ️ If you're looking for help with the Slate CRM platform, that's an unrelated project to us.
We've also got a Slate Slack team where you can ask questions and get answers from other people using Slate:
Please use the Slack instead of asking questions in issues, since we want to reserve issues for keeping track of bugs and features. We close questions in issues so that maintaining the project isn't overwhelming.
Submitting Pull Requests
All pull requests are super welcomed and greatly appreciated! Issues in need of a solution are marked with a ♥ help label if you're looking for somewhere to start.
Please include tests and docs with every pull request!
Reviewing and Merging
Before merging a pull request:
- Check that the description explains the problem, the resulting behavior, and any compatibility changes. Agree on breaking changes or substantial API and architecture changes with the maintainers before merging.
- Require a regression test for a bug fix that fails without the fix. Check affected examples and editing behaviors, including selections, nested blocks, voids, and input methods where relevant.
- Keep the implementation consistent with existing patterns and easy to follow. Keep documentation concise and update it when behavior or APIs change.
- Confirm that tests, type checking, formatting, and linting pass on the version being merged, and resolve outstanding review feedback.
- Include a changeset for changes to published packages. Changes limited to documentation, examples, or tests do not need one.
Passing CI is part of review, not a substitute for checking the behavior and compatibility of the change.
Repository Setup
The Slate repository is a monorepo of Yarn workspaces. Unlike more traditional repositories, this means that the repository must be built in order for tests, linting, or other common development activities to function as expected.
To run the build, you need to have the Slate repository cloned to your computer. After that, you need to cd into the directory where you cloned it, and install the dependencies with yarn and build the monorepo:
yarn install
yarn buildRunning Examples
To run the examples, start by building the monorepo as described in the Repository Setup section.
Then you can start the examples server with:
yarn startRunning Tests
To run the tests, start by building the monorepo as described in the Repository Setup section.
Then you can rerun the tests with:
yarn testIf you need to debug something, you can add a debugger line to the source, and then run yarn test:inspect.
If you only want to run a specific test or tests, you can run yarn run test:mocha --fgrep="slate-react rendering" flag which will filter the tests being run by grepping for the string in each test. (This is a Mocha flag that gets passed through.)
In addition to tests you should also run the linter:
yarn lintThis will catch TypeScript, Prettier, and Eslint errors.
yarn fixThis will fix Prettier and Eslint errors.
Running integration tests
To run integrations with Playwright, first run yarn start to run the examples website, then run yarn playwright in a separate session to open the Playwright test suite. Or alternatively, run just yarn test:integration-local.
Running integration tests in Docker
If tests fail on CI but pass locally (often due to OS differences), you can run tests in a Docker container that replicates the same environment as CI.
Prerequisites: The project must be built first (same as running tests locally).
yarn test:integration-dockerThe script will automatically:
- Start the development server (if not already running)
- Run tests inside a Docker container
- Stop the server when tests complete
You can also pass additional arguments to the test runner. For example, to run a specific test file:
yarn test:integration-docker playwright/integration/slate-react/selection.test.tsOr run a specific browser project:
yarn test:integration-docker --project=chromiumYou can combine arguments as well:
yarn test:integration-docker playwright/integration/examples/check-lists.test.ts --project chromiumTesting Input Methods
Here's a helpful page detailing how to test various input scenarios on Windows, Mac and Linux.
Android tests
When making changes that might affect Android compatibility, you can perform the manual Android tests at /examples/android-tests.
Publishing Releases
Releases are automated with Changesets and run from GitHub Actions, so there is no manual publish step.
Adding a Changeset
Any pull request that changes a published package should describe its version bump with:
yarn changesetCommit the generated file in .changeset/ alongside your changes.
Publishing to `@latest`
Once a pull request lands on main, .github/workflows/release.yml collects the pending changesets into a "Version Packages" pull request. Merging that pull request publishes the new versions to the latest channel, pushes the git tags and creates the matching GitHub releases.
Publishing to `@dev`
Every push to main also publishes a snapshot to the dev channel, so the tip of main stays installable:
yarn add slate@devRunning Prerelease Script
If we want to make sure that Slate code follows the preparations for a release but without actually publishing, run:
yarn prereleaseWhich will build, test and lint Slate code.
General Faq (`docs/general/faq.md`)
FAQ
A series of common questions people have about Slate:
Why is content pasted as plain text?
One of Slate's core principles is that, unlike most other editors, it does not prescribe a specific "schema" to the content you are editing. This means that Slate's core has no concept of "block quotes" or "bold formatting".
For the most part, this leads to increased flexibility without many downsides, but there are certain cases where you have to do a bit more work. Pasting is one of those cases.
Since Slate knows nothing about your domain, it can't know how to parse pasted HTML content (or other content). So, by default whenever a user pastes content into a Slate editor, it will parse it as plain text. If you want it to be smarter about pasted content, you need to override the insert_data command and deserialize the DataTransfer object's text/html data as you wish.
What browsers and devices does Slate support?
Slate's goal is to support all the modern browsers on both desktop and mobile devices.
Slate is in beta and is community-driven and so its support is not as robust as it could be.
On the desktop, it's currently tested against the latest few versions of Chrome, Edge, Firefox and Safari on desktops. And it does not work in Internet Explorer.
On mobile, iOS devices are supported but not regularly tested. Chrome on Android was until recently unsupported except for in older versions of Slate (0.47) but has recently been added. For clarity, due to the differences in Android's support of the beforeInput event, Android input uses compositions and mutations which is different from other browsers. This means that Android support progresses separately from other browsers and due to it being new, may have more bugs.
If you want to add or improve browser or device support, we'd love for you to submit a pull request! Or in the case of incompatible browsers, build a plugin.
For older browsers, such as IE11, a lot of the now standard native APIs aren't available. Slate's position on this is that it is up to the user to bring polyfills (like https://polyfill-fastly.io/) when needed for things like el.closest, etc. Otherwise we'd have to bundle and maintain lots of polyfills that others may not even need in the first place. For clarity, Slate makes no guarantees that it will work with older browsers, even with polyfills and at present, there are still unresolved issues with IE11.
General Resources (`docs/general/resources.md`)
Resources
A few resources that are helpful for building with Slate.
Libraries
These libraries are helpful when developing with Slate:
is-hotkeyis a simple way to check whether anonKeyDownhandler
should fire for a given hotkey, handling cross-platform concerns like cmd vs. ctrl keys for you automatically.
Extensions and Plugins
These extensions and plugins add additional features and capabilities to Slate:
- @liveblocks/yjs A fully-hosted WebSocket infrastructure and
persisted data store for Yjs documents - Plate Rich text editor plugin system for Slate & React
slate-angularAngular-based view layer, which is a useful supplement to
Slate for building a rich text editor using Angular.slate-yjsCollaborative editing utilities for Slate leveraging Yjsslate-collaborativeCollaborative editing utilities for Slate
leveraging Automergeslate-vue3Which is a useful supplement to Slate for building a rich text editor using Vue3, integrated all functions in an npm package- Velt Collaboration SDK adding comments, presence, live cursors and CRDT to Slate
Products
These products use Slate, and can give you an idea of what's possible:
- Aline: Digital contracting for the modern enterprise
- Archbee: Build better product docs with your team
- Campfire: The most versatile writing software [for fiction]
- Chatterbug: Learn languages from real people
- CoCalc: Collaborative calculation and data science
- Coda: Coda brings all your words, data, and teamwork into one powerful doc
- Decap CMS: Open source content management for your Git workflow
- Dropdeck: Magically create beautiful slides — faster than ever
- Easy Email Pro: A powerful, highly customizable email editor
- Eraser: The Whiteboard for Engineering Teams
- Formstep: Collect information from anyone, without the back-and-forth
- GitBook: Plan, centralize and share knowledge
- Discord: Text & voice channels to collaborate & share
- Grafana: Operational dashboards for your data
- Guilded: Better chat, happier communities
- Guru: Organize company information. Access it anywhere. [wiki]
- Hygraph: The federated content platform
- Hot Page: A graphical website builder for writing HTML and CSS from scratch
- Kitemaker: Product development tool built to manage the work, not the workers
- Living Spec: A modern way for product teams to work
- Notestamp: A note-taking web app that synchronizes your notes to audio, video and pdfs.
- Notes Together: Get mundane details out of your head
- Prezly: Turn your audience into fans
- Quill Forms: Open Source Typeform Alternative WordPress Plugin
- Sana: Reimagining learning with AI [LMS]
- Sanity.io: Platform for structured content [data driven content]
- Slite: Where remote teams make decisions and share knowledge
- Static CMS: Git-based CMS for Static Site Generators
- Taskade: Get work done in one unified workspace
- TRPG Engine
- Thoughts
Editors
These pre-packaged editors are built on top of Slate, and can be helpful to see how you might structure your code:
- Accord Project Markdown Editor is a WYSIWYG editor
for CommonMark. - Canner Editor is a rich text editor.
- Chatterslate helps teach language grammar and more
at Chatterbug. - CoCalc Collaborative Calculation editor in the Cloud
- French Press Editor is a customizeable editor with offline
support. - Nossas Editor is a drop-in WYSIWYG editor.
- Notestamp: Synchronize your text entries to media using this rich text editor that inserts clickable stamps alongside text.
- React Force Slate Editor is a
light-weight medium-style editor with no editor chrome. - React Page is a self-contained, customizable inline WYSIWYG editor
library. - Plate (Plugins for Slate) provides an editor with configurable and
extendable plugins. - Tripdocs: It's a modern, production-ready rich text editor.
(Or, if you have their exact use case, can be a drop-in editor for you.)
Libraries Slate Hyperscript (`docs/libraries/slate-hyperscript.md`)
Slate Hyperscript
This package contains a hyperscript helper for creating Slate documents with JSX!
Walkthroughs 01 Installing Slate (`docs/walkthroughs/01-installing-slate.md`)
Installing Slate
Slate is a monorepo divided up into multiple npm packages, so to install it you do:
yarn add slate slate-react slate-domYou'll also need to be sure to install Slate's peer dependencies:
yarn add react react-domNote, if you'd rather use a pre-bundled version of Slate, you can yarn add slate and retrieve the bundled dist/slate.js file! Check out the Using the Bundled Source guide for more information.
Once you've installed Slate, you'll need to import it.
// Import React dependencies.
import React, { useState } from 'react'
// Import the Slate editor factory.
import { createEditor } from 'slate'
// Import the Slate components and React plugin.
import { Slate, Editable, withReact } from 'slate-react'Before we use those imports, let's start with an empty <App> component:
// Define our app...
const App = () => {
return null
}The next step is to create a new Editor object. We want the editor to be stable across renders, so we use the useState hook without a setter:
const App = () => {
// Create a Slate editor object that won't change across renders.
const [editor] = useState(() => withReact(createEditor()))
return null
}Of course we haven't rendered anything, so you won't see any changes.
If you are using TypeScript, you will also need to extend the
EditorwithReactEditorand add annotations as per the documentation on TypeScript. The example below also includes the custom types required for the rest of this example.
// TypeScript users only add this code
import { BaseEditor, Descendant } from 'slate'
import { ReactEditor } from 'slate-react'
type CustomElement = { type: 'paragraph'; children: CustomText[] }
type CustomText = { text: string }
declare module 'slate' {
interface CustomTypes {
Editor: BaseEditor & ReactEditor
Element: CustomElement
Text: CustomText
}
}Next up is to render a <Slate> context provider.
The provider component keeps track of your Slate editor, its plugins, its value, its selection, and any changes that occur. It must be rendered above any <Editable> components. But it can also provide the editor state to other components like toolbars, menus, etc. using the useSlate hook.
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
// Render the Slate context.
return <Slate editor={editor} initialValue={initialValue} />
}You can think of the <Slate> component as providing a context to every component underneath it.
Slate Provider's
initialValueprop is only used as initial state for editor.children. If your code relies on replacing editor.children you should do so by replacing it directly instead of relying on theinitialValueprop to do this for you. See Slate PR 4540 for a more in-depth discussion.
This is a slightly different mental model than things like `` or <textarea>, because richtext documents are more complex. You'll often want to include toolbars, or live previews, or other complex components next to your editable content.
By having a shared context, those other components can execute commands, query the editor's state, etc.
The next step is to render the <Editable> component itself. The component acts like contenteditable; anywhere you render it will render an editable richtext document for the nearest editor context.
The example below uses the TypeScript declarations above and annotates initialValue with Descendant[]. JavaScript users can omit that annotation. Keep it when adapting the JavaScript examples in the following walkthroughs to TypeScript.
const initialValue: Descendant[] = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
// Add the editable component inside the context.
<Slate editor={editor} initialValue={initialValue}>
<Editable />
</Slate>
)
}There you have it!
That's the most basic example of Slate. If you render that onto the page, you should see a paragraph with the text A line of text in a paragraph. And when you type, you should see the text change!
Walkthroughs 02 Adding Event Handlers (`docs/walkthroughs/02-adding-event-handlers.md`)
Adding Event Handlers
Okay, so you've got Slate installed and rendered on the page, and when you type in it, you can see the changes reflected. But you want to do more than just type a plaintext string.
What makes Slate great is how easy it is to customize. Just like other React components you're used to, Slate allows you to pass in handlers that are triggered on certain events.
Let's use the onKeyDown handler to change the editor's content when we press a key.
Here's our app from earlier:
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable />
</Slate>
)
}Now we add an onKeyDown handler:
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable
// Define a new handler which prints the key that was pressed.
onKeyDown={event => {
console.log(event.key)
}}
/>
</Slate>
)
}Cool, now when a key is pressed in the editor, its corresponding keycode is logged in the console.
Now we want to make it actually change the content. For the purposes of our example, let's implement turning all ampersand, &, keystrokes into the word and upon being typed.
Our onKeyDown handler might look like this:
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable
onKeyDown={event => {
if (event.key === '&') {
// Prevent the ampersand character from being inserted.
event.preventDefault()
// Execute the `insertText` method when the event occurs.
editor.insertText('and')
}
}}
/>
</Slate>
)
}With that added, try typing &, and you should see it suddenly become and instead!
This offers a sense of what can be done with Slate's event handlers. Each one will be called with the event object, and you can use your editor to perform commands in response. Simple!
Walkthroughs 03 Defining Custom Elements (`docs/walkthroughs/03-defining-custom-elements.md`)
Defining Custom Elements
In our previous example, we started with a paragraph, but we never actually told Slate anything about the paragraph block type. We just let it use its internal default renderer, which uses a plain old ``.
But that's not all you can do. Slate lets you define any type of custom blocks you want, like block quotes, code blocks, list items, etc.
We'll show you how. Let's start with our app from earlier:
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable
onKeyDown={event => {
if (event.key === '&') {
event.preventDefault()
editor.insertText('and')
}
}}
/>
</Slate>
)
}Now let's add "code blocks" to our editor.
For TypeScript, replace the earlier CustomElement definition with one that allows both block types:
type CustomElement = {
type: 'paragraph' | 'code'
children: CustomText[]
}Import RenderElementProps from slate-react and use it for the props parameter of CodeElement, DefaultElement and the renderElement callback.
The problem is, code blocks won't just be rendered as a plain paragraph, they'll need to be rendered differently. To make that happen, we need to define a "renderer" for code element nodes.
Element renderers are just simple React components, like so:
// Define a React component renderer for our code blocks.
const CodeElement = props => {
return (
<pre {...props.attributes}>
<code>{props.children}</code>
</pre>
)
}Easy enough.
See the props.attributes reference? Slate passes attributes that should be rendered on the top-most element of your blocks, so that you don't have to build them up yourself. You must mix the attributes into your component.
And see that props.children reference? Slate will automatically render all of the children of a block for you, and then pass them to you just like any other React component would, via props.children. That way you don't have to muck around with rendering the proper text nodes or anything like that. You must render the children as the lowest leaf in your component.
And here's a component for the "default" elements:
const DefaultElement = props => {
return <p {...props.attributes}>{props.children}</p>
}Now, let's add that renderer to our Editor:
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
// Define a rendering function based on the element passed to `props`. We use
// `useCallback` here to memoize the function for subsequent renders.
const renderElement = useCallback(props => {
switch (props.element.type) {
case 'code':
return <CodeElement {...props} />
default:
return <DefaultElement {...props} />
}
}, [])
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable
// Pass in the `renderElement` function.
renderElement={renderElement}
onKeyDown={event => {
if (event.key === '&') {
event.preventDefault()
editor.insertText('and')
}
}}
/>
</Slate>
)
}
const CodeElement = props => {
return (
<pre {...props.attributes}>
<code>{props.children}</code>
</pre>
)
}
const DefaultElement = props => {
return <p {...props.attributes}>{props.children}</p>
}Okay, but now we'll need a way for the user to actually turn a block into a code block. So let's change our onKeyDown function to add a Ctrl-` shortcut that does just that:
// Import the `Editor` and `Transforms` helpers from Slate.
import { Editor, Transforms, Element } from 'slate'
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
const renderElement = useCallback(props => {
switch (props.element.type) {
case 'code':
return <CodeElement {...props} />
default:
return <DefaultElement {...props} />
}
}, [])
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable
renderElement={renderElement}
onKeyDown={event => {
if (event.key === '`' && event.ctrlKey) {
// Prevent the "`" from being inserted by default.
event.preventDefault()
// Otherwise, set the currently selected blocks type to "code".
Transforms.setNodes(
editor,
{ type: 'code' },
{ match: n => Element.isElement(n) && Editor.isBlock(editor, n) }
)
}
}}
/>
</Slate>
)
}
const CodeElement = props => {
return (
<pre {...props.attributes}>
<code>{props.children}</code>
</pre>
)
}
const DefaultElement = props => {
return <p {...props.attributes}>{props.children}</p>
}Now, if you press Ctrl-` the block your cursor is in should turn into a code block! Magic!
But we forgot one thing. When you hit Ctrl-` again, it should change the code block back into a paragraph. To do that, we'll need to add a bit of logic to change the type we set based on whether any of the currently selected blocks are already a code block:
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
const renderElement = useCallback(props => {
switch (props.element.type) {
case 'code':
return <CodeElement {...props} />
default:
return <DefaultElement {...props} />
}
}, [])
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable
renderElement={renderElement}
onKeyDown={event => {
if (event.key === '`' && event.ctrlKey) {
event.preventDefault()
// Determine whether any of the currently selected blocks are code blocks.
const [match] = Editor.nodes(editor, {
match: n => Element.isElement(n) && n.type === 'code',
})
// Toggle the block type depending on whether there's already a match.
Transforms.setNodes(
editor,
{ type: match ? 'paragraph' : 'code' },
{ match: n => Element.isElement(n) && Editor.isBlock(editor, n) }
)
}
}}
/>
</Slate>
)
}And there you have it! If you press Ctrl-` while inside a code block, it should turn back into a paragraph!
Walkthroughs 04 Applying Custom Formatting (`docs/walkthroughs/04-applying-custom-formatting.md`)
Applying Custom Formatting
In the previous guide we learned how to create custom block types that render chunks of text inside different containers. But Slate allows for more than just "blocks".
In this guide, we'll show you how to add custom formatting options, like bold, italic, code or strikethrough.
For TypeScript, add the mark to your existing CustomText definition:
type CustomText = { text: string; bold?: boolean }Import RenderLeafProps from slate-react and use it for the props parameter of Leaf and the renderLeaf callback. Continue to annotate element renderers with RenderElementProps and initial values with Descendant[].
So we start with our app from earlier:
const renderElement = props => {
switch (props.element.type) {
case 'code':
return <CodeElement {...props} />
default:
return <DefaultElement {...props} />
}
}
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable
renderElement={renderElement}
onKeyDown={event => {
if (event.key === '`' && event.ctrlKey) {
event.preventDefault()
const [match] = Editor.nodes(editor, {
match: n => Element.isElement(n) && n.type === 'code',
})
Transforms.setNodes(
editor,
{ type: match ? 'paragraph' : 'code' },
{ match: n => Element.isElement(n) && Editor.isBlock(editor, n) }
)
}
}}
/>
</Slate>
)
}And now, we'll edit the onKeyDown handler to make it so that when you press control-B, it will add a bold format to the currently selected text:
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
const renderElement = useCallback(props => {
switch (props.element.type) {
case 'code':
return <CodeElement {...props} />
default:
return <DefaultElement {...props} />
}
}, [])
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable
renderElement={renderElement}
onKeyDown={event => {
if (!event.ctrlKey) {
return
}
switch (event.key) {
// When "`" is pressed, keep our existing code block logic.
case '`': {
event.preventDefault()
const [match] = Editor.nodes(editor, {
match: n => Element.isElement(n) && n.type === 'code',
})
Transforms.setNodes(
editor,
{ type: match ? 'paragraph' : 'code' },
{
match: n => Element.isElement(n) && Editor.isBlock(editor, n),
}
)
break
}
// When "B" is pressed, bold the text in the selection.
case 'b': {
event.preventDefault()
Editor.addMark(editor, 'bold', true)
break
}
}
}}
/>
</Slate>
)
}Unlike the code format from the previous step, which is a block-level format, bold is a character-level format. Slate manages text contained within blocks (or any other element) using "leaves". Slate's character-level formats/styles are called "marks". Adjacent text with the same marks (styles) applied will be grouped within the same "leaf". When we use addMark to add our bold mark to the selected text, Slate will automatically break up the "leaves" using the selection boundaries and produce a new "leaf" with the bold mark added.
Okay, so we've got the hotkey handler setup... but! If you happen to now try selecting text and hitting Ctrl-B, you won't notice any change. That's because we haven't told Slate how to render a "bold" mark.
For every format you add, you need to tell Slate how to render it, just like for elements. So let's define a Leaf component:
// Define a React component to render leaves with bold text.
const Leaf = props => {
return (
<span
{...props.attributes}
style={{ fontWeight: props.leaf.bold ? 'bold' : 'normal' }}
>
{props.children}
</span>
)
}Pretty familiar, right? Note that it is described with a span - This is because all leaves must be an inline element. You can learn more about leaves in the Rendering section.
And now, let's tell Slate about that leaf. To do that, we'll pass in the renderLeaf prop to our editor.
/* Detailed source-code truncated for AI context efficiency. */Now, if you try selecting a piece of text and hitting Ctrl-B you should see it turn bold! Magic!
Walkthroughs 05 Executing Commands (`docs/walkthroughs/05-executing-commands.md`)
Executing Commands
Up until now, everything we've learned has been about how to write one-off logic for your specific Slate editor. But one of the most powerful things about Slate is that it lets you model your specific rich text "domain" however you'd like, and write less one-off code.
In the previous guides we've written some useful code to handle formatting code blocks and bold marks. And we've hooked up the onKeyDown handler to invoke that code. But we've always done it using the built-in Editor helpers directly, instead of using "commands".
Slate lets you augment the built-in editor object to handle your own custom rich text commands. And you can even use pre-packaged "plugins" which add a given set of functionality.
Let's see how this works.
We'll start with our app from earlier:
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
const renderElement = useCallback(props => {
switch (props.element.type) {
case 'code':
return <CodeElement {...props} />
default:
return <DefaultElement {...props} />
}
}, [])
const renderLeaf = useCallback(props => {
return <Leaf {...props} />
}, [])
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable
renderElement={renderElement}
renderLeaf={renderLeaf}
onKeyDown={event => {
if (!event.ctrlKey) {
return
}
switch (event.key) {
case '`': {
event.preventDefault()
const [match] = Editor.nodes(editor, {
match: n => Element.isElement(n) && n.type === 'code',
})
Transforms.setNodes(
editor,
{ type: match ? 'paragraph' : 'code' },
{
match: n => Element.isElement(n) && Editor.isBlock(editor, n),
}
)
break
}
case 'b': {
event.preventDefault()
Editor.addMark(editor, 'bold', true)
break
}
}
}}
/>
</Slate>
)
}It has the concept of "code blocks" and "bold formatting". But these things are all defined in one-off cases inside the onKeyDown handler. If you wanted to reuse that logic elsewhere you'd need to extract it.
We can instead implement these domain-specific concepts by creating custom helper functions:
/* Detailed source-code truncated for AI context efficiency. */Now our commands are clearly defined and you can invoke them from anywhere we have access to our editor object. For example, from hypothetical toolbar buttons:
/* Detailed source-code truncated for AI context efficiency. */That's the benefit of extracting the logic.
For TypeScript, the same helpers can accept the mark and block names from your document model. This uses the CustomText and CustomElement definitions from the previous walkthroughs, plus Descendant, RenderElementProps and RenderLeafProps from the earlier typing steps.
/* Detailed source-code truncated for AI context efficiency. */And there you have it! We just added a ton of functionality to the editor with very little work. And we can keep all of our command logic tested and isolated in a single place, making the code easier to maintain.
Walkthroughs 06 Saving To A Database (`docs/walkthroughs/06-saving-to-a-database.md`)
Saving to a Database
Now that you've learned the basics of how to add functionality to the Slate editor, you might be wondering how you'd go about saving the content you've been editing, such that you can come back to your app later and have it load.
In this guide, we'll show you how to add logic to save your Slate content to a database for storage and retrieval later.
Let's start with a basic editor:
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable />
</Slate>
)
}That will render a basic Slate editor on your page, and when you type things will change. But if you refresh the page, everything will be reverted back to its original value—nothing saves!
What we need to do is save the changes you make somewhere. For this example, we'll just be using Local Storage, but it will give you an idea for where you'd need to add your own database hooks.
So, in our onChange handler, we need to save the value if anything besides the selection was changed:
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate
editor={editor}
initialValue={initialValue}
onChange={value => {
const isAstChange = editor.operations.some(
op => 'set_selection' !== op.type
)
if (isAstChange) {
// Save the value to Local Storage.
const content = JSON.stringify(value)
localStorage.setItem('content', content)
}
}}
>
<Editable />
</Slate>
)
}Now whenever you edit the page, if you look in Local Storage, you should see the content value changing.
But... if you refresh the page, everything is still reset. Import useMemo from React to read the initial value from Local Storage, like so. For TypeScript, use useMemo<Descendant[]> to keep the result typed as your document value.
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
// Update the initial content to be pulled from Local Storage if it exists.
const initialValue = useMemo(() => {
const content = localStorage.getItem('content')
return (
(content ? JSON.parse(content) : null) || [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
)
}, [])
return (
<Slate
editor={editor}
initialValue={initialValue}
onChange={value => {
const isAstChange = editor.operations.some(
op => 'set_selection' !== op.type
)
if (isAstChange) {
// Save the value to Local Storage.
const content = JSON.stringify(value)
localStorage.setItem('content', content)
}
}}
>
<Editable />
</Slate>
)
}Now you should be able to save changes across refreshes!
Success—you've got JSON in your database.
But what if you want something other than JSON? Well, you'd need to serialize your value differently. For example, if you want to save your content as plain text instead of JSON, we can write some logic to serialize and deserialize plain text values:
// Import the `Node` helper interface from Slate.
import { Node } from 'slate'
// Define a serializing function that takes a value and returns a string.
const serialize = value => {
return (
value
// Return the string content of each paragraph in the value's children.
.map(n => Node.string(n))
// Join them all with line breaks denoting paragraphs.
.join('\n')
)
}
// Define a deserializing function that takes a string and returns a value.
const deserialize = string => {
// Return a value array of children derived by splitting the string.
return string.split('\n').map(line => {
return {
type: 'paragraph',
children: [{ text: line }],
}
})
}
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
// Use our deserializing function to read the data from Local Storage.
const initialValue = useMemo(
() => deserialize(localStorage.getItem('content') ?? ''),
[]
)
return (
<Slate
editor={editor}
initialValue={initialValue}
onChange={value => {
const isAstChange = editor.operations.some(
op => 'set_selection' !== op.type
)
if (isAstChange) {
// Serialize the value and save the string value to Local Storage.
localStorage.setItem('content', serialize(value))
}
}}
>
<Editable />
</Slate>
)
}That works! Now you're working with plain text.
You can emulate this strategy for any format you like. You can serialize to HTML, to Markdown, or even to your own custom JSON format that is tailored to your use case.
🤖 Note that even though you can serialize your content however you like, there are tradeoffs. The serialization process has a cost itself, and certain formats may be harder to work with than others. In general we recommend writing your own format only if your use case has a specific need for it. Otherwise, you're often better leaving the data in the format Slate uses.
Changes from outside the editor
Use value and onValueChange when your app's state, such as useState or a store, owns the document:
import React, { useState } from 'react'
import { createEditor, Descendant } from 'slate'
import { Editable, Slate, withReact } from 'slate-react'
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
const [value, setValue] = useState<Descendant[]>([
{ type: 'paragraph', children: [{ text: '' }] },
])
return (
<Slate editor={editor} value={value} onValueChange={setValue}>
<Editable />
</Slate>
)
}Pass back the value from onValueChange; Slate recognizes that exact object and doesn't apply it again. Any other value is applied as a change from outside the editor, through operations, so the selection moves with it and withHistory records it as its own undo step. Values you pass in aren't reported back through onValueChange. Don't pass initialValue together with value.
Keep unchanged node objects in your updates, for example setValue(current => [current[0], updatedBlock]). Shared nodes moved between parents keep their selections. A rebuilt deep-equal copy produces no operations but costs a content comparison.
Don't pass a server's response to an earlier save into value while the user is typing: it describes an older document, and applying it reverts the newer typing. When your app decides a server change is new content, apply it with Transforms.setChildren(editor, nextValue). Direct assignment to editor.children bypasses selection mapping and history. To clear the editor, pass a schema-valid empty block such as [{ type: 'paragraph', children: [{ text: '' }] }].
To change how values are applied, override editor.setChildren, for example wrapping it in HistoryEditor.withoutSaving for a stream. Undo still reverts only the user's own edits, since saved steps are moved past unsaved changes. Updates wait while the user is composing text or Android has pending input.
See the controlled value API and the Controlled value example.
Walkthroughs 07 Enabling Collaborative Editing (`docs/walkthroughs/07-enabling-collaborative-editing.md`)
Enabling Collaborative Editing
For a runnable example without a server, see Collaboration with Yjs.
A common use case for text editors is collaborative editing, and the Slate editor was designed with this in
mind. You can enable multiplayer editing with Yjs, a network-agnostic CRDT implementation
that allows you to share data among connected users. Because Yjs is network-agnostic, each project requires
a communication provider to link users together; the transport can run in the browser or use a back end.
In this guide, we'll show you how to set up a collaborative Slate editor using a Yjs provider. We'll also be
adding slate-yjs which allows you to add multiplayer features to Slate, such
as live cursors.
Let's start with a basic editor. This example uses the earlier TypeScript declarations; JavaScript users can omit the Descendant[] annotation and its import.
import React, { useState } from 'react'
import { createEditor, Descendant } from 'slate'
import { Editable, Slate, withReact } from 'slate-react'
const initialValue: Descendant[] = [
{ type: 'paragraph', children: [{ text: '' }] },
]
export const CollaborativeEditor = () => {
return <SlateEditor />
}
const SlateEditor = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable />
</Slate>
)
}Yjs is network-agnostic, which means each Yjs provider is set up in a slightly different way. For
example @liveblocks/yjs is
fully-hosted, whereas others such as y-websocket require you to host your own
WebSocket server. Because of this, we'll use code snippets that work for each provider, without going into too much
detail about setting up the provider itself.
This is how to connect to a collaborative Yjs document, ready to be used in your Slate editor.
import { useEffect, useMemo, useState } from 'react'
import { createEditor, Editor, Transforms } from 'slate'
import { Editable, Slate, withReact } from 'slate-react'
import * as Y from 'yjs'
const initialValue = [{ type: 'paragraph', children: [{ text: '' }] }]
export const CollaborativeEditor = () => {
const [connected, setConnected] = useState(false)
const [sharedType, setSharedType] = useState()
const [provider, setProvider] = useState()
// Set up your Yjs provider and document
useEffect(() => {
const yDoc = new Y.Doc()
const sharedDoc = yDoc.get('slate', Y.XmlText)
// Set up your Yjs provider. This line of code is different for each provider.
const yProvider = new YjsProvider(/* ... */)
yProvider.on('sync', setConnected)
setSharedType(sharedDoc)
setProvider(yProvider)
return () => {
yDoc?.destroy()
yProvider?.off('sync', setConnected)
yProvider?.destroy()
}
}, [])
if (!connected || !sharedType || !provider) {
return <div>Loading…</div>
}
return <SlateEditor />
}
const SlateEditor = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable />
</Slate>
)
}After setting up your Yjs document like this, you can then link it your editor by passing down sharedType, which
contains the multiplayer text, and by using functions from slate-yjs. We're also passing down provider which will be
helpful later.
/* Detailed source-code truncated for AI context efficiency. */That's all you need to attach Yjs to Slate!
Let's look at a real-world example of setting up Yjs—here's a code snippet for setting up
a Liveblocks provider. Liveblocks uses the concept of rooms,
spaces where users can
collaborative. To use a Liveblocks provider, you join a multiplayer room with RoomProvider, then pass the room
to new LiveblocksProvider, along with the Yjs document.
import LiveblocksProvider from '@liveblocks/yjs'
import { RoomProvider, useRoom } from '../liveblocks.config'
// Join a Liveblocks room and show the editor after connecting
export const App = () => {
return (
<RoomProvider id="my-room-name" initialPresence={{}}>
<ClientSideSuspense fallback={<div>Loading…</div>}>
{() => <CollaborativeEditor />}
</ClientSideSuspense>
</RoomProvider>
)
}
export const CollaborativeEditor = () => {
const room = useRoom()
const [connected, setConnected] = useState(false)
const [sharedType, setSharedType] = useState()
const [provider, setProvider] = useState()
// Connect to your Yjs provider and document
useEffect(() => {
const yDoc = new Y.Doc()
const sharedDoc = yDoc.get('slate', Y.XmlText)
// Set up your Liveblocks provider with the current room and document
const yProvider = new LiveblocksProvider(room, yDoc)
yProvider.on('sync', setConnected)
setSharedType(sharedDoc)
setProvider(yProvider)
return () => {
yDoc?.destroy()
yProvider?.off('sync', setConnected)
yProvider?.destroy()
}
}, [room])
if (!connected || !sharedType || !provider) {
return <div>Loading…</div>
}
return <SlateEditor sharedType={sharedType} provider={provider} />
}
const SlateEditor = ({ sharedType, provider }) => {
// ...
}Unlike other providers, Liveblocks hosts your Yjs back end for you, which means you don't need to run your own server
to get this working. For more information on setting up Liveblocks providers, make sure to read
their Slate getting started guide.
Note that Liveblocks is independent of the Slate project, and isn't required for collaboration, but it may be
convenient depending on your needs. Other providers are available
should you wish to set up and host a Yjs back end yourself.
After setting up Yjs, it's possible to add multiplayer cursors to your app. You can do this with hooks supplied by
slate-yjs, which allow you to find the cursor positions of other users. Here's an example of setting up a cursor
component.
import {
CursorOverlayData,
useRemoteCursorOverlayPositions,
} from '@slate-yjs/react'
import { useRef } from 'react'
export function Cursors({ children }) {
const containerRef = useRef(null)
const [cursors] = useRemoteCursorOverlayPositions({ containerRef })
return (
<div className="cursors" ref={containerRef}>
{children}
{cursors.map(cursor => (
<Selection key={cursor.clientId} {...cursor} />
))}
</div>
)
}
function Selection({ data, selectionRects, caretPosition }) {
if (!data) {
return null
}
const selectionStyle = {
backgroundColor: data.color,
}
return (
<>
{selectionRects.map((position, i) => (
<div
style={{ ...selectionStyle, ...position }}
className="selection"
key={i}
/>
))}
{caretPosition && <Caret caretPosition={caretPosition} data={data} />}
</>
)
}
function Caret({ caretPosition, data }) {
const caretStyle = {
...caretPosition,
background: data?.color,
}
const labelStyle = {
transform: 'translateY(-100%)',
background: data?.color,
}
return (
<div style={caretStyle} className="caretMarker">
<div className="caret" style={labelStyle}>
{data?.name}
</div>
</div>
)
}With some matching styles to set up the positioning:
.cursors {
position: relative;
}
.caretMarker {
position: absolute;
width: 2px;
}
.caret {
position: absolute;
font-size: 14px;
color: #fff;
white-space: nowrap;
top: 0;
border-radius: 6px;
border-bottom-left-radius: 0;
padding: 2px 6px;
pointer-events: none;
}
.selection {
position: absolute;
pointer-events: none;
opacity: 0.2;
}You can then import this into your SlateEditor component. Notice that we're using withCursors from slate-yjs,
adding provider.awareness and the current user's name to it. We're then wrapping <Editable> in the new <Cursors>
component we've just created.
import { useEffect, useMemo, useState } from 'react'
import { createEditor, Editor, Transforms } from 'slate'
import { Editable, Slate, withReact } from 'slate-react'
import { withCursors, withYjs, YjsEditor } from '@slate-yjs/core'
import { Cursors } from './Cursors'
import * as Y from 'yjs'
export const CollaborativeEditor = () => {
// ...
}
const SlateEditor = ({ sharedType, provider }) => {
const editor = useMemo(() => {
const e = withReact(
withCursors(withYjs(createEditor(), sharedType), provider.awareness, {
// The current user's name and color
data: {
name: 'Chris',
color: '#00ff00',
},
})
)
// Ensure editor always has at least 1 valid child
const { normalizeNode } = e
e.normalizeNode = (entry, options) => {
const [node] = entry
if (!Editor.isEditor(node) || node.children.length > 0) {
return normalizeNode(entry, options)
}
Transforms.insertNodes(editor, initialValue, { at: [0] })
}
return e
}, [])
useEffect(() => {
YjsEditor.connect(editor)
return () => YjsEditor.disconnect(editor)
}, [editor])
return (
<Slate editor={editor} initialValue={initialValue}>
<Cursors>
<Editable />
</Cursors>
</Slate>
)
}You should now be seeing multiplayer cursors! To learn more, make sure to read
the slate-yjs documentation.
Walkthroughs 08 Using The Bundled Source (`docs/walkthroughs/08-using-the-bundled-source.md`)
Using the Bundled Source
For most folks, you'll want to install Slate via npm, in which case you can follow the regular Installing Slate guide.
But, if you'd rather install Slate by simply adding a <script> tag to your application, this guide will help you. To make the "bundled" use case simpler, each version of Slate ships with a bundled source file called slate.js.
To get a copy of slate.js, download the version of Slate you want from npm:
npm install slate@latestAnd then look in the node_modules folder for the bundled slate.js file:
node_modules/
slate/
dist/
slate.js
slate.min.jsA minified version called slate.min.js is also included for convenience.
Before you can add slate.js to your page, you need to bring your own copy of react, react-dom and react-dom-server, like so:
<script src="./vendor/react.js"></script>
<script src="./vendor/react-dom.js"></script>
<script src="./vendor/react-dom-server.js"></script>This ensures that Slate isn't bundling its own copy of React, which would greatly increase the file size of your application.
Then you can add slate.js after those includes:
<script src="./vendor/slate.js"></script>To make things easier, for quick prototyping, you can also use the unpkg.com delivery network that makes working with bundled npm modules easier. In that case, your includes would look like:
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom-server.browser.production.min.js"></script>
<script src="https://unpkg.com/slate/dist/slate.js"></script>
<script src="https://unpkg.com/slate-react/dist/slate-react.js"></script>That's it, you're ready to go!
Walkthroughs 09 Performance (`docs/walkthroughs/09-performance.md`)
Improving Performance
When building a text editor, it's important for user interactions to take place without any noticeable delay. For small and moderately sized documents (less than 1000 blocks), you probably don't need to worry about performance. If your editor needs to support very large documents (10,000+ or 100,000+ blocks), follow this guide to ensure the editor stays responsive.
The Huge Document example contains an interactive playground where you can explore the effect of various factors on the performance of a very simple Slate editor.
The type of performance this guide is mostly concerned with is the Interaction to Next Paint (INP) while typing. If the INP is below roughly 100ms, typing should feel very responsive. The editor will still be usable when the INP duration is longer, but it will feel increasingly sluggish and unpleasant to use.
Other performance metrics to be aware of (but which are not currently covered in this guide) are time to first paint and the INP when performing non-typing operations (such as selecting all content or pasting).
INP is easiest to measure in Chrome using the Performance panel in DevTools, but there are ways to determine it in Firefox and Safari too. For example, in Firefox, you can use the Firefox Profiler to see a timeline of events.
There are three main areas that can be optimized:
Before you start optimizing, make sure you know which of these areas is most responsible for any slowness you're seeing. The best way of doing this is to use your browser's profiler (see the example for Firefox above), but you can also use these heuristics to guess which area is most at fault:
- If performance is much better in Firefox than in Chrome or Safari, DOM painting is usually the problem (tested May 2025).
- If disabling any custom normalization logic improves performance, the normalization logic is the problem.
- Otherwise, it's likely to be React.
Optimizing Slate Core
Usually, if the core Slate logic is causing a noticeable delay, it's because of normalizing. If custom normalization logic is causing slowness in your app, consider whether the logic can be made more efficient.
Understand that normalizeNode is called once for every modified node and every ancestor of a modified node. As a result, normalizeNode is called for the editor node whenever anything changes in the editor, but for other nodes it is called much less frequently.
Make sure you only normalize the node passed into normalizeNode and (occasionally) its direct children, not its children's descendants. Normalization logic should only be applied directly to the editor node when absolutely necessary, such when enforcing that the last block in the document is a paragraph.
Optimizing React
Reduce Renders
The renderElement prop and any React component it returns will re-render every time the element or any of its descendants changes. This is unavoidable. However, sometimes custom logic can cause React components to re-render more often than this, which can have a detrimental effect on performance.
Ensure that function props such as renderElement, renderLeaf, renderChunk and decorate do not change on every render. Either they should be defined at the top level of the file (not inside a component or hook), or they should be wrapped inside a useCallback and all dependencies should be properly memoized.
If unmodified elements are being re-rendered, check to see if they are subscribing to any contexts or hooks that are causing unnecessary re-renders. You can also apply these techniques to any toolbars or other non-element React components that may be re-rendering in response to changes in the editor.
The useSlate, useSlateSelection, useSlateSelector, useSelected and useFocused hooks cause React components to re-render in various circumstances. If you're using useSlate, consider if you can use useSlateStatic (which does not cause re-renders) instead. If you're using useSlateSelection, consider using editor.selection. If you only care about some value derived from the editor (such as whether a given mark is active), use useSlateSelector to only re-render when this value changes.
If your components depend on custom React contexts containing non-primitive values (such as objects or arrays), ensure that these values are properly memoized so that components only re-render when these values change. In some circumstances, you may instead want to consider passing a ref object or an unchanging getter function to retrieve the latest value.
// Provider
const myDataRef = useRef(myData)
myDataRef.current = myData
return <MyContext.Provider value={myDataRef}>{children}</MyContext.Provider>
// Consumer
// Does not re-render when `myData` changes
const myDataRef = useContext(MyContext)
const onClick = () => {
console.log(myDataRef.current)
}Enable Chunking (experimental)
Chunking is an internal optimization used by slate-react, and must be explicitly enabled. It works by splitting a node's children into nested "chunks", each of which is a separately memoized React component. This reduces the amount of work React needs to do when processing changes to the JSX, resulting in a 10x speed-up in ideal circumstances.
To enable chunking, you need to implement editor.getChunkSize(node: Ancestor) => number | null, which controls the number of nodes per lowest-level chunk for a given parent node. In most circumstances, setting the chunk size to 1000 for the editor and null for all other ancestors works well.
editor.getChunkSize = node => (Editor.isEditor(node) ? 1000 : null)Note that chunking can only be enabled for nodes whose children are all block elements. Attempting to enable chunking for leaf blocks (blocks containing inline nodes) will have no effect.
By default, chunking has no effect on the DOM. You can override this by passing a renderChunk prop to Editable.
Optimizing DOM Painting
In Chrome and Safari, painting large numbers of DOM nodes can be extremely slow, over 100x slower than the core Slate logic and React rendering combined in some cases. In Firefox, the impact of painting on performance is much less significant.
The best way of speeding up painting large documents is to use the content-visibility CSS property. When set to auto, this property instructs browsers not to paint content that is off-screen. However, it also comes with a performance overhead proportional to the number of DOM nodes it is applied to, which is especially bad in Safari. When rendering large documents in Safari, applying content-visibility: auto to each Slate element individually is often slower than not using it at all.
The recommended solution is to enable chunking and apply content-visibility: auto on each lowest-level chunk by passing a renderChunk prop to Editable.
const renderChunk = ({ attributes, lowest, children }: RenderChunkProps) => (
<div
{...attributes}
style={lowest ? { contentVisibility: 'auto' } : undefined}
>
{children}
</div>
)Note that this will modify the DOM structure of your editor, which may have adverse effects on its appearance. During development, it is recommended to set the chunk size to a small number such as 3 so that styling issues caused by nested chunks are easier to detect.
If you previously had a CSS rule such as this to apply spacing between top-level blocks:
[data-slate-editor] > * + * {
margin-top: 1em;
}It should be changed to this:
[data-slate-editor] > * + *,
[data-slate-chunk] > * + * {
margin-top: 1em;
}Also bear in mind this warning about content-visibility: auto from MDN:
Since styles for off-screen content are not rendered, elements intentionally hidden with
display: noneorvisibility: hiddenwill still appear in the accessibility tree. If you don't want an element to appear in the accessibility tree, usearia-hidden="true".
Walkthroughs 10 Collaboration With Yjs (`docs/walkthroughs/10-collaboration-with-yjs.md`)
Collaboration with Yjs
The collaboration example shows two editors sharing one document without a server. You can also open the example in another tab of the same browser. It uses @slate-yjs/core to bind Slate to Yjs and BroadcastChannel to exchange Yjs updates between tabs on the same origin. The document lasts while a tab is open; it is not saved.
What synchronizes
Each editor has its own Slate value, selection, history and Y.Doc. Its binding points to the Y.XmlText named content in that document. The binding translates local Slate operations into Yjs changes and applies incoming Yjs changes to Slate. Sending the whole Slate value after every keystroke would overwrite edits made elsewhere; exchanging Yjs updates lets Yjs merge changes instead.
Each editor opens its own BroadcastChannel with the same name, so updates reach the other editor on the page as well as editors in other tabs. On opening, it asks the others for their current state, then exchanges subsequent updates. Updates received from the channel use the channel as their transaction origin, so they are not broadcast again. This transport works within the same browser and origin; it does not connect different browsers or devices.
The example initializes every document from an identical template update containing one empty paragraph. Only the temporary template has a fixed client ID; each editable document keeps its randomly generated ID. This lets a new tab merge the same starting paragraph instead of inserting a second independent paragraph. In an application, load an existing shared document or initialize it once, rather than having each client independently insert the initial content.
Plugin order and lifecycle
Create the plugins from the inside out:
const editor = withReact(withYHistory(withYjs(createEditor(), sharedType)))withYjs installs the operation binding first. withYHistory adds history based on those Yjs transactions. withReact adapts the resulting editor to React and the DOM. Call YjsEditor.connect(editor) after mounting the Slate provider and YjsEditor.disconnect(editor) on cleanup. The shared Yjs document supplies the connected editor's content; Slate's initialValue is not the synchronization mechanism.
Keep normalization consistent across clients. The example inserts an empty paragraph if deleting the whole document leaves the editor with no children. A production schema also needs every client to agree on how to normalize its elements.
Selection during remote changes
Bindings should wrap incoming operations in Editor.withRemoteChanges(editor, fn). The synchronous scope uses inward affinity for an expanded selection: if Bob inserts at the end of Alice's selected word, Alice keeps the same word selected. Collapsed carets and local editing outside the scope keep their existing behavior. The flag is available through Editor.isRemoteChange(editor) and is restored when a nested scope or exception exits. This affects selection tracking only, not merging concurrent edits or saving history.
@slate-yjs/core 1.0.2 exposes editor.applyRemoteEvents. The example wraps that method after creating the editor:
const { applyRemoteEvents } = editor
editor.applyRemoteEvents = (events, origin) => {
Editor.withRemoteChanges(editor, () => applyRemoteEvents(events, origin))
}Undo
Use withYHistory instead of layering withHistory onto the collaborative editor. Its undo manager tracks each editor's local origin, so Alice's Undo reverses Alice's edits while retaining Bob's edits. Undo and redo produce shared changes and therefore update every connected view. The example exposes buttons for each editor and destroys each document and its undo manager when the example unmounts.
What belongs outside Slate
Slate provides the document model, operations, transforms, normalization and React editing surface. It does not merge concurrent edits, host rooms, persist documents, authenticate users or distribute cursor presence. Here Yjs merges document changes, the binding translates them, and BroadcastChannel transports updates.
For collaboration across devices, replace the example's channel with a provider such as y-websocket, y-webrtc or a hosted provider. WebRTC providers typically still need signaling. Add storage, authorization and room boundaries for your application.
Remote cursors are separate from document synchronization. @slate-yjs/react provides cursor hooks. Separate documents give each participant a distinct client ID, but cursors still need an awareness transport, presence cleanup and selection rendering. This example omits that additional setup to focus on document synchronization. See the collaborative editing guide for a provider with awareness.
Versions
The example pins @slate-yjs/core to 1.0.2 and yjs to 13.6.33. The binding declares slate >=0.70.0 and yjs ^13.5.29; this repo's Slate and the pinned Yjs version satisfy those ranges. Those ranges are a compatibility declaration, not a claim that this example has tested every accepted version. The example tests cover this repo's current versions.
Read the slate-yjs documentation and Yjs update API for the binding and transport APIs.
Walkthroughs 11 Accessibility (`docs/walkthroughs/11-accessibility.md`)
Accessibility
Slate renders the editable root as a contenteditable element with role="textbox" and aria-multiline="true". Everything else that makes an editor usable with a screen reader or a keyboard depends on what you render, so this guide lists what Slate does for you and what you need to add.
Name the editor
A textbox without a name is announced as just "edit text". Pass aria-label or aria-labelledby to Editable; it forwards them to the root element.
<h2 id="comment-heading">Comment</h2>
<Editable aria-labelledby="comment-heading" />When the page has a visible heading or label for the editor, prefer aria-labelledby so the visible text and the announced name stay the same.
Any other aria-* attribute you pass to Editable also lands on the root, such as aria-describedby, or aria-autocomplete, aria-controls and aria-activedescendant when the editor is the input of a combobox or mention picker.
Placeholders
While the placeholder is visible, Slate sets aria-placeholder on the root, and marks the visual placeholder aria-hidden, so assistive technology announces the hint once, as a hint, instead of reading it as document content.
If you pass renderPlaceholder, spread the attributes you receive onto your element to keep that behavior.
Read-only editors
With readOnly, Slate removes role="textbox" and aria-multiline, because the content is no longer editable. The root is then a plain div, and ARIA doesn't allow naming one, so screen readers may ignore an aria-label on it. If read-only content needs a name, wrap it in a labelled landmark instead:
<section aria-label="Release notes">
<Editable readOnly />
</section>Toolbars
- Render toolbar controls as `` elements, so they are focusable and activate with Enter and Space.
- Give icon-only buttons an
aria-label. - Set
aria-pressedon buttons that toggle a mark or block type, so their state is announced. - Call
event.preventDefault()inonPointerDown. Then a click doesn't move focus or the selection out of the editor.
The shared Button in the examples sets aria-pressed from its active prop.
Voids and embedded controls
Controls rendered inside void elements, such as inputs in an editable void or a URL field under an embed, need their own labels like any other form control: a <label> around the input, or an aria-label. Give embedded `` elements a title.
Images need an alt. When your image elements don't store a description, alt="" is the honest choice: it marks the image as decorative rather than having the file name announced.
Keyboard
Editable doesn't handle Tab, so Tab and Shift+Tab move focus into and out of the editor. If you bind Tab to indentation or list nesting, give keyboard users another way to leave the editor, and document it near the editor.
Testing
Automated checkers such as axe-core catch missing names, labels and contrast problems, and are worth running against your editor. They can't tell you whether editing works with a screen reader. Check that by typing, selecting and using your toolbar with VoiceOver on macOS or iOS, and NVDA or JAWS on Windows.
Api Locations Location (`docs/api/locations/location.md`)
Location API
The Location interface is a union of the ways to refer to a specific location in a Slate document: paths, points or ranges. Methods will often accept a Location instead of requiring only a Path, Point or Range.
type Location = Path | Point | RangeStatic methods
Check methods
`Location.isLocation(value: any) => value is Location`
Check if a value implements the Location interface.
Api Locations Path Ref (`docs/api/locations/path-ref.md`)
PathRef API
PathRef objects keep a specific path in a document synced over time as new operations are applied to the editor. It is created using the Editor.pathRef method. You can access their property current at any time for the up-to-date Path value. When you no longer need to track this location, call unref() to free the resources. The affinity refers to the direction the PathRef will go when a user inserts content at the current position of the Path.
interface PathRef {
current: Path | null
affinity: 'forward' | 'backward' | null
unref(): Path | null
[Symbol.dispose](): void
}Instance methods
`unref() => Path | null`
Free the resources used by the PathRef. This should be called when you no longer need to track the path. Returns the final path value before being unrefed, or null if the path was already invalid.
This removes the ref from Editor.pathRefs(editor) and sets current to null. If an operation removes the tracked node, the editor releases the ref automatically. Calling unref() again returns null.
`[Symbol.dispose]() => void`
Release the ref by calling unref(). This supports using declarations in runtimes or build tools with explicit resource management support. Repeated disposal is safe, including after an operation removes the tracked location.
TypeScript consumers need TypeScript 5.2 or later with esnext.disposable in their lib configuration. If the runtime lacks Symbol.dispose, install a polyfill before creating refs to use using; the fallback key is Symbol.for('Symbol.dispose'). Calling unref() continues to work without a polyfill.
Static methods
Transform methods
`PathRef.transform(ref: PathRef, op: Operation)`
Transform the path refs current value by an op.
The editor calls this as needed, so normally you won't need to.
Api Locations Path (`docs/api/locations/path.md`)
Path API
Path arrays are a list of indexes that describe a node's exact position in a Slate node tree. Although they are usually relative to the root Editor object, they can be relative to any Node object.
type Path = number[]Static methods
Retrieval methods
`Path.ancestors(path: Path, options: { reverse?: boolean } = {}) => Path[]`
Get a list of ancestor paths for a given path.
The paths are sorted from shallowest to deepest ancestor. However, if the reverse: true option is passed, they are reversed.
`Path.common(path: Path, another: Path) => Path`
Get the common ancestor path of two paths.
`Path.compare(path: Path, another: Path) => -1 | 0 | 1`
Compare a path to another, returning an integer indicating whether the path was before, at, or after the other.
Note: Two paths of unequal length can still receive a 0 result if one is directly above or below the other. If you want exact matching, use [[Path.equals]] instead.
`Path.levels(path: Path, options?) => Path[]`
Get a list of paths at every level down to a path. Note: this is the same as Path.ancestors, but includes the path itself.
The paths are sorted from shallowest to deepest. However, if the reverse: true option is passed, they are reversed.
Options: {reverse?: boolean}
`Path.next(path: Path) => Path`
Given a path, gets the path to the next sibling node. The method does not ensure that the returned Path is valid in the document.
`Path.parent(path: Path) => Path`
Given a path, return a new path referring to the parent node above it. If the path argument is equal to [], throws an error.
`Path.previous(path: Path) => Path`
Given a path, get the path to the previous sibling node. The method will throw an error if there are no previous siblings (e.g. if the Path is currently [1, 0], the previous path would be [1, -1] which is illegal and will throw an error).
`Path.relative(path: Path, ancestor: Path) => Path`
Given two paths, one that is an ancestor to the other, returns the relative path from the ancestor argument to the path argument. If the ancestor path is not actually an ancestor or equal to the path argument, throws an error.
Check methods
Check some attribute of a path. Always returns a boolean.
`Path.endsAfter(path: Path, another: Path) => boolean`
Check if a path ends after one of the indexes in another.
`Path.endsAt(path: Path, another: Path) => boolean`
Check if a path ends at one of the indexes in another.
`Path.endsBefore(path: Path, another: Path) => boolean`
Check if a path ends before one of the indexes in another.
`Path.equals(path: Path, another: Path) => boolean`
Check if a path is exactly equal to another.
`Path.hasPrevious(path: Path) => boolean`
Check if the path of previous sibling node exists
`Path.isAfter(path: Path, another: Path) => boolean`
Check if a path is after another.
`Path.isAncestor(path: Path, another: Path) => boolean`
Check if a path is an ancestor of another.
`Path.isBefore(path: Path, another: Path) => boolean`
Check if a path is before another.
`Path.isChild(path: Path, another: Path) => boolean`
Check if a path is a child of another.
`Path.isCommon(path: Path, another: Path) => boolean`
Check if a path is equal to or an ancestor of another.
`Path.isDescendant(path: Path, another: Path) => boolean`
Check if a path is a descendant of another.
`Path.isParent(path: Path, another: Path) => boolean`
Check if a path is the parent of another.
`Path.isPath(value: any) => value is Path`
Check is a value implements the Path interface.
`Path.isSibling(path: Path, another: Path) => boolean`
Check if a path is a sibling of another.
`Path.operationCanTransformPath(operation: Operation) => operation is InsertNodeOperation | RemoveNodeOperation | MergeNodeOperation | SplitNodeOperation | MoveNodeOperation`
Returns whether this operation can affect paths or not.
Transform method
`Path.transform(path: Path, operation: Operation, options?) => Path | null`
Transform a path by an operation.
Options: { affinity?: 'forward' | 'backward' | null }
Api Locations Point Entry (`docs/api/locations/point-entry.md`)
PointEntry API
PointEntry objects are returned when iterating over Point objects that belong to a range.
type PointEntry = [Point, 'anchor' | 'focus']Api Locations Point Ref (`docs/api/locations/point-ref.md`)
PointRef API
PointRef objects keep a specific point in a document synced over time as new operations are applied to the editor. It is created using the Editor.pointRef method. You can access their property current at any time for the up-to-date Point value. When you no longer need to track this location, call unref() to free the resources. The affinity refers to the direction the PointRef will go when a user inserts content at the current position of the Point.
interface PointRef {
current: Point | null
affinity: 'forward' | 'backward' | null
unref(): Point | null
[Symbol.dispose](): void
}Instance methods
`unref() => Point | null`
Call this when you no longer need to sync this point.
It also returns the current value.
This removes the ref from Editor.pointRefs(editor) and sets current to null. If an operation removes the node containing the point, the editor releases the ref automatically. Calling unref() again returns null.
`[Symbol.dispose]() => void`
Release the ref by calling unref(). This supports using declarations in runtimes or build tools with explicit resource management support. Repeated disposal is safe, including after an operation removes the tracked location.
TypeScript consumers need TypeScript 5.2 or later with esnext.disposable in their lib configuration. If the runtime lacks Symbol.dispose, install a polyfill before creating refs to use using; the fallback key is Symbol.for('Symbol.dispose'). Calling unref() continues to work without a polyfill.
Static methods
Transform methods
`PointRef.transform(ref: PointRef, op: Operation)`
Transform the point refs current value by an op.
The editor calls this as needed, so normally you won't need to.
Api Locations Point (`docs/api/locations/point.md`)
Point API
Point objects refer to a specific location in a text node in a Slate document. Its path refers to the location of the node in the tree, and its offset refers to distance into the node's string of text. Points may only refer to Text nodes.
interface Point {
path: Path
offset: number
}Static methods
Retrieval methods
`Point.compare(point: Point, another: Point) => -1 | 0 | 1`
Compare a point to another, returning an integer indicating whether the point was before, at or after the other.
Check methods
`Point.isAfter(point: Point, another: Point) => boolean`
Check if a point is after another.
`Point.isBefore(point: Point, another: Point) => boolean`
Check if a point is before another.
`Point.equals(point: Point, another: Point) => boolean`
Check if a point is exactly equal to another.
`Point.isPoint(value: any) => value is Point`
Check if a value implements the Point interface.
Transform methods
`Point.transform(point: Point, op: Operation, options?) => Point | null`
Transform a point by an op.
Options: {affinity?: 'forward' | 'backward' | null}
Api Locations Range Ref (`docs/api/locations/range-ref.md`)
RangeRef API
RangeRef objects keep a specific range in a document synced over time as new operations are applied to the editor. It is created using the Editor.rangeRef method. You can access their property current at any time for the up-to-date Range value. When you no longer need to track this location, call unref() to free the resources. The affinity refers to the direction the RangeRef will go when a user inserts content at the edges of the Range. inward means that the Range tends to stay the same size when content is inserted at its edges, and outward means that the Range tends to grow when content is inserted at its edges.
interface RangeRef {
current: Range | null
affinity: 'forward' | 'backward' | 'outward' | 'inward' | null
unref(): Range | null
[Symbol.dispose](): void
}For example:
const selectionRef = Editor.rangeRef(editor, editor.selection, {
affinity: 'inward',
})
// Allow the user to do stuff which might change the selection
Transforms.unwrapNodes(editor)
Transforms.select(editor, selectionRef.unref())Instance methods
`unref() => Range | null`
Call this when you no longer need to sync this range.
It also returns the current value.
This removes the ref from Editor.rangeRefs(editor) and sets current to null. If an operation removes a node containing either endpoint, the editor releases the ref automatically. Calling unref() again returns null.
`[Symbol.dispose]() => void`
Release the ref by calling unref(). This supports using declarations in runtimes or build tools with explicit resource management support. Repeated disposal is safe, including after an operation removes the tracked location.
TypeScript consumers need TypeScript 5.2 or later with esnext.disposable in their lib configuration. If the runtime lacks Symbol.dispose, install a polyfill before creating refs to use using; the fallback key is Symbol.for('Symbol.dispose'). Calling unref() continues to work without a polyfill.
Static methods
Transform methods
`RangeRef.transform(ref: RangeRef, op: Operation)`
Transform the range refs current value by an op.
The editor calls this as needed, so normally you won't need to.
Api Locations Range (`docs/api/locations/range.md`)
Range API
Range objects are a set of points that refer to a specific span of a Slate document. They can define a span inside a single node or they can span across multiple nodes. The editor's selection is stored as a range.
interface Range {
anchor: Point
focus: Point
}Static methods
Retrieval methods
`Range.direction(range: Range) => 'forward' | 'backward' | 'collapsed'`
Get the direction of a range: 'forward' when the focus point comes after the anchor point, 'backward' when it comes before, and 'collapsed' when they're at the same position.
`Range.edges(range: Range, options?) => [Point, Point]`
Get the start and end points of a range, in the order in which they appear in the document.
Options: {reverse?: boolean}
`Range.end(range: Range) => Point`
Get the end point of a range according to the order in which it appears in the document.
`Range.intersection(range: Range, another: Range) => Range | null`
Get the intersection of one range with another. If the two ranges do not overlap, return null.
`Range.points(range: Range) => Generator`
Iterate through the two point entries in a Range. First it will yield a PointEntry representing the anchor, then it will yield a PointEntry representing the focus.
`Range.start(range: Range) => Point`
Get the start point of a range according to the order in which it appears in the document.
Check methods
Check some attribute of a Range. Always returns a boolean.
`Range.equals(range: Range, another: Range) => boolean`
Check if a range is exactly equal to another.
`Range.includes(range: Range, target: Path | Point | Range) => boolean`
Check if a range includes a path, a point, or part of another range.
For clarity the definition of includes can mean partially includes. Another way to describe this is if one Range intersects the other Range.
`Range.surrounds(range: Range, target: Range) => boolean`
Check if a range includes another range.
`Range.isBackward(range: Range) => boolean`
Check if a range is backward, meaning that its anchor point appears after its focus point in the document. A collapsed range is not backward.
`Range.isCollapsed(range: Range) => boolean`
Check if a range is collapsed, meaning that both its anchor and focus points refer to the exact same position in the document.
`Range.isExpanded(range: Range) => boolean`
Check if a range is expanded. This is the opposite of Range.isCollapsed and is provided for legibility.
`Range.isForward(range: Range) => boolean`
Check if a range is forward. This is the opposite of Range.isBackward and is provided for legibility, so a collapsed range counts as forward. Use Range.direction to tell collapsed ranges apart.
`Range.isRange(value: any) => value is Range`
Check if a value implements the Range interface.
Transform methods
`Range.transform(range: Range, op: Operation, options) => Range | null`
Transform a range by an op.
Options: {affinity: 'forward' | 'backward' | 'outward' | 'inward' | null}
Api Locations Span (`docs/api/locations/span.md`)
Span API
A Span is a low-level way to refer to a Range using Element as the end points instead of a Point which requires the use of leaf text nodes.
type Span = [Path, Path]Static Methods
Check Methods
`Span.isSpan(value: any) => value is Span`
Check if a value implements the Span interface.
Api Nodes Editor (`docs/api/nodes/editor.md`)
Editor API
The Editor object stores all the state of a Slate editor. It can be extended by plugins to add helpers and implement new behaviors. It's a type of Node and its path is [].
interface Editor {
children: Node[]
selection: Range | null
operations: Operation[]
marks: Omit<Text, 'text'> | null
// Schema-specific node behaviors.
isInline: (element: Element) => boolean
isIsolated: (element: Element) => boolean
isVoid: (element: Element) => boolean
markableVoid: (element: Element) => boolean
inlineEdgeAffinity: (
element: Element,
edge: 'start' | 'end'
) => 'inside' | 'outside' | null
leafEdgeAffinity: (before: Text, after: Text) => 'backward' | 'forward' | null
getSplitProperties: (node: Element | Text, path: Path) => Partial<Node>
normalizeNode: (entry: NodeEntry) => void
onChange: (options?: { operation?: Operation }) => void
// Overrideable core actions.
addMark: (key: string, value: any) => void
apply: (operation: Operation) => void
deleteBackward: (unit: 'character' | 'word' | 'line' | 'block') => void
deleteForward: (unit: 'character' | 'word' | 'line' | 'block') => void
deleteFragment: () => void
insertBreak: () => void
insertFragment: (fragment: Node[]) => void
insertNode: (node: Node) => void
insertText: (text: string) => void
removeMark: (key: string) => void
}Instantiation methods
`createEditor() => Editor`
Note: This method is imported directly from Slate and is not part of the Editor object.
Creates a new, empty Editor object.
Static methods
Retrieval methods
`Editor.above(editor: Editor, options?) => NodeEntry | undefined`
Get the matching ancestor above a location in the document.
Options:
at?: Location = editor.selection: Where to start at which iseditor.selectionby default.match?: NodeMatch = () => true: Narrow the matchmode?: 'highest' | 'lowest' = 'lowest': Iflowest(default), returns the lowest matching ancestor. Ifhighest, returns the highest matching ancestor.voids?: boolean = false: Whenfalseignore void objects.
`Editor.after(editor: Editor, at: Location, options?) => Point | undefined`
Get the point after a location.
If there is no point after the location (e.g. we are at the bottom of the document) returns undefined.
Options: {distance?: number, unit?: 'offset' | 'character' | 'word' | 'line' | 'block', voids?: boolean}
For unit: 'word', isWordCharacter?: (character: string) => boolean customizes word boundaries. The callback receives a whole grapheme, including a combined character or emoji. For example, isWordCharacter: character => /[\w-]/.test(character) treats foo-bar_baz as one word. A custom callback replaces the default punctuation rules and language segmentation; it is ignored for other units.
`Editor.before(editor: Editor, at: Location, options?) => Point | undefined`
Get the point before a location.
If there is no point before the location (e.g. we are at the top of the document) returns undefined.
Options: {distance?: number, unit?: 'offset' | 'character' | 'word' | 'line' | 'block', voids?: boolean}
For unit: 'word', isWordCharacter?: (character: string) => boolean customizes word boundaries. The callback receives a whole grapheme, including a combined character or emoji. For example, isWordCharacter: character => /[\w-]/.test(character) treats foo-bar_baz as one word. A custom callback replaces the default punctuation rules and language segmentation; it is ignored for other units.
`Editor.edges(editor: Editor, at: Location) => [Point, Point]`
Get the start and end points of a location.
`Editor.end(editor: Editor, at: Location) => Point`
Get the end point of a location.
`Editor.first(editor: Editor, at: Location) => NodeEntry`
Get the first node at a location.
`Editor.fragment(editor: Editor, at: Location) => Descendant[]`
Get the fragment at a location.
`Editor.last(editor: Editor, at: Location) => NodeEntry`
Get the last node at a location.
`Editor.leaf(editor: Editor, at: Location, options?) => NodeEntry`
Get the leaf text node at a location.
Options: {depth?: number, edge?: 'start' | 'end'}
`Editor.levels(editor: Editor, options?) => Generator, void, undefined>`
Iterate through all of the levels at a location.
Options: {at?: Location, match?: NodeMatch, reverse?: boolean, voids?: boolean}
`Editor.insertionPoint(editor: Editor, point: Point) => Point`
Resolve a caret to the point that implicit insertion will use. Applies inlineEdgeAffinity first, then leafEdgeAffinity, with at most one move for each rule. Both default to null, which preserves the supplied point. The helper does not change the selection.
The rules apply to editor.insertText, insertFragment and insertion of inline elements with insertNodes only when at is omitted and the selection is collapsed. Explicit locations, expanded selections, and insertion of text or block nodes through insertNodes retain their existing behavior. IME composition remains native; these rules govern committed insertion.
`Editor.marks(editor: Editor) => Omit | null`
Get the marks that would be added to text at the current selection.
At a collapsed caret with a non-null edge rule, returns the receiving leaf’s marks, unless explicit editor.marks are set. When both edge rules return null, the existing previous-leaf behavior at offset zero is preserved.
If editor.marks is set (marks toggled with a collapsed selection), those are returned. With an expanded selection, it returns the marks of the first text node in the selection, skipping a node the selection only touches at its end, so it describes what typing over the selection would produce rather than marks shared by the whole selection. To check whether a mark applies to all of the selected text, iterate Editor.nodes(editor, { match: Text.isText }) and compare each node.
`Editor.next(editor: Editor, options?) => NodeEntry | undefined`
Get the matching node in the branch of the document after a location.
Note: To find the next Point, and not the next Node, use the Editor.after method
Options: {at?: Location, match?: NodeMatch, mode?: 'all' | 'highest' | 'lowest', voids?: boolean}
`Editor.node(editor: Editor, at: Location, options?) => NodeEntry`
Get the node at a location.
Options: depth?: number, edge?: 'start' | 'end'
`Editor.nodes(editor: Editor, options?) => Generator, void, undefined>`
At any given Location or Span in the editor provided by at (default is the current selection), the method returns a Generator of NodeEntry objects that represent the nodes that include at. At the top of the hierarchy is the Editor object itself.
Options: {at?: Location | Span, match?: NodeMatch, mode?: 'all' | 'highest' | 'lowest', universal?: boolean, reverse?: boolean, voids?: boolean, pass?: (node: NodeEntry => boolean)}
options.match: Provide a value to the match? option to limit the NodeEntry objects that are returned.
options.mode:
'all'(default): Return all matching nodes'highest': in a hierarchy of nodes, only return the highest level matching nodes'lowest': in a hierarchy of nodes, only return the lowest level matching nodes
options.pass: Skip the descendants of certain nodes (but not the nodes themselves).
options.reverse: Walk siblings from last to first. Ancestors still come before their descendants, so this isn't the forward order reversed: for [block[text a, text b], block[text c]] the forward order is editor, 0, 0.0, 0.1, 1, 1.0 and the reverse order is editor, 1, 1.0, 0, 0.1, 0.0. To get the exact reverse, collect the forward entries and reverse the array.
`Editor.parent(editor: Editor, at: Location, options?) => NodeEntry`
Get the parent node of a location.
Options: {depth?: number, edge?: 'start' | 'end'}
`Editor.path(editor: Editor, at: Location, options?) => Path`
Get the path of a location.
Options: {depth?: number, edge?: 'start' | 'end'}
`Editor.point(editor: Editor, at: Location, options?) => Point`
Get the start or end (default is start) point of a location.
Options: {edge?: 'start' | 'end'}
`Editor.positions(editor: Editor, options?) => Generator`
Iterate through all of the positions in the document where a Point can be placed. The first Point returns is always the starting point followed by the next Point as determined by the unit option.
Points inside non-selectable elements are skipped in both directions, including consecutive non-selectable elements.
Read options.unit to see how this method iterates through positions.
Note: By default void nodes are treated as a single point and iteration will not happen inside their content unless the voids option is set, then iteration will occur. Text immediately after an inline void starts a new traversal boundary, including when the surrounding text is empty. Word traversal restarts segmentation at that boundary.
Options:
at?: Location = editor.selection: TheLocationin which to iterate the positions of.unit?: 'offset' | 'character' | 'word' | 'line' | 'block' = 'offset':offset: Moves to the next offsetPoint. It will include thePointat the end of aTextobject and then move onto the firstPoint(at the 0th offset) of the nextTextobject. This may be counter-intuitive because the end of aTextand the beginning of the nextTextmight be thought of as the same position.character: Moves to the nextcharacterbut is not always the nextindexin the string. This is because Unicode encodings may require multiple bytes to create one character. Unlikeoffset,characterwill not count the end of aTextand the beginning of the nextTextas separate positions to return. Warning: The character offsets for Unicode characters does not appear to be reliable in some cases like a Smiley Emoji will be identified as 2 characters.word: Moves to the position immediately after the nextword. Inreversemode, moves to the position immediately before the previousword. Whitespace and punctuation end a word, and apostrophes inside a word don't. WhereIntl.Segmenteris available, a run of word characters is split further at its word boundaries, so Chinese, Japanese and Thai text without spaces moves and deletes one word at a time.line|block: Starts at the beginning position and then the position at the end of the block. Then starts at the beginning of the next block and then the end of the next block.
reverse?: boolean = false: Whentruereturns the positions in reverse order. In the case of theunitbeingword, the actual returned positions are different (i.e. we will get the start of a word in reverse instead of the end).voids?: boolean = false: Whentrueinclude void Nodes.
For unit: 'word', isWordCharacter?: (character: string) => boolean customizes word boundaries. The callback receives a whole grapheme, including a combined character or emoji. For example, isWordCharacter: character => /[\w-]/.test(character) treats foo-bar_baz as one word. A custom callback replaces the default punctuation rules and language segmentation; it is ignored for other units.
`Editor.previous(editor: Editor, options?) => NodeEntry | undefined`
Get the matching node in the branch of the document before a location.
Note: To find the previous Point, and not the previous Node, use the Editor.before method
Options: {at?: Location, match?: NodeMatch, mode?: 'all' | 'highest' | 'lowest', voids?: boolean}
`Editor.range(editor: Editor, at: Location, to?: Location) => Range`
Get a range of a location.
`Editor.start(editor: Editor, at: Location) => Point`
Get the start point of a location.
`Editor.string(editor: Editor, at: Location, options?) => string`
Get the text string content of a location.
Note: by default the text of void nodes is considered to be an empty string, regardless of content, unless the voids option is set.
Options: : {voids?: boolean}
`Editor.void(editor: Editor, options?) => NodeEntry | undefined`
Match a void node in the current branch of the editor.
Options: {at?: Location, mode?: 'highest' | 'lowest', voids?: boolean}
`Editor.word(editor: Editor, options?) => Range | undefined`
Get the range of the word around a point, within its block. Defaults to the selection's focus. Returns undefined when the point isn't touching a word, is inside a void, or there is no selection.
The word can span text nodes with different marks and inline elements such as links, but stops at inline voids. By default it finds the same words as the 'word' unit that word deletion and Editor.before/Editor.after use. Whitespace and punctuation end a word, and apostrophes inside a word don't. Where Intl.Segmenter is available, Chinese, Japanese and Thai text without spaces is split into its words. Pass isWordCharacter to define your own, for example to treat foo-bar.baz or @name as one word:
const range = Editor.word(editor, {
isWordCharacter: character => /[\w.@-]/.test(character),
})
const word = range && Editor.string(editor, range)Options: {at?: Point | Range, isWordCharacter?: (character: string) => boolean}
Editor.word reads the editor's value, which doesn't include text an input method is still composing. In React, use ReactEditor.getWord to include it.
Manipulation methods
`Editor.addMark(editor: Editor, key: string, value: any) => void`
Add a custom property to the leaf text nodes and any nodes that editor.markableVoid() allows in the current selection.
If the selection is currently collapsed, the marks will be added to the editor.marks property instead, and applied when text is inserted next.
`Editor.deleteBackward(editor: Editor, options?) => void`
Delete content in the editor backward from the current selection.
Options: {unit?: 'character' | 'word' | 'line' | 'block'}
`Editor.deleteForward(editor: Editor, options?) => void`
Delete content in the editor forward from the current selection.
Options: {unit?: 'character' | 'word' | 'line' | 'block'}
`Editor.deleteFragment(editor: Editor) => void`
Delete the content in the current selection.
A hanging selection from the start of a block to the start of a following sibling removes the fully selected blocks, preserving the following block. Inside an element identified by editor.isIsolated, deletion continues to unhang the selection and retain the block structure. Custom deleteFragment overrides still control deletion.
`Editor.insertBreak(editor: Editor) => void`
Insert a block break at the current selection.
`Editor.insertSoftBreak(editor: Editor) => void`
Insert a soft break at the current selection.
`Editor.insertFragment(editor: Editor, fragment: Node[], options?) => void`
Inserts a fragment at the specified location or (if not defined) the current selection or (if not defined) the end of the document.
Options: {at?: Location, hanging?: boolean, voids?: boolean}
`Editor.insertNode(editor: Editor, node: Node, options?) => void`
Atomically insert node at the specified location or (if not defined) the current selection or (if not defined) the end of the document.
Options supported: NodeOptions & {hanging?: boolean, select?: boolean}.
For example, insert a block before the second block and move the selection into it:
Editor.insertNode(
editor,
{ children: [{ text: 'New block' }] },
{
at: [1],
select: true,
}
)`Editor.insertText(editor: Editor, text: string, options?) => void`
Insert a string of text at the specified location or (if not defined) the current selection or (if not defined) the end of the document.
Options: {at?: Location, voids?: boolean}
Pending marks on editor.marks apply only when at is omitted. Text inserted at an explicit at leaves them for the next insertion at the selection, and does not need a selection.
To insert text at the start of the second block:
Editor.insertText(editor, 'Hello', { at: { path: [1, 0], offset: 0 } })`Editor.removeMark(editor: Editor, key: string) => void`
Remove a custom property from all of the leaf text nodes within non-void nodes or void nodes that editor.markableVoid() allows in the current selection.
If the selection is currently collapsed, the removal will be stored on editor.marks and applied to the text inserted next.
`Editor.unhangRange(editor: Editor, range: Range, options?) => Range`
Convert a range into a non-hanging one.
A "hanging" range is one created by the browser's "triple-click" selection behavior. When triple-clicking a block, the browser selects from the start of that block to the start of the next block. The range thus "hangs over" into the next block. If unhangRange is given such a range, it moves the end backwards until it's in a non-empty text node that precedes the hanging block.
Note that unhangRange is designed for the specific purpose of fixing triple-clicked blocks, and therefore currently has a number of caveats:
- It does not modify the start of the range; only the end. For example, it does not "unhang" a selection that starts at the end of a previous block.
- It only does anything if the start block is fully selected. For example, it does not handle ranges created by double-clicking the end of a paragraph (which browsers treat by selecting from the end of that paragraph to the start of the next).
Options:
voids?: boolean = false: Allow placing the end of the selection in a void node.
Check methods
`Editor.hasRange(editor: Editor, range: Range) => boolean`
Check whether both endpoint paths of a range exist in the editor. This checks paths, not whether offsets are within the text. DOMEditor.hasRange and ReactEditor.hasRange delegate to this method.
`Editor.hasBlocks(editor: Editor, element: Element) => boolean`
Check if a node has block children.
`Editor.hasInlines(editor: Editor, element: Element) => boolean`
Check if a node has inline and text children.
`Editor.hasTexts(editor: Editor, element: Element) => boolean`
Check if a node has text children.
`Editor.isBlock(editor: Editor, element: Element) => boolean`
Check if an element is a block element. It only accepts an Element, so check other values with Element.isElement first.
`Editor.isEditor(value: any) => value is Editor`
Check if a value is an Editor object.
`Editor.isEnd(editor: Editor, point: Point, at: Location) => boolean`
Check if a point is the end point of a location.
`Editor.isEdge(editor: Editor, point: Point, at: Location) => boolean`
Check if a point is an edge of a location.
`Editor.isEmpty(editor: Editor, element: Element) => boolean`
Check if an element is empty, accounting for void nodes.
`Editor.isInline(editor: Editor, element: Element) => boolean`
Check if an element is an inline element. It only accepts an Element, so check other values with Element.isElement first.
`Editor.isNormalizing(editor: Editor) => boolean`
Check if the editor is currently normalizing after each operation.
`Editor.isRemoteChange(editor: Editor) => boolean`
Check whether the editor is currently inside Editor.withRemoteChanges. It returns false outside that editor's scope.
`Editor.isStart(editor: Editor, point: Point, at: Location) => boolean`
Check if a point is the start point of a location.
`Editor.isVoid(editor: Editor, element: Element) => boolean`
Check if an element is a void element. It only accepts an Element, so check other values with Element.isElement first.
Normalization methods
`Editor.normalize(editor: Editor, options?) => void`
Normalize any dirty objects in the editor.
Options: {force?: boolean; operation?: Operation}
`Editor.withoutNormalizing(editor: Editor, fn: () => void) => void`
Call a function, deferring normalization until after it completes.
See Normalization - Implications for Other Code;
Remote operations
`Editor.withRemoteChanges(editor: Editor, fn: () => void) => void`
Apply remote operations inside a synchronous callback. An expanded selection uses inward affinity, so text inserted at either edge stays outside the selected content. Collapsed carets keep their usual forward behavior. Local operations outside the scope retain their existing selection behavior.
Scopes can nest and restore the previous flag even if the callback throws. The scope covers only the synchronous callback; apply asynchronous updates inside a new scope when they arrive. This helper does not synchronize operations or change history saving. Removing a selected node keeps the existing nearest-point fallback.
Editor.withRemoteChanges(editor, () => {
Editor.withoutNormalizing(editor, () => {
for (const operation of remoteOperations) editor.apply(operation)
})
})Ref Methods
`Editor.pathRef(editor: Editor, path: Path, options?) => PathRef`
Create a mutable ref for a Path object, which will stay in sync as new operations are applied to the editor.
Options: {affinity?: 'backward' | 'forward' | null}
`Editor.pathRefs(editor: Editor) => Set`
Get the set of currently tracked path refs of the editor.
`Editor.pointRef(editor: Editor, point: Point, options?) => PointRef`
Create a mutable ref for a Point object, which will stay in sync as new operations are applied to the editor.
Options: {affinity?: 'backward' | 'forward' | null}
`Editor.pointRefs(editor: Editor) => Set`
Get the set of currently tracked point refs of the editor.
`Editor.rangeRef(editor: Editor, range: Range, options?) => RangeRef`
Create a mutable ref for a Range object, which will stay in sync as new operations are applied to the editor.
Options: {affinity?: 'backward' | 'forward' | 'outward' | 'inward' | null}
`Editor.rangeRefs(editor: Editor) => Set`
Get the set of currently tracked range refs of the editor.
Instance Methods
Schema-specific instance methods to override
Replace these methods to modify the original behavior of the editor when building Plugins. When modifying behavior, call the original method when appropriate. For example, a plugin that marks image nodes as "void":
const withImages = editor => {
const { isVoid } = editor
editor.isVoid = element => {
return element.type === 'image' ? true : isVoid(element)
}
return editor
}Element type methods
Use these methods so that Slate can identify certain elements as inlines or voids.
`isInline(element: Element) => boolean`
Check if a value is an inline Element object.
`isVoid(element: Element) => boolean`
Check if a value is a void Element object.
`inlineEdgeAffinity(element: Element, edge: 'start' | 'end') => 'inside' | 'outside' | null`
Choose whether insertion at an inline edge belongs inside the inline or in the adjacent text outside it. The rule also applies when the caret names that adjacent text. Defaults to null, retaining the current point. An 'inside' rule never moves a caret into a void, read-only, or non-selectable inline.
At shared boundaries, the outermost inline edge takes precedence. Between adjacent inlines separated by empty text, rules are considered from left to right; the first non-null rule wins. Empty non-void inlines use their start edge, and an outside rule uses the text before the empty inline. These tie rules keep repeated resolution stable.
`leafEdgeAffinity(before: Text, after: Text) => 'backward' | 'forward' | null`
Choose which of two sibling text leaves receives insertion at their shared boundary. 'backward' uses the end of before; 'forward' uses the start of after. Defaults to null, retaining the current point. This rule runs after inline affinity and determines the receiving leaf’s marks reported by Editor.marks.
`isIsolated(element: Element) => boolean`
Mark elements whose content must not flow across their edges, such as table cells. Slate's default returns false.
For an isolated element:
- Backspace at its start and Delete at its end do nothing, so they don't merge it with a neighbour. Deleting by word or line stops at its edge.
- Deleting a range that crosses its edge removes the selected text but doesn't merge the blocks on either side. Isolated elements that are entirely inside the range are still removed.
insertBreak, andsplitNodeswith its default match, don't split it. They still split blocks inside it.splitNodeswith an explicitmatchthat selects the element still splits it.- Explicit
mergeNodescalls aren't affected.
const { isIsolated } = editor
editor.isIsolated = element =>
element.type === 'table-cell' || isIsolated(element)Split properties
`getSplitProperties(node: Element | Text, path: Path) => Partial`
Return the properties for the new right-hand node when Transforms.splitNodes splits node at its current path. The default is Node.extractProps(node), which copies every property except children and text. The original left-hand node keeps its properties.
Override this method to drop or replace properties such as element IDs. Return the full set of properties to keep, including text marks when splitting a text node; omit children and text. Commands that use splitNodes, including insertBreak, insertFragment and setNodes with split: true, use this method too, as does wrapNodes when it splits an inline element. See Node IDs for a plugin example.
Normalize methods
`normalizeNode(entry: NodeEntry, { operation, fallbackElement }) => void`
Normalize a Node according to the schema.
`shouldNormalize: (options) => boolean`
Override this method to prevent normalizing the editor.
Options: { dirtyPaths: Path[]; initialDirtyPathsLength: number; iteration: number; operation?: Operation }
Callback method
`onChange(options?: { operation?: Operation }) => void`
Called when there is a change in the editor.
Mark methods
`markableVoid: (element: Element) => boolean`
Tells which void nodes accept Marks. Slate's default implementation returns false, but if some void elements support formatting, override this function to include them.
`addMark(key: string, value: any) => void`
Add a custom property to the leaf text nodes within non-void nodes or void nodes that editor.markableVoid() allows in the current selection. If the selection is currently collapsed, the marks will be added to the editor.marks property instead, and applied when text is inserted next.
`removeMark(key: string) => void`
Remove a custom property from the leaf text nodes within non-void nodes or void nodes that editor.markableVoid() allows in the current selection.
getFragment method
`getFragment() => Descendant[]`
Returns the fragment at the current selection. Used when cutting or copying, as an example, to get the fragment at the current selection.
Delete methods
When a user presses backspace or delete, it invokes the method based on the selection. For example, if the selection is expanded over some text and the user presses the backspace key, deleteFragment will be called, but if the selection is collapsed, deleteBackward will be called.
`deleteBackward(options?: {unit?: 'character' | 'word' | 'line' | 'block'}) => void`
Delete content in the editor backward from the current selection.
`deleteForward(options?: {unit?: 'character' | 'word' | 'line' | 'block'}) => void`
Delete content in the editor forward from the current selection.
`deleteFragment() => void`
Delete the content of the current selection.
Insert methods
`insertFragment(fragment: Node[]) => void`
Insert a fragment at the current selection. If the selection is currently expanded, delete it first.
`insertBreak() => void`
Insert a block break at the current selection. If the selection is currently expanded, delete it first.
`insertSoftBreak() => void`
Insert a soft break at the current selection. If the selection is currently expanded, delete it first.
`insertNode(node: Node) => void`
Insert a node at the current selection. If the selection is currently expanded, delete it first.
`insertText(text: string) => void`
Insert text at the current selection. If the selection is currently expanded, delete it first.
Operation handling method
`apply(operation: Operation) => void`
Apply an operation in the editor.
External value method
`setChildren(children: Descendant[]) => void`
Overridable implementation used by Transforms.setChildren to apply external document changes through operations. withHistory wraps it in an isolated undo batch. Editors created by createEditor provide this method; structural editor implementations and mocks must add it.
Api Nodes Element (`docs/api/nodes/element.md`)
Element API
Element objects are a type of Node in a Slate document that contain other Element nodes or Text nodes.
interface Element {
children: Node[]
}Element Behavior Types
Element nodes behave differently depending on the Slate editor's configuration. An element can be:
- "block" or "inline" as defined by
editor.isInline - either "void" or "not void" as defined by
editor.isVoid
Block vs. Inline
A "block" element can only be siblings with other "block" elements. An "inline" node can be siblings with Text nodes or other "inline" elements.
Void vs Not Void
In a not "void" element, Slate handles the rendering of its children (e.g. in a paragraph where the Text and Inline children are rendered by Slate). In a "void" element, the children are rendered by the Element's render code.
Voids That Support Marks
Some void elements are effectively stand-ins for text, such as with the Mentions example, where the mention element renders the character's name. Users might want to format Void elements like this with bold, or set their font and size, so editor.markableVoid tells Slate whether or not to apply Marks to the text children of void elements.
Rendering Void Elements
Void Elements must
- always have one empty child text node (for selection)
- render using
attributesandchildren(so, their outermost HTML element can't be an HTML void element) - set
contentEditable={false}(for Firefox)
Typical rendering code will resemble this thematic-break (horizontal rule) element:
return (
<div {...attributes} contentEditable={false}>
{children}
<hr />
</div>
)For a "markable" void such as a mention element, marks on the empty child element can be used to determine how the void element is rendered (Slate Marks are applied only to Text leaves):
const Mention = ({ attributes, children, element }) => {
const selected = useSelected()
const focused = useFocused()
const style: React.CSSProperties = {
padding: '3px 3px 2px',
margin: '0 1px',
verticalAlign: 'baseline',
display: 'inline-block',
borderRadius: '4px',
backgroundColor: '#eee',
fontSize: '0.9em',
boxShadow: selected && focused ? '0 0 0 2px #B4D5FF' : 'none',
}
// See if our empty text child has any styling marks applied and apply those
if (element.children[0].bold) {
style.fontWeight = 'bold'
}
if (element.children[0].italic) {
style.fontStyle = 'italic'
}
return (
<span
{...attributes}
contentEditable={false}
data-cy={`mention-${element.character.replace(' ', '-')}`}
style={style}
>
{children}@{element.character}
</span>
)
}Static methods
Retrieval methods
`Element.matches(element: Element, props: Partial) => boolean`
Check if an element matches a set of props. Note: This checks custom properties, but it does not ensure that any children are equivalent.
Check methods
`Element.isAncestor(value: any) => value is Ancestor`
Check if a value implements the 'Ancestor' interface.
`Element.isElement(value: any) => value is Element`
Check if a value implements the Element interface.
`Element.isElementList(value: any) => value is Element[]`
Check if a value is an array of Element objects.
`Element.isElementType(value: any, elementVal: string, ElementKey: string = 'type'): value is T`
Check if a value implements the Element interface and has elementKey with selected value.
Default it check to type key value
Api Nodes Node Entry (`docs/api/nodes/node-entry.md`)
NodeEntry API
NodeEntry objects are returned when iterating over the nodes in a Slate document tree. They consist of an array with two elements: the Node and its Path relative to the root node in the document.
They are generics meaning that sometimes they will return a subset of Node types like an Element or Text.
type NodeEntry<T extends Node = Node> = [T, Path]Api Nodes Node (`docs/api/nodes/node.md`)
Node API
Static methods
Retrieval methods
`Node.ancestor(root: Node, path: Path) => Ancestor`
Get the node at a specific path, asserting that it is an ancestor node. If the specified node is not an ancestor node, throw an error.
`Node.ancestors(root: Node, path: Path, options?) => Generator>`
Return a generator of all the ancestor nodes above a specific path. By default, the order is top-down, from highest to lowest ancestor in the tree, but you can pass the reverse: true option to go bottom-up.
Options: {reverse?: boolean}
`Node.child(root: Node, index: number) => Descendant`
Get the child of a node at the specified index.
`Node.children(root: Node, path: Path, options?) => Generator>`
Iterate over the children of a node at a specific path.
Options: {reverse?: boolean}
`Node.common(root: Node, path: Path, another: Path) => NodeEntry`
Get an entry for the common ancestor node of two paths. It might be a Text node, an Element, or the Editor itself.
If the paths are equal, or one is an ancestor of the other, the entry is for the node at the shorter path. For example, Node.common(editor, [0, 0], [0, 0]) returns the text node at [0, 0], and Node.common(editor, [0], [0, 0]) returns the element at [0].
For the common block ancestor, see Editor Selection
`Node.descendant(root: Node, path: Path) => Descendant`
Get the node at a specific path, asserting that it's a descendant node.
`Node.descendants(root: Node, options?) => Generator>`
Return a generator of all the descendant node entries inside a root node. Each iteration will return a NodeEntry tuple consisting of [Node, Path].
Options: {from?: Path, to?: Path, reverse?: boolean, pass?: (node: NodeEntry => boolean)}
`Node.elements(root: Node, options?) => Generator`
Return a generator of all the element nodes inside a root node. Each iteration will return an ElementEntry tuple consisting of [Element, Path]. If the root node is an element, it will be included in the iteration as well.
Options: {from?: Path, to?: Path, reverse?: boolean, pass?: (node: NodeEntry => boolean)}
`Node.extractProps(node: Node) => NodeProps`
Extract all properties from a Node except for its content-related fields (children for Element nodes and text for Text nodes).
// For an Element node
const element = {
type: 'paragraph',
align: 'center',
children: [{ text: 'Try it out for yourself!' }],
}
const props = Node.extractProps(element)
// Returns: { type: 'paragraph', align: "center" }
// For a Text node
const text = { text: 'Hello', bold: true }
const props = Node.extractProps(text)
// Returns: { bold: true }`Node.first(root: Node, path: Path) => NodeEntry`
Get the first node entry in a root node from a path.
`Node.fragment(root: Node, range: Range) => Descendant[]`
Get the sliced fragment represented by the range.
`Node.findPath(root: Node, node: Node) => Path | undefined`
Find the path of node inside root by walking the tree, comparing nodes by identity. Returns [] for the root itself and undefined if node isn't in the tree. It doesn't need a rendered editor, so it works on the server too; ReactEditor.findPath is faster for rendered nodes and falls back to this.
`Node.get(root: Node, path: Path) => Node`
Get the descendant node referred to by a specific path. If the path is an empty array, get the root node itself.
`Node.getIf(root: Node, path: Path) => Node | undefined`
Get a descendant node at a specific path, returning undefined if the node does not exist. This is a safer alternative to Node.get() as it won't throw an error if the path is invalid.
const node = Node.getIf(root, [0, 1])
if (node) {
// node exists at path [0, 1]
} else {
// no node exists at path [0, 1]
}`Node.last(root: Node, path: Path) => NodeEntry`
Get the last node entry in a root node at a specific path.
`Node.leaf(root: Node, path: Path) => Text`
Get the node at a specific path, ensuring it's a leaf text node. If the node is not a leaf text node, throw an error.
`Node.levels(root: Node, path: Path, options?) => Generator`
Return a generator of the nodes in a branch of the tree, from a specific path. By default, the order is top-down, from the highest to the lowest node in the tree, but you can pass the reverse: true option to go bottom-up.
Options: {reverse?: boolean}
`Node.nodes(root: Node, options?) => Generator`
Return a generator of all the node entries of a root node. Each entry is returned as a [Node, Path] tuple, with the path referring to the node's position inside the root node.
Options: {from?: Path, to?: Path, reverse?: boolean, pass?: (node: NodeEntry => boolean)}
`Node.parent(root: Node, path: Path) => Ancestor`
Get the parent of a node at a specific path.
Text methods
Methods related to Text.
`Node.string(root: Node) => string`
Get the concatenated text string of a node's content. Note that this will not include spaces or line breaks between block nodes. This is not intended as a user-facing string, but as a string for performing offset-related computations for a node.
`Node.texts(root: Node, options?) => Generator>`
Return a generator of all leaf text nodes in a root node.
Options: {from?: Path, to?: Path, reverse?: boolean, pass?: (node: NodeEntry => boolean)}
Check methods
Methods used to check some attribute of a Node.
`Node.has(root: Node, path: Path) => boolean`
Check if a descendant node exists at a specific path.
`Node.isNode(value: any) => value is Node`
Check if a value implements the Node interface.
`Node.isNodeList(value: any) => value is Node[]`
Check if a value is a list of Node objects.
`Node.matches(root: Node, props: Partial) => boolean`
Check if a node matches a set of props.
Api Nodes Text (`docs/api/nodes/text.md`)
Text API
Text objects represent the nodes that contain the actual text content of a Slate document along with any formatting properties. They are always leaf nodes in the document tree as they cannot contain any children.
interface Text {
text: string
}Static methods
Retrieval methods
`Text.matches(text: Text, props: Partial) => boolean`
Check if text matches a set of props.
The way the check works is that it makes sure that (a) all the props exist in the text, and (b) if it exists, that it exactly matches the properties in the text.
If a props.text property is passed in, it will be ignored.
If there are properties in text that are not in props, those will be ignored when it comes to testing for a match.
`Text.decorations(node: Text, decorations: DecoratedRange[]) => { leaf: Text; position?: LeafPosition }[]`
Get the leaves and positions for a text node, given decorations.
Check methods
`Text.equals(text: Text, another: Text, options?) => boolean`
Check if two text nodes are equal.
Options: {loose?: boolean, ignore?: readonly string[]}
loose?: Whentrue, it checks if the properties of theTextobject are equal except for thetextproperty (i.e. theStringvalue of theText). Whenfalse(default), checks all properties includingtext.ignore?: Top-level property names to exclude from both nodes before comparing, such asignore: ['id']for application-generated IDs. Nested properties are still compared deeply, and neither input node is changed. Combine withloose: trueto ignore both text content and the named properties. The default is an empty list.
`Text.isText(value: any) => value is Text`
Check if a value implements the Text interface.
`Text.isTextList(value: any): value is Text[]`
Check if value is an Array of only Text objects.
Api Operations Operation (`docs/api/operations/operation.md`)
Operation API
Operation objects define the low-level instructions that Slate editors use to apply changes to their internal state. Representing all changes as operations is what allows Slate editors to easily implement history, collaboration, and other features.
Static methods
Manipulation methods
`Operation.inverse(op: Operation) => Operation`
Invert an operation, returning a new operation that will exactly undo the original when applied.
Check methods
`Operation.isNodeOperation(value: any) => boolean`
Check if a value is a NodeOperation object. Returns the value as a NodeOperation if it is one.
`Operation.isOperation(value: any) => boolean`
Check if a value is an Operation object. Returns the value as an Operation if it is one.
`Operation.isOperationList(value: any) => boolean`
Check if a value is a list of Operation objects. Returns the value as an Operation[] if it is one.
`Operation.isSelectionOperation(value: any) => boolean`
Check if a value is a SelectionOperation object. Returns the value as a SelectionOperation if it is one.
`Operation.isTextOperation(value: any) => boolean`
Check if a value is a TextOperation object. Returns the value as a TextOperation if it is one.
Libraries Slate History History Editor (`docs/libraries/slate-history/history-editor.md`)
History Editor
The HistoryEditor interface is added to the Editor when it is instantiated using the withHistory method.
const [editor] = useState(() => withReact(withHistory(createEditor())))This adds properties to editor that enables undo and redo in Slate.
There are also static methods for working with the Editor's undo/redo history.
export interface HistoryEditor extends BaseEditor {
history: History
undo: () => void
redo: () => void
writeHistory: (stack: 'undos' | 'redos', batch: any) => void
}Static methods
Undo and Redo
`HistoryEditor.redo(editor: HistoryEditor): void`
Redo to the next saved state.
`HistoryEditor.undo(editor: HistoryEditor): void`
Undo to the previous saved state. A saved selectionBefore is restored even if the current selection is null, such as after removing the last block. Redo restores that saved selection before replaying the batch. Standalone selection changes are not saved, so redo does not replay cursor moves made after its operations.
Merging and Saving
`HistoryEditor.withMerging(editor: HistoryEditor, fn: () => void): void`
Apply a series of changes inside a synchronous fn, These operations will
be merged into the previous history.
`HistoryEditor.withNewBatch(editor: HistoryEditor, fn: () => void): void`
Apply a series of changes inside a synchronous fn, ensuring that the first
operation starts a new batch in the history. Subsequent operations will be
merged as usual.
`HistoryEditor.withoutMerging(editor: HistoryEditor, fn: () => void): void`
Apply a series of changes inside a synchronous fn, without merging any of
the new operations into previous save point in the history.
Each transform called inside fn becomes its own undo step, and the normalization it triggers stays in that step. Use withNewBatch to make several transforms one step.
`HistoryEditor.withoutSaving(editor: HistoryEditor, fn: () => void): void`
Apply a series of changes inside a synchronous fn, without saving any of
their operations into the history.
Undo and redo steps already in the history are moved past these changes, so a
later undo still reverts the user's own edit even when the unsaved change
inserted, removed or edited content around it. A step whose content was
removed, or that can no longer be applied, such as a split whose halves are no
longer next to each other, is dropped.
Check methods
`HistoryEditor.isHistoryEditor(value: any): value is HistoryEditor`
Check if a value is a HistoryEditor (i.e. it has the HistoryEditor interface).
`HistoryEditor.isMerging(editor: HistoryEditor): boolean | undefined`
Get the merge flag's current value.
`HistoryEditor.isSaving(editor: HistoryEditor): boolean | undefined`
Get the saving flag's current value.
Instance methods
`undo(): void`
Undo the last batch of operations
`redo(): void`
Redo the last undone batch of operations
`writeHistory(stack: 'undos'| 'redos', batch: any) => void`
Push a batch of operations as either undos or redos onto editor.undos or editor.redos
Libraries Slate History History (`docs/libraries/slate-history/history.md`)
History
The History object contains the undo and redo history for the editor.
It can be accessed from an Editor instance as the property history.
This property is only available on the Editor if the editor was instantiated using the withHistory method which adds undo/redo functionality to the Slate editor.
export interface History {
redos: Batch[]
undos: Batch[]
}
interface Batch {
operations: Operation[]
selectionBefore: Range | null
}Static Methods
`History.isHistory(value: any): value is History`
Returns true if the passed in value is a History object and also acts as a type guard for History.
Libraries Slate History With History (`docs/libraries/slate-history/with-history.md`)
withHistory
The withHistory plugin adds the HistoryEditor to an Editor instance and keeps track of the operation history of a Slate editor as operations are applied to it, using undo and redo stacks.
`withHistory(editor: T): T & HistoryEditor`
Add HistoryEditor interface to an instance of any Editor.
When used with withReact, withHistory should be applied inside. For example:
const [editor] = useState(() => withReact(withHistory(createEditor())))The plugin also overrides editor.setChildren. Each Transforms.setChildren call starts its own undo batch, including normalization, and does not merge with typing before or after the external update. A deep-equal update creates no history entry.
Libraries Slate React Editable (`docs/libraries/slate-react/editable.md`)
Editable component
`Editable(props: EditableProps): React.JSX.Element`
The Editable component is the main editing component. Note that it must be inside a Slate component.
Keyboard focus (Tab or Shift+Tab) restores the editor's existing selection. If there is no selection, the browser chooses the initial caret position. Clicking the editor places the caret at the clicked position.
Props
It takes as its props, any props accepted by a Textarea element plus the following props.
type EditableProps = {
decorate?: (entry: NodeEntry) => Range[]
onDOMBeforeInput?: (event: InputEvent) => void
placeholder?: string
readOnly?: boolean
role?: string
style?: React.CSSProperties
renderElement?: (props: RenderElementProps) => React.JSX.Element
renderLeaf?: (props: RenderLeafProps) => React.JSX.Element
renderPlaceholder?: (props: RenderPlaceholderProps) => React.JSX.Element
scrollSelectionIntoView?: (editor: ReactEditor, domRange: DOMRange) => void
as?: React.ElementType
disableDefaultStyles?: boolean
} & React.TextareaHTMLAttributes<HTMLDivElement>NOTE: Detailed breakdown of Props not completed. Refer to the source code at the moment. Under construction.
`placeholder?: string = ""`
The text to display as a placeholder when the Editor is empty. A typical value for placeholder would be "Enter text here..." or "Start typing...". The placeholder text will not be treated as an actual value and will disappear when the user starts typing in the Editor. While it is shown, the editor root gets an aria-placeholder with the same text.
`readOnly?: boolean = false`
When set to true, renders the editor in a "read-only" state. In this state, user input and interactions will not modify the editor's content.
Caller-provided event handlers still run in read-only mode; Slate skips its own editing behavior. Add tabIndex={0} to make a read-only editor keyboard-focusable. Read-only editors do not receive a tab index by default.
If this prop is omitted or set to false, the editor remains in the default "editable" state, allowing users to interact with and modify the content.
This prop is particularly useful when you want to display text or rich media content without allowing users to edit it, such as when displaying published content or a preview of the user's input.
`renderElement?: (props: RenderElementProps) => React.JSX.Element`
The renderElement prop is a function used to render a custom component for a specific type of Element node in the Slate.js document model.
Here is the type of the RenderElementProps passed into the function.
export interface RenderElementProps {
children: any
element: Element
attributes: {
'data-slate-node': 'element'
'data-slate-inline'?: true
'data-slate-void'?: true
dir?: 'rtl'
ref: any
}
}The attributes must be added to the props of the top level HTML element returned from the function and the children must be rendered somewhere inside the returned JSX.
Here is a typical usage of renderElement with two types of elements.
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
// Define a rendering function based on the element passed to `props`. We use
// `useCallback` here to memoize the function for subsequent renders.
const renderElement = useCallback(props => {
switch (props.element.type) {
case 'code':
return <CodeElement {...props} />
default:
return <DefaultElement {...props} />
}
}, [])
return (
<Slate editor={editor} initialValue={initialValue}>
<Editable
// Pass in the `renderElement` function.
renderElement={renderElement}
/>
</Slate>
)
}
const CodeElement = props => {
return (
<pre {...props.attributes}>
<code>{props.children}</code>
</pre>
)
}
const DefaultElement = props => {
return <p {...props.attributes}>{props.children}</p>
}`renderLeaf?: (props: RenderLeafProps) => React.JSX.Element`
The renderLeaf prop allows you to customize the rendering of leaf nodes in the document tree of your Slate editor. A "leaf" in Slate is the smallest chunk of text and its associated formatting attributes.
The renderLeaf function receives an object of type RenderLeafProps as its argument:
export interface RenderLeafProps {
children: any
leaf: Text
text: Text
attributes: {
'data-slate-leaf': true
}
/**
* The position of the leaf within the Text node, only present when the text node is split by decorations.
*/
leafPosition?: {
start: number
end: number
isFirst?: true
isLast?: true
}
}Example usage:
<Editor
renderLeaf={({ attributes, children, leaf }) => {
return (
<span
{...attributes}
style={{ fontWeight: leaf.bold ? 'bold' : 'normal' }}
>
{children}
</span>
)
}}
/>`renderText?: (props: RenderTextProps) => React.JSX.Element`
The renderText prop allows you to customize the rendering of the container element for a Text node in the Slate editor. This is useful when you need to wrap the entire text node content or add elements associated with the text node as a whole, regardless of how decorations might split the text into multiple leaves.
The renderText function receives an object of type RenderTextProps as its argument:
export interface RenderTextProps {
text: Text
children: any
attributes: {
'data-slate-node': 'text'
ref: any
}
}Example usage:
<Editable
renderText={({ attributes, children, text }) => {
return (
<span {...attributes} className="custom-text">
{children}
{text.tooltipContent && <Tooltip content={text.tooltipContent} />}
</span>
)
}}
/>`renderPlaceholder?: (props: RenderPlaceholderProps) => React.JSX.Element`
The renderPlaceholder prop allows you to customize how the placeholder of the Slate.js Editable component is rendered when the editor is empty. The placeholder will only be shown when the editor's content is empty.
The RenderPlaceholderProps interface looks like this:
export type RenderPlaceholderProps = {
children: any
attributes: {
'data-slate-placeholder': boolean
'aria-hidden': boolean
dir?: 'rtl'
contentEditable: boolean
ref: React.RefCallback<any>
style: React.CSSProperties
}
}An example usage might look like:
<Editable
placeholder="Enter text here..."
renderPlaceholder={({ attributes, children }) => {
const styledAttributes = {
...attributes,
style: {
...attributes.style,
color: 'gray',
},
}
return <div {...styledAttributes}>{children}</div>
}}
/>Note that the attributes prop that comes in will contain a style object already. This object contains important styling properties which will make the placeholder behave like a placeholder. As such, it is advisable to extend styles and to focus on things like changing colors, opacity etc. Changing positioning, for example, could cause undesirable behavior.
`scrollSelectionIntoView?: (editor: ReactEditor, domRange: DOMRange) => void`
Slate has its own default method to scroll a DOM selection into view that works for most cases; however, if the default behavior isn't working for you, possible due to some complex styling, you may need to override the default behavior by providing a different function here.
`as?: React.ElementType = "div"`
The as prop specifies the type of element that will be used to render the Editable component in your React application. By default, this is a div.
`disableDefaultStyles?: boolean = false`
The disableDefaultStyles prop determines whether the default styles of the Slate.js Editable component are applied or not.
Please note that with this prop set to true, you will need to ensure that your styles cater to all the functionalities of the editor that rely on specific styles to work properly.
Here are the default styles:
const defaultStyles = {
// Allow positioning relative to the editable element.
position: 'relative',
// Preserve adjacent whitespace and new lines.
whiteSpace: 'pre-wrap',
// Allow words to break if they are too long.
wordWrap: 'break-word',
// Make the minimum height that of the placeholder.
...(placeholderHeight ? { minHeight: placeholderHeight } : {}),
}Libraries Slate React Event Handling (`docs/libraries/slate-react/event-handling.md`)
Slate React Event Handling
By default, the Editable component comes with a set of event handlers that handle typical rich-text editing behaviors (for example, it implements its own onCopy, onPaste, onDrop, and onKeyDown handlers).
In some cases you may want to extend or override Slate's default behavior, which can be done by passing your own event handler(s) to the Editable component.
Your custom event handler can control whether or not Slate should execute its own event handling for a given event after your handler runs depending on the return value of your event handler as described below.
import {Editable} from 'slate-react';
function MyEditor() {
const onClick = event => {
// Implement custom event logic...
// When no value is returned, Slate will execute its own event handler when
// neither isDefaultPrevented nor isPropagationStopped was set on the event
};
const onDrop = event => {
// Implement custom event logic...
// No matter the state of the event, treat it as being handled by returning
// true here, Slate will skip its own event handler
return true;
};
const onDragStart = event => {
// Implement custom event logic...
// No matter the status of the event, treat event as *not* being handled by
// returning false, Slate will execute its own event handler afterward
return false;
};
return (
<Editable
onClick={onClick}
onDrop={onDrop}
onDragStart={onDragStart}
{/*...*/}
/>
)
}Native `input` events
Slate applies most edits itself instead of letting the browser change the DOM. For each beforeinput event it usually calls preventDefault() and applies the change with transforms, so the browser never fires the matching input event. That includes deletions, line breaks, pastes, digits and punctuation.
The browser inserts the text natively, and fires input, only when all of these hold:
- the edit types a single letter
a–zor a space - the selection is collapsed and isn't at the start of a text node
- no marks are pending, such as after toggling bold with nothing selected
- the caret isn't at the end of a link
So don't rely on onInput, or a native input listener on the editable element, to observe changes. Instead:
- use
onValueChange(oronChange) on<Slate>to react to every change of the value - use
onDOMBeforeInputon<Editable>to see, or take over, an edit before Slate applies it
Pastes are an exception for onDOMBeforeInput. Slate handles a paste in onPaste and cancels the native event, so no beforeinput fires, when the pasted data is plain text only ("paste without formatting"), in Safari and other WebKit browsers, and in browsers without beforeinput support. To observe every paste, use onPaste on <Editable> or override editor.insertData.
Libraries Slate React Hooks (`docs/libraries/slate-react/hooks.md`)
Slate React Hooks
`useComposing(): boolean`
Get the current composing state of the editor. It deals with compositionstart, compositionupdate, compositionend events.
Composition events are triggered by typing (composing) with a language that uses a composition character (e.g. Chinese, Japanese, Korean, etc.) example.
`useElement(): Element`
Get the current element object. Re-renders whenever the element or any of its descendants changes.
`useElementIf(): Element | null`
The same as useElement() but returns null instead of throwing an error when not inside an element.
`useFocused(): boolean`
Get the current focused state of the editor.
`useReadOnly(): boolean`
Get the current readOnly state of the editor.
`useSelected(): boolean`
Get the current selected state of an element. An element is selected if editor.selection exists and overlaps any part of the element.
`useSlate(): Editor`
Get the current editor object. Re-renders whenever changes occur in the editor.
`useSlateStatic(): Editor`
Get the current editor object from the React context. A version of useSlate that does not re-render the context. Previously called useEditor.
`useSlateSelection(): (BaseRange & { placeholder?: string | undefined; onPlaceholderResize?: ((node: HTMLElement | null) => void) | undefined }) | null`
Get the current editor selection. Only re-renders when the selection changes.
`useSlateSelector(selector: (editor: Editor) => T, equalityFn?: (a: T, b: T) => boolean): T`
Use redux style selectors to prevent re-rendering on every keystroke.
Bear in mind re-rendering can only prevented if the returned value is a value type or for reference types (e.g. objects and arrays) add a custom equality function.
If selector is memoized using useCallback, then it will only be called when it or the editor state changes. Otherwise, selector will be called every time the component renders.
Example:
const isSelectionActive = useSlateSelector(editor => Boolean(editor.selection))Libraries Slate React React Editor (`docs/libraries/slate-react/react-editor.md`)
ReactEditor
ReactEditor is added to Editor when it is instantiated using the withReact method.
const [editor] = useState(() => withReact(withHistory(createEditor())))Static methods
Check methods
`ReactEditor.isComposing(editor: ReactEditor): boolean`
Check if the user is currently composing inside the editor.
`ReactEditor.isFocused(editor: ReactEditor): boolean`
Check if the editor is focused.
`ReactEditor.isMounted(editor: ReactEditor): boolean`
Check if the editor is mounted, meaning it is rendered and has a DOM element. Methods that resolve DOM nodes, such as toDOMNode, throw for an editor that is not mounted.
`ReactEditor.isReadOnly(editor: ReactEditor): boolean`
Check if the editor is in read-only mode.
Focus and selection methods
`ReactEditor.blur(editor: ReactEditor): void`
Blur the editor.
`ReactEditor.focus(editor: ReactEditor): void`
Focus the editor.
In tests that run in jsdom, use ReactEditor.focus(editor) instead of calling focus() on the editable element. Editable doesn't treat a native focus event in jsdom as a focus of the editor, partly because jsdom doesn't implement isContentEditable, so ReactEditor.isFocused and useFocused stay false. ReactEditor.focus sets the focused state itself.
`ReactEditor.deselect(editor: ReactEditor): void`
Deselect the editor.
DOM translation methods
`ReactEditor.findKey(editor: ReactEditor, node: Node): Key`
Find a key for a Slate node.
Returns an instance of Key which looks like { id: string }
`ReactEditor.findPath(editor: ReactEditor, node: Node): Path`
Find the path of Slate node.
`ReactEditor.hasDOMNode(editor: ReactEditor, target: DOMNode, options: { editable?: boolean } = {}): boolean`
Check if a DOM node is within the editor.
`ReactEditor.toDOMNode(editor: ReactEditor, node: Node): HTMLElement`
Find the native DOM element from a Slate node.
`ReactEditor.toDOMPoint(editor: ReactEditor, point: Point): DOMPoint`
Find a native DOM selection point from a Slate point.
`ReactEditor.toDOMRange(editor: ReactEditor, range: Range): DOMRange`
Find a native DOM range from a Slate range.
`ReactEditor.toSlateNode(editor: ReactEditor, domNode: DOMNode): Node`
Find a Slate node from a native DOM element.
`ReactEditor.findEventRange(editor: ReactEditor, event: any, options?: { suppressThrow?: boolean }): Range | null`
Get the target range from a DOM event. The range is resolved from the event's coordinates, which can point outside of the editor even when the event's target lies inside it; with suppressThrow: true this returns null instead of throwing in that case.
`ReactEditor.toSlatePoint(editor: ReactEditor, domPoint: DOMPoint): Point | null`
Find a Slate point from a DOM selection's domNode and domOffset.
`ReactEditor.toSlateRange(editor: ReactEditor, domRange: DOMRange | DOMStaticRange | DOMSelection, options?: { exactMatch?: boolean } = {}): Range | null`
Find a Slate range from a DOM range or selection.
Word methods
`ReactEditor.getWord(editor: ReactEditor, options?: { at?: Point | Range, isWordCharacter?: (character: string) => boolean }): { range: Range, text: string } | undefined`
Like Editor.word, but while an input method is composing it reads the composing text from the DOM and uses the DOM caret when at isn't given. text is the word as currently shown. During a composition, range counts the composing characters, so it only matches the editor's value once the composition ends.
DataTransfer methods
`ReactEditor.insertData(editor: ReactEditor, data: DataTransfer): void`
Insert data from a DataTransfer into the editor. This is a proxy method to call in this order insertFragmentData(editor: ReactEditor, data: DataTransfer) and then insertTextData(editor: ReactEditor, data: DataTransfer).
`ReactEditor.insertFragmentData(editor: ReactEditor, data: DataTransfer): true`
Insert fragment data from a DataTransfer into the editor. Returns true if some content has been effectively inserted.
`ReactEditor.insertTextData(editor: ReactEditor, data: DataTransfer): true`
Insert text data from a DataTransfer into the editor. Returns true if some content has been effectively inserted.
`ReactEditor.setFragmentData(editor: ReactEditor, data: DataTransfer, originEvent?: 'drag' | 'copy' | 'cut'): void`
Sets data from the currently selected fragment on a DataTransfer.
`ReactEditor.resolveDOMPoint(editor: ReactEditor, point: Point): DOMPoint | null`
Like toDOMPoint, but returns null instead of throwing. A point can be missing for ordinary reasons, for example during a React commit, before Editable mounts, or after editor.children was replaced, so a miss isn't reported.
`ReactEditor.resolveDOMRange(editor: ReactEditor, range: Range): DOMRange | null`
Like toDOMRange, but returns null instead of throwing, including when either point is missing or the editor's window isn't known yet.
`ReactEditor.resolveEventRange(editor: ReactEditor, event: any): Range | null`
Like findEventRange, but returns null when the event doesn't map to a range in the editor.
`ReactEditor.resolveDOMNode(editor: ReactEditor, node: Node): HTMLElement | null`
Like toDOMNode, but returns null when the node isn't rendered.
`ReactEditor.resolveSlateNode(editor: ReactEditor, domNode: DOMNode): Node | null`
Like toSlateNode, but returns null when the DOM node isn't inside a Slate node.
`ReactEditor.resolveSlatePoint(editor: ReactEditor, domPoint: DOMPoint, options?: { exactMatch?: boolean, searchDirection?: 'forward' | 'backward' }): Point | null`
Like toSlatePoint, but returns null instead of throwing, including in the cases where suppressThrow: true still throws, such as before Editable mounts. exactMatch defaults to false.
`ReactEditor.resolveSlateRange(editor: ReactEditor, domRange: DOMRange | DOMStaticRange | DOMSelection, options?: { exactMatch?: boolean }): Range | null`
Like toSlateRange, but returns null instead of throwing, including for a selection with no range. exactMatch defaults to false.
Instance methods
`editor.onDOMError(error: unknown): void`
Where DOM mapping errors are reported without throwing. Slate reports here when an element mounts and one of its children has no DOM node, usually because renderElement didn't render the children prop. The error names the element's type and path. The resolve lookups return null quietly, since a miss is often ordinary. By default it hands the error to the browser's reportError, so it shows in the console and reaches window.onerror. Override it to send errors to your own logging:
const { onDOMError } = editor
editor.onDOMError = error => {
logger.warn(error)
onDOMError(error)
}The to lookups still throw; use the resolve versions to get null instead.
Libraries Slate React Slate (`docs/libraries/slate-react/slate.md`)
Slate Component
`Slate(props: SlateProps): React.JSX.Element`
The Slate component must include somewhere in its children the Editable component.
Props
type SlateProps = {
editor: ReactEditor
initialValue?: Descendant[]
value?: Descendant[]
children: React.ReactNode
onChange?: (value: Descendant[]) => void
onSelectionChange?: (selection: Selection) => void
onValueChange?: (value: Descendant[]) => void
}`props.editor: ReactEditor`
An instance of ReactEditor
`props.initialValue?: Descendant[]`
The initial value of the editor. It is loaded into the editor when Slate mounts, and again if a different editor is passed.
If you leave it out, the editor's existing editor.children are used, which suits editors you create and fill ahead of rendering. Leaving it out when editor.children is empty throws, since that is usually a forgotten setup step; pass initialValue={[]} if an empty editor is intended.
An editor needs at least one block to hold the cursor, so an empty array is loaded as one empty block, { children: [{ text: '' }] }. The block has no type, so if your schema requires one, pass your own empty block instead, for example [{ type: 'paragraph', children: [{ text: '' }] }].
Changing initialValue afterwards has no effect. Use value for controlled content, apply transforms, or remount Slate with a new key.
Each editor must have its own node objects. To render several editors from the same value, give each one a deep copy, for example with structuredClone(value). Sharing the same objects between editors breaks the lookups Slate uses to map nodes to the DOM.
`props.value?: Descendant[]`
Control the document with a value from your app, and store the user's edits with onValueChange. Passing both value and initialValue throws. The first value loads the editor as initialValue does. Later values are applied in a layout effect through editor.setChildren (Transforms.setChildren), so the selection and history stay valid.
It follows the contract of a React controlled input:
- Pass back the value from
onValueChange. That exact object is recognized and not applied again. - Any other value is treated as a change from outside the editor and applied, including an older value the editor emitted earlier, so an app can restore a previous version.
- Values you pass in, and their normalization, are not reported through
onValueChange.onChangestill fires.
Don't feed responses from a server into value while the user can still type. A response to an earlier save describes an older document, and applying it reverts the typing made since. Apply outside changes with Transforms.setChildren at the point your app decides they are new content.
Keep unchanged node objects when building a new value. Identity makes unchanged subtrees cheap to recognize and lets moved nodes keep the selection inside them. Deep-equal copies produce no operations but need a content comparison.
To change how values are applied, override editor.setChildren. For example, to keep a stream out of undo:
const { setChildren } = editor
editor.setChildren = children =>
HistoryEditor.withoutSaving(editor, () => setChildren(children))Updates wait while the editor is composing or Android has pending input, and only the latest pending value is applied afterwards. Pending updates are dropped when Slate unmounts or its editor changes.
To switch to a different document, remount Slate with a new key instead of passing the new document as value. Applying a whole new document records it as an undo step and diffs it against the old one.
`props.children: React.ReactNode`
The children which must contain an Editable component.
`props.onChange: (value: Descendant[]) => void`
An optional callback function which you can use to be notified of changes in the editor's value.
`props.onValueChange?: (value: Descendant[]) => void`
Like props.onChange, but only called when the editor's value changes, not for selection-only changes.
`props.onSelectionChange?: (selection: Selection) => void`
An optional callback function which you can use to be notified of changes of the editor's selection.
Libraries Slate React With React (`docs/libraries/slate-react/with-react.md`)
withReact
Adds React and DOM specific behaviors to the editor.
`withReact(editor: T, clipboardFormatKey = 'x-slate-fragment'): T & ReactEditor`
When used with withHistory, withReact should be applied outside. For example:
const [editor] = useState(() => withReact(withHistory(createEditor())))`clipboardFormatKey` option
The clipboardFormatKey option allows you to customize the DataTransfer type when Slate data is copied to the clipboard. By default, it is application/x-slate-fragment but it can be customized using this option.
This can be useful when a user copies from one Slate editor to a differently configured Slate editor. This could cause nodes to be inserted which are not correctly typed for the receiving editor, corrupting the document. By customizing the clipboardFormatKey one can ensure that the raw JSON data isn't copied between editors with different schemas.
--- METRICS ---
- Files Extracted: 71
- Estimated Token Budget: ~100366 tokens
- Canonical Reference: https://codewiki.google/github.com/ianstormtaylor/editor