@tldraw/store 5.5.2 → 5.6.0-canary.0091c91994d6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-cjs/index.d.ts +7 -0
- package/dist-cjs/index.js +1 -1
- package/dist-cjs/lib/AtomMap.js +2 -2
- package/dist-cjs/lib/AtomMap.js.map +2 -2
- package/dist-cjs/lib/Store.js +87 -32
- package/dist-cjs/lib/Store.js.map +2 -2
- package/dist-cjs/lib/StoreQueries.js +20 -19
- package/dist-cjs/lib/StoreQueries.js.map +2 -2
- package/dist-cjs/lib/StoreSchema.js +33 -14
- package/dist-cjs/lib/StoreSchema.js.map +2 -2
- package/dist-esm/index.d.mts +7 -0
- package/dist-esm/index.mjs +1 -1
- package/dist-esm/lib/AtomMap.mjs +2 -2
- package/dist-esm/lib/AtomMap.mjs.map +2 -2
- package/dist-esm/lib/Store.mjs +95 -34
- package/dist-esm/lib/Store.mjs.map +2 -2
- package/dist-esm/lib/StoreQueries.mjs +21 -20
- package/dist-esm/lib/StoreQueries.mjs.map +2 -2
- package/dist-esm/lib/StoreSchema.mjs +33 -14
- package/dist-esm/lib/StoreSchema.mjs.map +2 -2
- package/package.json +13 -15
- package/src/lib/AtomMap.test.ts +7 -0
- package/src/lib/AtomMap.ts +2 -2
- package/src/lib/Store.test.ts +148 -0
- package/src/lib/Store.ts +129 -43
- package/src/lib/StoreListeners.test.ts +152 -1
- package/src/lib/StoreQueries.ts +24 -21
- package/src/lib/StoreSchema.test.ts +78 -0
- package/src/lib/StoreSchema.ts +41 -13
package/src/lib/AtomMap.ts
CHANGED
|
@@ -275,11 +275,11 @@ export class AtomMap<K, V> implements Map<K, V> {
|
|
|
275
275
|
deleteMany(keys: Iterable<K>): [K, V][] {
|
|
276
276
|
return transact(() => {
|
|
277
277
|
const deleted: [K, V][] = []
|
|
278
|
-
const newAtoms = this.atoms.
|
|
278
|
+
const newAtoms = this.atoms.__unsafe__getWithoutCapture().withMutations((atoms) => {
|
|
279
279
|
for (const key of keys) {
|
|
280
280
|
const valueAtom = atoms.get(key)
|
|
281
281
|
if (!valueAtom) continue
|
|
282
|
-
const oldValue = valueAtom.
|
|
282
|
+
const oldValue = valueAtom.__unsafe__getWithoutCapture()
|
|
283
283
|
assert(oldValue !== UNINITIALIZED)
|
|
284
284
|
|
|
285
285
|
deleted.push([key, oldValue])
|
package/src/lib/Store.test.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { react } from '@tldraw/state'
|
|
|
2
2
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
3
3
|
import { BaseRecord, RecordId } from './BaseRecord'
|
|
4
4
|
import { createMigrationSequence } from './migrate'
|
|
5
|
+
import { RecordsDiff } from './RecordsDiff'
|
|
5
6
|
import { createRecordType } from './RecordType'
|
|
6
7
|
import { createComputedCache, Store } from './Store'
|
|
7
8
|
import { StoreSchema } from './StoreSchema'
|
|
@@ -228,6 +229,34 @@ describe('Store: reading and writing (S)', () => {
|
|
|
228
229
|
expect(unsafeOnly).toEqual(['Jimmy Tolks'])
|
|
229
230
|
stop2()
|
|
230
231
|
})
|
|
232
|
+
|
|
233
|
+
it('[S11] a reaction that puts records does not re-run for unrelated store changes', () => {
|
|
234
|
+
const a = Author.create({ name: 'A' })
|
|
235
|
+
const b = Author.create({ name: 'B' })
|
|
236
|
+
store.put([a, b])
|
|
237
|
+
let runs = 0
|
|
238
|
+
const stop = react('writer', () => {
|
|
239
|
+
runs++
|
|
240
|
+
store.put([{ ...a, name: 'A' + runs }])
|
|
241
|
+
})
|
|
242
|
+
store.put([{ ...b, name: 'B2' }])
|
|
243
|
+
expect(runs).toBe(1)
|
|
244
|
+
stop()
|
|
245
|
+
})
|
|
246
|
+
|
|
247
|
+
it('[S11] a reaction that removes records does not re-run for unrelated store changes', () => {
|
|
248
|
+
const a = Author.create({ name: 'A' })
|
|
249
|
+
const b = Author.create({ name: 'B' })
|
|
250
|
+
store.put([a, b])
|
|
251
|
+
let runs = 0
|
|
252
|
+
const stop = react('remover', () => {
|
|
253
|
+
runs++
|
|
254
|
+
store.remove([a.id])
|
|
255
|
+
})
|
|
256
|
+
store.put([{ ...b, name: 'B2' }])
|
|
257
|
+
expect(runs).toBe(1)
|
|
258
|
+
stop()
|
|
259
|
+
})
|
|
231
260
|
})
|
|
232
261
|
|
|
233
262
|
describe('Store: serialization and snapshots (S)', () => {
|
|
@@ -765,3 +794,122 @@ describe('integrity (IC)', () => {
|
|
|
765
794
|
store.dispose()
|
|
766
795
|
})
|
|
767
796
|
})
|
|
797
|
+
|
|
798
|
+
describe('Store: repeated ids in one put (S)', () => {
|
|
799
|
+
let store: Store<LibraryType>
|
|
800
|
+
beforeEach(() => {
|
|
801
|
+
store = new Store({ props: {}, schema: schema() })
|
|
802
|
+
})
|
|
803
|
+
afterEach(() => {
|
|
804
|
+
store.dispose()
|
|
805
|
+
})
|
|
806
|
+
|
|
807
|
+
it('[S12] repeated ids in one put record one update whose from is the pre-put record', () => {
|
|
808
|
+
const author = Author.create({ name: 'Start' })
|
|
809
|
+
store.put([author])
|
|
810
|
+
const entries: RecordsDiff<LibraryType>[] = []
|
|
811
|
+
store.addHistoryInterceptor((entry) => entries.push(entry.changes))
|
|
812
|
+
|
|
813
|
+
store.put([
|
|
814
|
+
{ ...author, name: 'Middle' },
|
|
815
|
+
{ ...author, name: 'End' },
|
|
816
|
+
])
|
|
817
|
+
|
|
818
|
+
expect(entries).toHaveLength(1)
|
|
819
|
+
expect(entries[0].updated).toEqual({
|
|
820
|
+
[author.id]: [author, { ...author, name: 'End' }],
|
|
821
|
+
})
|
|
822
|
+
})
|
|
823
|
+
|
|
824
|
+
it('[S12] a record created then updated in one put is recorded as a single addition', () => {
|
|
825
|
+
const author = Author.create({ name: 'Start' })
|
|
826
|
+
const entries: RecordsDiff<LibraryType>[] = []
|
|
827
|
+
store.addHistoryInterceptor((entry) => entries.push(entry.changes))
|
|
828
|
+
|
|
829
|
+
store.put([author, { ...author, name: 'End' }])
|
|
830
|
+
|
|
831
|
+
expect(entries).toHaveLength(1)
|
|
832
|
+
expect(entries[0]).toEqual({
|
|
833
|
+
added: { [author.id]: { ...author, name: 'End' } },
|
|
834
|
+
updated: {},
|
|
835
|
+
removed: {},
|
|
836
|
+
})
|
|
837
|
+
})
|
|
838
|
+
|
|
839
|
+
it('[S12] a record changed and changed back within one put records nothing', () => {
|
|
840
|
+
const author = Author.create({ name: 'Start' })
|
|
841
|
+
store.put([author])
|
|
842
|
+
const stored = store.get(author.id)!
|
|
843
|
+
const entries: RecordsDiff<LibraryType>[] = []
|
|
844
|
+
store.addHistoryInterceptor((entry) => entries.push(entry.changes))
|
|
845
|
+
const afterChange = vi.fn()
|
|
846
|
+
store.sideEffects.registerAfterChangeHandler('author', afterChange)
|
|
847
|
+
|
|
848
|
+
store.put([{ ...stored, name: 'Middle' }, stored])
|
|
849
|
+
|
|
850
|
+
expect(entries).toEqual([])
|
|
851
|
+
expect(afterChange).not.toHaveBeenCalled()
|
|
852
|
+
expect(store.get(author.id)).toBe(stored)
|
|
853
|
+
})
|
|
854
|
+
})
|
|
855
|
+
|
|
856
|
+
describe('computed caches after deletion (CC)', () => {
|
|
857
|
+
let store: Store<LibraryType>
|
|
858
|
+
beforeEach(() => {
|
|
859
|
+
store = new Store({ props: {}, schema: schema() })
|
|
860
|
+
})
|
|
861
|
+
afterEach(() => {
|
|
862
|
+
store.dispose()
|
|
863
|
+
})
|
|
864
|
+
|
|
865
|
+
it('[CC6] derive and areRecordsEqual are never called with a deleted record', () => {
|
|
866
|
+
const author = Author.create({ name: 'A' })
|
|
867
|
+
store.put([author])
|
|
868
|
+
const deriveArgs: unknown[] = []
|
|
869
|
+
const equalArgs: unknown[] = []
|
|
870
|
+
const cache = store.createComputedCache(
|
|
871
|
+
'names',
|
|
872
|
+
(record: Author) => {
|
|
873
|
+
deriveArgs.push(record)
|
|
874
|
+
return record.name
|
|
875
|
+
},
|
|
876
|
+
{
|
|
877
|
+
areRecordsEqual: (a, b) => {
|
|
878
|
+
equalArgs.push(a, b)
|
|
879
|
+
return a.name === b.name
|
|
880
|
+
},
|
|
881
|
+
}
|
|
882
|
+
)
|
|
883
|
+
const seen: (string | undefined)[] = []
|
|
884
|
+
react('reader', () => seen.push(cache.get(author.id)))
|
|
885
|
+
expect(seen).toEqual(['A'])
|
|
886
|
+
|
|
887
|
+
store.remove([author.id])
|
|
888
|
+
expect(seen).toEqual(['A', undefined])
|
|
889
|
+
|
|
890
|
+
// and the record can come back with the same id
|
|
891
|
+
store.put([{ ...author, name: 'B' }])
|
|
892
|
+
expect(seen).toEqual(['A', undefined, 'B'])
|
|
893
|
+
|
|
894
|
+
for (const arg of [...deriveArgs, ...equalArgs]) {
|
|
895
|
+
expect(typeof arg).toBe('object')
|
|
896
|
+
}
|
|
897
|
+
})
|
|
898
|
+
|
|
899
|
+
it('[CC6] a reader sees a re-created record even when derive gave the same value before deletion', () => {
|
|
900
|
+
const author = Author.create({ name: 'Real name' })
|
|
901
|
+
store.put([author])
|
|
902
|
+
// undefined for the live record, and must not throw on the deleted state, or the error
|
|
903
|
+
// itself counts as a change and hides the bug
|
|
904
|
+
const cache = store.createComputedCache('pen-names', (record: Author) =>
|
|
905
|
+
record.isPseudonym ? record.name : undefined
|
|
906
|
+
)
|
|
907
|
+
const seen: (string | undefined)[] = []
|
|
908
|
+
react('reader', () => seen.push(cache.get(author.id)))
|
|
909
|
+
expect(seen).toEqual([undefined])
|
|
910
|
+
|
|
911
|
+
store.remove([author.id])
|
|
912
|
+
store.put([{ ...author, name: 'Pen name', isPseudonym: true }])
|
|
913
|
+
expect(seen.at(-1)).toBe('Pen name')
|
|
914
|
+
})
|
|
915
|
+
})
|
package/src/lib/Store.ts
CHANGED
|
@@ -1,4 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
Atom,
|
|
3
|
+
Reactor,
|
|
4
|
+
Signal,
|
|
5
|
+
atom,
|
|
6
|
+
computed,
|
|
7
|
+
isUninitialized,
|
|
8
|
+
reactor,
|
|
9
|
+
transact,
|
|
10
|
+
} from '@tldraw/state'
|
|
2
11
|
import {
|
|
3
12
|
WeakCache,
|
|
4
13
|
assert,
|
|
@@ -14,12 +23,16 @@ import {
|
|
|
14
23
|
import { AtomMap } from './AtomMap'
|
|
15
24
|
import { IdOf, RecordId, UnknownRecord } from './BaseRecord'
|
|
16
25
|
import { devFreeze } from './devFreeze'
|
|
17
|
-
import { isRecordsDiffEmpty, RecordsDiff, squashRecordDiffs } from './RecordsDiff'
|
|
26
|
+
import { hasAnyKey, isRecordsDiffEmpty, RecordsDiff, squashRecordDiffs } from './RecordsDiff'
|
|
18
27
|
import { RecordScope } from './RecordType'
|
|
19
28
|
import { StoreQueries } from './StoreQueries'
|
|
20
29
|
import { SerializedSchema, StoreSchema } from './StoreSchema'
|
|
21
30
|
import { StoreSideEffects } from './StoreSideEffects'
|
|
22
31
|
|
|
32
|
+
// The value of a cached computed whose record has been deleted (see `createComputedCache`). It never
|
|
33
|
+
// reaches callers: `get` resolves the record's atom first, and there is none for a deleted id.
|
|
34
|
+
const DELETED_RECORD = Symbol('deleted record')
|
|
35
|
+
|
|
23
36
|
/**
|
|
24
37
|
* Extracts the record type from a record ID type.
|
|
25
38
|
*
|
|
@@ -513,11 +526,16 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
513
526
|
this.scopedTypes = scopedTypes
|
|
514
527
|
}
|
|
515
528
|
|
|
529
|
+
private isFlushingHistory = false
|
|
530
|
+
|
|
516
531
|
public _flushHistory() {
|
|
517
532
|
// If we have accumulated history, flush it and update listeners
|
|
518
|
-
|
|
519
|
-
|
|
533
|
+
const version = this.history.__unsafe__getWithoutCapture()
|
|
534
|
+
const entries = this.historyAccumulator.flush(version)
|
|
535
|
+
if (entries.length > 0) {
|
|
520
536
|
const errors: unknown[] = []
|
|
537
|
+
const wasFlushingHistory = this.isFlushingHistory
|
|
538
|
+
this.isFlushingHistory = true
|
|
521
539
|
for (const { changes, source } of entries) {
|
|
522
540
|
// Filtered diffs are computed at most once per scope per entry, and shared by every
|
|
523
541
|
// listener watching that scope.
|
|
@@ -544,6 +562,7 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
544
562
|
}
|
|
545
563
|
}
|
|
546
564
|
}
|
|
565
|
+
this.isFlushingHistory = wasFlushingHistory
|
|
547
566
|
if (errors.length > 0) throw errors[0]
|
|
548
567
|
}
|
|
549
568
|
}
|
|
@@ -582,14 +601,22 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
582
601
|
* @param changes - The changes to add to the history.
|
|
583
602
|
*/
|
|
584
603
|
private updateHistory(changes: RecordsDiff<R>): void {
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
604
|
+
// Don't capture: a reaction that writes to the store must not become a dependent of the
|
|
605
|
+
// history atom, or every other store change would re-run it (and it could loop forever).
|
|
606
|
+
const version = this.history.__unsafe__getWithoutCapture() + 1
|
|
607
|
+
// Set the atom before recording the entry: interceptors run inside `add`, and a flush they
|
|
608
|
+
// trigger (e.g. via `listen`) would otherwise discard the entry as not yet committed.
|
|
609
|
+
this.history.set(version, changes)
|
|
610
|
+
this.historyAccumulator.add(
|
|
611
|
+
{
|
|
612
|
+
changes,
|
|
613
|
+
source: this.isMergingRemoteChanges ? 'remote' : 'user',
|
|
614
|
+
},
|
|
615
|
+
version
|
|
616
|
+
)
|
|
589
617
|
if (this.listeners.size === 0) {
|
|
590
618
|
this.historyAccumulator.clear()
|
|
591
619
|
}
|
|
592
|
-
this.history.set(this.history.get() + 1, changes)
|
|
593
620
|
}
|
|
594
621
|
|
|
595
622
|
validate(phase: 'initialize' | 'createRecord' | 'updateRecord' | 'tests') {
|
|
@@ -622,12 +649,6 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
622
649
|
// Iterate through all records, creating, updating or removing as needed
|
|
623
650
|
let record: R
|
|
624
651
|
|
|
625
|
-
// There's a chance that, despite having records, all of the values are
|
|
626
|
-
// identical to what they were before; and so we'd end up with an "empty"
|
|
627
|
-
// history entry. Let's keep track of whether we've actually made any
|
|
628
|
-
// changes (e.g. additions, deletions, or updates that produce a new value).
|
|
629
|
-
let didChange = false
|
|
630
|
-
|
|
631
652
|
const source = this.isMergingRemoteChanges ? 'remote' : 'user'
|
|
632
653
|
|
|
633
654
|
for (let i = 0, n = records.length; i < n; i++) {
|
|
@@ -652,14 +673,23 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
652
673
|
record = devFreeze(validated)
|
|
653
674
|
this.records.set(record.id, record)
|
|
654
675
|
|
|
655
|
-
|
|
656
|
-
|
|
676
|
+
if (additions[record.id]) {
|
|
677
|
+
// the same record was created earlier in this call: fold the update into it
|
|
678
|
+
additions[record.id] = record
|
|
679
|
+
} else {
|
|
680
|
+
// an earlier update to the same record in this call owns the `from`
|
|
681
|
+
const from = updates[record.id]?.[0] ?? initialValue
|
|
682
|
+
if (from === record) {
|
|
683
|
+
// back to where it started within this call: nothing to record
|
|
684
|
+
delete updates[record.id]
|
|
685
|
+
} else {
|
|
686
|
+
updates[record.id] = [from, record]
|
|
687
|
+
}
|
|
688
|
+
}
|
|
657
689
|
this.addDiffForAfterEvent(initialValue, record)
|
|
658
690
|
} else {
|
|
659
691
|
record = this.sideEffects.handleBeforeCreate(record, source)
|
|
660
692
|
|
|
661
|
-
didChange = true
|
|
662
|
-
|
|
663
693
|
// If we don't have an atom, create one.
|
|
664
694
|
|
|
665
695
|
// Validate the record
|
|
@@ -681,8 +711,9 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
681
711
|
}
|
|
682
712
|
}
|
|
683
713
|
|
|
684
|
-
//
|
|
685
|
-
|
|
714
|
+
// Validation may have left every record identical to before, in which case there is no
|
|
715
|
+
// change-set to record.
|
|
716
|
+
if (!hasAnyKey(additions) && !hasAnyKey(updates)) return
|
|
686
717
|
this.updateHistory({
|
|
687
718
|
added: additions,
|
|
688
719
|
updated: updates,
|
|
@@ -1008,6 +1039,18 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
1008
1039
|
this.listeners.add(listener)
|
|
1009
1040
|
|
|
1010
1041
|
return () => {
|
|
1042
|
+
// Flush so this listener's history ends at exactly now, but not from inside a flush:
|
|
1043
|
+
// the other listeners would then receive changes made during that flush before the
|
|
1044
|
+
// entry they are still being handed.
|
|
1045
|
+
if (!this.isFlushingHistory) {
|
|
1046
|
+
try {
|
|
1047
|
+
this._flushHistory()
|
|
1048
|
+
} catch (error) {
|
|
1049
|
+
// Removers run in teardown loops (Editor.dispose, TLSyncClient.close); throwing here
|
|
1050
|
+
// would skip the cleanups that follow.
|
|
1051
|
+
console.error(error)
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1011
1054
|
this.listeners.delete(listener)
|
|
1012
1055
|
|
|
1013
1056
|
if (this.listeners.size === 0) {
|
|
@@ -1054,11 +1097,22 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
1054
1097
|
* Run `fn` and return a {@link RecordsDiff} of the changes that occurred as a result.
|
|
1055
1098
|
*/
|
|
1056
1099
|
extractingChanges(fn: () => void): RecordsDiff<R> {
|
|
1057
|
-
const
|
|
1058
|
-
const dispose = this.historyAccumulator.addInterceptor((entry) =>
|
|
1100
|
+
const collected: Array<{ version: number; changes: RecordsDiff<R> }> = []
|
|
1101
|
+
const dispose = this.historyAccumulator.addInterceptor((entry, version) => {
|
|
1102
|
+
// a nested transaction that rolled back inside `fn` leaves entries stamped at or past the
|
|
1103
|
+
// next committed version — see HistoryAccumulator
|
|
1104
|
+
while (collected.length && collected[collected.length - 1].version >= version) {
|
|
1105
|
+
collected.pop()
|
|
1106
|
+
}
|
|
1107
|
+
collected.push({ version, changes: entry.changes })
|
|
1108
|
+
})
|
|
1059
1109
|
try {
|
|
1060
1110
|
transact(fn)
|
|
1061
|
-
|
|
1111
|
+
const current = this.history.__unsafe__getWithoutCapture()
|
|
1112
|
+
while (collected.length && collected[collected.length - 1].version > current) {
|
|
1113
|
+
collected.pop()
|
|
1114
|
+
}
|
|
1115
|
+
return squashRecordDiffs(collected.map((c) => c.changes))
|
|
1062
1116
|
} finally {
|
|
1063
1117
|
dispose()
|
|
1064
1118
|
}
|
|
@@ -1077,7 +1131,7 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
1077
1131
|
for (const [_from, to] of objectMapValues(diff.updated)) {
|
|
1078
1132
|
const type = this.schema.getType(to.typeName)
|
|
1079
1133
|
if (ignoreEphemeralKeys && type.ephemeralKeySet.size) {
|
|
1080
|
-
const existing = this.
|
|
1134
|
+
const existing = this.unsafeGetWithoutCapture(to.id)
|
|
1081
1135
|
if (!existing) {
|
|
1082
1136
|
toPut.push(to)
|
|
1083
1137
|
continue
|
|
@@ -1118,6 +1172,12 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
1118
1172
|
* signal for the underlying record. Return a signal (usually a computed) for the cached value.
|
|
1119
1173
|
* For simple derivations, use {@link Store.createComputedCache}. This function is useful if you
|
|
1120
1174
|
* need more precise control over intermediate values.
|
|
1175
|
+
*
|
|
1176
|
+
* After the record is deleted the record signal holds `UNINITIALIZED` rather than a record, and
|
|
1177
|
+
* a signal that a reader still depends on can be re-derived once more in that state. Guard with
|
|
1178
|
+
* `isUninitialized` and return a value no live record can produce: returning the same value the
|
|
1179
|
+
* record last had (e.g. `undefined`) leaves readers stale if a record with that id comes back.
|
|
1180
|
+
* {@link Store.createComputedCache} handles this for you.
|
|
1121
1181
|
*/
|
|
1122
1182
|
createCache<Result, Record extends R = R>(
|
|
1123
1183
|
create: (id: IdOf<Record>, recordSignal: Signal<R>) => Signal<Result>
|
|
@@ -1145,18 +1205,33 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
1145
1205
|
derive: (record: Record) => Result | undefined,
|
|
1146
1206
|
opts?: CreateComputedCacheOpts<Result, Record>
|
|
1147
1207
|
): ComputedCache<Result, Record> {
|
|
1208
|
+
const areRecordsEqual = opts?.areRecordsEqual
|
|
1209
|
+
const areResultsEqual = opts?.areResultsEqual
|
|
1148
1210
|
return this.createCache((id, record) => {
|
|
1149
|
-
const recordSignal =
|
|
1150
|
-
? computed(`${name}:${id}:isEqual`, () => record.get(), {
|
|
1211
|
+
const recordSignal = areRecordsEqual
|
|
1212
|
+
? computed(`${name}:${id}:isEqual`, () => record.get(), {
|
|
1213
|
+
// a deleted record's atom holds UNINITIALIZED, which user code must not see
|
|
1214
|
+
isEqual: (a, b) =>
|
|
1215
|
+
isUninitialized(a) || isUninitialized(b) ? a === b : areRecordsEqual(a, b),
|
|
1216
|
+
})
|
|
1151
1217
|
: record
|
|
1152
1218
|
|
|
1153
1219
|
return computed<Result | undefined>(
|
|
1154
1220
|
name + ':' + id,
|
|
1155
1221
|
() => {
|
|
1156
|
-
|
|
1222
|
+
// The computed can be re-derived after its record is deleted (e.g. by a reaction
|
|
1223
|
+
// checking whether its parents changed), when the atom holds UNINITIALIZED. Return
|
|
1224
|
+
// DELETED_RECORD rather than undefined: it never equals a real result, so a reader
|
|
1225
|
+
// re-runs, looks the id up again, and so sees the record if it comes back.
|
|
1226
|
+
const value = recordSignal.get()
|
|
1227
|
+
if (isUninitialized(value)) return DELETED_RECORD as any
|
|
1228
|
+
return derive(value as Record)
|
|
1157
1229
|
},
|
|
1158
1230
|
{
|
|
1159
|
-
isEqual:
|
|
1231
|
+
isEqual: areResultsEqual
|
|
1232
|
+
? (a, b) =>
|
|
1233
|
+
a === DELETED_RECORD || b === DELETED_RECORD ? a === b : areResultsEqual(a, b)
|
|
1234
|
+
: undefined,
|
|
1160
1235
|
}
|
|
1161
1236
|
)
|
|
1162
1237
|
})
|
|
@@ -1343,13 +1418,18 @@ function squashHistoryEntries<T extends UnknownRecord>(
|
|
|
1343
1418
|
class HistoryAccumulator<T extends UnknownRecord> {
|
|
1344
1419
|
private _history: HistoryEntry<T>[] = []
|
|
1345
1420
|
|
|
1346
|
-
|
|
1421
|
+
// The `history` atom value each entry was recorded at. A transaction that aborts rolls that atom
|
|
1422
|
+
// back but cannot unwind this array, so an entry stamped at or past the atom's current value
|
|
1423
|
+
// belongs to a rolled-back change-set and must not reach listeners.
|
|
1424
|
+
private _versions: number[] = []
|
|
1425
|
+
|
|
1426
|
+
private _interceptors: Set<(entry: HistoryEntry<T>, version: number) => void> = new Set()
|
|
1347
1427
|
|
|
1348
1428
|
/**
|
|
1349
|
-
* Add an interceptor that will be called for each history entry
|
|
1350
|
-
* Returns a function to remove the interceptor.
|
|
1429
|
+
* Add an interceptor that will be called for each history entry, with the version it was
|
|
1430
|
+
* recorded at (see `add`). Returns a function to remove the interceptor.
|
|
1351
1431
|
*/
|
|
1352
|
-
addInterceptor(fn: (entry: HistoryEntry<T
|
|
1432
|
+
addInterceptor(fn: (entry: HistoryEntry<T>, version: number) => void) {
|
|
1353
1433
|
this._interceptors.add(fn)
|
|
1354
1434
|
return () => {
|
|
1355
1435
|
this._interceptors.delete(fn)
|
|
@@ -1357,13 +1437,15 @@ class HistoryAccumulator<T extends UnknownRecord> {
|
|
|
1357
1437
|
}
|
|
1358
1438
|
|
|
1359
1439
|
/**
|
|
1360
|
-
* Add a history entry
|
|
1440
|
+
* Add a history entry recorded at `version` (the `history` atom value it sets).
|
|
1361
1441
|
* Calls all registered interceptors with the entry.
|
|
1362
1442
|
*/
|
|
1363
|
-
add(entry: HistoryEntry<T
|
|
1443
|
+
add(entry: HistoryEntry<T>, version: number) {
|
|
1444
|
+
this.discardFrom(version)
|
|
1364
1445
|
this._history.push(entry)
|
|
1446
|
+
this._versions.push(version)
|
|
1365
1447
|
for (const interceptor of this._interceptors) {
|
|
1366
|
-
interceptor(entry)
|
|
1448
|
+
interceptor(entry, version)
|
|
1367
1449
|
}
|
|
1368
1450
|
}
|
|
1369
1451
|
|
|
@@ -1371,9 +1453,10 @@ class HistoryAccumulator<T extends UnknownRecord> {
|
|
|
1371
1453
|
* Flush all accumulated history entries, squashing adjacent entries from the same source.
|
|
1372
1454
|
* Clears the internal history buffer.
|
|
1373
1455
|
*/
|
|
1374
|
-
flush() {
|
|
1456
|
+
flush(currentVersion: number) {
|
|
1457
|
+
this.discardFrom(currentVersion + 1)
|
|
1375
1458
|
const history = squashHistoryEntries(this._history)
|
|
1376
|
-
this.
|
|
1459
|
+
this.clear()
|
|
1377
1460
|
return history
|
|
1378
1461
|
}
|
|
1379
1462
|
|
|
@@ -1382,13 +1465,16 @@ class HistoryAccumulator<T extends UnknownRecord> {
|
|
|
1382
1465
|
*/
|
|
1383
1466
|
clear() {
|
|
1384
1467
|
this._history = []
|
|
1468
|
+
this._versions = []
|
|
1385
1469
|
}
|
|
1386
1470
|
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1471
|
+
// Drops the entries recorded at or after `version`. Entries are in ascending version order: the
|
|
1472
|
+
// atom increments by one per entry, and a rollback is followed by exactly this discard.
|
|
1473
|
+
private discardFrom(version: number) {
|
|
1474
|
+
while (this._versions.length && this._versions[this._versions.length - 1] >= version) {
|
|
1475
|
+
this._versions.pop()
|
|
1476
|
+
this._history.pop()
|
|
1477
|
+
}
|
|
1392
1478
|
}
|
|
1393
1479
|
}
|
|
1394
1480
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { react, RESET_VALUE, transact } from '@tldraw/state'
|
|
1
|
+
import { react, RESET_VALUE, transact, transaction } from '@tldraw/state'
|
|
2
2
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
3
3
|
import { BaseRecord, RecordId } from './BaseRecord'
|
|
4
4
|
import { RecordsDiff, reverseRecordsDiff } from './RecordsDiff'
|
|
@@ -461,6 +461,93 @@ describe('applying diffs (H)', () => {
|
|
|
461
461
|
})
|
|
462
462
|
})
|
|
463
463
|
|
|
464
|
+
describe('listeners: rollback (H)', () => {
|
|
465
|
+
it('[H11] listeners never see change-sets from a transaction that rolled back', async () => {
|
|
466
|
+
const listener = vi.fn()
|
|
467
|
+
store.listen(listener)
|
|
468
|
+
const author = tolkein()
|
|
469
|
+
|
|
470
|
+
expect(() =>
|
|
471
|
+
store.atomic(() => {
|
|
472
|
+
store.put([author])
|
|
473
|
+
throw new Error('abort')
|
|
474
|
+
})
|
|
475
|
+
).toThrow('abort')
|
|
476
|
+
expect(store.get(author.id)).toBeUndefined()
|
|
477
|
+
|
|
478
|
+
// a later, committed change flushes whatever the accumulator still holds
|
|
479
|
+
store.put([Author.create({ name: 'Ursula K. Le Guin' })])
|
|
480
|
+
await new Promise((resolve) => requestAnimationFrame(resolve))
|
|
481
|
+
|
|
482
|
+
const addedIds = listener.mock.calls.flatMap(([entry]) => Object.keys(entry.changes.added))
|
|
483
|
+
expect(addedIds).not.toContain(author.id)
|
|
484
|
+
expect(addedIds).toHaveLength(1)
|
|
485
|
+
})
|
|
486
|
+
|
|
487
|
+
it('[H11] a rolled-back nested transaction only discards its own change-sets', async () => {
|
|
488
|
+
const listener = vi.fn()
|
|
489
|
+
store.listen(listener)
|
|
490
|
+
const kept = tolkein()
|
|
491
|
+
const dropped = Author.create({ name: 'Dropped' })
|
|
492
|
+
|
|
493
|
+
transact(() => {
|
|
494
|
+
store.put([kept])
|
|
495
|
+
try {
|
|
496
|
+
transaction(() => {
|
|
497
|
+
store.put([dropped])
|
|
498
|
+
throw new Error('inner')
|
|
499
|
+
})
|
|
500
|
+
} catch {
|
|
501
|
+
// the outer transaction commits
|
|
502
|
+
}
|
|
503
|
+
})
|
|
504
|
+
await new Promise((resolve) => requestAnimationFrame(resolve))
|
|
505
|
+
|
|
506
|
+
expect(store.get(kept.id)).toBeDefined()
|
|
507
|
+
expect(store.get(dropped.id)).toBeUndefined()
|
|
508
|
+
const addedIds = listener.mock.calls.flatMap(([entry]) => Object.keys(entry.changes.added))
|
|
509
|
+
expect(addedIds).toEqual([kept.id])
|
|
510
|
+
})
|
|
511
|
+
})
|
|
512
|
+
|
|
513
|
+
describe('extracting changes across rolled-back nested transactions (H)', () => {
|
|
514
|
+
it('[H7] extractingChanges excludes changes from a nested transaction that rolled back', () => {
|
|
515
|
+
const kept = tolkein()
|
|
516
|
+
const dropped = Author.create({ name: 'Dropped' })
|
|
517
|
+
const changes = store.extractingChanges(() => {
|
|
518
|
+
store.put([kept])
|
|
519
|
+
try {
|
|
520
|
+
transaction(() => {
|
|
521
|
+
store.put([dropped])
|
|
522
|
+
throw new Error('inner')
|
|
523
|
+
})
|
|
524
|
+
} catch {
|
|
525
|
+
// swallowed: the outer work continues
|
|
526
|
+
}
|
|
527
|
+
})
|
|
528
|
+
expect(Object.keys(changes.added)).toEqual([kept.id])
|
|
529
|
+
expect(store.get(dropped.id)).toBeUndefined()
|
|
530
|
+
})
|
|
531
|
+
})
|
|
532
|
+
|
|
533
|
+
describe('listeners added from an interceptor (H)', () => {
|
|
534
|
+
it('[H8] a flush triggered from inside an interceptor still delivers the entry being recorded', () => {
|
|
535
|
+
const first = vi.fn()
|
|
536
|
+
store.listen(first)
|
|
537
|
+
let added = false
|
|
538
|
+
store.addHistoryInterceptor(() => {
|
|
539
|
+
if (added) return
|
|
540
|
+
added = true
|
|
541
|
+
// listen() flushes synchronously while the entry is still being recorded
|
|
542
|
+
store.listen(() => {})
|
|
543
|
+
})
|
|
544
|
+
|
|
545
|
+
store.put([tolkein()])
|
|
546
|
+
store._flushHistory()
|
|
547
|
+
expect(first).toHaveBeenCalledTimes(1)
|
|
548
|
+
})
|
|
549
|
+
})
|
|
550
|
+
|
|
464
551
|
describe('applying diffs with ignoreEphemeralKeys (H)', () => {
|
|
465
552
|
it('[H10] ignoreEphemeralKeys also applies the removal of a non-ephemeral key', () => {
|
|
466
553
|
const visitId = Visit.createId('jane')
|
|
@@ -514,3 +601,67 @@ describe('listeners: dispose (H)', () => {
|
|
|
514
601
|
}
|
|
515
602
|
})
|
|
516
603
|
})
|
|
604
|
+
|
|
605
|
+
describe('listeners: removing a listener (H)', () => {
|
|
606
|
+
const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve))
|
|
607
|
+
|
|
608
|
+
beforeEach(() => {
|
|
609
|
+
// @ts-expect-error - test-only escape hatch
|
|
610
|
+
globalThis.__FORCE_RAF_IN_TESTS__ = true
|
|
611
|
+
return () => {
|
|
612
|
+
// @ts-expect-error - test-only escape hatch
|
|
613
|
+
globalThis.__FORCE_RAF_IN_TESTS__ = false
|
|
614
|
+
}
|
|
615
|
+
})
|
|
616
|
+
|
|
617
|
+
it('[H14] the remover delivers pending change-sets before removing the listener', async () => {
|
|
618
|
+
const listener = vi.fn()
|
|
619
|
+
const removeListener = store.listen(listener)
|
|
620
|
+
store.put([tolkein()])
|
|
621
|
+
expect(listener).not.toHaveBeenCalled()
|
|
622
|
+
|
|
623
|
+
removeListener()
|
|
624
|
+
expect(listener).toHaveBeenCalledTimes(1)
|
|
625
|
+
|
|
626
|
+
store.put([hobbit()])
|
|
627
|
+
await nextFrame()
|
|
628
|
+
expect(listener).toHaveBeenCalledTimes(1)
|
|
629
|
+
})
|
|
630
|
+
|
|
631
|
+
it('[H14] the remover logs a listener error from its flush instead of throwing it', async () => {
|
|
632
|
+
const error = new Error('listener failed')
|
|
633
|
+
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
634
|
+
const listener = vi.fn(() => {
|
|
635
|
+
throw error
|
|
636
|
+
})
|
|
637
|
+
try {
|
|
638
|
+
const removeListener = store.listen(listener)
|
|
639
|
+
store.put([tolkein()])
|
|
640
|
+
|
|
641
|
+
expect(removeListener).not.toThrow()
|
|
642
|
+
expect(consoleError).toHaveBeenCalledWith(error)
|
|
643
|
+
|
|
644
|
+
store.put([hobbit()])
|
|
645
|
+
await nextFrame()
|
|
646
|
+
expect(listener).toHaveBeenCalledTimes(1)
|
|
647
|
+
} finally {
|
|
648
|
+
consoleError.mockRestore()
|
|
649
|
+
}
|
|
650
|
+
})
|
|
651
|
+
|
|
652
|
+
it('[H14] a listener that writes and then removes itself mid-flush does not reorder the others', async () => {
|
|
653
|
+
const received: string[][] = []
|
|
654
|
+
const removeWriter = store.listen(() => {
|
|
655
|
+
store.put([hobbit()])
|
|
656
|
+
removeWriter()
|
|
657
|
+
})
|
|
658
|
+
store.listen(({ changes }) => received.push(Object.keys(changes.added)))
|
|
659
|
+
|
|
660
|
+
const author = tolkein()
|
|
661
|
+
store.put([author])
|
|
662
|
+
await nextFrame()
|
|
663
|
+
await nextFrame()
|
|
664
|
+
|
|
665
|
+
expect(received).toEqual([[author.id], [hobbit().id]])
|
|
666
|
+
})
|
|
667
|
+
})
|