#### Is this adding or improving a _feature_ or fixing a _bug_? Improvement / debt. #### What's the new behavior? This pull request removes the `Change` object as we know it, and folds all of its behaviors into the new `Editor` controller instead, simplifying a lot of the confusion around what is a "change vs. editor" and when to use which. It makes the standard API a **lot** nicer to use I think. --- ###### NEW **The `editor.command` and `editor.query` methods can take functions.** Previously they only accepted a `type` string and would look up the command or query by type. Now, they also accept a custom function. This is helpful for plugin authors, who want to accept a "command option", since it gives users more flexibility to write one-off commands or queries. For example a plugin could be passed either: ```js Hotkey({ hotkey: 'cmd+b', command: 'addBoldMark', }) ``` Or a custom command function: ```js Hotkey({ hotkey: 'cmd+b', command: editor => editor.addBoldMark().moveToEnd() }) ``` ###### BREAKING **The `Change` object has been removed.** The `Change` object as we know it previously has been removed, and all of its behaviors have been folded into the `Editor` controller. This includes the top-level commands and queries methods, as well as methods like `applyOperation` and `normalize`. _All places that used to receive `change` now receive `editor`, which is API equivalent._ **Changes are now flushed to `onChange` asynchronously.** Previously this was done synchronously, which resulted in some strange race conditions in React environments. Now they will always be flushed asynchronously, just like `setState`. **The `render*` and `decorate*` middleware signatures have changed!** Previously the `render*` and `decorate*` middleware was passed `(props, next)`. However now, for consistency with the other middleware they are all passed `(props, editor, next)`. This way, all middleware always receive `editor` and `next` as their final two arguments. **The `normalize*` and `validate*` middleware signatures have changed!** Previously the `normalize*` and `validate*` middleware was passed `(node, next)`. However now, for consistency with the other middleware they are all passed `(node, editor, next)`. This way, all middleware always receive `editor` and `next` as their final two arguments. **The `editor.event` method has been removed.** Previously this is what you'd use when writing tests to simulate events being fired—which were slightly different to other running other middleware. With the simplification to the editor and to the newly-consistent middleware signatures, you can now use `editor.run` directly to simulate events: ```js editor.run('onKeyDown', { key: 'Tab', ... }) ``` ###### DEPRECATED **The `editor.change` method is deprecated.** With the removal of the `Change` object, there's no need anymore to create the small closures with `editor.change()`. Instead you can directly invoke commands on the editor in series, and all of the changes will be emitted asynchronously on the next tick. ```js editor .insertText('word') .moveFocusForward(10) .addMark('bold') ``` **The `applyOperations` method is deprecated.** Instead you can loop a set of operations and apply each one using `applyOperation`. This is to reduce the number of methods exposed on the `Editor` to keep it simpler. **The `change.call` method is deprecated.** Previously this was used to call a one-off function as a change method. Now this behavior is equivalent to calling `editor.command(fn)` instead. --- Fixes: https://github.com/ianstormtaylor/slate/issues/2334 Fixes: https://github.com/ianstormtaylor/slate/issues/2282
6.0 KiB
Previous:
Adding Event Handlers
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:
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:
// 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
:
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 `renderNode` prop...
<Editor
value={this.state.value}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
renderNode={this.renderNode}
/>
)
}
// Add a `renderNode` method to render a `CodeNode` for code blocks.
renderNode = (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:
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}
renderNode={this.renderNode}
/>
)
}
renderNode = (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), 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:
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}
renderNode={this.renderNode}
/>
)
}
renderNode = (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!
Next:
Applying Custom Formatting