1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-03-06 05:49:47 +01:00
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

229 lines
6.4 KiB
JavaScript

import Plain from 'slate-plain-serializer'
import { Editor } from 'slate-react'
import Prism from 'prismjs'
import React from 'react'
/**
* Add the markdown syntax to Prism.
*/
// eslint-disable-next-line
;Prism.languages.markdown=Prism.languages.extend("markup",{}),Prism.languages.insertBefore("markdown","prolog",{blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},code:[{pattern:/^(?: {4}|\t).+/m,alias:"keyword"},{pattern:/``.+?``|`[^`\n]+`/,alias:"keyword"}],title:[{pattern:/\w+.*(?:\r?\n|\r)(?:==+|--+)/,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#+.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])([\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:/(^|[^\\])(\*\*|__)(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/,lookbehind:!0,inside:{punctuation:/^\*\*|^__|\*\*$|__$/}},italic:{pattern:/(^|[^\\])([*_])(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/,lookbehind:!0,inside:{punctuation:/^[*_]|[*_]$/}},url:{pattern:/!?\[[^\]]+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)| ?\[[^\]\n]*\])/,inside:{variable:{pattern:/(!?\[)[^\]]+(?=\]$)/,lookbehind:!0},string:{pattern:/"(?:\\.|[^"\\])*"(?=\)$)/}}}}),Prism.languages.markdown.bold.inside.url=Prism.util.clone(Prism.languages.markdown.url),Prism.languages.markdown.italic.inside.url=Prism.util.clone(Prism.languages.markdown.url),Prism.languages.markdown.bold.inside.italic=Prism.util.clone(Prism.languages.markdown.italic),Prism.languages.markdown.italic.inside.bold=Prism.util.clone(Prism.languages.markdown.bold); // prettier-ignore
/**
* The markdown preview example.
*
* @type {Component}
*/
class MarkdownPreview extends React.Component {
/**
* Deserialize the initial editor value.
*
* @type {Object}
*/
state = {
value: Plain.deserialize(
'Slate is flexible enough to add **decorations** that can format text based on its content. For example, this editor has **Markdown** preview decorations on it, to make it _dead_ simple to make an editor with built-in Markdown previewing.\n## Try it out!\nTry it out for yourself!'
),
}
/**
*
* Render the example.
*
* @return {Component} component
*/
render() {
return (
<Editor
placeholder="Write some markdown..."
value={this.state.value}
onChange={this.onChange}
renderMark={this.renderMark}
decorateNode={this.decorateNode}
/>
)
}
/**
* Render a Slate mark.
*
* @param {Object} props
* @param {Editor} editor
* @param {Function} next
* @return {Element}
*/
renderMark = (props, editor, next) => {
const { children, mark, attributes } = props
switch (mark.type) {
case 'bold':
return <strong {...attributes}>{children}</strong>
case 'code':
return <code {...attributes}>{children}</code>
case 'italic':
return <em {...attributes}>{children}</em>
case 'underlined':
return <u {...attributes}>{children}</u>
case 'title': {
return (
<span
{...attributes}
style={{
fontWeight: 'bold',
fontSize: '20px',
margin: '20px 0 10px 0',
display: 'inline-block',
}}
>
{children}
</span>
)
}
case 'punctuation': {
return (
<span {...attributes} style={{ opacity: 0.2 }}>
{children}
</span>
)
}
case 'list': {
return (
<span
{...attributes}
style={{
paddingLeft: '10px',
lineHeight: '10px',
fontSize: '20px',
}}
>
{children}
</span>
)
}
case 'hr': {
return (
<span
{...attributes}
style={{
borderBottom: '2px solid #000',
display: 'block',
opacity: 0.2,
}}
>
{children}
</span>
)
}
default: {
return next()
}
}
}
/**
* On change.
*
* @param {Editor} editor
*/
onChange = ({ value }) => {
this.setState({ value })
}
/**
* Define a decorator for markdown styles.
*
* @param {Node} node
* @param {Function} next
* @return {Array}
*/
decorateNode(node, editor, next) {
const others = next() || []
if (node.object != 'block') return others
const string = node.text
const texts = node.getTexts().toArray()
const grammar = Prism.languages.markdown
const tokens = Prism.tokenize(string, grammar)
const decorations = []
let startText = texts.shift()
let endText = startText
let startOffset = 0
let endOffset = 0
let start = 0
function getLength(token) {
if (typeof token == 'string') {
return token.length
} else if (typeof token.content == 'string') {
return token.content.length
} else {
return token.content.reduce((l, t) => l + getLength(t), 0)
}
}
for (const token of tokens) {
startText = endText
startOffset = endOffset
const length = getLength(token)
const end = start + length
let available = startText.text.length - startOffset
let remaining = length
endOffset = startOffset + remaining
while (available < remaining) {
endText = texts.shift()
remaining = length - available
available = endText.text.length
endOffset = remaining
}
if (typeof token != 'string') {
const dec = {
anchor: {
key: startText.key,
offset: startOffset,
},
focus: {
key: endText.key,
offset: endOffset,
},
mark: {
type: token.type,
},
}
decorations.push(dec)
}
start = end
}
return [...others, ...decorations]
}
}
/**
* Export.
*/
export default MarkdownPreview