浏览代码

Update README.md

main
Steve Ruiz 3 年前
父节点
当前提交
cb3ebde9ac
没有帐户链接到提交者的电子邮件
共有 1 个文件被更改,包括 8 次插入350 次删除
  1. 8
    350
      README.md

+ 8
- 350
README.md 查看文件

@@ -19,6 +19,8 @@ To support this project (and gain access to the project while it is in developme
19 19
 
20 20
 ## Local Development
21 21
 
22
+To work on the packages (@tldraw/core or @tldraw/tldraw), you'll want to run the dev server.
23
+
22 24
 1. Download or clone the repository.
23 25
 
24 26
    ```bash
@@ -34,357 +36,13 @@ To support this project (and gain access to the project while it is in developme
34 36
 3. Start the development server.
35 37
 
36 38
    ```bash
37
-   yarn dev
39
+   yarn start
38 40
    ```
39 41
 
40
-4. Open the local site at `https://localhost:3000`.
41
-
42
-This project is a [Next.js](https://nextjs.org/) project. If you've worked with Next.js before, the tldraw code-base and setup instructions should all be very familiar.
43
-
44
-## How it works
45
-
46
-The app's state is a very large state machine located in `state/state.ts`. The machine is organized as a tree of state notes, such as `selecting` and `pinching`.
47
-
48
-```
49
-root
50
-├── loading
51
-└── ready
52
-    ├── selecting
53
-    │   ├── notPointing
54
-    │   ├── pointingBounds
55
-    │   ├── translatingSelection
56
-    │   └── ...
57
-    ├── usingTool
58
-    ├── pinching
59
-    └── ...
60
-```
61
-
62
-### State Nodes
63
-
64
-Nodes may be active or inactive. The root node is always active. Depending on what's happened in the app, different branches of the state tree may be active, while other branches may be inactive.
65
-
66
-```ts
67
-pinching: {
68
-  onExit: { secretlyDo: 'updateZoomCSS' },
69
-  initial: 'selectPinching',
70
-  states: {
71
-    selectPinching: {
72
-      on: {
73
-        STOPPED_PINCHING: { to: 'selecting' },
74
-      },
75
-    },
76
-    toolPinching: {
77
-      on: {
78
-        STOPPED_PINCHING: { to: 'usingTool.previous' },
79
-      },
80
-    },
81
-  },
82
-},
83
-```
84
-
85
-State nodes are both a way to describe the state (e.g., "the pinching state is active") and a way of organizing events. Each node has a set of events (`on`). When the state receives an event, it will execute the event handlers on each of the machine's _active_ states where the event is present.
86
-
87
-### Event Handlers
88
-
89
-Event handlers contain references to event handler functions: `actions`, `conditions`, `results`, and `async`s. These are defined at the bottom of the state machine's configuration.
90
-
91
-An event handler may be a single action:
92
-
93
-```ts
94
-on: {
95
-  MOVED_POINTER: 'updateRotateSession',
96
-}
97
-```
98
-
99
-Or it may be an array of actions:
100
-
101
-```ts
102
-on: {
103
-  MOVED_TO_PAGE: ['moveSelectionToPage', 'zoomCameraToSelectionActual'],
104
-}
105
-```
106
-
107
-Or it may be an object with conditions under `if` or `unless` and actions under `do`:
108
-
109
-```ts
110
-on: {
111
-  SAVED_CODE: {
112
-    unless: 'isReadOnly',
113
-    do: 'saveCode',
114
-  }
115
-}
116
-```
117
-
118
-An event handler may also contain transitions under `to`:
119
-
120
-```ts
121
-on: {
122
-  STOPPED_PINCHING: { to: 'selecting' },
123
-},
124
-```
125
-
126
-As well as nested event handlers under control flow, `then` and `else`.
127
-
128
-```ts
129
-on: {
130
-  STOPPED_POINTING: {
131
-    if: 'isPressingShiftKey',
132
-    then: {
133
-      if: 'isPointedShapeSelected',
134
-      do: 'pullPointedIdFromSelectedIds',
135
-    },
136
-    else: {
137
-      if: 'isPointingShape',
138
-      do: [
139
-        'clearSelectedIds',
140
-        'setPointedId',
141
-        'pushPointedIdToSelectedIds',
142
-      ],
143
-    },
144
-  },
145
-}
146
-```
147
-
148
-And finally, an event handler may have arrays of event handler objects.
149
-
150
-```ts
151
-on: {
152
-  STOPPED_POINTING: [
153
-    'completeSession',
154
-    {
155
-      if: 'isToolLocked',
156
-      to: 'dot.creating',
157
-      else: {
158
-        to: 'selecting'
159
-      },
160
-    },
161
-  ],
162
-}
163
-```
164
-
165
-### Event Handler Functions
166
-
167
-The configuration's event handlers work by calling event handler functions. While each event handler function does a different job, all event handler functions receive the _same_ three parameters:
168
-
169
-1. The machine's current `data` draft
170
-2. The payload sent by the event that has caused the function to run
171
-3. The most recent result returned by a `result` function
172
-
173
-> Note: The `payload` and `result` parameters must be typed manually inline.
174
-
175
-```ts
176
-eventHandlerFn(data, payload: { id: string }, result: Shape) {}
177
-```
178
-
179
-Results may return any value.
180
-
181
-```ts
182
-pageById(data, payload: { id: string }) {
183
-  return data.document.pages[payload.id]
184
-}
185
-```
186
-
187
-Conditions must return `true` or `false`.
188
-
189
-```ts
190
-pageIsCurrentPage(data, payload, result: Page) {
191
-  return data.currentPageId === result.id
192
-}
193
-```
194
-
195
-Actions may mutate the `data` draft.
196
-
197
-```ts
198
-setCurrentPageId(data, payload, result: Page) {
199
-  data.currentPageId = result.id
200
-}
201
-```
202
-
203
-In a state's event handlers, event handler functions are referred to by name.
204
-
205
-```ts
206
-on: {
207
-  SOME_EVENT: {
208
-    get: "pageById"
209
-    unless: "pageIsCurrentPage",
210
-    do: "setCurrentPageId"
211
-  }
212
-}
213
-```
214
-
215
-Asyncs are asynchronous functions. They work like results, but resolve data instead.
216
-
217
-```ts
218
-async getCurrentUser(data) {
219
-  return fetch(`https://tldraw/api/users/${data.currentUserId}`)
220
-}
221
-```
222
-
223
-These are used in asynchronous event handlers:
224
-
225
-```ts
226
-loadingUser: {
227
-  async: {
228
-    await: "getCurrentUser",
229
-    onResolve: { to: "user" },
230
-    onReject: { to: "error" },
231
-  }
232
-}
233
-```
234
-
235
-### State Updates
236
-
237
-The state will update each time it:
238
-
239
-1. receives an event...
240
-2. that causes it to run an event handler...
241
-3. that passes its conditions...
242
-4. and that contains either an action or a transition
42
+4. Open the local site at `https://localhost:5000`.
243 43
 
244
-Such updates are batched: while a single event may cause several event handlers to run, the state will update only once provided that at least one of the event handlers caused an action or transition to occur.
44
+To work on the app itself (that embeds @tldraw/tldraw), run the Next.js app:
245 45
 
246
-When a state updates, it will cause any subscribed components to update via hooks.
247
-
248
-### Subscribing to State
249
-
250
-To use the state's data reactively, we use the `useSelector` hook.
251
-
252
-```tsx
253
-import state, { useSelector } from 'state'
254
-
255
-function SomeComponent() {
256
-  const pointingId = useSelector((s) => s.data.pointingId)
257
-
258
-  return <div>The pointing id is {pointingId}</div>
259
-}
260
-```
261
-
262
-Each time the state updates, the hook will check whether the data returned by the selector function matches its previous data. If the answer is false (ie if the data is new) the hook will update and the new data will become its previous data.
263
-
264
-The hook may also accept a second parameter, a comparison function. If the selector function returns anything other than a primitive, we will often use a comparison function to correctly find changes.
265
-
266
-```tsx
267
-import state, { useSelector } from 'state'
268
-import { deepCompareArrays } from 'utils'
269
-
270
-function SomeComponent() {
271
-  const selectedIds = useSelector(
272
-    (s) => tld.getSelectedShapes(s.data).map((shape) => shape.id),
273
-    deepCompareArrays
274
-  )
275
-
276
-  return <div>The selected ids are {selectedIds.toString()}</div>
277
-}
278
-```
279
-
280
-### Events
281
-
282
-Events are sent from the user interface to the state.
283
-
284
-```ts
285
-import state from 'state'
286
-
287
-state.send('SELECTED_DRAW_TOOL')
288
-```
289
-
290
-Events may also include payloads of data.
291
-
292
-```ts
293
-state.send('ALIGNED', { type: AlignType.Right })
294
-```
295
-
296
-The payload will become the second parameter of any event handler function that runs as a result of the event.
297
-
298
-Note that with very few exceptions, we send events to the state regardless of whether the state can handle the event. Whether the event should have an effect—and what that effect should be—these questions are left entirely to the state machine.
299
-
300
-> Note: You can send an event to the state from anywhere in the app: even from components that are not subscribed to the state. See the components/style-panel files for examples.
301
-
302
-### Commands and History
303
-
304
-The app uses a command pattern to keep track of what has happened in the app, and to support an undo and redo stack. Each command includes a `do` method and an `undo` method. When the command is created, it will run its `do` method. If it is "undone", it will run its `undo` method. If the command is "redone", it will run its `do` method again.
305
-
306
-```ts
307
-export default function nudgeCommand(data: Data, delta: number[]): void {
308
-  const initialShapes = tld.getSelectedShapeSnapshot(data, () => null)
309
-
310
-  history.execute(
311
-    data,
312
-    new Command({
313
-      name: 'nudge_shapes',
314
-      category: 'canvas',
315
-      do(data) {
316
-        tld.mutateShapes(
317
-          data,
318
-          initialShapes.map((shape) => shape.id),
319
-          (shape, utils) => {
320
-            utils.setProperty(shape, 'point', vec.add(shape.point, delta))
321
-          }
322
-        )
323
-      },
324
-      undo(data) {
325
-        tld.mutateShapes(
326
-          data,
327
-          initialShapes.map((shape) => shape.id),
328
-          (shape, utils) => {
329
-            utils.setProperty(shape, 'point', vec.sub(shape.point, delta))
330
-          }
331
-        )
332
-      },
333
-    })
334
-  )
335
-}
336
-```
337
-
338
-Undos are not done programatically. It's the responsibility of a command to ensure that any mutations made in its `do` method are correctly reversed in its `undo` method.
339
-
340
-> Note: All mutations to a shape must be done through a shape's utils (the structure returned by `getShapeUtils`). Currently, many commands do this directly: however we're currently working on a more robust API for this, with built-in support for side effects, such as shown with `mutateShapes` above.
341
-
342
-### Sessions
343
-
344
-Not every change to the app's state needs to be put into the undo / redo stack. Sessions are a way of managing the data associated with certain states that lie _between_ commands, such as when a user is dragging a shape to a new position.
345
-
346
-Sessions are managed by the SessionManager (`state/session`). It guarantees that only one session is active at a time and allows other parts of the app's state to access information about the current session.
347
-
348
-A session's life cycle is accessed via four methods, `begin`, `update`, `cancel` and `complete`. Different sessions will implement these methods in different ways.
349
-
350
-A session begins when constructed.
351
-
352
-```ts
353
-session.begin(
354
-  new Sessions.TranslateSession(
355
-    data,
356
-    tld.screenToWorld(inputs.pointer.origin, data)
357
-  )
358
-)
359
-```
360
-
361
-Next, the session receives updates. Note that we're passing in the `data` draft from an action. The session will make any necessary changes to the draft.
362
-
363
-```ts
364
-session.update<Sessions.TranslateSession>(
365
-  data,
366
-  tld.screenToWorld(payload.point, data),
367
-  payload.shiftKey,
368
-  payload.altKey
369
-)
370
-```
371
-
372
-> Note: To get proper typing in `session.update`, you must provide the generic type of the session you're updating.
373
-
374
-When a session completes, the session calls a method. This way, a user is able to travel back through the undo stack, visit only discrete commands (like deleting a shape) and those commands that marked the end of a session.
375
-
376
-```ts
377
-session.complete(data)
378
-```
379
-
380
-A session may also be cancelled.
381
-
382
-```ts
383
-session.cancel(data)
384
-```
385
-
386
-When cancelled, it is the responsibility of the session to restore the state to exactly how it was when the session began, reversing any changes that were made to the state during the session.
387
-
388
-For this reason, many sessions begin by taking a snapshot of the current draft.
389
-
390
-> Because the draft is a JavaScript Proxy, you must deep clone any parts of the draft that you want to include in a snapshot. (Direct references will fail as the underlying Proxy will have expired.) While the memory size of a snapshot is not usually a concern, this deep-cloning process is thread-blocking, so try to snapshot only the parts of the `data` draft that you need.
46
+   ```bash
47
+   yarn start:www
48
+   ```

正在加载...
取消
保存