### Start Examples Server
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/general/contributing.md
After building the monorepo, start the examples server to view and interact with Slate examples.
```text
yarn start
```
--------------------------------
### Example Start Point
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/03-locations.md
Represents the beginning of a text node, useful for cursor placement.
```javascript
const start = {
path: [0, 0],
offset: 0,
}
```
--------------------------------
### Install Dependencies and Build Monorepo
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/general/contributing.md
Before running tests or examples, install project dependencies and build the monorepo using Yarn.
```text
yarn install
yarn build
```
--------------------------------
### Open Examples Site Quickly
Source: https://github.com/ianstormtaylor/slate/blob/main/site/examples/Readme.md
A shortcut command to quickly open the Slate examples site in your browser.
```sh
yarn open
```
--------------------------------
### Basic Slate Editor Setup
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/07-enabling-collaborative-editing.md
This is a foundational setup for a Slate editor before integrating collaborative features. It initializes a basic Slate editor instance.
```jsx
import { Slate } from 'slate-react'
const initialValue = {
children: [{ text: '' }],
}
export const CollaborativeEditor = () => {
return
}
const SlateEditor = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
)
}
```
--------------------------------
### Example Document Structure
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/03-locations.md
Illustrates a simple document structure used for path examples.
```javascript
const editor = {
children: [
{
type: 'paragraph',
children: [
{
text: 'A line of text!',
},
],
},
],
}
```
--------------------------------
### Basic Slate Editor Setup
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/02-adding-event-handlers.md
This is the initial setup for a Slate editor before adding any event handlers. It includes the necessary imports and basic component structure.
```jsx
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
)
}
```
--------------------------------
### Run Integration Tests Locally
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/general/contributing.md
Execute integration tests locally. This can be done after starting the examples server or by running `yarn test:integration-local` directly.
```text
yarn test:integration-local
```
--------------------------------
### Install Slate and React Dependencies
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/01-installing-slate.md
Install Slate and its core React plugin, along with React and ReactDOM as peer dependencies.
```text
yarn add slate slate-react
```
```text
yarn add react react-dom
```
--------------------------------
### Install Slate via npm
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/08-using-the-bundled-source.md
To obtain the bundled `slate.js` file, install Slate using npm. The bundled file is located in the `dist` directory.
```text
npm install slate@latest
```
--------------------------------
### Range.start
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/locations/range.md
Get the start point of a range according to the order in which it appears in the document.
```APIDOC
## Range.start
### Description
Get the start point of a `range` according to the order in which it appears in the document.
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
### Parameters
- **range** (Range) - Required - The range to get the start point from.
### Returns
- `Point` - The start point of the range.
```
--------------------------------
### Editor.start
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Retrieves the starting point of a given location.
```APIDOC
## Editor.start(editor: Editor, at: Location)
### Description
Get the start point of a location.
### Parameters
#### Path Parameters
- **editor** (Editor) - Required - The editor instance.
- **at** (Location) - Required - The location to get the start point from.
```
--------------------------------
### Editor.point
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Gets the start or end point of a given location. Defaults to the start point.
```APIDOC
## Editor.point(editor: Editor, at: Location, options?)
### Description
Get the `start` or `end` (default is `start`) point of a location.
### Parameters
#### Path Parameters
- **editor** (Editor) - Required - The editor instance.
- **at** (Location) - Required - The location to get the point from.
#### Options
- **edge** ('start' | 'end') - Optional - The edge of the location to consider. Defaults to 'start'.
```
--------------------------------
### Editor.isStart
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Checks if a given point is the start point of a specified location.
```APIDOC
## Editor.isStart
### Description
Check if a point is the start point of a location.
### Signature
`Editor.isStart(editor: Editor, point: Point, at: Location) => boolean`
```
--------------------------------
### Slate Range Helper Functions
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/01-interfaces.md
Shows how to use built-in Slate helper functions to get the start and end points of a range and check if a range is collapsed.
```javascript
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)) {
// ...
}
```
--------------------------------
### Initial Slate App Setup
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/05-executing-commands.md
Sets up a basic Slate editor with initial content and defines render functions for elements and leaves. It includes an onKeyDown handler for basic formatting.
```jsx
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
default:
return
}
}, [])
const renderLeaf = useCallback(props => {
return
}, [])
return (
{
if (!event.ctrlKey) {
return
}
switch (event.key) {
case '`': {
event.preventDefault()
const [match] = Editor.nodes(editor, {
match: n => n.type === 'code',
})
Transforms.setNodes(
editor,
{ type: match ? null : 'code' },
{
match: n => Element.isElement(n) && Editor.isBlock(editor, n),
}
)
break
}
case 'b': {
event.preventDefault()
Editor.addMark(editor, 'bold', true)
break
}
}
}}
/>
)
}
```
--------------------------------
### Initial Slate Editor Setup
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/03-defining-custom-elements.md
Sets up a basic Slate editor with an initial value containing a paragraph. This serves as the foundation for adding custom elements.
```jsx
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
{
if (event.key === '&') {
event.preventDefault()
editor.insertText('and')
}
}}
/>
)
}
```
--------------------------------
### Built-in Slate Commands
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/06-commands.md
Examples of common built-in commands for text manipulation and structure changes.
```javascript
Editor.insertText(editor, 'A new string of text to be inserted.')
```
```javascript
Editor.deleteBackward(editor, { unit: 'word' })
```
```javascript
Editor.insertBreak(editor)
```
--------------------------------
### Liveblocks RoomProvider Setup for Collaborative Editing
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/07-enabling-collaborative-editing.md
Integrates Liveblocks for real-time collaboration by joining a multiplayer room. Use ClientSideSuspense to handle loading states.
```jsx
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 (
Loading…}>
{() => }
)
}
```
--------------------------------
### Get Location Edges
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Determines the start and end points of a given location within the document.
```typescript
Editor.edges(editor: Editor, at: Location) => [Point, Point]
```
--------------------------------
### Example End Point
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/03-locations.md
Represents the end of a text node, useful for cursor placement.
```javascript
const end = {
path: [0, 0],
offset: 15,
}
```
--------------------------------
### Connecting to a Yjs Collaborative Document
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/07-enabling-collaborative-editing.md
This snippet shows how to initialize a Yjs document and set up a Yjs provider. The specific provider setup (`new YjsProvider(/* ... */)`) will vary depending on your chosen backend.
```jsx
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 = {
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
Loading…
}
return
}
const SlateEditor = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
)
}
```
--------------------------------
### Basic Slate Editor Setup
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/07-enabling-collaborative-editing.md
This is the basic structure for a Slate editor component. It requires an editor instance and initial value.
```jsx
```
--------------------------------
### Start New History Batch
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-history/history-editor.md
Apply changes within a function, ensuring the first operation starts a new batch in the history. Subsequent operations are merged normally.
```typescript
HistoryEditor.withNewBatch(editor: HistoryEditor, fn: () => void): void
```
--------------------------------
### Initial Editor Setup with Block Formatting
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/04-applying-custom-formatting.md
Sets up a basic Slate editor with initial content and a custom renderer for 'code' blocks. Handles toggling between 'paragraph' and 'code' block types using a `control-` backtick hotkey.
```jsx
const renderElement = props => {
switch (props.element.type) {
case 'code':
return
default:
return
}
}
const initialValue = [
{
type: 'paragraph',
children: [{ text: 'A line of text in a paragraph.' }],
},
]
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
return (
{
if (event.key === '`' && event.ctrlKey) {
event.preventDefault()
const [match] = Editor.nodes(editor, {
match: n => n.type === 'code',
})
Transforms.setNodes(
editor,
{ type: match ? 'paragraph' : 'code' },
{ match: n => Element.isElement(n) && Editor.isBlock(editor, n) }
)
}
}}
/>
)
}
```
--------------------------------
### Editor.first
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the first node at a given location in the document.
```APIDOC
## Editor.first(editor: Editor, at: Location)
### Description
Get the first node at a location.
### Parameters
#### Path Parameters
None
#### Query Parameters
- **at** (Location) - Required - The location to get the first node from.
### Returns
- `NodeEntry`: The first node entry at the location.
```
--------------------------------
### CDN Script Includes for Slate
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/08-using-the-bundled-source.md
For quick prototyping, use unpkg.com to include Slate and its React dependencies via script tags. This method avoids local installation.
```markup
```
--------------------------------
### Path.next
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/locations/path.md
Given a path, gets the path to the next sibling node.
```APIDOC
## Path.next
### Description
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.
### Signature
`Path.next(path: Path) => Path`
### Parameters
#### Path Parameters
- **path** (Path) - The path to find the next sibling for.
### Returns
`Path` - The path to the next sibling.
```
--------------------------------
### Setting up Collaborative Editor with Yjs
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/07-enabling-collaborative-editing.md
This snippet shows the core setup for a collaborative Slate editor. It uses `withYjs` to integrate Yjs functionality and `withCursors` to handle remote cursors. Ensure you have `sharedType` and `provider` instances from Yjs.
```javascript
import { withReact, useSlate } from 'slate-react'
import { withHistory } from 'slate-history'
import { withYjs, YjsEditor } from '@slate-yjs/core'
import { withCursors } from '@slate-yjs/core'
import { useMemo, useEffect } from 'react'
import { createEditor, Editor, Transforms } from 'slate'
const initialValue = [
{
type: 'paragraph',
children: [{ text: '' }],
},
]
const SlateEditor = ({ sharedType, provider }) => {
const editor = useMemo(() => {
const e = withReact(
withHistory(
withCursors(
withYjs(createEditor(), sharedType, {
// The current user's name and color
data: {
name: 'Chris',
color: '#00ff00',
},
}),
provider.awareness,
{
// The cursor's data
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(e, initialValue, { at: [0] })
}
return e
}, [])
useEffect(() => {
YjsEditor.connect(editor)
return () => YjsEditor.disconnect(editor)
}, [editor])
return (
)
}
```
--------------------------------
### Path.levels
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/locations/path.md
Get a list of paths at every level down to a given path, including the path itself.
```APIDOC
## Path.levels
### Description
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.
### Signature
`Path.levels(path: Path, options?) => Path[]`
### Parameters
#### Path Parameters
- **path** (Path) - The path to get levels for.
- **options** ({ reverse?: boolean }) - Optional. If `true`, the paths are reversed from deepest to shallowest.
### Returns
`Path[]` - An array of paths at each level.
```
--------------------------------
### Node.first
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/node.md
Retrieves the first node entry within a root node starting from a given path.
```APIDOC
## Node.first
### Description
Get the first node entry in a root node from a `path`.
### Method
`Node.first(root: Node, path: Path) => NodeEntry`
```
--------------------------------
### Path.previous
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/locations/path.md
Given a path, get the path to the previous sibling node.
```APIDOC
## Path.previous
### Description
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).
### Signature
`Path.previous(path: Path) => Path`
### Parameters
#### Path Parameters
- **path** (Path) - The path to find the previous sibling for.
### Returns
`Path` - The path to the previous sibling.
```
--------------------------------
### Integrating Leaf Rendering into the Editor
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/04-applying-custom-formatting.md
This snippet shows the complete `App` component setup, including the `renderElement` callback and the `initialValue`. It's a placeholder for where the `renderLeaf` prop would be integrated to use the custom `Leaf` component.
```jsx
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
default:
return
}
}, [])
```
--------------------------------
### Editor.before
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the point before a location in the document. If there is no point before the location (e.g., at the top of the document), it returns undefined.
```APIDOC
## Editor.before(editor: Editor, at: Location, options?)
### Description
Get the point before a location.
### Parameters
#### Path Parameters
None
#### Query Parameters
- **at** (Location) - Required - The location to find the point before.
- **distance** (number) - Optional - The distance to move before the location.
- **unit** ('offset' | 'character' | 'word' | 'line' | 'block') - Optional - The unit of distance.
- **voids** (boolean) - Optional - Whether to consider void objects.
### Returns
- `Point | undefined`: The point before the location, or undefined if none exists.
```
--------------------------------
### Example Text Node with Bold Mark
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/02-nodes.md
Illustrates a text node with custom properties, such as 'bold', to implement formatting like bold text. These properties are often referred to as marks.
```javascript
const text = {
text: 'A string of bold text',
bold: true,
}
```
--------------------------------
### useSlate
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-react/hooks.md
Get the current editor object. Re-renders whenever changes occur in the editor.
```APIDOC
## useSlate()
### Description
Get the current editor object. Re-renders whenever changes occur in the editor.
### Returns
- `Editor`: The current editor object.
```
--------------------------------
### useElement
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-react/hooks.md
Get the current element object. Re-renders whenever the element or any of its descendants changes.
```APIDOC
## useElement()
### Description
Get the current element object. Re-renders whenever the element or any of its descendants changes.
### Returns
- `Element`: The current element object.
```
--------------------------------
### Custom Leaf Node Rendering with renderLeaf
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-react/editable.md
Shows how to customize the rendering of leaf nodes (text segments) using the `renderLeaf` prop. This example applies bold styling based on the `leaf.bold` property.
```jsx
{
return (
{children}
)
}}
/>
```
--------------------------------
### Editor Helper Functions
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/07-editor.md
Utilize helper functions like `Editor.start` to get specific points within the document or `Editor.fragment` to extract content at a given range.
```javascript
// 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)
```
--------------------------------
### Avoid Infinite Normalization Loops
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/11-normalizing.md
This example demonstrates an incorrect normalization approach that can lead to infinite loops. Ensure that fixes applied during normalization actually resolve the invalid state, rather than perpetuating it.
```javascript
// 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
}
```
--------------------------------
### Editor.edges
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the start and end points of a given location in the document.
```APIDOC
## Editor.edges(editor: Editor, at: Location)
### Description
Get the start and end points of a location.
### Parameters
#### Path Parameters
None
#### Query Parameters
- **at** (Location) - Required - The location to get the edges of.
### Returns
- `[Point, Point]`: An array containing the start and end points.
```
--------------------------------
### placeholder prop
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-react/editable.md
The `placeholder` prop defines the text to be displayed when the editor is empty. It disappears once the user starts typing.
```APIDOC
#### `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.
```
--------------------------------
### Integrating Cursors with Slate Editor
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/07-enabling-collaborative-editing.md
Shows how to integrate the Cursors component and `withCursors` from `slate-yjs` into the main Slate editor setup. This involves passing provider awareness and user information.
```jsx
import { useEffect, useMemo, useState } from 'react'
import { createEditor, Editor, Transforms } from 'slate'
import { Editable, Slate, withReact } from 'slate-react'
```
--------------------------------
### useComposing
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-react/hooks.md
Get the current `composing` state of the editor. It deals with `compositionstart`, `compositionupdate`, `compositionend` events, which are triggered by typing with a language that uses a composition character (e.g. Chinese, Japanese, Korean, etc.).
```APIDOC
## useComposing()
### Description
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.).
### Returns
- `boolean`: The current composing state of the editor.
```
--------------------------------
### Insert Nodes Example
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/transforms.md
Atomically inserts nodes at a specified location, or the current selection, or the end of the document. Use this to insert content without replacing the current selection.
```javascript
Transforms.insertNodes(
editor,
{ type: targetType, children: [{ text: '' }] },
{ at: [editor.children.length] }
)
```
--------------------------------
### Range.edges
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/locations/range.md
Get the start and end points of a range, in the order in which they appear in the document.
```APIDOC
## Range.edges
### Description
Get the start and end points of a `range`, in the order in which they appear in the document.
### Parameters
#### Path Parameters
- None
#### Query Parameters
- **options** (object) - Optional - `{reverse?: boolean}`
### Parameters
- **range** (Range) - Required - The range to get the edges from.
### Returns
- `[Point, Point]` - An array containing the start and end points of the range.
```
--------------------------------
### Slate Node Helper Functions
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/01-interfaces.md
Demonstrates using built-in Slate helper functions to get the string content of an element and retrieve a node at a specific path.
```javascript
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)
```
--------------------------------
### getFragment
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Returns the fragment at the current selection. Used when cutting or copying, as an example, to get the fragment at the current selection.
```APIDOC
## getFragment() => Descendant[]
### Description
Returns the fragment at the current selection. Used when cutting or copying, as an example, to get the fragment at the current selection.
```
--------------------------------
### Editor.next
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the next matching node in the document branch after a given location, with options to specify match, mode, and void handling.
```APIDOC
## Editor.next(editor: Editor, options?)
### Description
Get the matching node in the branch of the document after a location.
### Parameters
#### Path Parameters
None
#### Query Parameters
- **at** (Location) - Optional - The location to start searching from.
- **match** (NodeMatch) - Optional - A function to filter the nodes.
- **mode** ('all' | 'highest' | 'lowest') - Optional - The mode for matching nodes.
- **voids** (boolean) - Optional - Whether to include void nodes.
### Returns
- `NodeEntry | undefined`: The next matching node entry, or undefined if not found.
```
--------------------------------
### Custom Element Properties Example
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/01-interfaces.md
Illustrates adding custom 'type' and 'url' properties to paragraph and link elements, respectively. Slate recognizes these but does not use them directly.
```javascript
const paragraph = {
type: 'paragraph',
children: [...],
}
const link = {
type: 'link',
url: 'https://example.com',
children: [...]
}
```
--------------------------------
### Initialize Editor with History and React
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-history/with-history.md
When using `withReact`, ensure `withHistory` is applied inside it to correctly integrate history management.
```javascript
const [editor] = useState(() => withReact(withHistory(createEditor())))
```
--------------------------------
### Connecting to Yjs Provider with Liveblocks
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/07-enabling-collaborative-editing.md
Sets up a Yjs document and connects it to a Liveblocks room using LiveblocksProvider. Handles connection status and document cleanup.
```jsx
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 Loading…
}
return
}
const SlateEditor = ({ sharedType, provider }) => {
// ...
}
```
--------------------------------
### Publish Experimental Release with Lerna
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/general/contributing.md
Create an experimental release tagged as `@experimental` using Lerna. This is for testing the publish process itself, and end users should not expect usability. Follow the prompts provided by Lerna.
```bash
yarn release:experimental
```
--------------------------------
### useReadOnly
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-react/hooks.md
Get the current `readOnly` state of the editor.
```APIDOC
## useReadOnly()
### Description
Get the current `readOnly` state of the editor.
### Returns
- `boolean`: The current read-only state of the editor.
```
--------------------------------
### useFocused
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-react/hooks.md
Get the current `focused` state of the editor.
```APIDOC
## useFocused()
### Description
Get the current `focused` state of the editor.
### Returns
- `boolean`: The current focused state of the editor.
```
--------------------------------
### Path.common
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/locations/path.md
Get the common ancestor path of two paths.
```APIDOC
## Path.common
### Description
Get the common ancestor path of two paths.
### Signature
`Path.common(path: Path, another: Path) => Path`
### Parameters
#### Path Parameters
- **path** (Path) - The first path.
- **another** (Path) - The second path.
### Returns
`Path` - The common ancestor path.
```
--------------------------------
### Editor.last
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the last node at a given location in the document.
```APIDOC
## Editor.last(editor: Editor, at: Location)
### Description
Get the last node at a location.
### Parameters
#### Path Parameters
None
#### Query Parameters
- **at** (Location) - Required - The location to get the last node from.
### Returns
- `NodeEntry`: The last node entry at the location.
```
--------------------------------
### Use a Plugin with createEditor
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/08-plugins.md
Apply the `withImages` plugin to a newly created Slate editor instance.
```javascript
import { createEditor } from 'slate'
const editor = withImages(createEditor())
```
--------------------------------
### Import Slate Editor Components
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/01-installing-slate.md
Import necessary components and hooks from Slate and Slate-React for editor functionality.
```jsx
// 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'
```
--------------------------------
### Editor.end
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the end point of a given location in the document.
```APIDOC
## Editor.end(editor: Editor, at: Location)
### Description
Get the end point of a location.
### Parameters
#### Path Parameters
None
#### Query Parameters
- **at** (Location) - Required - The location to get the end point of.
### Returns
- `Point`: The end point of the location.
```
--------------------------------
### Editor.unhangRange
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Converts a range into a non-hanging one. This is primarily for fixing browser triple-click selections, adjusting the end of the range to be within a non-empty text node preceding the hanging block. It does not modify the start of the range and has specific caveats regarding double-clicks and selections starting at the end of a block.
```APIDOC
## Editor.unhangRange
### Description
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).
### Signature
`Editor.unhangRange(editor: Editor, range: Range, options?) => Range`
### Parameters
#### Query Parameters
- **voids** (boolean) - Optional, defaults to `false` - Allow placing the end of the selection in a void node.
```
--------------------------------
### Initialize Slate Editor with useState
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/01-installing-slate.md
Create a stable Slate editor instance using `useState` to ensure it doesn't change across renders.
```jsx
const App = () => {
// Create a Slate editor object that won't change across renders.
const [editor] = useState(() => withReact(createEditor()))
return null
}
```
--------------------------------
### Editor.rangeRefs
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the set of currently tracked range refs of the editor.
```APIDOC
## Editor.rangeRefs(editor: Editor) => Set
### Description
Get the set of currently tracked range refs of the editor.
```
--------------------------------
### Editor.pointRefs
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the set of currently tracked point refs of the editor.
```APIDOC
## Editor.pointRefs(editor: Editor) => Set
### Description
Get the set of currently tracked point refs of the editor.
```
--------------------------------
### Custom Command Namespace
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/06-commands.md
Demonstrates how to create a custom namespace for your editor commands, extending the base Editor object.
```javascript
const MyEditor = {
...Editor,
insertParagraph(editor) {
// ...
},
}
```
--------------------------------
### Run Prerelease Script
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/general/contributing.md
Execute the prerelease script to build, test, and lint Slate code without actually publishing a release. This ensures the code is prepared for a release.
```bash
yarn prerelease
```
--------------------------------
### Editor.pathRefs
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the set of currently tracked path refs of the editor.
```APIDOC
## Editor.pathRefs(editor: Editor) => Set
### Description
Get the set of currently tracked path refs of the editor.
```
--------------------------------
### Run Tests
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/general/contributing.md
Execute the test suite for Slate. For debugging, use `yarn test:inspect`.
```text
yarn test
```
--------------------------------
### useSlateSelection
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-react/hooks.md
Get the current editor selection. Only re-renders when the selection changes.
```APIDOC
## useSlateSelection()
### Description
Get the current editor selection. Only re-renders when the selection changes.
### Returns
- `Range | null`: The current editor selection, or null if no selection exists. The range object may include `placeholder` and `onPlaceholderResize` properties.
```
--------------------------------
### Instance Method for Writing History
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-history/history-editor.md
Manually push batches to the undo or redo stacks.
```APIDOC
## writeHistory(stack: 'undos'| 'redos', batch: any) => void
### Description
Push a batch of operations as either `undos` or `redos` onto `editor.undos` or `editor.redos`.
### Method
Instance method
### Parameters
- **stack** ('undos' | 'redos') - Required - The stack to push the batch onto.
- **batch** (any) - Required - The batch of operations to push.
```
--------------------------------
### Editor.fragment
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the fragment of nodes within a given location in the document.
```APIDOC
## Editor.fragment(editor: Editor, at: Location)
### Description
Get the fragment at a location.
### Parameters
#### Path Parameters
None
#### Query Parameters
- **at** (Location) - Required - The location to get the fragment from.
### Returns
- `Descendant[]`: An array of descendant nodes representing the fragment.
```
--------------------------------
### Publish Next Release with Lerna
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/general/contributing.md
Publish a release tagged as `@next` using Lerna. Use this for releases with significant or complex changes where stability is uncertain. Follow the prompts provided by Lerna.
```bash
yarn release:next
```
--------------------------------
### Editor.marks
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the marks that would be applied to text at the current selection in the editor.
```APIDOC
## Editor.marks(editor: Editor)
### Description
Get the marks that would be added to text at the current selection.
### Parameters
None
### Returns
- `Omit | null`: An object containing the marks, or null if no marks are present.
```
--------------------------------
### Path.compare
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/locations/path.md
Compare a path to another, returning -1, 0, or 1.
```APIDOC
## Path.compare
### Description
Compare a path to another, returning an integer indicating whether the path was before (-1), at (0), or after (1) 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.
### Signature
`Path.compare(path: Path, another: Path) => -1 | 0 | 1`
### Parameters
#### Path Parameters
- **path** (Path) - The path to compare.
- **another** (Path) - The path to compare against.
### Returns
`-1 | 0 | 1` - Indicating the order of the paths.
```
--------------------------------
### Range.end
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/locations/range.md
Get the end point of a range according to the order in which it appears in the document.
```APIDOC
## Range.end
### Description
Get the end point of a `range` according to the order in which it appears in the document.
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
### Parameters
- **range** (Range) - Required - The range to get the end point from.
### Returns
- `Point` - The end point of the range.
```
--------------------------------
### Publish Latest Release with Lerna
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/general/contributing.md
Publish a normal release tagged as `@latest` using Lerna. This command automatically runs the `prerelease` script first, which includes building, testing, and linting.
```bash
yarn release:latest
```
--------------------------------
### Instance Methods for Undo and Redo
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-history/history-editor.md
Directly call undo and redo on the editor instance.
```APIDOC
## undo(): void
### Description
Undo the last batch of operations.
### Method
Instance method
```
```APIDOC
## redo(): void
### Description
Redo the last undone batch of operations.
### Method
Instance method
```
--------------------------------
### Render Slate Context Provider
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/walkthroughs/01-installing-slate.md
Wrap the application with the `` component to provide the editor context, including the editor instance and initial value.
```jsx
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
}
```
--------------------------------
### Get End Point of Location
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Retrieves the end point of a specified location in the document.
```typescript
Editor.end(editor: Editor, at: Location) => Point
```
--------------------------------
### Run Integration Tests in Docker
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/general/contributing.md
Execute integration tests within a Docker container to replicate the CI environment. This is useful when tests fail on CI but pass locally due to OS differences. The script automatically starts the server, runs tests, and stops the server.
```bash
yarn test:integration-docker
```
```bash
yarn test:integration-docker playwright/integration/slate-react/selection.test.ts
```
```bash
yarn test:integration-docker --project=chromium
```
```bash
yarn test:integration-docker playwright/integration/examples/check-lists.test.ts --project chromium
```
--------------------------------
### Element with Custom Properties
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/concepts/02-nodes.md
Demonstrates adding custom properties like `url` to `Element` nodes, such as for defining link nodes.
```javascript
const link = {
type: 'link',
url: 'https://example.com',
children: [...],
}
```
--------------------------------
### Node.string
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/node.md
Gets the concatenated text string of a node's content, useful for offset computations.
```APIDOC
## Node.string
### Description
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.
### Method
`Node.string(root: Node) => string`
```
--------------------------------
### Custom Element Rendering with renderElement
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-react/editable.md
Demonstrates how to use the `renderElement` prop to customize the rendering of different element types within the Slate editor. It requires memoization with `useCallback` for performance.
```javascript
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
default:
return
}
}, [])
return (
)
}
const CodeElement = props => {
return (
{props.children}
)
}
const DefaultElement = props => {
return {props.children}
}
```
--------------------------------
### Get Fragment at Location
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Extracts the content (a fragment of nodes) present at a given location in the document.
```typescript
Editor.fragment(editor: Editor, at: Location) => Descendant[]
```
--------------------------------
### Static Methods for Undo and Redo
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-history/history-editor.md
These static methods allow direct control over the editor's undo and redo history.
```APIDOC
## HistoryEditor.redo(editor: HistoryEditor): void
### Description
Redo to the next saved state.
### Method
Static method
### Parameters
- **editor** (HistoryEditor) - Required - The editor instance to perform the action on.
```
```APIDOC
## HistoryEditor.undo(editor: HistoryEditor): void
### Description
Undo to the previous saved state.
### Method
Static method
### Parameters
- **editor** (HistoryEditor) - Required - The editor instance to perform the action on.
```
--------------------------------
### Range.intersection
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/locations/range.md
Get the intersection of one range with another. If the two ranges do not overlap, return null.
```APIDOC
## Range.intersection
### Description
Get the intersection of one `range` with `another`. If the two ranges do not overlap, return `null`.
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
### Parameters
- **range** (Range) - Required - The first range.
- **another** (Range) - Required - The second range.
### Returns
- `Range | null` - The intersection of the two ranges, or `null` if they do not overlap.
```
--------------------------------
### Get Common Ancestor Path
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/locations/path.md
Finds the common ancestor path between two given paths.
```typescript
Path.common(path: Path, another: Path) => Path
```
--------------------------------
### apply
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Apply an operation in the editor.
```APIDOC
## apply(operation: Operation) => void
### Description
Apply an operation in the editor.
### Parameters
#### Path Parameters
- **operation** (Operation) - Required - The operation to apply.
```
--------------------------------
### Editor.path
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Gets the path of a specified location within the editor. Supports optional depth and edge options.
```APIDOC
## Editor.path(editor: Editor, at: Location, options?)
### Description
Get the path of a location.
### Parameters
#### Path Parameters
- **editor** (Editor) - Required - The editor instance.
- **at** (Location) - Required - The location to get the path from.
#### Options
- **depth** (number) - Optional - The depth to retrieve the path.
- **edge** ('start' | 'end') - Optional - The edge of the location to consider.
```
--------------------------------
### as
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/libraries/slate-react/editable.md
Specifies the HTML element type used to render the Editable component. Defaults to 'div'.
```APIDOC
## `as`
### Description
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`.
### Type
`React.ElementType` (defaults to `"div"`)
```
--------------------------------
### Editor.leaf
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the leaf text node at a given location in the document, with options to specify depth and edge.
```APIDOC
## Editor.leaf(editor: Editor, at: Location, options?)
### Description
Get the leaf text node at a location.
### Parameters
#### Path Parameters
None
#### Query Parameters
- **at** (Location) - Required - The location to get the leaf node from.
- **depth** (number) - Optional - The depth to search for the leaf node.
- **edge** ('start' | 'end') - Optional - The edge of the location to search from.
### Returns
- `NodeEntry`: The leaf node entry at the location.
```
--------------------------------
### Editor.after
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Get the point after a location in the document. If there is no point after the location (e.g., at the bottom of the document), it returns undefined.
```APIDOC
## Editor.after(editor: Editor, at: Location, options?)
### Description
Get the point after a location.
### Parameters
#### Path Parameters
None
#### Query Parameters
- **at** (Location) - Required - The location to find the point after.
- **distance** (number) - Optional - The distance to move after the location.
- **unit** ('offset' | 'character' | 'word' | 'line' | 'block') - Optional - The unit of distance.
- **voids** (boolean) - Optional - Whether to consider void objects.
### Returns
- `Point | undefined`: The point after the location, or undefined if none exists.
```
--------------------------------
### Get Last Node at Location
Source: https://github.com/ianstormtaylor/slate/blob/main/docs/api/nodes/editor.md
Finds the last node entry located at a specific location in the document.
```typescript
Editor.last(editor: Editor, at: Location) => NodeEntry
```