mirror of
https://github.com/ianstormtaylor/slate.git
synced 2025-08-30 10:29:48 +02:00
Next (#3093)
* remove some key usage from core, refactor Operations.apply * undeprecate some methods * convert more key usage to paths * update deprecations * convert selection commands to use all paths * refactor word boundary selection logic * convert many at-range commands to use paths * convert wrapBlock and wrapInline to not use keys * cleanup * remove chainability from editor * simplify commands, queries and middleware * convert deleteAtRange * remove key usage from schema, deprecate *ByKey methods * migrate *ByKey tests, remove index from *ByPath signatures * rename at-current-range tests * deprecate mode key usage, migrate more tests away from keys * deprecate range and point methods which rely on keys to work * refactor insertBlock, without fixing warnings * add pathRef/pointRef, fix insertBlock/Inline deprecations, work on insertFragment * refactor insertFragment * get rich-text example rendering * fix lint * refactor query files, fix more tests * remove unused queries, refactor others * deprecate splitDescendantsByPath * merge master * add typescript, convert slate, slate-hyperscript, slate-plain-serializer * add Point, Path, Range, Annotation tests * add Annotation, Change, Element, Fragment, Mark, Range, Selection, Value interfaces tests * add Operation and Text tests * add Node tests * get operations and normalization tests working for slate * get *AtPath command tests passing * rename *AtPath command tests * rename * get *AtPoint tests working * rename * rename * add value queries tests * add element, mark and path queries tests * convert most on-selection tests * convert on-selection commands * rename * get addMarks and delete commands working * rename * rename * rename * refactor value.positions(), work on delete tests * progress on delete tests * more delete work * finish delete tests * start converting to at-based commands * restructure query tests * restructure operations tests * more work converting to multi-purpose commands * lots of progress on converting to at-based commands * add unwrapNodes * remove setValue * more progress * refactor node commands to use consistent matching logic * cleanup, get non-fragment commands passing * remove annotations and isAtomic * rename surround/pluck to cover/uncover * add location concept, change at-path to from-path for iterables * refactor batches * add location-based queries * refactor hanging logic * more location query work * renaming * use getMatch more * add split to wrap/unwrap * flip levels/ancestors ordering * switch splitNodes to use levels * change split to always:false by default * fix tests * add more queries tests * fixing more delete logic * add more splitNodes tests * get rest of delete tests passing * fix location-based logic in some commands * cleanup * get previous packages tests passing again * add slate-history package * start slate-schema work * start of react working * rendering fixes * get rich and plain text examples working * get image example working with hooks and dropping * refactor onDrop to be internal * inline more event handlers * refactor lots of event-related logic * change rendering to use render props * delete unused stuff * cleanup dom utils * remove unused deps * remove unnecessary packages, add placeholder * remove slate-react-placeholder package * remove unused dep * remove unnecessary tests, fix readonly example * convert checklists example * switch to next from webpack * get link example working * convert more examples * preserve keys, memoized leafs/texts, fix node lookup * fix to always useLayoutEffect for ordering * fix annotations to be maps, memoize elements * remove Change interface * remove String interface * rename Node.entries to Node.nodes * remove unnecessary value queries * default to selection when iterating, cleanup * remove unused files * update scroll into view logic * fix undoing, remove constructor types * dont sync selection while composing * add workflows * remove unused deps * convert mentions example * tweaks * convert remaining examples * rename h to jsx, update schema * fix schema tests * fix slate-schema logic and tests * really fix slate-schema and forced-layout example * get start of insertFragment tests working * remove Fragment interface * remove debugger * get all non-skipped tests passing * cleanup deps * run prettier * configure eslint for typescript * more eslint fixes... * more passing * update some docs * fix examples * port windows undo hotkey change * fix deps, add basic firefox support * add event overriding, update walkthroughs * add commands, remove classes, cleanup examples * cleanup rollup config * update tests * rename queries tests * update other tests * update walkthroughs * cleanup interface exports * cleanup, change mark transforms to require location * undo mark transform change * more * fix tests * fix example * update walkthroughs * update docs * update docs * remove annotations * remove value, move selection and children to editor * add migrating doc * fix lint * fix tests * fix DOM types aliasing * add next export * update deps, fix prod build * fix prod build * update scripts * update docs and changelogs * update workflow and pull request template
This commit is contained in:
117
docs/walkthroughs/01-installing-slate.md
Normal file
117
docs/walkthroughs/01-installing-slate.md
Normal file
@@ -0,0 +1,117 @@
|
||||
# Installing Slate
|
||||
|
||||
Slate is a monorepo divided up into multi npm packages, so to install it you do:
|
||||
|
||||
```
|
||||
yarn add slate slate-react
|
||||
```
|
||||
|
||||
You'll also need to be sure to install Slate's peer dependencies:
|
||||
|
||||
```
|
||||
yarn add react react-dom
|
||||
```
|
||||
|
||||
_Note, 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](./using-the-bundled-source.md) guide for more information._
|
||||
|
||||
Once you've installed Slate, you'll need to import it.
|
||||
|
||||
Slate exposes a set of modules that you'll use to build your editor. The most important of which are the `Editor` class and the `<Editable>` component.
|
||||
|
||||
```js
|
||||
// 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:
|
||||
|
||||
```jsx
|
||||
// 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 `useMemo` hook:
|
||||
|
||||
```jsx
|
||||
const App = () => {
|
||||
// Create a Slate editor object that won't change across renders.
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
return null
|
||||
}
|
||||
```
|
||||
|
||||
Of course we haven't rendered anything, so you won't see any changes.
|
||||
|
||||
Next up is to render a `<Slate>` context provider.
|
||||
|
||||
The provider component leeps track of your Slate editor, it's plugins, it's default value, 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.
|
||||
|
||||
```jsx
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
// Render the Slate editor context.
|
||||
return <Slate editor={editor} />
|
||||
}
|
||||
```
|
||||
|
||||
You can think of the `<Slate>` component as provided an "un-controlled" editor context to every component underneath it.
|
||||
|
||||
This is a slightly different mental model than things like `<input>` or `<textarea>`, because rich-text 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.
|
||||
|
||||
Okay, so the next step is to render the `<Editable>` component itself:
|
||||
|
||||
```jsx
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
return (
|
||||
// Add the editable component inside the context.
|
||||
<Slate editor={editor}>
|
||||
<Editable />
|
||||
</Slate>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The `<Editable>` component acts like `contenteditable`. Anywhere you render it will render an editable rich-text document for the nearest editor context.
|
||||
|
||||
There's only last step. So far we haven't defined what the default value of the editor is, so it's empty. Let's fix that by defining an initial value.
|
||||
|
||||
The value is just plain JSON. Here's one contains a single paragraph block with some text in it:
|
||||
|
||||
```js
|
||||
// Create our default value...
|
||||
const defaultValue = [
|
||||
{
|
||||
type: 'paragraph',
|
||||
children: [
|
||||
{
|
||||
text: 'A line of text in a paragraph.',
|
||||
marks: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
return (
|
||||
// Add the default value as a prop to the editor context.
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<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!
|
||||
|
||||
You'll notice that there is no `onChange` handler defined. That's because the `<Slate>` context acts like an **un-controlled** component, with the changes automatically being propogated to any context consumers. However, just like with un-controlled components you can attach an `onChange` prop to listen for changes. We'll cover that later.
|
68
docs/walkthroughs/02-adding-event-handlers.md
Normal file
68
docs/walkthroughs/02-adding-event-handlers.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# 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. You've already seen how the `onChange` handler can be used to store the changed editor value, but let's try adding more...
|
||||
|
||||
Let's use the `onKeyDown` handler to change the editor's content when we press a key.
|
||||
|
||||
Here's our app from earlier:
|
||||
|
||||
```js
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<Editable />
|
||||
</Slate>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Now we add an `onKeyDown` handler:
|
||||
|
||||
```js
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<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:
|
||||
|
||||
```js
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<Editable
|
||||
onKeyDown={event => {
|
||||
if (event.key === '&') {
|
||||
// Prevent the ampersand character from being inserted.
|
||||
event.preventDefault()
|
||||
// Execute a command to insert text when the event occurs.
|
||||
editor.exec({ type: 'insert_text', text: '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 the `editor` that lets you perform commands. Simple!
|
195
docs/walkthroughs/03-defining-custom-elements.md
Normal file
195
docs/walkthroughs/03-defining-custom-elements.md
Normal file
@@ -0,0 +1,195 @@
|
||||
# Defining Custom Block Nodes
|
||||
|
||||
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 `<div>`.
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<Editable
|
||||
onKeyDown={event => {
|
||||
if (event.key === '&') {
|
||||
event.preventDefault()
|
||||
editor.exec({ type: 'insert_text', text: 'and' })
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Slate>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Now let's add "code blocks" to our editor.
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
// 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:
|
||||
|
||||
```js
|
||||
const DefaultElement = props => {
|
||||
return <p {...props.attributes}>{props.children}</p>
|
||||
}
|
||||
```
|
||||
|
||||
Now, let's add that renderer to our `Editor`:
|
||||
|
||||
```js
|
||||
const App = () => {
|
||||
const editor = useMemo(() => 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} defaultValue={defaultValue}>
|
||||
<Editable
|
||||
// Pass in the `renderElement` function.
|
||||
renderElement={renderElement}
|
||||
onKeyDown={event => {
|
||||
if (event.key === '&') {
|
||||
event.preventDefault()
|
||||
editor.exec({ type: 'insert_text', text: '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:
|
||||
|
||||
```js
|
||||
// Import the `Editor` helpers from Slate.
|
||||
import { Editor } from 'slate'
|
||||
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
const renderElement = useCallback(props => {
|
||||
switch (props.element.type) {
|
||||
case 'code':
|
||||
return <CodeElement {...props} />
|
||||
default:
|
||||
return <DefaultElement {...props} />
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<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".
|
||||
Editor.setNodes(editor, { type: 'code' }, { match: 'block' })
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</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:
|
||||
|
||||
```js
|
||||
const App = () => {
|
||||
const [value, setValue] = useState(initialValue)
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
const renderElement = useCallback(props => {
|
||||
switch (props.element.type) {
|
||||
case 'code':
|
||||
return <CodeElement {...props} />
|
||||
default:
|
||||
return <DefaultElement {...props} />
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<Editable
|
||||
renderElement={renderElement}
|
||||
onKeyDown={event => {
|
||||
if (event.key === '`' && event.ctrlKey) {
|
||||
event.preventDefault()
|
||||
// Determine whether any of the currently selected blocks are code blocks.
|
||||
const { selection } = editor
|
||||
const isCode = selection
|
||||
? Editor.match(editor, selection, { type: 'code' })
|
||||
: false
|
||||
|
||||
// Toggle the block type depending on `isCode`.
|
||||
Editor.setNodes(
|
||||
editor,
|
||||
{ type: isCode ? 'paragraph' : 'code' },
|
||||
{ match: 'block' }
|
||||
)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Slate>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
And there you have it! If you press `Ctrl-\`` while inside a code block, it should turn back into a paragraph!
|
181
docs/walkthroughs/04-applying-custom-formatting.md
Normal file
181
docs/walkthroughs/04-applying-custom-formatting.md
Normal file
@@ -0,0 +1,181 @@
|
||||
# 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~~.
|
||||
|
||||
So we start with our app from earlier:
|
||||
|
||||
```js
|
||||
const App = () => {
|
||||
const [value, setValue] = useState(initialValue)
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
const renderElement = useCallback(props => {
|
||||
switch (props.element.type) {
|
||||
case 'code':
|
||||
return <CodeElement {...props} />
|
||||
default:
|
||||
return <DefaultElement {...props} />
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<Editable
|
||||
renderElement={renderElement}
|
||||
onKeyDown={event => {
|
||||
if (event.key === '`' && event.ctrlKey) {
|
||||
event.preventDefault()
|
||||
const { selection } = editor
|
||||
const isCode = selection
|
||||
? Editor.match(editor, selection, { type: 'code' })
|
||||
: false
|
||||
|
||||
Editor.setNodes(
|
||||
editor,
|
||||
{ type: isCode ? 'paragraph' : 'code' },
|
||||
{ match: 'block' }
|
||||
)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Slate>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
And now, we'll edit the `onKeyDown` handler to make it so that when you press `control-B`, it will add a "bold" mark to the currently selected text:
|
||||
|
||||
```js
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
const renderElement = useCallback(props => {
|
||||
switch (prop.element.type) {
|
||||
case 'code':
|
||||
return <CodeElement {...props} />
|
||||
default:
|
||||
return <DefaultElement {...props} />
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<Editable
|
||||
renderElement={renderElement}
|
||||
onKeyDown={event => {
|
||||
if (!event.ctrlKey) {
|
||||
return
|
||||
}
|
||||
|
||||
// When "`" is pressed, keep our existing code block logic.
|
||||
switch (event.key) {
|
||||
case '`': {
|
||||
event.preventDefault()
|
||||
const { selection } = editor
|
||||
const isCode = selection
|
||||
? Editor.match(editor, selection, { type: 'code' })
|
||||
: false
|
||||
|
||||
Editor.setNodes(
|
||||
editor,
|
||||
{ type: isCode ? null : 'code' },
|
||||
{ match: 'block' }
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
// When "B" is pressed, add a bold mark to the text.
|
||||
case 'b': {
|
||||
event.preventDefault()
|
||||
Editor.addMarks(editor, [{ type: 'bold' }])
|
||||
break
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Slate>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
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 mark type you want to add to your schema, you need to give Slate a "renderer" for that mark, just like elements. So let's define our `bold` mark:
|
||||
|
||||
```js
|
||||
// Define a React component to render bold text with.
|
||||
const BoldMark = props => {
|
||||
return <strong {...props.attributes}>{props.children}</strong>
|
||||
}
|
||||
```
|
||||
|
||||
Pretty familiar, right?
|
||||
|
||||
And now, let's tell Slate about that mark. To do that, we'll pass in the `renderMark` prop to our editor. Also, let's allow our mark to be toggled by changing `addMark` to `toggleMark`.
|
||||
|
||||
```js
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
const renderElement = useCallback(props => {
|
||||
switch (props.element.type) {
|
||||
case 'code':
|
||||
return <CodeElement {...props} />
|
||||
default:
|
||||
return <DefaultElement {...props} />
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Define a mark rendering function that is memoized with `useCallback`.
|
||||
const renderMark = useCallback(props => {
|
||||
switch (props.mark.type) {
|
||||
case 'bold': {
|
||||
return <BoldMark {...props} />
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<Editable
|
||||
renderElement={renderElement}
|
||||
// Pass in the `renderMark` function.
|
||||
renderMark={renderMark}
|
||||
onKeyDown={event => {
|
||||
if (!event.ctrlKey) {
|
||||
return
|
||||
}
|
||||
|
||||
switch (event.key) {
|
||||
case '`': {
|
||||
event.preventDefault()
|
||||
const { selection } = editor
|
||||
const isCode = selection
|
||||
? Editor.match(editor, selection, { type: 'code' })
|
||||
: false
|
||||
|
||||
Editor.setNodes(
|
||||
editor,
|
||||
{ type: isCode ? null : 'code' },
|
||||
{ match: 'block' }
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
case 'b': {
|
||||
event.preventDefault()
|
||||
Editor.addMarks(editor, [{ type: 'bold' }])
|
||||
break
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Slate>
|
||||
)
|
||||
}
|
||||
|
||||
const BoldMark = props => {
|
||||
return <strong {...props.attributes}>{props.children}</strong>
|
||||
}
|
||||
```
|
||||
|
||||
Now, if you try selecting a piece of text and hitting `Ctrl-B` you should see it turn bold! Magic!
|
342
docs/walkthroughs/05-executing-commands.md
Normal file
342
docs/walkthroughs/05-executing-commands.md
Normal file
@@ -0,0 +1,342 @@
|
||||
# Using 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:
|
||||
|
||||
```js
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
const renderElement = useCallback(props => {
|
||||
switch (props.element.type) {
|
||||
case 'code':
|
||||
return <CodeElement {...props} />
|
||||
default:
|
||||
return <DefaultElement {...props} />
|
||||
}
|
||||
}, [])
|
||||
|
||||
const renderMark = useCallback(props => {
|
||||
switch (props.mark.type) {
|
||||
case 'bold': {
|
||||
return <BoldMark {...props} />
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<Editable
|
||||
renderElement={renderElement}
|
||||
renderMark={renderMark}
|
||||
onKeyDown={event => {
|
||||
if (!event.ctrlKey) {
|
||||
return
|
||||
}
|
||||
|
||||
switch (event.key) {
|
||||
case '`': {
|
||||
event.preventDefault()
|
||||
const { selection } = editor
|
||||
const isCode = selection
|
||||
? Editor.match(editor, selection, { type: 'code' })
|
||||
: false
|
||||
|
||||
Editor.setNodes(
|
||||
editor,
|
||||
{ type: isCode ? null : 'code' },
|
||||
{ match: 'block' }
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
case 'b': {
|
||||
event.preventDefault()
|
||||
Editor.addMarks(editor, [{ type: 'bold' }])
|
||||
break
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Slate>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
It has the concept of "code blocks" and "bold marks". 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 extending the `editor` object:
|
||||
|
||||
```js
|
||||
// Create a custom editor plugin function that will augment the editor.
|
||||
const withCustom = editor => {
|
||||
return editor
|
||||
}
|
||||
|
||||
const App = () => {
|
||||
// Wrap the editor with our new `withCustom` plugin.
|
||||
const editor = useMemo(() => withCustom(withReact(createEditor())), [])
|
||||
const renderElement = useCallback(props => {
|
||||
switch (props.element.type) {
|
||||
case 'code':
|
||||
return <CodeElement {...props} />
|
||||
default:
|
||||
return <DefaultElement {...props} />
|
||||
}
|
||||
}, [])
|
||||
|
||||
const renderMark = useCallback(props => {
|
||||
switch (props.mark.type) {
|
||||
case 'bold': {
|
||||
return <BoldMark {...props} />
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<Editable
|
||||
renderElement={renderElement}
|
||||
renderMark={renderMark}
|
||||
onKeyDown={event => {
|
||||
if (!event.ctrlKey) {
|
||||
return
|
||||
}
|
||||
|
||||
switch (event.key) {
|
||||
case '`': {
|
||||
event.preventDefault()
|
||||
const { selection } = editor
|
||||
const isCode = selection
|
||||
? Editor.match(editor, selection, { type: 'code' })
|
||||
: false
|
||||
|
||||
Editor.setNodes(
|
||||
editor,
|
||||
{ type: isCode ? null : 'code' },
|
||||
{ match: 'block' }
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
case 'b': {
|
||||
event.preventDefault()
|
||||
Editor.toggleMarks(editor, [{ type: 'bold' }])
|
||||
break
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Slate>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Since we haven't yet defined (or overridden) any commands in `withCustom`, nothing will change yet. Our app will still function exactly as it did before.
|
||||
|
||||
However, now we can start extract bits of logic into reusable methods:
|
||||
|
||||
```js
|
||||
const withCustom = editor => {
|
||||
const { exec } = editor
|
||||
|
||||
editor.exec = command => {
|
||||
// Define a command to toggle the bold mark formatting.
|
||||
if (command.type === 'toggle_bold_mark') {
|
||||
const isActive = CustomEditor.isBoldMarkActive(editor)
|
||||
// Delegate to the existing `add_mark` and `remove_mark` commands, so that
|
||||
// other plugins can override them if they need to still.
|
||||
editor.exec({
|
||||
type: isActive ? 'remove_mark' : 'add_mark',
|
||||
mark: { type: 'bold' },
|
||||
})
|
||||
}
|
||||
|
||||
// Define a command to toggle the code block formatting.
|
||||
else if (command.type === 'toggle_code_block') {
|
||||
const isActive = CustomEditor.isCodeBlockActive(editor)
|
||||
// There is no `set_nodes` command, so we can transform the editor
|
||||
// directly using the helper instead.
|
||||
Editor.setNodes(
|
||||
editor,
|
||||
{ type: isActive ? null : 'code' },
|
||||
{ match: 'block' }
|
||||
)
|
||||
}
|
||||
|
||||
// Otherwise, fall back to the built-in `exec` logic for everything else.
|
||||
else {
|
||||
exec(command)
|
||||
}
|
||||
}
|
||||
|
||||
return editor
|
||||
}
|
||||
|
||||
// Define our own custom set of helpers for common queries.
|
||||
const CustomEditor = {
|
||||
isBoldMarkActive(editor) {
|
||||
const { selection } = editor
|
||||
const activeMarks = Editor.activeMarks(editor)
|
||||
return activeMarks.some(mark => mark.type === 'bold')
|
||||
},
|
||||
|
||||
isCodeBlockActive(editor) {
|
||||
const { selection } = editor
|
||||
const isCode = selection
|
||||
? Editor.match(editor, selection, { type: 'code' })
|
||||
: false
|
||||
return isCode
|
||||
},
|
||||
}
|
||||
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withCustom(withReact(createEditor())), [])
|
||||
const renderElement = useCallback(props => {
|
||||
switch (props.element.type) {
|
||||
case 'code':
|
||||
return <CodeElement {...props} />
|
||||
default:
|
||||
return <DefaultElement {...props} />
|
||||
}
|
||||
}, [])
|
||||
|
||||
const renderMark = useCallback(props => {
|
||||
switch (props.mark.type) {
|
||||
case 'bold': {
|
||||
return <BoldMark {...props} />
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<Editable
|
||||
renderElement={renderElement}
|
||||
renderMark={renderMark}
|
||||
// Replace the `onKeyDown` logic with our new commands.
|
||||
onKeyDown={event => {
|
||||
if (!event.ctrlKey) {
|
||||
return
|
||||
}
|
||||
|
||||
switch (event.key) {
|
||||
case '`': {
|
||||
event.preventDefault()
|
||||
editor.exec({ type: 'toggle_code_block' })
|
||||
break
|
||||
}
|
||||
|
||||
case 'b': {
|
||||
event.preventDefault()
|
||||
editor.exec({ type: 'toggle_bold_mark' })
|
||||
break
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Slate>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
const App = () => {
|
||||
const [value, setValue] = useState(initialValue)
|
||||
const editor = useMemo(() => withCustom(withReact(createEditor())), [])
|
||||
const renderElement = useCallback(props => {
|
||||
switch (props.element.type) {
|
||||
case 'code':
|
||||
return <CodeElement {...props} />
|
||||
default:
|
||||
return <DefaultElement {...props} />
|
||||
}
|
||||
}, [])
|
||||
|
||||
const renderMark = useCallback(props => {
|
||||
switch (props.mark.type) {
|
||||
case 'bold': {
|
||||
return <BoldMark {...props} />
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
// Add a toolbar with buttons that call the same methods.
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<div>
|
||||
<button
|
||||
onMouseDown={event => {
|
||||
event.preventDefault()
|
||||
editor.exec({ type: 'toggle_bold_mark' })
|
||||
}}
|
||||
>
|
||||
Bold
|
||||
</button>
|
||||
<button
|
||||
onMouseDown={event => {
|
||||
event.preventDefault()
|
||||
editor.exec({ type: 'toggle_code_block' })
|
||||
}}
|
||||
>
|
||||
Code Block
|
||||
</button>
|
||||
</div>
|
||||
<Editable
|
||||
editor={editor}
|
||||
value={value}
|
||||
renderElement={renderElement}
|
||||
renderMark={renderMark}
|
||||
onChange={newValue => setValue(newValue)}
|
||||
onKeyDown={event => {
|
||||
if (!event.ctrlKey) {
|
||||
return
|
||||
}
|
||||
|
||||
switch (event.key) {
|
||||
case '`': {
|
||||
event.preventDefault()
|
||||
editor.exec({ type: 'toggle_code_block' })
|
||||
break
|
||||
}
|
||||
|
||||
case 'b': {
|
||||
event.preventDefault()
|
||||
editor.exec({ type: 'toggle_bold_mark' })
|
||||
break
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Slate>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
That's the benefit of extracting the logic.
|
||||
|
||||
And you don't necessarily need to define it all in the same plugin. You can use the plugin pattern to add logic and behaviors to an editor from elsewhere.
|
||||
|
||||
For example, you can use the `slate-history` package to add a history stack to your editor, like so:
|
||||
|
||||
```js
|
||||
import { Editor } from 'slate'
|
||||
import { withHistory } from 'slate-history'
|
||||
|
||||
const editor = useMemo(
|
||||
() => withCustom(withHistory(withReact(createEditor()))),
|
||||
[]
|
||||
)
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
That's why plugins are awesome. They let you get really expressive while also making your codebase easier to manage. And since Slate is built with plugins as a primary consideration, using them is dead simple!
|
163
docs/walkthroughs/06-saving-to-a-database.md
Normal file
163
docs/walkthroughs/06-saving-to-a-database.md
Normal file
@@ -0,0 +1,163 @@
|
||||
# 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:
|
||||
|
||||
```js
|
||||
import React, { useMemo } from 'react'
|
||||
import { createEditor } from 'slate'
|
||||
import { Slate, Editable, withReact } from 'slate-react'
|
||||
|
||||
const defaultValue = [
|
||||
{
|
||||
children: [
|
||||
{
|
||||
text: 'A line of text in a paragraph.',
|
||||
marks: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
return (
|
||||
<Slate editor={editor} defaultValue={defaultValue}>
|
||||
<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](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), 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`:
|
||||
|
||||
```js
|
||||
const defaultValue = [
|
||||
{
|
||||
children: [
|
||||
{
|
||||
text: 'A line of text in a paragraph.',
|
||||
marks: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
return (
|
||||
<Slate
|
||||
editor={editor}
|
||||
defaultValue={defaultValue}
|
||||
onChange={value => {
|
||||
// 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. That's because we need to make sure the initial value is pulled from that same Local Storage location, like so:
|
||||
|
||||
```js
|
||||
// Update the initial content to be pulled from Local Storage if it exists.
|
||||
const existingValue = JSON.parse(localStorage.getItem('content'))
|
||||
const defaultValue = existingValue || [
|
||||
{
|
||||
children: [
|
||||
{
|
||||
text: 'A line of text in a paragraph.',
|
||||
marks: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
return (
|
||||
<Slate
|
||||
editor={editor}
|
||||
defaultValue={defaultValue}
|
||||
onChange={value => {
|
||||
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:
|
||||
|
||||
```js
|
||||
// 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 text content of each paragraph in the value's children.
|
||||
.map(n => Node.text(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 {
|
||||
children: [{ text: line, marks: [] }],
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Use our deserializing function to read the data from Local Storage.
|
||||
const existingValue = localStorage.getItem('content')
|
||||
const initialValue = deserialize(existingValue || '')
|
||||
|
||||
const App = () => {
|
||||
const editor = useMemo(() => withReact(createEditor()), [])
|
||||
return (
|
||||
<Slate
|
||||
editor={editor}
|
||||
defaultValue={defaultValue}
|
||||
onChange={value => {
|
||||
// Serialize the value and save the string value to Local Storage.
|
||||
const content = serialize(newValue)
|
||||
localStorage.setItem('content', content)
|
||||
}}
|
||||
>
|
||||
<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.
|
@@ -22,13 +22,12 @@ node_modules/
|
||||
|
||||
A 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 `immutable`, `react`, `react-dom` and `react-dom-server`, like so:
|
||||
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:
|
||||
|
||||
```html
|
||||
<script src="./vendor/react.js"></script>
|
||||
<script src="./vendor/react-dom.js"></script>
|
||||
<script src="./vendor/react-dom-server.js"></script>
|
||||
<script src="./vendor/immutable.js"></script>
|
||||
```
|
||||
|
||||
This ensures that Slate isn't bundling its own copy of Immutable and React, which would greatly increase the file size of your application.
|
||||
@@ -45,13 +44,8 @@ To make things easier, for quick prototyping, you can also use the [`unpkg.com`]
|
||||
<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/immutable/dist/immutable.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!
|
||||
|
||||
<br/>
|
||||
<p align="center"><strong>Next:</strong><br/><a href="./adding-event-handlers.md">Adding Event Handlers</a></p>
|
||||
<br/>
|
@@ -1,106 +0,0 @@
|
||||
<br/>
|
||||
<p align="center"><strong>Previous:</strong><br/><a href="./installing-slate.md">Installing Slate</a></p>
|
||||
<br/>
|
||||
|
||||
# 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. You've already seen how the `onChange` handler can be used to store the changed editor value, but let's try adding more...
|
||||
|
||||
Let's use the `onKeyDown` handler to change the editor's content when we press a key.
|
||||
|
||||
Here's our app from earlier:
|
||||
|
||||
```js
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
render() {
|
||||
return <Editor value={this.state.value} onChange={this.onChange} />
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now we add an `onKeyDown` handler:
|
||||
|
||||
```js
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
// Define a new handler which prints the key that was pressed.
|
||||
onKeyDown = (event, editor, next) => {
|
||||
console.log(event.key)
|
||||
return next()
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Editor
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
onKeyDown={this.onKeyDown}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
onKeyDown = (event, editor, next) => {
|
||||
// Return with no changes if the keypress is not '&'
|
||||
if (event.key !== '&') return next()
|
||||
|
||||
// Prevent the ampersand character from being inserted.
|
||||
event.preventDefault()
|
||||
|
||||
// Change the value by inserting 'and' at the cursor's position.
|
||||
editor.insertText('and')
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Editor
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
onKeyDown={this.onKeyDown}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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 the `editor` that lets you perform commands. Simple!
|
||||
|
||||
<br/>
|
||||
<p align="center"><strong>Next:</strong><br/><a href="./defining-custom-block-nodes.md">Defining Custom Block Nodes</a></p>
|
||||
<br/>
|
@@ -1,201 +0,0 @@
|
||||
<br/>
|
||||
<p align="center"><strong>Previous:</strong><br/><a href="./defining-custom-block-nodes.md">Defining Custom Block Nodes</a></p>
|
||||
<br/>
|
||||
|
||||
# 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~~.
|
||||
|
||||
So we start with our app from earlier:
|
||||
|
||||
```js
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
onKeyDown = (event, editor, next) => {
|
||||
if (event.key != '`' || !event.ctrlKey) return next()
|
||||
event.preventDefault()
|
||||
const isCode = editor.value.blocks.some(block => block.type == 'code')
|
||||
|
||||
editor.setBlocks(isCode ? 'paragraph' : 'code')
|
||||
return true
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Editor
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
onKeyDown={this.onKeyDown}
|
||||
renderBlock={this.renderBlock}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
renderBlock = (props, editor, next) => {
|
||||
switch (props.node.type) {
|
||||
case 'code':
|
||||
return <CodeNode {...props} />
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And now, we'll edit the `onKeyDown` handler to make it so that when you press `control-B`, it will add a "bold" mark to the currently selected text:
|
||||
|
||||
```js
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
onKeyDown = (event, editor, next) => {
|
||||
if (!event.ctrlKey) return next()
|
||||
|
||||
// Decide what to do based on the key code...
|
||||
switch (event.key) {
|
||||
// When "B" is pressed, add a "bold" mark to the text.
|
||||
case 'b': {
|
||||
event.preventDefault()
|
||||
editor.addMark('bold')
|
||||
break
|
||||
}
|
||||
// When "`" is pressed, keep our existing code block logic.
|
||||
case '`': {
|
||||
const isCode = editor.value.blocks.some(block => block.type == 'code')
|
||||
event.preventDefault()
|
||||
editor.setBlocks(isCode ? 'paragraph' : 'code')
|
||||
break
|
||||
}
|
||||
// Otherwise, let other plugins handle it.
|
||||
default: {
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Editor
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
onKeyDown={this.onKeyDown}
|
||||
renderBlock={this.renderBlock}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
renderBlock = (props, editor, next) => {
|
||||
switch (props.node.type) {
|
||||
case 'code':
|
||||
return <CodeNode {...props} />
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Okay, so we've got the hotkey handler setup... but! If you happen to now try selecting text and hitting `control-B`, you won't notice any change. That's because we haven't told Slate how to render a "bold" mark.
|
||||
|
||||
For every mark type you want to add to your schema, you need to give Slate a "renderer" for that mark, just like nodes. So let's define our `bold` mark:
|
||||
|
||||
```js
|
||||
// Define a React component to render bold text with.
|
||||
function BoldMark(props) {
|
||||
return <strong>{props.children}</strong>
|
||||
}
|
||||
```
|
||||
|
||||
Pretty simple, right?
|
||||
|
||||
And now, let's tell Slate about that mark. To do that, we'll pass in the `renderMark` prop to our editor. Also, let's allow our mark to be toggled by changing `addMark` to `toggleMark`.
|
||||
|
||||
```js
|
||||
function BoldMark(props) {
|
||||
return <strong>{props.children}</strong>
|
||||
}
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
onKeyDown = (event, editor, next) => {
|
||||
if (!event.ctrlKey) return next()
|
||||
|
||||
switch (event.key) {
|
||||
case 'b': {
|
||||
event.preventDefault()
|
||||
editor.toggleMark('bold')
|
||||
break
|
||||
}
|
||||
case '`': {
|
||||
const isCode = editor.value.blocks.some(block => block.type == 'code')
|
||||
event.preventDefault()
|
||||
editor.setBlocks(isCode ? 'paragraph' : 'code')
|
||||
break
|
||||
}
|
||||
default: {
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Editor
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
onKeyDown={this.onKeyDown}
|
||||
renderBlock={this.renderBlock}
|
||||
// Add the `renderMark` prop...
|
||||
renderMark={this.renderMark}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
renderBlock = (props, editor, next) => {
|
||||
switch (props.node.type) {
|
||||
case 'code':
|
||||
return <CodeNode {...props} />
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
|
||||
// Add a `renderMark` method to render marks.
|
||||
renderMark = (props, editor, next) => {
|
||||
switch (props.mark.type) {
|
||||
case 'bold':
|
||||
return <BoldMark {...props} />
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now, if you try selecting a piece of text and hitting `control-B` you should see it turn bold! Magic!
|
||||
|
||||
<br/>
|
||||
<p align="center"><strong>Next:</strong><br/><a href="./using-plugins.md">Using Plugins</a></p>
|
||||
<br/>
|
@@ -1,229 +0,0 @@
|
||||
<br/>
|
||||
<p align="center"><strong>Previous:</strong><br/><a href="./adding-event-handlers.md">Adding Event Handlers</a></p>
|
||||
<br/>
|
||||
|
||||
# Defining Custom Block Nodes
|
||||
|
||||
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 `<div>`.
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
onKeyDown = (event, editor, next) => {
|
||||
if (event.key != '&') return next()
|
||||
event.preventDefault()
|
||||
editor.insertText('and')
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Editor
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
onKeyDown={this.onKeyDown}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now let's add "code blocks" to our editor.
|
||||
|
||||
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` nodes.
|
||||
|
||||
Node renderers are just simple React components, like so:
|
||||
|
||||
```js
|
||||
// Define a React component renderer for our code blocks.
|
||||
function CodeNode(props) {
|
||||
return (
|
||||
<pre {...props.attributes}>
|
||||
<code>{props.children}</code>
|
||||
</pre>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Pretty simple.
|
||||
|
||||
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.
|
||||
|
||||
Now, let's add that renderer to our `Editor`:
|
||||
|
||||
```js
|
||||
function CodeNode(props) {
|
||||
return (
|
||||
<pre {...props.attributes}>
|
||||
<code>{props.children}</code>
|
||||
</pre>
|
||||
)
|
||||
}
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
onKeyDown = (event, editor, next) => {
|
||||
if (event.key != '&') return next()
|
||||
event.preventDefault()
|
||||
editor.insertText('and')
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
// Pass in the `renderBlock` prop...
|
||||
<Editor
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
onKeyDown={this.onKeyDown}
|
||||
renderBlock={this.renderBlock}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Add a `renderBlock` method to render a `CodeNode` for code blocks.
|
||||
renderBlock = (props, editor, next) => {
|
||||
switch (props.node.type) {
|
||||
case 'code':
|
||||
return <CodeNode {...props} />
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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 `control-\`` shortcut that does just that:
|
||||
|
||||
```js
|
||||
function CodeNode(props) {
|
||||
return (
|
||||
<pre {...props.attributes}>
|
||||
<code>{props.children}</code>
|
||||
</pre>
|
||||
)
|
||||
}
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
onKeyDown = (event, editor, next) => {
|
||||
// Return with no changes if it's not the "`" key with ctrl pressed.
|
||||
if (event.key != '`' || !event.ctrlKey) return next()
|
||||
|
||||
// Prevent the "`" from being inserted by default.
|
||||
event.preventDefault()
|
||||
|
||||
// Otherwise, set the currently selected blocks type to "code".
|
||||
editor.setBlocks('code')
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Editor
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
onKeyDown={this.onKeyDown}
|
||||
renderBlock={this.renderBlock}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
renderBlock = (props, editor, next) => {
|
||||
switch (props.node.type) {
|
||||
case 'code':
|
||||
return <CodeNode {...props} />
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now, if you press `control-\`` the block your cursor is in should turn into a code block! Magic!
|
||||
|
||||
_Note: The Edge browser does not currently support `control-...` key events (see [issue](https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/742263/)), so this example won't work on it._
|
||||
|
||||
But we forgot one thing. When you hit `control-\`` 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:
|
||||
|
||||
```js
|
||||
function CodeNode(props) {
|
||||
return (
|
||||
<pre {...props.attributes}>
|
||||
<code>{props.children}</code>
|
||||
</pre>
|
||||
)
|
||||
}
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
onKeyDown = (event, editor, next) => {
|
||||
if (event.key != '`' || !event.ctrlKey) return next()
|
||||
|
||||
event.preventDefault()
|
||||
|
||||
// Determine whether any of the currently selected blocks are code blocks.
|
||||
const isCode = editor.value.blocks.some(block => block.type == 'code')
|
||||
|
||||
// Toggle the block type depending on `isCode`.
|
||||
editor.setBlocks(isCode ? 'paragraph' : 'code')
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Editor
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
onKeyDown={this.onKeyDown}
|
||||
renderBlock={this.renderBlock}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
renderBlock = (props, editor, next) => {
|
||||
switch (props.node.type) {
|
||||
case 'code':
|
||||
return <CodeNode {...props} />
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And there you have it! If you press `control-\`` while inside a code block, it should turn back into a paragraph!
|
||||
|
||||
<br/>
|
||||
<p align="center"><strong>Next:</strong><br/><a href="./applying-custom-formatting.md">Applying Custom Formatting</a></p>
|
||||
<br/>
|
@@ -1,104 +0,0 @@
|
||||
# Installing Slate
|
||||
|
||||
Slate is a monorepo divided up into multi npm packages, so to install it you do:
|
||||
|
||||
```
|
||||
npm install slate slate-react
|
||||
```
|
||||
|
||||
You'll also need to be sure to install Slate's peer dependencies:
|
||||
|
||||
```
|
||||
npm install react react-dom immutable
|
||||
```
|
||||
|
||||
_Note, if you'd rather use a pre-bundled version of Slate, you can `npm install slate` and retrieve the bundled `dist/slate.js` file! Check out the [Using the Bundled Source](./using-the-bundled-source.md) guide for more information._
|
||||
|
||||
Once you've installed Slate, you'll need to import it.
|
||||
|
||||
Slate exposes a set of modules that you'll use to build your editor. The most important of which is an `Editor` component.
|
||||
|
||||
```js
|
||||
// Import the Slate editor.
|
||||
import { Editor } from 'slate-react'
|
||||
```
|
||||
|
||||
In addition to rendering the editor, you need to give Slate a "initial value" to render as content. We'll use the `Value` model that ships with Slate to create a new initial value that just contains a single paragraph block with some text in it:
|
||||
|
||||
```js
|
||||
// Import the `Value` model.
|
||||
import { Editor } from 'slate-react'
|
||||
import { Value } from 'slate'
|
||||
|
||||
// Create our initial value...
|
||||
const initialValue = Value.fromJSON({
|
||||
document: {
|
||||
nodes: [
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{
|
||||
object: 'text',
|
||||
text: 'A line of text in a paragraph.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
And now that we've created our initial value, we define our `App` and pass it into Slate's `Editor` component, like so:
|
||||
|
||||
```js
|
||||
// Import React!
|
||||
import React from 'react'
|
||||
import { Editor } from 'slate-react'
|
||||
import { Value } from 'slate'
|
||||
|
||||
const initialValue = Value.fromJSON({
|
||||
document: {
|
||||
nodes: [
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{
|
||||
object: 'text',
|
||||
text: 'A line of text in a paragraph.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
// Define our app...
|
||||
class App extends React.Component {
|
||||
// Set the initial value when the app is first constructed.
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
// On change, update the app's React state with the new editor value.
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
// Render the editor.
|
||||
render() {
|
||||
return <Editor value={this.state.value} onChange={this.onChange} />
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You'll notice that the `onChange` handler passed into the `Editor` component just updates the app's state with the newest changed value. That way, when it re-renders the editor, the new value is reflected with your changes.
|
||||
|
||||
And that's 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!
|
||||
|
||||
<br/>
|
||||
<p align="center"><strong>Next:</strong><br/><a href="./adding-event-handlers.md">Adding Event Handlers</a></p>
|
||||
<br/>
|
@@ -1,305 +0,0 @@
|
||||
<br/>
|
||||
<p align="center"><strong>Previous:</strong><br/><a href="./saving-to-a-database.md">Saving to a Database</a></p>
|
||||
<br/>
|
||||
|
||||
# Saving and Loading HTML Content
|
||||
|
||||
In the previous guide, we looked at how to serialize the Slate editor's content and save it for later. What if you want to save the content as HTML? It's a slightly more involved process, but this guide will show you how to do it.
|
||||
|
||||
Let's start with a basic editor:
|
||||
|
||||
```js
|
||||
import { Editor } from 'slate-react'
|
||||
import Plain from 'slate-plain-serializer'
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: Plain.deserialize(''),
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
render() {
|
||||
return <Editor value={this.state.value} onChange={this.onChange} />
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That will render a basic Slate editor on your page.
|
||||
|
||||
Now... we need to add the [`Html`](../reference/slate-html-serializer/index.md) serializer. And to do that, we need to tell it a bit about the schema we plan on using. For this example, we'll work with a schema that has a few different parts:
|
||||
|
||||
* A `paragraph` block.
|
||||
* A `code` block for code samples.
|
||||
* A `quote` block for quotes...
|
||||
* And `bold`, `italic` and `underline` formatting.
|
||||
|
||||
By default, the `Html` serializer knows nothing about our schema, just like Slate itself. To fix this, we need to pass it a set of `rules`. Each rule defines how to serialize and deserialize a Slate object.
|
||||
|
||||
To start, let's create a new rule with a `deserialize` function for paragraph blocks.
|
||||
|
||||
```js
|
||||
const rules = [
|
||||
// Add our first rule with a deserializing function.
|
||||
{
|
||||
deserialize(el, next) {
|
||||
if (el.tagName.toLowerCase() == 'p') {
|
||||
return {
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
data: {
|
||||
className: el.getAttribute('class'),
|
||||
},
|
||||
nodes: next(el.childNodes),
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
The `el` argument that the `deserialize` function receives is just a DOM element. And the `next` argument is a function that will deserialize any element(s) we pass it, which is how you recurse through each node's children.
|
||||
|
||||
Okay, that's `deserialize`, now let's define the `serialize` property of the paragraph rule as well:
|
||||
|
||||
```js
|
||||
const rules = [
|
||||
{
|
||||
deserialize(el, next) {
|
||||
if (el.tagName.toLowerCase() == 'p') {
|
||||
return {
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
data: {
|
||||
className: el.getAttribute('class'),
|
||||
},
|
||||
nodes: next(el.childNodes),
|
||||
}
|
||||
}
|
||||
},
|
||||
// Add a serializing function property to our rule...
|
||||
serialize(obj, children) {
|
||||
if (obj.object == 'block' && obj.type == 'paragraph') {
|
||||
return <p className={obj.data.get('className')}>{children}</p>
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
The `serialize` function should also feel familiar. It's just taking [Slate models](../reference/slate) and turning them into React elements, which will then be rendered to an HTML string.
|
||||
|
||||
The `obj` argument of the `serialize` function will either be a [`Node`](../reference/slate/node.md), a [`Mark`](../reference/slate/mark.md) or a special immutable [`String`](../reference/serializers/html.md#ruleserialize) object. And the `children` argument is a React element describing the nested children of the object in question, for recursing.
|
||||
|
||||
Okay, so now our serializer can handle `paragraph` nodes.
|
||||
|
||||
Let's add the other types of blocks we want:
|
||||
|
||||
```js
|
||||
// Refactor block tags into a dictionary for cleanliness.
|
||||
const BLOCK_TAGS = {
|
||||
p: 'paragraph',
|
||||
blockquote: 'quote',
|
||||
pre: 'code',
|
||||
}
|
||||
|
||||
const rules = [
|
||||
{
|
||||
// Switch deserialize to handle more blocks...
|
||||
deserialize(el, next) {
|
||||
const type = BLOCK_TAGS[el.tagName.toLowerCase()]
|
||||
if (type) {
|
||||
return {
|
||||
object: 'block',
|
||||
type: type,
|
||||
data: {
|
||||
className: el.getAttribute('class'),
|
||||
},
|
||||
nodes: next(el.childNodes),
|
||||
}
|
||||
}
|
||||
},
|
||||
// Switch serialize to handle more blocks...
|
||||
serialize(obj, children) {
|
||||
if (obj.object == 'block') {
|
||||
switch (obj.type) {
|
||||
case 'paragraph':
|
||||
return <p className={obj.data.get('className')}>{children}</p>
|
||||
case 'quote':
|
||||
return <blockquote>{children}</blockquote>
|
||||
case 'code':
|
||||
return (
|
||||
<pre>
|
||||
<code>{children}</code>
|
||||
</pre>
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
Now each of our block types is handled.
|
||||
|
||||
You'll notice that even though code blocks are nested in a `<pre>` and a `<code>` element, we don't need to specifically handle that case in our `deserialize` function, because the `Html` serializer will automatically recurse through `el.childNodes` if no matching deserializer is found. This way, unknown tags will just be skipped over in the tree, instead of their contents omitted completely.
|
||||
|
||||
Okay. So now our serializer can handle blocks, but we need to add our marks to it as well. Let's do that with a new rule...
|
||||
|
||||
```js
|
||||
const BLOCK_TAGS = {
|
||||
blockquote: 'quote',
|
||||
p: 'paragraph',
|
||||
pre: 'code',
|
||||
}
|
||||
|
||||
// Add a dictionary of mark tags.
|
||||
const MARK_TAGS = {
|
||||
em: 'italic',
|
||||
strong: 'bold',
|
||||
u: 'underline',
|
||||
}
|
||||
|
||||
const rules = [
|
||||
{
|
||||
deserialize(el, next) {
|
||||
const type = BLOCK_TAGS[el.tagName.toLowerCase()]
|
||||
if (type) {
|
||||
return {
|
||||
object: 'block',
|
||||
type: type,
|
||||
data: {
|
||||
className: el.getAttribute('class'),
|
||||
},
|
||||
nodes: next(el.childNodes),
|
||||
}
|
||||
}
|
||||
},
|
||||
serialize(obj, children) {
|
||||
if (obj.object == 'block') {
|
||||
switch (obj.type) {
|
||||
case 'code':
|
||||
return (
|
||||
<pre>
|
||||
<code>{children}</code>
|
||||
</pre>
|
||||
)
|
||||
case 'paragraph':
|
||||
return <p className={obj.data.get('className')}>{children}</p>
|
||||
case 'quote':
|
||||
return <blockquote>{children}</blockquote>
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
// Add a new rule that handles marks...
|
||||
{
|
||||
deserialize(el, next) {
|
||||
const type = MARK_TAGS[el.tagName.toLowerCase()]
|
||||
if (type) {
|
||||
return {
|
||||
object: 'mark',
|
||||
type: type,
|
||||
nodes: next(el.childNodes),
|
||||
}
|
||||
}
|
||||
},
|
||||
serialize(obj, children) {
|
||||
if (obj.object == 'mark') {
|
||||
switch (obj.type) {
|
||||
case 'bold':
|
||||
return <strong>{children}</strong>
|
||||
case 'italic':
|
||||
return <em>{children}</em>
|
||||
case 'underline':
|
||||
return <u>{children}</u>
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
Great, that's all of the rules we need! Now let's create a new `Html` serializer and pass in those rules:
|
||||
|
||||
```js
|
||||
import Html from 'slate-html-serializer'
|
||||
|
||||
// Create a new serializer instance with our `rules` from above.
|
||||
const html = new Html({ rules })
|
||||
```
|
||||
|
||||
And finally, now that we have our serializer initialized, we can update our app to use it to save and load content, like so:
|
||||
|
||||
```js
|
||||
// Load the initial value from Local Storage or a default.
|
||||
const initialValue = localStorage.getItem('content') || '<p></p>'
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: html.deserialize(initialValue),
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
// When the document changes, save the serialized HTML to Local Storage.
|
||||
if (value.document != this.state.value.document) {
|
||||
const string = html.serialize(value)
|
||||
localStorage.setItem('content', string)
|
||||
}
|
||||
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Editor
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
// Add the ability to render our nodes and marks...
|
||||
renderBlock={this.renderNode}
|
||||
renderMark={this.renderMark}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
renderNode = (props, editor, next) => {
|
||||
switch (props.node.type) {
|
||||
case 'code':
|
||||
return (
|
||||
<pre {...props.attributes}>
|
||||
<code>{props.children}</code>
|
||||
</pre>
|
||||
)
|
||||
case 'paragraph':
|
||||
return (
|
||||
<p {...props.attributes} className={props.node.data.get('className')}>
|
||||
{props.children}
|
||||
</p>
|
||||
)
|
||||
case 'quote':
|
||||
return <blockquote {...props.attributes}>{props.children}</blockquote>
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
|
||||
// Add a `renderMark` method to render marks.
|
||||
renderMark = (props, editor, next) => {
|
||||
const { mark, attributes } = props
|
||||
switch (mark.type) {
|
||||
case 'bold':
|
||||
return <strong {...attributes}>{props.children}</strong>
|
||||
case 'italic':
|
||||
return <em {...attributes}>{props.children}</em>
|
||||
case 'underline':
|
||||
return <u {...attributes}>{props.children}</u>
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And that's it! When you make any changes in your editor, you should see the updated HTML being saved to Local Storage. And when you refresh the page, those changes should be carried over.
|
@@ -1,224 +0,0 @@
|
||||
<br/>
|
||||
<p align="center"><strong>Previous:</strong><br/><a href="./using-plugins.md">Using Plugins</a></p>
|
||||
<br/>
|
||||
|
||||
# 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:
|
||||
|
||||
```js
|
||||
import { Editor } from 'slate-react'
|
||||
import { Value } from 'slate'
|
||||
|
||||
const initialValue = Value.fromJSON({
|
||||
document: {
|
||||
nodes: [
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{
|
||||
object: 'text',
|
||||
text: 'A line of text in a paragraph.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
render() {
|
||||
return <Editor value={this.state.value} onChange={this.onChange} />
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), 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`. But the `value` argument that `onChange` receives is an immutable object, so we can't just save it as-is. We need to serialize it to a format we understand first, like JSON!
|
||||
|
||||
```js
|
||||
const initialValue = Value.fromJSON({
|
||||
document: {
|
||||
nodes: [
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{
|
||||
object: 'text',
|
||||
text: 'A line of text in a paragraph.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
// Save the value to Local Storage.
|
||||
const content = JSON.stringify(value.toJSON())
|
||||
localStorage.setItem('content', content)
|
||||
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
render() {
|
||||
return <Editor value={this.state.value} onChange={this.onChange} />
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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. That's because we need to make sure the initial value is pulled from that same Local Storage location, like so:
|
||||
|
||||
```js
|
||||
// Update the initial content to be pulled from Local Storage if it exists.
|
||||
const existingValue = JSON.parse(localStorage.getItem('content'))
|
||||
const initialValue = Value.fromJSON(
|
||||
existingValue || {
|
||||
document: {
|
||||
nodes: [
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{
|
||||
object: 'text',
|
||||
text: 'A line of text in a paragraph.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
const content = JSON.stringify(value.toJSON())
|
||||
localStorage.setItem('content', content)
|
||||
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
render() {
|
||||
return <Editor value={this.state.value} onChange={this.onChange} />
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now you should be able to save changes across refreshes!
|
||||
|
||||
However, if you inspect the change handler, you'll notice that it's actually saving the Local Storage value on _every_ change to the editor, even when only the selection changes! This is because `onChange` is called for _every_ change. For Local Storage, this doesn't really matter, but if you're saving things to a database via HTTP request, this would result in a lot of unnecessary requests. You can fix this by checking against the previous `document` value.
|
||||
|
||||
```js
|
||||
const existingValue = JSON.parse(localStorage.getItem('content'))
|
||||
const initialValue = Value.fromJSON(
|
||||
existingValue || {
|
||||
document: {
|
||||
nodes: [
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{
|
||||
object: 'text',
|
||||
text: 'A line of text in a paragraph.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
// Check to see if the document has changed before saving.
|
||||
if (value.document != this.state.value.document) {
|
||||
const content = JSON.stringify(value.toJSON())
|
||||
localStorage.setItem('content', content)
|
||||
}
|
||||
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
render() {
|
||||
return <Editor value={this.state.value} onChange={this.onChange} />
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now your content will be saved only when the content itself changes!
|
||||
|
||||
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, you can use the `Plain` serializer that ships with Slate, like so:
|
||||
|
||||
```js
|
||||
// Switch to using the Plain serializer.
|
||||
import { Editor } from 'slate-react'
|
||||
import Plain from 'slate-plain-serializer'
|
||||
|
||||
const existingValue = localStorage.getItem('content')
|
||||
const initialValue = Plain.deserialize(
|
||||
existingValue || 'A string of plain text.'
|
||||
)
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
if (value.document != this.state.value.document) {
|
||||
const content = Plain.serialize(value)
|
||||
localStorage.setItem('content', content)
|
||||
}
|
||||
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
render() {
|
||||
return <Editor value={this.state.value} onChange={this.onChange} />
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That works! Now you're working with plain text.
|
||||
|
||||
However, sometimes you may want something a bit more custom, and a bit more complex... good old fashioned HTML. In that case, check out the next guide...
|
||||
|
||||
<br/>
|
||||
<p align="center"><strong>Next:</strong><br/><a href="./saving-and-loading-html-content.md">Saving and Loading HTML Content</a></p>
|
||||
<br/>
|
@@ -1,194 +0,0 @@
|
||||
<br/>
|
||||
<p align="center"><strong>Previous:</strong><br/><a href="./applying-custom-formatting.md">Applying Custom Formatting</a></p>
|
||||
<br/>
|
||||
|
||||
# Using Plugins
|
||||
|
||||
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 beautiful things about Slate is actually its plugin system and how it lets you write less one-off code.
|
||||
|
||||
In the previous guide, we actually wrote some pretty useful code for adding **bold** formatting to ranges of text when a key is pressed. But most of that code wasn't really specific to **bold** text; it could just as easily have applied to _italic_ text or `code` text if we switched a few variables.
|
||||
|
||||
So let's break that logic out into a reusable plugin that can toggle _any_ mark on _any_ key press.
|
||||
|
||||
Starting with our app from earlier:
|
||||
|
||||
```js
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
onKeyDown = (event, editor, next) => {
|
||||
if (event.key != 'b' || !event.ctrlKey) return next()
|
||||
event.preventDefault()
|
||||
editor.toggleMark('bold')
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Editor
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
onKeyDown={this.onKeyDown}
|
||||
renderMark={this.renderMark}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
renderMark = (props, editor, next) => {
|
||||
switch (props.mark.type) {
|
||||
case 'bold':
|
||||
return <strong {...props.attributes}>{props.children}</strong>
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Let's write a new function that takes a set of options: the mark `type` to toggle and the `key` to press.
|
||||
|
||||
```js
|
||||
function MarkHotkey(options) {
|
||||
// Grab our options from the ones passed in.
|
||||
const { type, key } = options
|
||||
}
|
||||
```
|
||||
|
||||
Okay, that was easy. But it doesn't do anything.
|
||||
|
||||
To fix that, we need our plugin function to return a "plugin object" that Slate recognizes. Slate's plugin objects are just plain JavaScript objects whose properties map to the same handlers on the `Editor`.
|
||||
|
||||
In this case, our plugin object will have one property, an `onKeyDown` handler, with its logic copied right from our current app's code:
|
||||
|
||||
```js
|
||||
function MarkHotkey(options) {
|
||||
const { type, key } = options
|
||||
|
||||
// Return our "plugin" object, containing the `onKeyDown` handler.
|
||||
return {
|
||||
onKeyDown(event, editor, next) {
|
||||
// If it doesn't match our `key`, let other plugins handle it.
|
||||
if (!event.ctrlKey || event.key != key) return next()
|
||||
|
||||
// Prevent the default characters from being inserted.
|
||||
event.preventDefault()
|
||||
|
||||
// Toggle the mark `type`.
|
||||
editor.toggleMark(type)
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Boom! Now we're getting somewhere. That code is reusable for any type of mark.
|
||||
|
||||
Now that we have our plugin, let's remove the hard-coded logic from our app and replace it with our brand new `MarkHotkey` plugin instead, passing in the same options that will keep our **bold** functionality intact:
|
||||
|
||||
```js
|
||||
// Initialize our bold-mark-adding plugin.
|
||||
const boldPlugin = MarkHotkey({
|
||||
type: 'bold',
|
||||
key: 'b',
|
||||
})
|
||||
|
||||
// Create an array of plugins.
|
||||
const plugins = [boldPlugin]
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
// Add the `plugins` property to the editor, and remove `onKeyDown`.
|
||||
<Editor
|
||||
plugins={plugins}
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
renderMark={this.renderMark}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
renderMark = (props, editor, next) => {
|
||||
switch (props.mark.type) {
|
||||
case 'bold':
|
||||
return <strong>{props.children}</strong>
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Awesome. If you test out the editor now, you'll notice that everything still works just as it did before. But the beauty of the logic being encapsulated in a plugin is that we can add more mark types _extremely_ easily now!
|
||||
|
||||
Let's add _italic_, `code`, ~~strikethrough~~ and underline marks:
|
||||
|
||||
```js
|
||||
// Initialize a plugin for each mark...
|
||||
const plugins = [
|
||||
MarkHotkey({ key: 'b', type: 'bold' }),
|
||||
MarkHotkey({ key: '`', type: 'code' }),
|
||||
MarkHotkey({ key: 'i', type: 'italic' }),
|
||||
MarkHotkey({ key: '~', type: 'strikethrough' }),
|
||||
MarkHotkey({ key: 'u', type: 'underline' }),
|
||||
]
|
||||
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
value: initialValue,
|
||||
}
|
||||
|
||||
onChange = ({ value }) => {
|
||||
this.setState({ value })
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Editor
|
||||
plugins={plugins}
|
||||
value={this.state.value}
|
||||
onChange={this.onChange}
|
||||
renderMark={this.renderMark}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
renderMark = (props, editor, next) => {
|
||||
switch (props.mark.type) {
|
||||
case 'bold':
|
||||
return <strong>{props.children}</strong>
|
||||
// Add our new mark renderers...
|
||||
case 'code':
|
||||
return <code>{props.children}</code>
|
||||
case 'italic':
|
||||
return <em>{props.children}</em>
|
||||
case 'strikethrough':
|
||||
return <del>{props.children}</del>
|
||||
case 'underline':
|
||||
return <u>{props.children}</u>
|
||||
default:
|
||||
return next()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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 mark hotkey logic tested and isolated in a single place, making the code easier to maintain.
|
||||
|
||||
That's why plugins are awesome. They let you get really expressive while also making your codebase easier to manage. And since Slate is built with plugins as a primary consideration, using them is dead simple!
|
||||
|
||||
<br/>
|
||||
<p align="center"><strong>Next:</strong><br/><a href="./saving-to-a-database.md">Saving to a Database</a></p>
|
||||
<br/>
|
Reference in New Issue
Block a user