Wykres commitów

18 Commity (main)

Autor SHA1 Wiadomość Data
alex f9ed1bf2c9
Force `interface` instead of `type` for better docs (#3815)
Typescript's type aliases (`type X = thing`) can refer to basically
anything, which makes it hard to write an automatic document formatter
for them. Interfaces on the other hand are only object, so they play
much nicer with docs. Currently, object-flavoured type aliases don't
really get expanded at all on our docs site, which means we have a bunch
of docs content that's not shown on the site.

This diff introduces a lint rule that forces `interface X {foo: bar}`s
instead of `type X = {foo: bar}` where possible, as it results in a much
better documentation experience:

Before:
<img width="437" alt="Screenshot 2024-05-22 at 15 24 13"
src="https://github.com/tldraw/tldraw/assets/1489520/32606fd1-6832-4a1e-aa5f-f0534d160c92">

After:
<img width="431" alt="Screenshot 2024-05-22 at 15 33 01"
src="https://github.com/tldraw/tldraw/assets/1489520/4e0d59ee-c38e-4056-b9fd-6a7f15d28f0f">


### Change Type

- [x] `sdk` — Changes the tldraw SDK
- [x] `docs` — Changes to the documentation, examples, or templates.
- [x] `improvement` — Improving existing features
2024-05-22 15:55:49 +00:00
alex ab807afda3
Store-level "operation end" event (#3748)
This adds a store-level "operation end" event which fires at the end of
atomic operations. It includes some other changes too:

- The `SideEffectManager` now lives in & is a property of the store as
`StoreSideEffects`. One benefit to this is that instead of overriding
methods on the store to register side effects (meaning the store can
only ever be used in one place) the store now calls directly into the
side effect manager, which is responsible for dealing with any other
callbacks
- The history manager's "batch complete" event is gone, in favour of
this new event. We were using the batch complete event for only one
thing, calling `onChildrenChange` - which meant it wasn't getting called
for undo/redo events, which aren't part of a batch. `onChildrenChange`
is now called after each atomic store operation affecting children.

I've also added a rough pin example which shows (kinda messily) how you
might use the operation complete handler to traverse a graph of bindings
and resolve constraints between them.

### Change Type

- [x] `sdk` — Changes the tldraw SDK
- [x] `feature` — New feature

### Release Notes

#### Breaking changes
`editor.registerBatchCompleteHandler` has been replaced with
`editor.registerOperationCompleteHandler`
2024-05-14 09:42:41 +00:00
alex 91903c9761
Move arrow helpers from editor to tldraw (#3721)
With the new work on bindings, we no longer need to keep any arrows
stuff hard-coded in `editor`, so let's move it to `tldraw` with the rest
of the shapes.

Couple other changes as part of this:
- We had two different types of `WeakMap` backed cache, but we now only
have one
- There's a new free-standing version of `createComputedCache` that
doesn't need access to the editor/store in order to create the cache.
instead, it returns a `{get(editor, id)}` object and instantiates the
cache on a per-editor basis for each call.
- Fixed a bug in `createSelectedComputedCache` where the selector
derivation would get re-created on every call to `get`

### Change Type

- [x] `sdk` — Changes the tldraw SDK
- [x] `improvement` — Improving existing features

### Release Notes

#### Breaking changes
- `editor.getArrowInfo(shape)` has been replaced with
`getArrowInfo(editor, shape)`
- `editor.getArrowsBoundTo(shape)` has been removed. Instead, use
`editor.getBindingsToShape(shape, 'arrow')` and follow the `fromId` of
each binding to the corresponding arrow shape
- These types have moved from `@tldraw/editor` to `tldraw`:
    - `TLArcInfo`
    - `TLArrowInfo`
    - `TLArrowPoint`
- `WeakMapCache` has been removed
2024-05-09 09:48:01 +00:00
alex da35f2bd75
Bindings (#3326)
First draft of the new bindings API. We'll follow this up with some API
refinements, tests, documentation, and examples.

Bindings are a new record type for establishing relationships between
two shapes so they can update at the same time.

### Change Type

- [x] `sdk` — Changes the tldraw SDK
- [x] `feature` — New feature

### Release Notes

#### Breaking changes
- The `start` and `end` properties on `TLArrowShape` no longer have
`type: point | binding`. Instead, they're always a point, which may be
out of date if a binding exists. To check for & retrieve arrow bindings,
use `getArrowBindings(editor, shape)` instead.
- `getArrowTerminalsInArrowSpace` must be passed a `TLArrowBindings` as
a third argument: `getArrowTerminalsInArrowSpace(editor, shape,
getArrowBindings(editor, shape))`
- The following types have been renamed:
    - `ShapeProps` -> `RecordProps`
    - `ShapePropsType` -> `RecordPropsType`
    - `TLShapePropsMigrations` -> `TLPropsMigrations`
    - `SchemaShapeInfo` -> `SchemaPropsInfo`

---------

Co-authored-by: David Sheldrick <d.j.sheldrick@gmail.com>
2024-05-08 12:37:31 +00:00
alex 8151e6f586
Automatic undo/redo (#3364)
Our undo-redo system before this diff is based on commands. A command
is:
- A function that produces some data required to perform and undo a
change
- A function that actually performs the change, based on the data
- Another function that undoes the change, based on the data
- Optionally, a function to _redo_ the change, although in practice we
never use this

Each command that gets run is added to the undo/redo stack unless it
says it shouldn't be.

This diff replaces this system of commands with a new one where all
changes to the store are automatically recorded in the undo/redo stack.
You can imagine the new history manager like a tape recorder - it
automatically records everything that happens to the store in a special
diff, unless you "pause" the recording and ask it not to. Undo and redo
rewind/fast-forward the tape to certain marks.

As the command concept is gone, the things that were commands are now
just functions that manipulate the store.

One other change here is that the store's after-phase callbacks (and the
after-phase side-effects as a result) are now batched up and called at
the end of certain key operations. For example, `applyDiff` would
previously call all the `afterCreate` callbacks before making any
removals from the diff. Now, it (and anything else that uses
`store.atomic(fn)` will defer firing any after callbacks until the end
of an operation. before callbacks are still called part-way through
operations.

## Design options
Automatic recording is a fairly large big semantic change, particularly
to the standalone `store.put`/`store.remove` etc. commands. We could
instead make not-recording the default, and make recording opt-in
instead. However, I think auto-record-by-default is the right choice for
a few reasons:

1. Switching to a recording-based vs command-based undo-redo model is
fundamentally a big semantic change. In the past, `store.put` etc. were
always ignored. Now, regardless of whether we choose record-by-default
or ignore-by-default, the behaviour of `store.put` is _context_
dependant.
2. Switching to ignore-by-default means that either our commands don't
record undo/redo history any more (unless wrapped in
`editor.history.record`, a far larger semantic change) or they have to
always-record/all accept a history options bag. If we choose
always-record, we can't use commands within `history.ignore` as they'll
start recording again. If we choose the history options bag, we have to
accept those options in 10s of methods - basically the entire `Editor`
api surface.

Overall, given that some breaking semantic change here is unavoidable, I
think that record-by-default hits the right balance of tradeoffs. I
think it's a better API going forward, whilst also not being too
disruptive as the APIs it affects are very "deep" ones that we don't
typically encourage people to use.



### Change Type

- [x] `sdk` — Changes the tldraw SDK
- [x] `improvement` — Improving existing features
- [x] `galaxy brain` — Architectural changes

### Release Note
#### Breaking changes
##### 1. History Options
Previously, some (not all!) commands accepted a history options object
with `squashing`, `ephemeral`, and `preserveRedoStack` flags. Squashing
enabled/disabled a memory optimisation (storing individual commands vs
squashing them together). Ephemeral stopped a command from affecting the
undo/redo stack at all. Preserve redo stack stopped commands from wiping
the redo stack. These flags were never available consistently - some
commands had them and others didn't.

In this version, most of these flags have been removed. `squashing` is
gone entirely (everything squashes & does so much faster than before).
There were a couple of commands that had a special default - for
example, `updateInstanceState` used to default to being `ephemeral`.
Those maintain the defaults, but the options look a little different now
- `{ephemeral: true}` is now `{history: 'ignore'}` and
`{preserveRedoStack: true}` is now `{history:
'record-preserveRedoStack'}`.

If you were previously using these options in places where they've now
been removed, you can use wrap them with `editor.history.ignore(fn)` or
`editor.history.batch(fn, {history: 'record-preserveRedoStack'})`. For
example,
```ts
editor.nudgeShapes(..., { ephemeral: true })
```
can now be written as
```ts
editor.history.ignore(() => {
    editor.nudgeShapes(...)
})
```

##### 2. Automatic recording
Previously, only commands (e.g. `editor.updateShapes` and things that
use it) were added to the undo/redo stack. Everything else (e.g.
`editor.store.put`) wasn't. Now, _everything_ that touches the store is
recorded in the undo/redo stack (unless it's part of
`mergeRemoteChanges`). You can use `editor.history.ignore(fn)` as above
if you want to make other changes to the store that aren't recorded -
this is short for `editor.history.batch(fn, {history: 'ignore'})`

When upgrading to this version of tldraw, you shouldn't need to change
anything unless you're using `store.put`, `store.remove`, or
`store.applyDiff` outside of `store.mergeRemoteChanges`. If you are, you
can preserve the functionality of those not being recorded by wrapping
them either in `mergeRemoteChanges` (if they're multiplayer-related) or
`history.ignore` as appropriate.

##### 3. Side effects
Before this diff, any changes in side-effects weren't captured by the
undo-redo stack. This was actually the motivation for this change in the
first place! But it's a pretty big change, and if you're using side
effects we recommend you double-check how they interact with undo/redo
before/after this change. To get the old behaviour back, wrap your side
effects in `editor.history.ignore`.

##### 4. Mark options
Previously, `editor.mark(id)` accepted two additional boolean
parameters: `onUndo` and `onRedo`. If these were set to false, then when
undoing or redoing we'd skip over that mark and keep going until we
found one with those values set to true. We've removed those options -
if you're using them, let us know and we'll figure out an alternative!
2024-04-24 18:26:10 +00:00
David Sheldrick 4f70a4f4e8
New migrations again (#3220)
Describe what your pull request does. If appropriate, add GIFs or images
showing the before and after.

### Change Type

- [x] `sdk` — Changes the tldraw SDK
- [x] `galaxy brain` — Architectural changes



### Test Plan

1. Add a step-by-step description of how to test your PR here.
2.

- [ ] Unit Tests
- [ ] End to end tests

### Release Notes

#### BREAKING CHANGES

- The `Migrations` type is now called `LegacyMigrations`.
- The serialized schema format (e.g. returned by
`StoreSchema.serialize()` and `Store.getSnapshot()`) has changed. You
don't need to do anything about it unless you were reading data directly
from the schema for some reason. In which case it'd be best to avoid
that in the future! We have no plans to change the schema format again
(this time was traumatic enough) but you never know.
- `compareRecordVersions` and the `RecordVersion` type have both
disappeared. There is no replacement. These were public by mistake
anyway, so hopefully nobody had been using it.
- `compareSchemas` is a bit less useful now. Our migrations system has
become a little fuzzy to allow for simpler UX when adding/removing
custom extensions and 3rd party dependencies, and as a result we can no
longer compare serialized schemas in any rigorous manner. You can rely
on this function to return `0` if the schemas are the same. Otherwise it
will return `-1` if the schema on the right _seems_ to be newer than the
schema on the left, but it cannot guarantee that in situations where
migration sequences have been removed over time (e.g. if you remove one
of the builtin tldraw shapes).

Generally speaking, the best way to check schema compatibility now is to
call `store.schema.getMigrationsSince(persistedSchema)`. This will throw
an error if there is no upgrade path from the `persistedSchema` to the
current version.

- `defineMigrations` has been deprecated and will be removed in a future
release. For upgrade instructions see
https://tldraw.dev/docs/persistence#Updating-legacy-shape-migrations-defineMigrations

- `migrate` has been removed. Nobody should have been using this but if
you were you'll need to find an alternative. For migrating tldraw data,
you should stick to using `schema.migrateStoreSnapshot` and, if you are
building a nuanced sync engine that supports some amount of backwards
compatibility, also feel free to use `schema.migratePersistedRecord`.
- the `Migration` type has changed. If you need the old one for some
reason it has been renamed to `LegacyMigration`. It will be removed in a
future release.
- the `Migrations` type has been renamed to `LegacyMigrations` and will
be removed in a future release.
- the `SerializedSchema` type has been augmented. If you need the old
version specifically you can use `SerializedSchemaV1`

---------

Co-authored-by: Steve Ruiz <steveruizok@gmail.com>
2024-04-15 12:53:42 +00:00
David Sheldrick 4a2040f92c
Faster validations + record reference stability at the same time (#2848)
This PR adds a validation mode whereby previous known-to-be-valid values
can be used to speed up the validation process itself. At the same time
it enables us to do fine-grained equality checking on records much more
quickly than by using something like lodash isEqual, and using that we
can prevent triggering effects for record updates that don't actually
alter any values in the store.

Here's some preliminary perf testing of average time spent in
`store.put()` during some common interactions

| task | before (ms) | after (ms) |
| ---- | ---- | ---- |
| drawing lines | 0.0403 | 0.0214 |
| drawing boxes | 0.0408 | 0.0348 |
| translating lines | 0.0352 | 0.0042 |
| translating boxes | 0.0051 | 0.0032 |
| rotating lines | 0.0312 | 0.0065 |
| rotating boxes | 0.0053 | 0.0035 |
| brush selecting boxes | 0.0200 | 0.0232 |
| traversal with shapes | 0.0130 | 0.0108 |
| traversal without shapes | 0.0201 | 0.0173 |

**traversal** means moving the camera and pointer around the canvas

#### Discussion

At the scale of hundredths of a millisecond these .put operations are so
fast that even if they became literally instantaneous the change would
not be human perceptible. That said, there is an overall marked
improvement here. Especially for dealing with draw shapes.

These figures are also mostly in line with expectations, aside from a
couple of things:

- I don't understand why the `brush selecting boxes` task got slower
after the change.
- I don't understand why the `traversal` tasks are slower than the
`translating boxes` task, both before and after. I would expect that
.putting shape records would be much slower than .putting pointer/camera
records (since the latter have fewer and simpler properties)

### Change Type

- [x] `patch` — Bug fix

### Test Plan

1. Add a step-by-step description of how to test your PR here.
2.

- [ ] Unit Tests
- [ ] End to end tests

### Release Notes

- Add a brief release note for your PR here.
2024-02-20 12:35:25 +00:00
David Sheldrick 386a2396d1
Fix shape drag perf (#1932)
This prevents geometry from being recalculated when dragging shapes
around. It uses an equality check on the shape props to opt out of
recalculations. This still allows bounds to be calculated based on other
reactive values, so if folks really want to use x,y values or opacity or
whatever, they can call editor.getShape(id) when making their
calculation.

### Change Type

- [x] `patch` — Bug fix
- [ ] `minor` — New feature
- [ ] `major` — Breaking change
- [ ] `dependencies` — Changes to package dependencies[^1]
- [ ] `documentation` — Changes to the documentation only[^2]
- [ ] `tests` — Changes to any test code only[^2]
- [ ] `internal` — Any other changes that don't affect the published
package[^2]
- [ ] I don't know

[^1]: publishes a `patch` release, for devDependencies use `internal`
[^2]: will not publish a new version


### Release Notes

- Fixes a perf regression for dragging shapes around
2023-09-19 15:29:13 +00:00
Steve Ruiz 48a1bb4d88
Migrate snapshot (#1843)
Add `Store.migrateSnapshot`, another surface API alongside getSnapshot
and loadSnapshot.

### Change Type

- [x] `minor` — New feature

### Release Notes

- [editor] add `Store.migrateSnapshot`
2023-09-08 17:04:53 +00:00
Steve Ruiz 507bba82fd
SideEffectManager (#1785)
This PR extracts the side effect manager from #1778.

### Change Type

- [x] `major` — Breaking change
2023-08-02 11:05:14 +00:00
Steve Ruiz 79fae186e4
Revert "Editor commands API / effects" (#1783)
Reverts tldraw/tldraw#1778.

Fuzz testing picked up errors related to deleting pages and undo/redo
which may doom this PR.

### Change Type

- [x] `major` — Breaking change
2023-08-01 17:03:31 +00:00
Steve Ruiz e17074a8b3
Editor commands API / effects (#1778)
This PR shrinks the commands API surface and adds a manager
(`CleanupManager`) for side effects.

### Change Type

- [x] `major` — Breaking change

### Test Plan

Use the app! Especially undo and redo. Our tests are passing but I've
found more cases where our coverage fails to catch issues.

### Release Notes

- tbd
2023-08-01 13:21:14 +00:00
Steve Ruiz 2d5b2bdc94
[tweak] migrate store snapshot arguments (#1659)
This PR updates the `migrateStoreSnapshot` method in @tldraw/store

### Change Type

- [x] `major` — Breaking change

### Test Plan

- [x] Unit Tests
2023-06-27 13:59:07 +00:00
Steve Ruiz ed8d4d9e05
[improvement] store snapshot types (#1657)
This PR improves the types for the Store.

- renames `StoreSnapshot` to `SerializedStore`, which is the return type
of `Store.serialize`
- creates `StoreSnapshot` as a type for the return type of
`Store.getSnapshot` / the argument type for `Store.loadSnapshot`
- creates `TLStoreSnapshot` as the type used for the `TLStore`.

This came out of a session I had with a user. This should prevent
needing to import types from `@tldraw/store` directly.

### Change Type

- [x] `major` — Breaking change

### Test Plan

- [x] Unit Tests

### Release Notes

- [dev] Rename `StoreSnapshot` to `SerializedStore`
- [dev] Create new `StoreSnapshot` as type related to
`getSnapshot`/`loadSnapshot`
2023-06-27 12:25:55 +00:00
Steve Ruiz 5cb08711c1
Incorporate signia as @tldraw/state (#1620)
It tried to get out but we're dragging it back in. 

This PR brings [signia](https://github.com/tldraw/signia) back into
tldraw as @tldraw/state.

### Change Type

- [x] major

---------

Co-authored-by: David Sheldrick <d.j.sheldrick@gmail.com>
2023-06-20 13:31:26 +00:00
David Sheldrick f15a8797f0
Independent instance state persistence (#1493)
This PR 

- Removes UserDocumentRecordType
  - moving isSnapMode to user preferences
  - moving isGridMode and isPenMode to InstanceRecordType
  - deleting the other properties which are no longer needed.
 
- Creates a separate pipeline for persisting instance state.
  
Previously the instance state records were stored alongside the document
state records, and in order to load the state for a particular instance
(in our case, a particular tab) you needed to pass the 'instanceId'
prop. This prop ended up totally pervading the public API and people ran
into all kinds of issues with it, e.g. using the same instance id in
multiple editor instances.

There was also an issue whereby it was hard for us to clean up old
instance state so the idb table ended up bloating over time.
  
This PR makes it so that rather than passing an instanceId, you load the
instance state yourself while creating the store. It provides tools to
make that easy.

- Undoes the assumption that we might have more than one instance's
state in the store.

- Like `document`, `instance` now has a singleton id
`instance:instance`.
- Page state ids and camera ids are no longer random, but rather derive
from the page they belong to. This is like having a foreign primary key
in SQL databases. It's something i'd love to support fully as part of
the RecordType/Store api.

Tests to do

- [x] Test Migrations
- [x] Test Store.listen filtering
- [x] Make type sets in Store public and readonly
- [x] Test RecordType.createId
- [x] Test Instance state snapshot loading/exporting
- [x] Manual test File I/O
- [x] Manual test Vscode extension with multiple tabs
- [x] Audit usages of store.query
- [x] Audit usages of changed types: InstanceRecordType, 'instance',
InstancePageStateRecordType, 'instance_page_state', 'user_document',
'camera', CameraRecordType, InstancePresenceRecordType,
'instance_presence'
- [x] Test user preferences
- [x] Manual test isSnapMode and isGridMode and isPenMode
- [ ] Test indexedDb functions
- [x] Add instanceId stuff back


### Change Type

- [x] `major` — Breaking Change


### Test Plan

1. Add a step-by-step description of how to test your PR here.
2.

- [ ] Unit Tests
- [ ] Webdriver tests

### Release Notes

- Add a brief release note for your PR here.
2023-06-05 14:11:07 +00:00
Steve Ruiz 4b6383ed90
tlschema cleanup (#1509)
This PR cleans up the file names and imports for @tldraw/tlschema.

It also:
- renames some erroneously named validators / migrators (e.g.
`pageTypeValidator` -> `pageValidator`)
- removes the duplicated `languages.ts` and makes `tlschema` the source
of truth for languages
- renames ID to RecordId

### Change Type

- [x] `major` — Breaking Change

### Release Notes

- [editor] Remove `app.createShapeId`
- [tlschema] Cleans up exports
2023-06-03 20:46:53 +00:00
Steve Ruiz c1b84bf246
Rename tlstore to store (#1507)
This PR renames the `@tldraw/tlstore` package to `@tldraw/store`, mainly
to avoid confusion between `TLStore`. Will be doing the same with other
packages.

### Change Type

- [x] `major` — Breaking Change

### Release Notes

- Replace @tldraw/tlstore with @tldraw/store
2023-06-03 08:59:04 +00:00