1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-03-06 13:59:47 +01:00
slate/docs/guides/rendering.md
Ian Storm Taylor 8dd919dc34
remove change, fold into editor (#2337)
#### 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
2018-10-27 12:18:23 -07:00

5.7 KiB

Rendering

One of the best parts of Slate is that it's built with React, so it fits right into your existing application. It doesn't re-invent its own view layer that you have to learn. It tries to keep everything as React-y as possible.

To that end, Slate gives you control over the rendering behavior of every node and mark in your document, any placeholders you want to render, and even the top-level editor itself.

You can define these behaviors by passing props into the editor, or you can define them in Slate plugins.

Nodes & Marks

Using custom components for the nodes and marks is the most common rendering need. Slate makes this easy to do, you just define a renderNode function.

The function is called with the node's props, including props.node which is the node itself. You can use these to determine what to render. For example, you can render nodes using simple HTML elements:

function renderNode(props, editor, next) {
  const { node, attributes, children } = props

  switch (node.type) {
    case 'paragraph':
      return <p {...attributes}>{children}</p>
    case 'quote':
      return <blockquote {...attributes}>{children}</blockquote>
    case 'image': {
      const src = node.data.get('src')
      return <img {...attributes} src={src} />
    }
    default:
      return next()
  }
}

🤖 Be sure to mix in props.attributes and render props.children in your node components! The attributes are required for utilities like Slate's findDOMNode, and the children are the actual text content of your nodes.

You don't have to use simple HTML elements, you can use your own custom React components too:

function renderNode(props, editor, next) {
  switch (props.node.type) {
    case 'paragraph':
      return <ParagraphComponent {...props} />
    case 'quote':
      return <QuoteComponent {...props} />
    case 'image':
      return <ImageComponent {...props} />
    default:
      return next()
  }
}

And you can just as easily put that renderNode logic into a plugin, and pass that plugin into your editor instead:

function SomeRenderingPlugin() {
  return {
    renderNode(props, editor, next) {
      ...
    }
  }
}

const plugins = [
  SomeRenderingPlugin(),
  ...
]

<Editor
  plugins={plugins}
  ...
/>

Marks work the same way, except they invoke the renderMark function. Like so:

function renderMark(props, editor, next) {
  const { children, mark, attributes } = props
  switch (mark.type) {
    case 'bold':
      return <strong {...{ attributes }}>{children}</strong>
    case 'italic':
      return <em {...{ attributes }}>{children}</em>
    case 'code':
      return <code {...{ attributes }}>{children}</code>
    case 'underline':
      return <u {...{ attributes }}>{children}</u>
    case 'strikethrough':
      return <strike {...{ attributes }}>{children}</strike>
    default:
      return next()
  }
}

Be sure to mix props.attributes in your renderMark. attributes provides data-* dom attributes for spell-check in non-IE browsers.

That way, if you happen to have a global stylesheet that defines strong, em, etc. styles then your editor's content will already be formatted!

🤖 Be aware though that marks aren't guaranteed to be "contiguous". Which means even though a word is bolded, it's not guaranteed to render as a single <strong> element. If some of its characters are also italic, it might be split up into multiple elements—one <strong>wo</strong> and one <em><strong>rd</strong></em>.

Placeholders

By default Slate will render a placeholder for you which mimics the native DOM placeholder attribute of <input> and <textarea> elements—it's in the same typeface as the editor, and it's slightly translucent. And as soon as the document has any content, the placeholder disappears.

However sometimes you want to customize things. Or maybe you want to render placeholders inside specific blocks like inside an image caption. To do that, you can define your own renderPlaceholder function:

function renderPlaceholder(props, editor, next) {
  const { node } = props
  if (node.object != 'block') return next()
  if (node.type != 'caption') return next()
  if (node.text != '') return next()

  return (
    <span
      contentEditable={false}
      style={{ display: 'inline-block', width: '0', whiteSpace: 'nowrap', opacity: '0.33' }}
    >
      {editor.props.placeholder}
    </span>
  )
}

<Editor
  renderPlaceholder={renderPlaceholder}
  ...
/>

That will render a simple placeholder element inside all of your caption blocks until someone decides to write in a caption.

The Editor Itself

Not only can you control the rendering behavior of the components inside the editor, but you can also control the rendering of the editor itself.

This sounds weird, but it can be pretty useful if you want to render additional top-level elements from inside a plugin. To do so, you use the renderEditor function:

function renderEditor(props, editor, next) {
  const { editor } = props
  const wordCount = countWords(editor.value.text)
  const children = next()
  return (
    <React.Fragment>
      {children}
      <span className="word-count">{wordCount}</span>
    </React.Fragment>
  )
}

<Editor
  renderEditor={renderEditor}
  ...
/>

Here we're rendering a small word count number underneath all of the content of the editor. Whenever you change the content of the editor, renderEditor will be called, and the word count will be updated.

This is very similar to how higher-order components work! Except it allows each plugin in Slate's plugin stack to wrap the editor's children.

🤖 Be sure to remember to render children in your renderEditor functions, because that contains the editor's own elements!