@tldraw/store 5.5.2 → 5.6.0-canary.035b741dc331
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 +1 -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 +70 -29
- 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 +1 -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 +71 -30
- 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 +87 -0
- package/src/lib/Store.ts +90 -38
- 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/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,61 @@ 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
|
+
})
|
package/src/lib/Store.ts
CHANGED
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
import { AtomMap } from './AtomMap'
|
|
15
15
|
import { IdOf, RecordId, UnknownRecord } from './BaseRecord'
|
|
16
16
|
import { devFreeze } from './devFreeze'
|
|
17
|
-
import { isRecordsDiffEmpty, RecordsDiff, squashRecordDiffs } from './RecordsDiff'
|
|
17
|
+
import { hasAnyKey, isRecordsDiffEmpty, RecordsDiff, squashRecordDiffs } from './RecordsDiff'
|
|
18
18
|
import { RecordScope } from './RecordType'
|
|
19
19
|
import { StoreQueries } from './StoreQueries'
|
|
20
20
|
import { SerializedSchema, StoreSchema } from './StoreSchema'
|
|
@@ -513,11 +513,16 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
513
513
|
this.scopedTypes = scopedTypes
|
|
514
514
|
}
|
|
515
515
|
|
|
516
|
+
private isFlushingHistory = false
|
|
517
|
+
|
|
516
518
|
public _flushHistory() {
|
|
517
519
|
// If we have accumulated history, flush it and update listeners
|
|
518
|
-
|
|
519
|
-
|
|
520
|
+
const version = this.history.__unsafe__getWithoutCapture()
|
|
521
|
+
const entries = this.historyAccumulator.flush(version)
|
|
522
|
+
if (entries.length > 0) {
|
|
520
523
|
const errors: unknown[] = []
|
|
524
|
+
const wasFlushingHistory = this.isFlushingHistory
|
|
525
|
+
this.isFlushingHistory = true
|
|
521
526
|
for (const { changes, source } of entries) {
|
|
522
527
|
// Filtered diffs are computed at most once per scope per entry, and shared by every
|
|
523
528
|
// listener watching that scope.
|
|
@@ -544,6 +549,7 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
544
549
|
}
|
|
545
550
|
}
|
|
546
551
|
}
|
|
552
|
+
this.isFlushingHistory = wasFlushingHistory
|
|
547
553
|
if (errors.length > 0) throw errors[0]
|
|
548
554
|
}
|
|
549
555
|
}
|
|
@@ -582,14 +588,22 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
582
588
|
* @param changes - The changes to add to the history.
|
|
583
589
|
*/
|
|
584
590
|
private updateHistory(changes: RecordsDiff<R>): void {
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
591
|
+
// Don't capture: a reaction that writes to the store must not become a dependent of the
|
|
592
|
+
// history atom, or every other store change would re-run it (and it could loop forever).
|
|
593
|
+
const version = this.history.__unsafe__getWithoutCapture() + 1
|
|
594
|
+
// Set the atom before recording the entry: interceptors run inside `add`, and a flush they
|
|
595
|
+
// trigger (e.g. via `listen`) would otherwise discard the entry as not yet committed.
|
|
596
|
+
this.history.set(version, changes)
|
|
597
|
+
this.historyAccumulator.add(
|
|
598
|
+
{
|
|
599
|
+
changes,
|
|
600
|
+
source: this.isMergingRemoteChanges ? 'remote' : 'user',
|
|
601
|
+
},
|
|
602
|
+
version
|
|
603
|
+
)
|
|
589
604
|
if (this.listeners.size === 0) {
|
|
590
605
|
this.historyAccumulator.clear()
|
|
591
606
|
}
|
|
592
|
-
this.history.set(this.history.get() + 1, changes)
|
|
593
607
|
}
|
|
594
608
|
|
|
595
609
|
validate(phase: 'initialize' | 'createRecord' | 'updateRecord' | 'tests') {
|
|
@@ -622,12 +636,6 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
622
636
|
// Iterate through all records, creating, updating or removing as needed
|
|
623
637
|
let record: R
|
|
624
638
|
|
|
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
639
|
const source = this.isMergingRemoteChanges ? 'remote' : 'user'
|
|
632
640
|
|
|
633
641
|
for (let i = 0, n = records.length; i < n; i++) {
|
|
@@ -652,14 +660,23 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
652
660
|
record = devFreeze(validated)
|
|
653
661
|
this.records.set(record.id, record)
|
|
654
662
|
|
|
655
|
-
|
|
656
|
-
|
|
663
|
+
if (additions[record.id]) {
|
|
664
|
+
// the same record was created earlier in this call: fold the update into it
|
|
665
|
+
additions[record.id] = record
|
|
666
|
+
} else {
|
|
667
|
+
// an earlier update to the same record in this call owns the `from`
|
|
668
|
+
const from = updates[record.id]?.[0] ?? initialValue
|
|
669
|
+
if (from === record) {
|
|
670
|
+
// back to where it started within this call: nothing to record
|
|
671
|
+
delete updates[record.id]
|
|
672
|
+
} else {
|
|
673
|
+
updates[record.id] = [from, record]
|
|
674
|
+
}
|
|
675
|
+
}
|
|
657
676
|
this.addDiffForAfterEvent(initialValue, record)
|
|
658
677
|
} else {
|
|
659
678
|
record = this.sideEffects.handleBeforeCreate(record, source)
|
|
660
679
|
|
|
661
|
-
didChange = true
|
|
662
|
-
|
|
663
680
|
// If we don't have an atom, create one.
|
|
664
681
|
|
|
665
682
|
// Validate the record
|
|
@@ -681,8 +698,9 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
681
698
|
}
|
|
682
699
|
}
|
|
683
700
|
|
|
684
|
-
//
|
|
685
|
-
|
|
701
|
+
// Validation may have left every record identical to before, in which case there is no
|
|
702
|
+
// change-set to record.
|
|
703
|
+
if (!hasAnyKey(additions) && !hasAnyKey(updates)) return
|
|
686
704
|
this.updateHistory({
|
|
687
705
|
added: additions,
|
|
688
706
|
updated: updates,
|
|
@@ -1008,6 +1026,18 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
1008
1026
|
this.listeners.add(listener)
|
|
1009
1027
|
|
|
1010
1028
|
return () => {
|
|
1029
|
+
// Flush so this listener's history ends at exactly now, but not from inside a flush:
|
|
1030
|
+
// the other listeners would then receive changes made during that flush before the
|
|
1031
|
+
// entry they are still being handed.
|
|
1032
|
+
if (!this.isFlushingHistory) {
|
|
1033
|
+
try {
|
|
1034
|
+
this._flushHistory()
|
|
1035
|
+
} catch (error) {
|
|
1036
|
+
// Removers run in teardown loops (Editor.dispose, TLSyncClient.close); throwing here
|
|
1037
|
+
// would skip the cleanups that follow.
|
|
1038
|
+
console.error(error)
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1011
1041
|
this.listeners.delete(listener)
|
|
1012
1042
|
|
|
1013
1043
|
if (this.listeners.size === 0) {
|
|
@@ -1054,11 +1084,22 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
1054
1084
|
* Run `fn` and return a {@link RecordsDiff} of the changes that occurred as a result.
|
|
1055
1085
|
*/
|
|
1056
1086
|
extractingChanges(fn: () => void): RecordsDiff<R> {
|
|
1057
|
-
const
|
|
1058
|
-
const dispose = this.historyAccumulator.addInterceptor((entry) =>
|
|
1087
|
+
const collected: Array<{ version: number; changes: RecordsDiff<R> }> = []
|
|
1088
|
+
const dispose = this.historyAccumulator.addInterceptor((entry, version) => {
|
|
1089
|
+
// a nested transaction that rolled back inside `fn` leaves entries stamped at or past the
|
|
1090
|
+
// next committed version — see HistoryAccumulator
|
|
1091
|
+
while (collected.length && collected[collected.length - 1].version >= version) {
|
|
1092
|
+
collected.pop()
|
|
1093
|
+
}
|
|
1094
|
+
collected.push({ version, changes: entry.changes })
|
|
1095
|
+
})
|
|
1059
1096
|
try {
|
|
1060
1097
|
transact(fn)
|
|
1061
|
-
|
|
1098
|
+
const current = this.history.__unsafe__getWithoutCapture()
|
|
1099
|
+
while (collected.length && collected[collected.length - 1].version > current) {
|
|
1100
|
+
collected.pop()
|
|
1101
|
+
}
|
|
1102
|
+
return squashRecordDiffs(collected.map((c) => c.changes))
|
|
1062
1103
|
} finally {
|
|
1063
1104
|
dispose()
|
|
1064
1105
|
}
|
|
@@ -1077,7 +1118,7 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
|
|
|
1077
1118
|
for (const [_from, to] of objectMapValues(diff.updated)) {
|
|
1078
1119
|
const type = this.schema.getType(to.typeName)
|
|
1079
1120
|
if (ignoreEphemeralKeys && type.ephemeralKeySet.size) {
|
|
1080
|
-
const existing = this.
|
|
1121
|
+
const existing = this.unsafeGetWithoutCapture(to.id)
|
|
1081
1122
|
if (!existing) {
|
|
1082
1123
|
toPut.push(to)
|
|
1083
1124
|
continue
|
|
@@ -1343,13 +1384,18 @@ function squashHistoryEntries<T extends UnknownRecord>(
|
|
|
1343
1384
|
class HistoryAccumulator<T extends UnknownRecord> {
|
|
1344
1385
|
private _history: HistoryEntry<T>[] = []
|
|
1345
1386
|
|
|
1346
|
-
|
|
1387
|
+
// The `history` atom value each entry was recorded at. A transaction that aborts rolls that atom
|
|
1388
|
+
// back but cannot unwind this array, so an entry stamped at or past the atom's current value
|
|
1389
|
+
// belongs to a rolled-back change-set and must not reach listeners.
|
|
1390
|
+
private _versions: number[] = []
|
|
1391
|
+
|
|
1392
|
+
private _interceptors: Set<(entry: HistoryEntry<T>, version: number) => void> = new Set()
|
|
1347
1393
|
|
|
1348
1394
|
/**
|
|
1349
|
-
* Add an interceptor that will be called for each history entry
|
|
1350
|
-
* Returns a function to remove the interceptor.
|
|
1395
|
+
* Add an interceptor that will be called for each history entry, with the version it was
|
|
1396
|
+
* recorded at (see `add`). Returns a function to remove the interceptor.
|
|
1351
1397
|
*/
|
|
1352
|
-
addInterceptor(fn: (entry: HistoryEntry<T
|
|
1398
|
+
addInterceptor(fn: (entry: HistoryEntry<T>, version: number) => void) {
|
|
1353
1399
|
this._interceptors.add(fn)
|
|
1354
1400
|
return () => {
|
|
1355
1401
|
this._interceptors.delete(fn)
|
|
@@ -1357,13 +1403,15 @@ class HistoryAccumulator<T extends UnknownRecord> {
|
|
|
1357
1403
|
}
|
|
1358
1404
|
|
|
1359
1405
|
/**
|
|
1360
|
-
* Add a history entry
|
|
1406
|
+
* Add a history entry recorded at `version` (the `history` atom value it sets).
|
|
1361
1407
|
* Calls all registered interceptors with the entry.
|
|
1362
1408
|
*/
|
|
1363
|
-
add(entry: HistoryEntry<T
|
|
1409
|
+
add(entry: HistoryEntry<T>, version: number) {
|
|
1410
|
+
this.discardFrom(version)
|
|
1364
1411
|
this._history.push(entry)
|
|
1412
|
+
this._versions.push(version)
|
|
1365
1413
|
for (const interceptor of this._interceptors) {
|
|
1366
|
-
interceptor(entry)
|
|
1414
|
+
interceptor(entry, version)
|
|
1367
1415
|
}
|
|
1368
1416
|
}
|
|
1369
1417
|
|
|
@@ -1371,9 +1419,10 @@ class HistoryAccumulator<T extends UnknownRecord> {
|
|
|
1371
1419
|
* Flush all accumulated history entries, squashing adjacent entries from the same source.
|
|
1372
1420
|
* Clears the internal history buffer.
|
|
1373
1421
|
*/
|
|
1374
|
-
flush() {
|
|
1422
|
+
flush(currentVersion: number) {
|
|
1423
|
+
this.discardFrom(currentVersion + 1)
|
|
1375
1424
|
const history = squashHistoryEntries(this._history)
|
|
1376
|
-
this.
|
|
1425
|
+
this.clear()
|
|
1377
1426
|
return history
|
|
1378
1427
|
}
|
|
1379
1428
|
|
|
@@ -1382,13 +1431,16 @@ class HistoryAccumulator<T extends UnknownRecord> {
|
|
|
1382
1431
|
*/
|
|
1383
1432
|
clear() {
|
|
1384
1433
|
this._history = []
|
|
1434
|
+
this._versions = []
|
|
1385
1435
|
}
|
|
1386
1436
|
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1437
|
+
// Drops the entries recorded at or after `version`. Entries are in ascending version order: the
|
|
1438
|
+
// atom increments by one per entry, and a rollback is followed by exactly this discard.
|
|
1439
|
+
private discardFrom(version: number) {
|
|
1440
|
+
while (this._versions.length && this._versions[this._versions.length - 1] >= version) {
|
|
1441
|
+
this._versions.pop()
|
|
1442
|
+
this._history.pop()
|
|
1443
|
+
}
|
|
1392
1444
|
}
|
|
1393
1445
|
}
|
|
1394
1446
|
|
|
@@ -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
|
+
})
|
package/src/lib/StoreQueries.ts
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
RESET_VALUE,
|
|
8
8
|
withDiff,
|
|
9
9
|
} from '@tldraw/state'
|
|
10
|
-
import { areArraysShallowEqual, isEqual
|
|
10
|
+
import { areArraysShallowEqual, isEqual } from '@tldraw/utils'
|
|
11
11
|
import { AtomMap } from './AtomMap'
|
|
12
12
|
import { IdOf, UnknownRecord } from './BaseRecord'
|
|
13
13
|
import { executeQuery, objectMatchesQuery, QueryExpression } from './executeQuery'
|
|
@@ -324,25 +324,24 @@ export class StoreQueries<R extends UnknownRecord> {
|
|
|
324
324
|
|
|
325
325
|
const setConstructors = new Map<any, IncrementalSetConstructor<IdOf<S>>>()
|
|
326
326
|
|
|
327
|
-
const
|
|
327
|
+
const setConstructorFor = (value: any) => {
|
|
328
328
|
let setConstructor = setConstructors.get(value)
|
|
329
|
-
if (!setConstructor)
|
|
329
|
+
if (!setConstructor) {
|
|
330
330
|
setConstructor = new IncrementalSetConstructor<IdOf<S>>(
|
|
331
331
|
prevValue.get(value) ?? new Set()
|
|
332
332
|
)
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
const remove = (value: any, id: IdOf<S>) => {
|
|
338
|
-
let set = setConstructors.get(value)
|
|
339
|
-
if (!set) set = new IncrementalSetConstructor<IdOf<S>>(prevValue.get(value) ?? new Set())
|
|
340
|
-
set.remove(id)
|
|
341
|
-
setConstructors.set(value, set)
|
|
333
|
+
setConstructors.set(value, setConstructor)
|
|
334
|
+
}
|
|
335
|
+
return setConstructor
|
|
342
336
|
}
|
|
337
|
+
const add = (value: any, id: IdOf<S>) => setConstructorFor(value).add(id)
|
|
338
|
+
const remove = (value: any, id: IdOf<S>) => setConstructorFor(value).remove(id)
|
|
343
339
|
|
|
340
|
+
// for-in rather than objectMapValues: this runs per frame while dragging, and an
|
|
341
|
+
// allocation per diff per index adds up (see the note in RecordsDiff.ts)
|
|
344
342
|
for (const changes of history) {
|
|
345
|
-
for (const
|
|
343
|
+
for (const id in changes.added) {
|
|
344
|
+
const record = changes.added[id as IdOf<R>]
|
|
346
345
|
if (record.typeName === typeName) {
|
|
347
346
|
const value = getPropertyValue(record as S)
|
|
348
347
|
if (value !== undefined) {
|
|
@@ -350,7 +349,8 @@ export class StoreQueries<R extends UnknownRecord> {
|
|
|
350
349
|
}
|
|
351
350
|
}
|
|
352
351
|
}
|
|
353
|
-
for (const
|
|
352
|
+
for (const id in changes.updated) {
|
|
353
|
+
const [from, to] = changes.updated[id as IdOf<R>]
|
|
354
354
|
if (to.typeName === typeName) {
|
|
355
355
|
const prev = getPropertyValue(from as S)
|
|
356
356
|
const next = getPropertyValue(to as S)
|
|
@@ -364,7 +364,8 @@ export class StoreQueries<R extends UnknownRecord> {
|
|
|
364
364
|
}
|
|
365
365
|
}
|
|
366
366
|
}
|
|
367
|
-
for (const
|
|
367
|
+
for (const id in changes.removed) {
|
|
368
|
+
const record = changes.removed[id as IdOf<R>]
|
|
368
369
|
if (record.typeName === typeName) {
|
|
369
370
|
const value = getPropertyValue(record as S)
|
|
370
371
|
if (value !== undefined) {
|
|
@@ -564,17 +565,18 @@ export class StoreQueries<R extends UnknownRecord> {
|
|
|
564
565
|
return fromScratchWithDiff(prevValue)
|
|
565
566
|
}
|
|
566
567
|
|
|
567
|
-
const setConstructor = new IncrementalSetConstructor<IdOf<S>>(
|
|
568
|
-
prevValue
|
|
569
|
-
) as IncrementalSetConstructor<IdOf<S>>
|
|
568
|
+
const setConstructor = new IncrementalSetConstructor<IdOf<S>>(prevValue)
|
|
570
569
|
|
|
570
|
+
// for-in rather than objectMapValues: see the index derive above
|
|
571
571
|
for (const changes of history) {
|
|
572
|
-
for (const
|
|
572
|
+
for (const id in changes.added) {
|
|
573
|
+
const added = changes.added[id as IdOf<R>]
|
|
573
574
|
if (added.typeName === typeName && objectMatchesQuery(query, added)) {
|
|
574
575
|
setConstructor.add(added.id)
|
|
575
576
|
}
|
|
576
577
|
}
|
|
577
|
-
for (const
|
|
578
|
+
for (const id in changes.updated) {
|
|
579
|
+
const updated = changes.updated[id as IdOf<R>][1]
|
|
578
580
|
if (updated.typeName === typeName) {
|
|
579
581
|
if (objectMatchesQuery(query, updated)) {
|
|
580
582
|
setConstructor.add(updated.id)
|
|
@@ -583,7 +585,8 @@ export class StoreQueries<R extends UnknownRecord> {
|
|
|
583
585
|
}
|
|
584
586
|
}
|
|
585
587
|
}
|
|
586
|
-
for (const
|
|
588
|
+
for (const id in changes.removed) {
|
|
589
|
+
const removed = changes.removed[id as IdOf<R>]
|
|
587
590
|
if (removed.typeName === typeName) {
|
|
588
591
|
setConstructor.remove(removed.id)
|
|
589
592
|
}
|