Tldraw/docs/docs/editor.mdx

290 wiersze
12 KiB
Markdown

---
title: Editor
status: published
author: steveruizok
date: 3/22/2023
order: 3
keywords:
- ui
- app
- editor
- control
- select
---
##### Table of Contents
- [Introduction](#introduction)
- [State](#state)
- [Events](#events)
- [Inputs](#inputs)
- [Common things to do with the editor](#common-things-to-do-with-the-editor)
## Introduction
The [`Editor`](/gen/editor/Editor) class is the main way of controlling tldraw's editor. You can use it to manage the editor's internal state, make changes to the document, or respond to changes that have occurred.
By design, the [`Editor`](/gen/editor/Editor)'s surface area is very large. Almost everything is available through it. Need to create some shapes? Use [`editor.createShapes()`](/gen/editor/Editor#createShapes). Need to delete them? Use [`editor.deleteShapes()`](/gen/editor/Editor#deleteShapes). Need a sorted array of every shape on the current page? Use [`editor.sortedShapesArray`](/gen/editor/Editor#sortedShapesArray).
This page gives a broad idea of how the [`Editor`](/gen/editor/Editor) class is organized and some of the architectural concepts involved. The full reference is available in the [Editor API](/gen/editor/Editor).
## State
The editor holds the raw state of the document in its [`store`](/gen/editor/Editor#store) property. Data is kept here as a table of JSON serializable records.
For example, the store contains a `page` record for each page in the current document, as well as an `instancePageState` record for each page that stores information about the editor's state for that page, and a single `instanceState` for each editor instance which stores the id of the user's current page.
The editor also exposes many _computed_ values which are derived from other records in the store. For example, [`editor.selectedIds`](/gen/editor/Editor#selectedIds) is a computed property that will return the editor's current selected shape ids for its current page.
You can use these properties directly or you can use them in signals.
```tsx
import { track, useEditor } from "@tldraw/tldraw"
export const SelectedIdsCount = track(() => {
const editor = useEditor()
return (
<div>{editor.selectedIds.length}</div>
)
})
```
### Changing the state
The [`Editor`](/gen/editor/Editor) class has many methods for updating its state. For example, you can change the current page's selection using [`editor.setSelectedIds`](/gen/editor/Editor#setSelectedIds). You can also use other convenience methods, such as [`editor.select`](/gen/editor/Editor#), [`editor.deselect`](/gen/editor/Editor#deselect), [`editor.selectAll`](/gen/editor/Editor#selectAll), or [`editor.selectNone`](/gen/editor/Editor#selectNone).
```ts
editor.selectNone()
editor.select(myShapeId, myOtherShapeId)
editor.selectedIds // [myShapeId, myOtherShapeId]
```
Each change to the state happens within a transaction. You can batch changes into a single transaction using the [`editor.batch`](/gen/editor/Editor#batch) method. It's a good idea to batch wherever possible, as this reduces the overhead for persisting or distributing those changes.
### Listening for changes
You can subscribe to changes using [`editor.store.listen`](/gen/store/Store#listen). Each time a transaction completes, the editor will call the callback with a history entry. This entry contains information about the records that were added, changed, or deleted, as well as whether the change was caused by the user or from a remote change.
```ts
editor.store.listen(entry => {
entry // { changes, source }
})
```
### Remote changes
By default, changes to the editor's store are assumed to have come from the editor itself. You can use [`editor.store.mergeRemoteChanges`](/gen/store/Store#mergeRemoteChanges) to make changes in the store that will be emitted via [`store.listen`](/gen/store/Store#listen) with the `source` property as `'remote'`.
If you're setting up some kind of multiplayer backend, you would want to send only the `'user'` changes to the server and merge the changes from the server using [`editor.store.mergeRemoteChanges`](/gen/store/Store#mergeRemoteChanges).
### Undo and redo
The history stack in tldraw contains two types of data: "marks" and "commands". Commands have their own `undo` and `redo` methods that describe how the state should change when the command is undone or redone.
You can call [`editor.mark(id)`](/gen/editor/Editor#mark) to add a mark to the history stack with the given `id`.
When you call [`editor.undo()`](/gen/editor/Editor#undo), the editor will undo each command until it finds either a mark or the start of the stack. When you call [`editor.redo()`](/gen/editor/Editor#redo), the editor will redo each command until it finds either a mark or the end of the stack.
```ts
// A
editor.mark("duplicate everything")
editor.selectAll()
editor.duplicateShapes(editor.selectedIds)
// B
editor.undo() // will return to A
editor.redo() // will return to B
```
You can call [`editor.bail()`](/gen/editor/Editor#bail) to undo and delete all commands in the stack until the first mark.
```ts
// A
editor.mark("duplicate everything")
editor.selectAll()
editor.duplicateShapes(editor.selectedIds)
// B
editor.bail() // will return to A
editor.redo() // will do nothing
```
You can use [`editor.bailToMark(id)`](/gen/editor/Editor#bailToMark) to undo and delete all commands and marks until you reach a mark with the given `id`.
```ts
// A
editor.mark("first")
editor.selectAll()
// B
editor.mark("second")
editor.duplicateShapes(editor.selectedIds)
// C
editor.bailToMark("first") // will to A
```
## Events
The [`Editor`](/gen/editor/Editor) class receives events from its [`dispatch`](/gen/editor/Editor#dispatch) method. When the [`Editor`](/gen/editor/Editor) receives an event, it is first handled internally to update [`editor.inputs`](/gen/editor/Editor#inputs) and other state before, and then sent into to the editor's state chart.
You shouldn't need to use the [`dispatch`](/gen/editor/Editor#dispatch) method directly, however you may write code in the state chart that responds to these events. See the [Tools page](tools) to learn how to do that, or read below for a more detailed information about the state chart itself.
### State Chart
The [`Editor`](/gen/editor/Editor) class has a "state chart", or a tree of [`StateNode`](/gen/editor/StateNode) instances, that contain the logic for the editor's tools such as the select tool or the draw tool. User interactions such as moving the cursor will produce different changes to the state depending on which nodes are active.
Each node can be active or inactive. Each state node may also have zero or more children. When a state is active, and if the state has children, one (and only one) of its children must also be active. When a state node receives an event from its parent, it has the opportunity to handle the event before passing the event to its active child. The node can handle an event in any way: it can ignore the event, update records in the store, or run a _transition_ that changes which states nodes are active.
When a user interaction is sent to the editor via its [`dispatch`](/gen/editor/Editor#dispatch) method, this event is sent to the editor's root state node (`editor.root`) and passed then down through the chart's active states until either it reaches a leaf node or until one of those nodes produces a transaction.
<Image title="Events" src="/images/api/events.png" alt="A diagram showing an event being sent to the editor and handled in the state chart." title="The editor passes an event into the state start where it is handled by each active state in order."/>
### Path
You can get the editor's current "path" of active states via `editor.root.path`. In the above example, the value would be `"root.select.idle"`.
You can check whether a path is active via [`editor.isIn`](/gen/editor/Editor#isIn), or else check whether multiple paths are active via [`editor.isInAny`](/gen/editor/Editor#isInAny).
```ts
editor.store.path // 'root.select.idle'
editor.isIn('root.select') // true
editor.isIn('root.select.idle') // true
editor.isIn('root.select.pointing_shape') // false
editor.isInAny('editor.select.idle', 'editor.select.pointing_shape') // true
```
Note that the paths you pass to [`isIn`](/gen/editor/Editor#isIn) or [`isInAny`](/gen/editor/Editor#isInAny) can be the full path or a partial of the start of the path. For example, if the full path is `root.select.idle`, then [`isIn`](/gen/editor/isIn) would return true for the paths `root`, `root.select`, or `root.select.idle`.
> If all you're interested in is the state below `root`, there is a convenience property, [`editor.currentToolId`](/gen/editor/Editor#currentToolId), that can help with the editor's currently selected tool.
```tsx
import { track, useEditor } from "@tldraw/tldraw"
export const CreatingBubbleToolUi = track(() => {
const editor = useEditor()
const isSelected = editor.isIn('root.bubble.creating')
if (!editor.currentToolId === 'bubble') return
return (
<div data-isSelected={isSelected}>Creating Bubble</div>
)
})
```
## Inputs
The editor's [`inputs`](/gen/editor/Editor#inputs) object holds information about the user's current input state, including their cursor position (in page space _and_ screen space), which keys are pressed, what their multi-click state is, and whether they are dragging, pointing, pinching, and so on.
Note that the modifier keys include a short delay after being released in order to prevent certain errors when modeling interactions. For example, when a user releases the "Shift" key, [`editor.inputs.shiftKey`](/gen/editor/Editor#inputs) will remain `true` for another 100 milliseconds or so.
This property is stored as regular data. It is not reactive.
## Common things to do with the editor
### Create shapes
```ts
editor.createShapes([
{
id,
type: 'geo',
x: 0,
y: 0,
props: {
geo: 'rectangle',
w: 100,
h: 100,
dash: 'draw',
color: 'blue',
size: 'm',
},
},
])
```
### Update shapes
```ts
const shape = editor.selectedShapes[0]
editor.updateShapes([
{
id: shape.id, // required
type: shape.type, // required
x: 100,
y: 100,
props: {
w: 200,
},
},
])
```
### Delete shapes
```ts
const shape = editor.selectedShapes[0]
editor.deleteShapes([shape.id])
```
### Get a shape by its id
```ts
editor.getShapeById(myShapeId)
```
### Move the camera
```ts
editor.setCamera(0, 0, 1)
```
## Meta
Shapes have a `meta` property that you can fill with your own data. This should feel like a bit of a hack, however it's intended to be an escape hatch for applications where you want to use tldraw's shapes but also want to attach a bit of extra data to the shape.
Note that tldraw's regular shape definitions have an unknown object for the shape's `meta` property. To type your shape's meta, use a union like this:
```ts
type MyShapeWithMeta = TLGeoShape & { meta: { createdBy: string } }
const shape = editor.getShapeById<MyShapeWithMeta>(myGeoShape.id)
```
You can update a shape's `meta` property in the same way you would update its props, using `Editor.updateShapes`.
```ts
editor.updateShapes<MyShapeWithMeta>([{
id: myGeoShape.id,
type: "geo",
meta: {
createdBy: "Steve"
}
}])
```
Like `props`, the data in a shape's `meta` object must be JSON serializable.
In addition to setting meta properties this way, you can also set the default meta data for shapes using the Editor's `getShapeInitialMeta` method.
```tsx
editor.getShapeInitialMeta = (shape: TLShape) => {
if (shape.type === 'text') {
return { createdBy: currentUser.id, lastModified: Date.now() }
} else {
return { createdBy: currentUser.id }
}
}
```
Whenever new shapes are created using the `createShapes` method, the shape's meta property will be set using the `getShapeInitialMeta` method. By default this method returns an empty object.
---
See the [tldraw repository](https://github.com/tldraw/tldraw/tree/main/apps/examples) for an example of how to use tldraw's Editor API to control the editor.