1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-03-06 13:59:47 +01:00
slate/docs/guides/schemas.md

118 lines
6.4 KiB
Markdown
Raw Normal View History

2017-10-27 18:59:20 -07:00
# Schemas
One of Slate's principles is that it doesn't assume anything about the type of content you're building an editor for. Some editors will want **bold**, _italic_, ~~strikethrough~~, and some won't. Some will want comments and highlighting, some won't. You _can_ build all of these things with Slate, but Slate doesn't assume anything out of the box.
This turns out to be extremely helpful when building complex editors, because it means you have full control over your content—you are never fighting with assumptions that the "core" library has made.
That said, just because Slate is agnostic doesn't mean you aren't going to need to enforce a "schema" for your documents.
To that end, Slate lets you define validations for the structure of your documents, and to fix them if the document ever becomes invalid. This guide will show you how they work.
2017-10-27 18:59:20 -07:00
> 🤖 To see a full example of a schema in affect, check out the [Forced Layout](https://github.com/ianstormtaylor/slate/blob/405cef0225c314b4162d587c74cfce6b65a7b257/examples/forced-layout/index.js#L62) example.
2018-09-18 03:26:18 +02:00
2017-10-27 18:59:20 -07:00
## Basic Schemas
Slate schemas are defined as JavaScript objects, with properties that describe the document, block nodes, and inline nodes in your editor. Here's a simple schema:
2017-10-27 18:59:20 -07:00
```jsx
2017-10-27 18:59:20 -07:00
const schema = {
document: {
Refactor schema (#1993) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? - Tweaking the declarative schema definition syntax to make it easier to represent more complex states, as well as enable it to validate previously impossible things. - Rename `validateNode` to `normalizeNode` for clarity. - Introduce `validateNode`, `checkNode`, `assertNode` helpers for more advanced use cases, like front-end API validation of "invalid" fields that need to be fixed before they are sent to the server. #### How does this change work? The `schema.blocks/inlines/document` entries are now a shorthand for a more powerful `schema.rules` syntax. For example, this now allows for declaratively validating by a node's data, regardless of type: ```js { rules: [ { match: { data: { id: '2kd293lry' }, }, nodes: [ { match: { type: 'paragraph' }}, { match: { type: 'image' }}, ] } ] } ``` Previously you'd have to use `validateNode` for this, since the syntax wasn't flexible enough to validate nodes without hard-coding their `type`. This also simplifies the "concatenation" of schema rules, because under the covers all of them are implemented using the `schema.rules` array, so they simply take effect in order, just like everything else in plugins. #### Have you checked that...? <!-- Please run through this checklist for your pull request: --> * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1842 Fixes: #1923
2018-07-27 15:27:07 -07:00
nodes: [
{
match: [{ type: 'paragraph' }, { type: 'image' }],
},
],
2017-10-27 18:59:20 -07:00
},
blocks: {
paragraph: {
Refactor schema (#1993) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? - Tweaking the declarative schema definition syntax to make it easier to represent more complex states, as well as enable it to validate previously impossible things. - Rename `validateNode` to `normalizeNode` for clarity. - Introduce `validateNode`, `checkNode`, `assertNode` helpers for more advanced use cases, like front-end API validation of "invalid" fields that need to be fixed before they are sent to the server. #### How does this change work? The `schema.blocks/inlines/document` entries are now a shorthand for a more powerful `schema.rules` syntax. For example, this now allows for declaratively validating by a node's data, regardless of type: ```js { rules: [ { match: { data: { id: '2kd293lry' }, }, nodes: [ { match: { type: 'paragraph' }}, { match: { type: 'image' }}, ] } ] } ``` Previously you'd have to use `validateNode` for this, since the syntax wasn't flexible enough to validate nodes without hard-coding their `type`. This also simplifies the "concatenation" of schema rules, because under the covers all of them are implemented using the `schema.rules` array, so they simply take effect in order, just like everything else in plugins. #### Have you checked that...? <!-- Please run through this checklist for your pull request: --> * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1842 Fixes: #1923
2018-07-27 15:27:07 -07:00
nodes: [
{
match: { object: 'text' },
},
],
2017-10-27 18:59:20 -07:00
},
image: {
isVoid: true,
data: {
src: v => v && isUrl(v),
},
},
},
2017-10-27 18:59:20 -07:00
}
<Editor
schema={schema}
value={this.state.value}
...
/>
```
2017-10-27 18:59:20 -07:00
2017-11-17 02:14:38 +07:00
Hopefully just by reading this definition you'll understand what kinds of blocks are allowed in the document and what properties they can have—schemas are designed to prioritize legibility.
2017-10-27 18:59:20 -07:00
refactor normalization to be operations-based (#2193) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? This changes the normalization logic to be operations (and `key`) based, instead of the current logic which is more haphazard, and which has bugs that lead to non-normalized documents in certain cases. #### How does this change work? Now, every time a change method is called, after it applies its operations, those operations will be normalized. Based on each operation we can know exactly which nodes are "dirty" and need to be re-validated. This change also makes it easy for the `withoutNormalizing` (previously `withoutNormalization`) helper to be much more performant, and only normalize the "dirty" nodes instead of being forced to handle the entire document. To accommodate this new behavior, the old "operation flags" have been removed, replaced with a set of more consistent helpers: - `withoutNormalizing` - `withoutSaving` - `withoutMerging` All of them take functions that will be run with the desired behavior in scope, similar to how Immutable.js's own `withMutations` works. Previously this was done with a more complex set of flags, which could be set and unset in a confusing number of different ways, and it was generally not very well thought out. Hopefully this cleans it up, and makes it more approachable for people. We also automatically use the `withoutNormalizing` helper function for all of the changes that occur as part of schema `normalize` functions. Previously people had to use `{ normalize: false }` everywhere in those functions which was error-prone. With this new architecture, you sure almost never need to think about normalization. Except for cases where you explicitly want to move through an interim state that is invalid according to Slate's default schema or your own custom schema. In which case you'd use `withoutNormalizing` to allow the invalid interim state to be moved through. #### Have you checked that...? * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1363 Fixes: #2134 Fixes: #2135 Fixes: #2136 Fixes: #1579 Fixes: #2132 Fixes: #1657
2018-09-21 11:15:04 -07:00
This schema defines a document that only allows `paragraph` and `image` blocks. In the case of `paragraph` blocks, they can only contain text nodes. And in the case of `image` blocks, they are void nodes with a `data.src` property that is a URL. Simple enough, right?
2017-10-27 18:59:20 -07:00
The magic is that by passing a schema like this into your editor, it will automatically "validate" the document when changes are made, to make sure the schema is being adhered to. If it is, great. But if it isn't, and one of the nodes in the document is invalid, the editor will automatically "normalize" the node, to make the document valid again.
2017-10-27 18:59:20 -07:00
This way you can guarantee that the data is in a format that you expect, so you don't have to handle tons of edge-cases or invalid states in your own code.
> 🤖 Internally, Slate converts those schema definitions into plugins that enforce certain behaviors when changes are applied to the document.
2017-10-27 18:59:20 -07:00
## Custom Normalizers
By default, Slate will normalize any invalid states to ensure that the document is valid again. However, since Slate doesn't have that much information about your schema, its default normalization techniques might not always be what you want.
For example, with the above schema, if a block that isn't a `paragraph` or an `image` is discovered in the document, Slate will simply remove it.
2018-06-12 10:42:09 -07:00
But you might want to preserve the node, and instead just convert it to a `paragraph`-this way you aren't losing whatever the node's content was. Slate doesn't know those kinds of specifics about your data model, and trying to express all of these types of preferences in a declarative schema is a huge recipe for complexity.
2017-10-27 18:59:20 -07:00
Instead, Slate lets you define your own custom normalization logic.
```js
const schema = {
document: {
Refactor schema (#1993) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? - Tweaking the declarative schema definition syntax to make it easier to represent more complex states, as well as enable it to validate previously impossible things. - Rename `validateNode` to `normalizeNode` for clarity. - Introduce `validateNode`, `checkNode`, `assertNode` helpers for more advanced use cases, like front-end API validation of "invalid" fields that need to be fixed before they are sent to the server. #### How does this change work? The `schema.blocks/inlines/document` entries are now a shorthand for a more powerful `schema.rules` syntax. For example, this now allows for declaratively validating by a node's data, regardless of type: ```js { rules: [ { match: { data: { id: '2kd293lry' }, }, nodes: [ { match: { type: 'paragraph' }}, { match: { type: 'image' }}, ] } ] } ``` Previously you'd have to use `validateNode` for this, since the syntax wasn't flexible enough to validate nodes without hard-coding their `type`. This also simplifies the "concatenation" of schema rules, because under the covers all of them are implemented using the `schema.rules` array, so they simply take effect in order, just like everything else in plugins. #### Have you checked that...? <!-- Please run through this checklist for your pull request: --> * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1842 Fixes: #1923
2018-07-27 15:27:07 -07:00
nodes: [{
match: [{ type: 'paragraph' }, { type: 'image' }],
}],
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
normalize: (editor, error) => {
Refactor schema (#1993) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? - Tweaking the declarative schema definition syntax to make it easier to represent more complex states, as well as enable it to validate previously impossible things. - Rename `validateNode` to `normalizeNode` for clarity. - Introduce `validateNode`, `checkNode`, `assertNode` helpers for more advanced use cases, like front-end API validation of "invalid" fields that need to be fixed before they are sent to the server. #### How does this change work? The `schema.blocks/inlines/document` entries are now a shorthand for a more powerful `schema.rules` syntax. For example, this now allows for declaratively validating by a node's data, regardless of type: ```js { rules: [ { match: { data: { id: '2kd293lry' }, }, nodes: [ { match: { type: 'paragraph' }}, { match: { type: 'image' }}, ] } ] } ``` Previously you'd have to use `validateNode` for this, since the syntax wasn't flexible enough to validate nodes without hard-coding their `type`. This also simplifies the "concatenation" of schema rules, because under the covers all of them are implemented using the `schema.rules` array, so they simply take effect in order, just like everything else in plugins. #### Have you checked that...? <!-- Please run through this checklist for your pull request: --> * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1842 Fixes: #1923
2018-07-27 15:27:07 -07:00
if (error.code == 'child_type_invalid') {
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
editor.setNodeByKey(error.child.key, { type: 'paragraph' })
2017-10-27 18:59:20 -07:00
}
}
},
...
}
```
That's an example of defining your own custom `normalize` option for the document validation. If the invalid reason is `child_type_invalid`, it will set the child to be a `paragraph`.
2018-06-12 10:42:09 -07:00
When Slate discovers an invalid child, it will first check to see if your custom normalizer handles that case; if your normalizer handles it, then Slate won't run any of its default behavior. This way, you can opt-in to customizing the normalization logic for specific cases without having to re-implement all of the defaults yourself.
2017-10-27 18:59:20 -07:00
This gives you the best of both worlds. You can write simple, terse, declarative validation rules that can be highly optimized. But you can still define fine-grained, imperative normalization logic for when invalid states occur.
Refactor schema (#1993) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? - Tweaking the declarative schema definition syntax to make it easier to represent more complex states, as well as enable it to validate previously impossible things. - Rename `validateNode` to `normalizeNode` for clarity. - Introduce `validateNode`, `checkNode`, `assertNode` helpers for more advanced use cases, like front-end API validation of "invalid" fields that need to be fixed before they are sent to the server. #### How does this change work? The `schema.blocks/inlines/document` entries are now a shorthand for a more powerful `schema.rules` syntax. For example, this now allows for declaratively validating by a node's data, regardless of type: ```js { rules: [ { match: { data: { id: '2kd293lry' }, }, nodes: [ { match: { type: 'paragraph' }}, { match: { type: 'image' }}, ] } ] } ``` Previously you'd have to use `validateNode` for this, since the syntax wasn't flexible enough to validate nodes without hard-coding their `type`. This also simplifies the "concatenation" of schema rules, because under the covers all of them are implemented using the `schema.rules` array, so they simply take effect in order, just like everything else in plugins. #### Have you checked that...? <!-- Please run through this checklist for your pull request: --> * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1842 Fixes: #1923
2018-07-27 15:27:07 -07:00
> 🤖 For a full list of error `code` types, check out the [`Schema` reference](../reference/slate/schema.md).
2017-10-27 18:59:20 -07:00
Refactor schema (#1993) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? - Tweaking the declarative schema definition syntax to make it easier to represent more complex states, as well as enable it to validate previously impossible things. - Rename `validateNode` to `normalizeNode` for clarity. - Introduce `validateNode`, `checkNode`, `assertNode` helpers for more advanced use cases, like front-end API validation of "invalid" fields that need to be fixed before they are sent to the server. #### How does this change work? The `schema.blocks/inlines/document` entries are now a shorthand for a more powerful `schema.rules` syntax. For example, this now allows for declaratively validating by a node's data, regardless of type: ```js { rules: [ { match: { data: { id: '2kd293lry' }, }, nodes: [ { match: { type: 'paragraph' }}, { match: { type: 'image' }}, ] } ] } ``` Previously you'd have to use `validateNode` for this, since the syntax wasn't flexible enough to validate nodes without hard-coding their `type`. This also simplifies the "concatenation" of schema rules, because under the covers all of them are implemented using the `schema.rules` array, so they simply take effect in order, just like everything else in plugins. #### Have you checked that...? <!-- Please run through this checklist for your pull request: --> * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1842 Fixes: #1923
2018-07-27 15:27:07 -07:00
## Low-level Normalizations
2017-10-27 18:59:20 -07:00
Refactor schema (#1993) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? - Tweaking the declarative schema definition syntax to make it easier to represent more complex states, as well as enable it to validate previously impossible things. - Rename `validateNode` to `normalizeNode` for clarity. - Introduce `validateNode`, `checkNode`, `assertNode` helpers for more advanced use cases, like front-end API validation of "invalid" fields that need to be fixed before they are sent to the server. #### How does this change work? The `schema.blocks/inlines/document` entries are now a shorthand for a more powerful `schema.rules` syntax. For example, this now allows for declaratively validating by a node's data, regardless of type: ```js { rules: [ { match: { data: { id: '2kd293lry' }, }, nodes: [ { match: { type: 'paragraph' }}, { match: { type: 'image' }}, ] } ] } ``` Previously you'd have to use `validateNode` for this, since the syntax wasn't flexible enough to validate nodes without hard-coding their `type`. This also simplifies the "concatenation" of schema rules, because under the covers all of them are implemented using the `schema.rules` array, so they simply take effect in order, just like everything else in plugins. #### Have you checked that...? <!-- Please run through this checklist for your pull request: --> * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1842 Fixes: #1923
2018-07-27 15:27:07 -07:00
Sometimes though, the declarative validation syntax isn't fine-grained enough to handle a specific piece of validation. That's okay, because you can actually define schema validations in Slate as regular functions when you need more control, using the `normalizeNode` property of plugins and editors.
2017-10-27 18:59:20 -07:00
Refactor schema (#1993) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? - Tweaking the declarative schema definition syntax to make it easier to represent more complex states, as well as enable it to validate previously impossible things. - Rename `validateNode` to `normalizeNode` for clarity. - Introduce `validateNode`, `checkNode`, `assertNode` helpers for more advanced use cases, like front-end API validation of "invalid" fields that need to be fixed before they are sent to the server. #### How does this change work? The `schema.blocks/inlines/document` entries are now a shorthand for a more powerful `schema.rules` syntax. For example, this now allows for declaratively validating by a node's data, regardless of type: ```js { rules: [ { match: { data: { id: '2kd293lry' }, }, nodes: [ { match: { type: 'paragraph' }}, { match: { type: 'image' }}, ] } ] } ``` Previously you'd have to use `validateNode` for this, since the syntax wasn't flexible enough to validate nodes without hard-coding their `type`. This also simplifies the "concatenation" of schema rules, because under the covers all of them are implemented using the `schema.rules` array, so they simply take effect in order, just like everything else in plugins. #### Have you checked that...? <!-- Please run through this checklist for your pull request: --> * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1842 Fixes: #1923
2018-07-27 15:27:07 -07:00
> 🤖 Actually, under the covers the declarative schemas are all translated into `normalizeNode` functions too!
2017-10-27 18:59:20 -07:00
Refactor schema (#1993) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? - Tweaking the declarative schema definition syntax to make it easier to represent more complex states, as well as enable it to validate previously impossible things. - Rename `validateNode` to `normalizeNode` for clarity. - Introduce `validateNode`, `checkNode`, `assertNode` helpers for more advanced use cases, like front-end API validation of "invalid" fields that need to be fixed before they are sent to the server. #### How does this change work? The `schema.blocks/inlines/document` entries are now a shorthand for a more powerful `schema.rules` syntax. For example, this now allows for declaratively validating by a node's data, regardless of type: ```js { rules: [ { match: { data: { id: '2kd293lry' }, }, nodes: [ { match: { type: 'paragraph' }}, { match: { type: 'image' }}, ] } ] } ``` Previously you'd have to use `validateNode` for this, since the syntax wasn't flexible enough to validate nodes without hard-coding their `type`. This also simplifies the "concatenation" of schema rules, because under the covers all of them are implemented using the `schema.rules` array, so they simply take effect in order, just like everything else in plugins. #### Have you checked that...? <!-- Please run through this checklist for your pull request: --> * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1842 Fixes: #1923
2018-07-27 15:27:07 -07:00
When you define a `normalizeNode` function, you either return nothing if the node's already valid, or you return a normalizer function that will make the node valid if it isn't. Here's an example:
2017-10-27 18:59:20 -07:00
```js
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
function normalizeNode(node, editor, next) {
2017-10-27 18:59:20 -07:00
const { nodes } = node
if (node.object !== 'block') return next()
if (nodes.size !== 3) return next()
if (nodes.first().object !== 'text') return next()
if (nodes.last().object !== 'text') return next()
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
return () => editor.removeNodeByKey(node.key)
2017-10-27 18:59:20 -07:00
}
```
This validation defines a very specific (honestly, useless) behavior, where if a node is a block and has three children, the first and last of which are text nodes, it is removed. I don't know why you'd ever do that, but the point is that you can get very specific with your validations this way. Any property of the node can be examined.
2017-10-27 18:59:20 -07:00
Refactor schema (#1993) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? - Tweaking the declarative schema definition syntax to make it easier to represent more complex states, as well as enable it to validate previously impossible things. - Rename `validateNode` to `normalizeNode` for clarity. - Introduce `validateNode`, `checkNode`, `assertNode` helpers for more advanced use cases, like front-end API validation of "invalid" fields that need to be fixed before they are sent to the server. #### How does this change work? The `schema.blocks/inlines/document` entries are now a shorthand for a more powerful `schema.rules` syntax. For example, this now allows for declaratively validating by a node's data, regardless of type: ```js { rules: [ { match: { data: { id: '2kd293lry' }, }, nodes: [ { match: { type: 'paragraph' }}, { match: { type: 'image' }}, ] } ] } ``` Previously you'd have to use `validateNode` for this, since the syntax wasn't flexible enough to validate nodes without hard-coding their `type`. This also simplifies the "concatenation" of schema rules, because under the covers all of them are implemented using the `schema.rules` array, so they simply take effect in order, just like everything else in plugins. #### Have you checked that...? <!-- Please run through this checklist for your pull request: --> * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1842 Fixes: #1923
2018-07-27 15:27:07 -07:00
When you need this level of specificity, using the `normalizeNode` property of the editor or plugins is handy.
2017-10-27 18:59:20 -07:00
Refactor schema (#1993) #### Is this adding or improving a _feature_ or fixing a _bug_? Improvement. #### What's the new behavior? - Tweaking the declarative schema definition syntax to make it easier to represent more complex states, as well as enable it to validate previously impossible things. - Rename `validateNode` to `normalizeNode` for clarity. - Introduce `validateNode`, `checkNode`, `assertNode` helpers for more advanced use cases, like front-end API validation of "invalid" fields that need to be fixed before they are sent to the server. #### How does this change work? The `schema.blocks/inlines/document` entries are now a shorthand for a more powerful `schema.rules` syntax. For example, this now allows for declaratively validating by a node's data, regardless of type: ```js { rules: [ { match: { data: { id: '2kd293lry' }, }, nodes: [ { match: { type: 'paragraph' }}, { match: { type: 'image' }}, ] } ] } ``` Previously you'd have to use `validateNode` for this, since the syntax wasn't flexible enough to validate nodes without hard-coding their `type`. This also simplifies the "concatenation" of schema rules, because under the covers all of them are implemented using the `schema.rules` array, so they simply take effect in order, just like everything else in plugins. #### Have you checked that...? <!-- Please run through this checklist for your pull request: --> * [x] The new code matches the existing patterns and styles. * [x] The tests pass with `yarn test`. * [x] The linter passes with `yarn lint`. (Fix errors with `yarn prettier`.) * [x] The relevant examples still work. (Run examples with `yarn watch`.) #### Does this fix any issues or need any specific reviewers? Fixes: #1842 Fixes: #1923
2018-07-27 15:27:07 -07:00
However, only use it when you absolutely have to. And when you do, make sure to optimize the function's performance. `normalizeNode` will be called **every time the node changes**, so it should be as performant as possible. That's why the example above returns early, so that the smallest amount of work is done each time it is called.