1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-08-27 00:54:22 +02:00
* 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:
Ian Storm Taylor
2019-11-27 20:54:42 -05:00
committed by GitHub
parent 02b87d5968
commit 4ff6972096
2367 changed files with 45706 additions and 80698 deletions

View 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!