@tldraw/editor 5.5.0-next.4d6473b0bda1 → 5.5.0-next.9352f6ad229c

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.
Files changed (30) hide show
  1. package/dist-cjs/index.js +1 -1
  2. package/dist-cjs/lib/editor/Editor.js +15 -9
  3. package/dist-cjs/lib/editor/Editor.js.map +2 -2
  4. package/dist-cjs/lib/editor/shapes/group/GroupShapeUtil.js +14 -6
  5. package/dist-cjs/lib/editor/shapes/group/GroupShapeUtil.js.map +3 -3
  6. package/dist-cjs/lib/utils/sync/LocalIndexedDb.js +13 -17
  7. package/dist-cjs/lib/utils/sync/LocalIndexedDb.js.map +2 -2
  8. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js +78 -40
  9. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js.map +2 -2
  10. package/dist-cjs/version.js +3 -3
  11. package/dist-cjs/version.js.map +1 -1
  12. package/dist-esm/index.mjs +1 -1
  13. package/dist-esm/lib/editor/Editor.mjs +15 -9
  14. package/dist-esm/lib/editor/Editor.mjs.map +2 -2
  15. package/dist-esm/lib/editor/shapes/group/GroupShapeUtil.mjs +14 -6
  16. package/dist-esm/lib/editor/shapes/group/GroupShapeUtil.mjs.map +3 -3
  17. package/dist-esm/lib/utils/sync/LocalIndexedDb.mjs +13 -17
  18. package/dist-esm/lib/utils/sync/LocalIndexedDb.mjs.map +2 -2
  19. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs +78 -40
  20. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs.map +2 -2
  21. package/dist-esm/version.mjs +3 -3
  22. package/dist-esm/version.mjs.map +1 -1
  23. package/package.json +7 -7
  24. package/src/lib/editor/Editor.ts +32 -16
  25. package/src/lib/editor/shapes/group/GroupShapeUtil.tsx +23 -8
  26. package/src/lib/utils/sync/LocalIndexedDb.test.ts +28 -0
  27. package/src/lib/utils/sync/LocalIndexedDb.ts +18 -20
  28. package/src/lib/utils/sync/TLLocalSyncClient.test.ts +236 -0
  29. package/src/lib/utils/sync/TLLocalSyncClient.ts +106 -54
  30. package/src/version.ts +3 -3
@@ -2288,12 +2288,14 @@ export class Editor extends EventEmitter<TLEventMap> {
2288
2288
  firstParentId &&
2289
2289
  selectedShapeIds.every((shapeId) => this.getShape(shapeId)?.parentId === firstParentId) &&
2290
2290
  !isPageId(firstParentId)
2291
- const filteredShapes = isSelectedWithinContainer
2292
- ? this.getCurrentPageShapes().filter((shape) => shape.parentId === firstParentId)
2293
- : this.getCurrentPageShapes().filter((shape) => isPageId(shape.parentId))
2294
- const readingOrderShapes = isSelectedWithinContainer
2295
- ? this._getShapesInReadingOrder(filteredShapes)
2296
- : this.getCurrentPageShapesInReadingOrder()
2291
+ // Locked shapes (and children of locked containers) can't be selected by clicking or
2292
+ // select all, so traversal skips them too
2293
+ const filteredShapes = this.getCurrentPageShapes().filter(
2294
+ (shape) =>
2295
+ !this.isShapeOrAncestorLocked(shape) &&
2296
+ (isSelectedWithinContainer ? shape.parentId === firstParentId : isPageId(shape.parentId))
2297
+ )
2298
+ const readingOrderShapes = this._getShapesInReadingOrder(filteredShapes)
2297
2299
  const currentShapeId: TLShapeId | undefined =
2298
2300
  selectedShapeIds.length === 1
2299
2301
  ? selectedShapeIds[0]
@@ -2302,6 +2304,9 @@ export class Editor extends EventEmitter<TLEventMap> {
2302
2304
  let adjacentShapeId: TLShapeId
2303
2305
  if (direction === 'next' || direction === 'prev') {
2304
2306
  const shapeIds = readingOrderShapes.map((shape) => shape.id)
2307
+ // Every candidate can be filtered out (e.g. a locked shape is selected and nothing
2308
+ // else is unlocked); indexing an empty list would hand getShape undefined
2309
+ if (shapeIds.length === 0) return
2305
2310
 
2306
2311
  const currentIndex = currentShapeId ? shapeIds.indexOf(currentShapeId) : -1
2307
2312
  // With no current index, stepping from -1 makes 'prev' land one shape
@@ -3595,6 +3600,18 @@ export class Editor extends EventEmitter<TLEventMap> {
3595
3600
  const { isLocked } = this._cameraOptions.__unsafe__getWithoutCapture()
3596
3601
  if (isLocked && !opts?.force) return this
3597
3602
 
3603
+ const _point = Vec.Cast(point)
3604
+
3605
+ // Reject non-finite values before anything else, so the call is a no-op rather than a
3606
+ // partial one. An animated move writes the camera from a 'tick' listener, and a listener
3607
+ // that throws stops TickManager scheduling the next frame, which kills every frame-driven
3608
+ // behavior for the rest of the session instead of surfacing the error to the caller.
3609
+ if (!Number.isFinite(_point.x) || !Number.isFinite(_point.y) || !Number.isFinite(_point.z)) {
3610
+ throw Error(
3611
+ `Editor.setCamera: expected finite values, got (${_point.x}, ${_point.y}, ${_point.z}).`
3612
+ )
3613
+ }
3614
+
3598
3615
  // Stop any camera animations
3599
3616
  this.stopCameraAnimation()
3600
3617
 
@@ -3603,12 +3620,6 @@ export class Editor extends EventEmitter<TLEventMap> {
3603
3620
  this.stopFollowingUser()
3604
3621
  }
3605
3622
 
3606
- const _point = Vec.Cast(point)
3607
-
3608
- if (!Number.isFinite(_point.x)) _point.x = 0
3609
- if (!Number.isFinite(_point.y)) _point.y = 0
3610
- if (_point.z === undefined || !Number.isFinite(_point.z)) point.z = this.getZoomLevel()
3611
-
3612
3623
  const camera = this.getConstrainedCamera(_point, opts)
3613
3624
 
3614
3625
  if (opts?.animation) {
@@ -4134,6 +4145,7 @@ export class Editor extends EventEmitter<TLEventMap> {
4134
4145
  // If we're not on the same page, move to the page they're on
4135
4146
  const isOnSamePage = presence.currentPageId === this.getCurrentPageId()
4136
4147
  if (!isOnSamePage) {
4148
+ this.markHistoryStoppingPoint('change-page')
4137
4149
  this.setCurrentPage(presence.currentPageId)
4138
4150
  }
4139
4151
 
@@ -7431,8 +7443,10 @@ export class Editor extends EventEmitter<TLEventMap> {
7431
7443
  const shapesMovingTogether = [shape]
7432
7444
  const boundsOfShapesMovingTogether: Box[] = [shapePageBounds]
7433
7445
 
7446
+ // Seed with bindings in both directions, otherwise an arrow visited before the shapes it
7447
+ // binds ends up in a cluster of its own and the result depends on input order
7434
7448
  this.collectShapesViaArrowBindings({
7435
- bindings: this.getBindingsToShape(shape.id, 'arrow'),
7449
+ bindings: this.getBindingsInvolvingShape(shape.id, 'arrow'),
7436
7450
  initialShapes: freshShapes,
7437
7451
  resultShapes: shapesMovingTogether,
7438
7452
  resultBounds: boundsOfShapesMovingTogether,
@@ -11489,9 +11503,11 @@ export class Editor extends EventEmitter<TLEventMap> {
11489
11503
  break
11490
11504
  }
11491
11505
  case 'keyboard': {
11492
- // please, please
11493
- if (info.key === 'ShiftRight') info.key = 'ShiftLeft'
11494
- if (info.key === 'AltRight') info.key = 'AltLeft'
11506
+ // Left and right modifier keys are the same key to us. `inputs.keys` stores
11507
+ // `code`, so normalize that: a `ShiftRight` left as-is would never match the
11508
+ // `ShiftLeft` that nudging checks or that `_releaseShiftKey` clears.
11509
+ if (info.code === 'ShiftRight') info.code = 'ShiftLeft'
11510
+ if (info.code === 'AltRight') info.code = 'AltLeft'
11495
11511
  if (info.code === 'ControlRight') info.code = 'ControlLeft'
11496
11512
  if (info.code === 'MetaRight') info.code = 'MetaLeft'
11497
11513
 
@@ -39,14 +39,29 @@ export class GroupShapeUtil extends ShapeUtil<TLGroupShape> {
39
39
  return new Rectangle2d({ width: 1, height: 1, isFilled: false })
40
40
  }
41
41
 
42
- return new Group2d({
43
- children: children.map((childId) => {
44
- const shape = this.editor.getShape(childId)!
45
- return this.editor
46
- .getShapeGeometry(childId)
47
- .transform(this.editor.getShapeLocalTransform(shape)!, { isLabel: false })
48
- }),
49
- })
42
+ // A child id can outlive its record. The children index and the geometry cache are separate
43
+ // derivations, so inside a transaction that removes a child the index can still name it while
44
+ // `getShapeGeometry` already answers nothing — its `!` hides that it returns `undefined` for a
45
+ // record the store no longer holds. Asserting instead of checking threw a `TypeError` out of a
46
+ // reactive recompute, where no caller could catch it.
47
+ const geometries: Geometry2d[] = []
48
+ for (const childId of children) {
49
+ const child = this.editor.getShape(childId)
50
+ if (!child) continue
51
+ const geometry = this.editor.getShapeGeometry(childId)
52
+ if (!geometry) continue
53
+ const transform = this.editor.getShapeLocalTransform(child)
54
+ if (!transform) continue
55
+ geometries.push(geometry.transform(transform, { isLabel: false }))
56
+ }
57
+
58
+ // Every child resolved to nothing, so there is no meaningful extent to report. Matches the
59
+ // no-children case above rather than building an empty `Group2d`, whose bounds are `NaN`.
60
+ if (geometries.length === 0) {
61
+ return new Rectangle2d({ width: 1, height: 1, isFilled: false })
62
+ }
63
+
64
+ return new Group2d({ children: geometries })
50
65
  }
51
66
 
52
67
  component(shape: TLGroupShape) {
@@ -106,6 +106,34 @@ describe('LocalIndexedDb', () => {
106
106
  })
107
107
  })
108
108
 
109
+ it('commits a write that is still in flight when the db is closed', async () => {
110
+ const db = new LocalIndexedDb('test-0')
111
+ const write = db.storeSnapshot({ schema, snapshot: { 'shape:1': { id: 'shape:1' } } })
112
+ await db.close()
113
+ await write
114
+
115
+ const reopened = new LocalIndexedDb('test-0')
116
+ expect((await reopened.load())?.records).toEqual([{ id: 'shape:1' }])
117
+ await reopened.close()
118
+ })
119
+
120
+ it('rejects a transaction that aborts after its requests succeeded while closing', async () => {
121
+ const db = new LocalIndexedDb('test-0')
122
+ let closing: Promise<void> | undefined
123
+ // A commit can fail after every request succeeded, so the request promises cannot report it.
124
+ // @ts-expect-error Exercise the transaction boundary directly to inject a commit failure.
125
+ const write = db.tx('readwrite', ['records'], async (tx) => {
126
+ await tx.objectStore('records').put({ id: 'shape:1' }, 'shape:1')
127
+ closing = db.close()
128
+ tx.abort()
129
+ })
130
+ try {
131
+ await expect(write).rejects.toMatchObject({ name: 'AbortError' })
132
+ } finally {
133
+ await closing
134
+ }
135
+ })
136
+
109
137
  describe('#storeChanges', () => {
110
138
  it('allows merging changes into an existing store', async () => {
111
139
  const db = new LocalIndexedDb('test-0')
@@ -141,26 +141,22 @@ export class LocalIndexedDb {
141
141
  assert(!this.isClosed, 'db is closed')
142
142
  const db = await this.getDb()
143
143
  const tx = db.transaction(names, mode)
144
- // need to add a catch here early to prevent unhandled promise rejection
145
- // during react-strict-mode where this tx.done promise can be rejected
146
- // before we have a chance to await on it
147
- const done = tx.done.catch((e: unknown) => {
148
- if (!this.isClosed) {
149
- throw e
150
- }
151
- })
144
+ // Commit failures may arrive before the callback finishes; observe them immediately
145
+ // while preserving the rejection for the await below.
146
+ const done = tx.done
147
+ done.catch(noop)
152
148
  try {
153
149
  return await cb(tx)
154
150
  } finally {
155
- if (!this.isClosed) {
156
- await done
157
- } else {
158
- tx.abort()
159
- }
151
+ // let the transaction commit even if close() was called meanwhile, otherwise a
152
+ // persist racing an unmount is silently rolled back
153
+ await done
160
154
  }
161
155
  })()
162
156
  this.pendingTransactionSet.add(txPromise)
163
- txPromise.finally(() => this.pendingTransactionSet.delete(txPromise))
157
+ // not `.finally()`: the promise it returns would re-reject with nobody observing it
158
+ const cleanup = () => this.pendingTransactionSet.delete(txPromise)
159
+ txPromise.then(cleanup, cleanup)
164
160
  return txPromise
165
161
  }
166
162
 
@@ -208,17 +204,19 @@ export class LocalIndexedDb {
208
204
  const schemaStore = tx.objectStore(Table.Schema)
209
205
  const sessionStateStore = tx.objectStore(Table.SessionState)
210
206
 
207
+ const requests: Promise<unknown>[] = []
211
208
  for (const [id, record] of Object.entries(changes.added)) {
212
- await recordsStore.put(record, id)
209
+ requests.push(recordsStore.put(record, id))
213
210
  }
214
211
 
215
212
  for (const [_prev, updated] of Object.values(changes.updated)) {
216
- await recordsStore.put(updated, updated.id)
213
+ requests.push(recordsStore.put(updated, updated.id))
217
214
  }
218
215
 
219
216
  for (const id of Object.keys(changes.removed)) {
220
- await recordsStore.delete(id)
217
+ requests.push(recordsStore.delete(id))
221
218
  }
219
+ await Promise.all(requests)
222
220
 
223
221
  schemaStore.put(schema.serialize(), Table.Schema)
224
222
  if (sessionStateSnapshot && sessionId) {
@@ -254,9 +252,9 @@ export class LocalIndexedDb {
254
252
 
255
253
  await recordsStore.clear()
256
254
 
257
- for (const [id, record] of Object.entries(snapshot)) {
258
- await recordsStore.put(record, id)
259
- }
255
+ await Promise.all(
256
+ Object.entries(snapshot).map(([id, record]) => recordsStore.put(record, id))
257
+ )
260
258
 
261
259
  schemaStore.put(schema.serialize(), Table.Schema)
262
260
 
@@ -3,6 +3,7 @@ import { IndexKey, promiseWithResolve } from '@tldraw/utils'
3
3
  import { Mock, vi } from 'vitest'
4
4
  import { createTLStore } from '../../config/createTLStore'
5
5
  import { hardReset } from './hardReset'
6
+ import { LocalIndexedDb } from './LocalIndexedDb'
6
7
  import { TLLocalSyncClient } from './TLLocalSyncClient'
7
8
 
8
9
  class BroadcastChannelMock {
@@ -214,6 +215,73 @@ test('pagehide does not write before the initial load has completed', async () =
214
215
  expect(client.db.storeChanges).not.toHaveBeenCalled()
215
216
  })
216
217
 
218
+ test('diffs received while the client is still loading are applied once it has loaded', async () => {
219
+ const { client, channel, tick } = testClient()
220
+ const remotePage = PageRecordType.create({ name: 'remote', index: 'a0' as IndexKey })
221
+ channel.onmessage?.({
222
+ data: {
223
+ type: 'diff',
224
+ storeId: 'other-tab',
225
+ schema: client.serializedSchema,
226
+ changes: { added: { [remotePage.id]: remotePage }, updated: {}, removed: {} },
227
+ },
228
+ } as any)
229
+ expect(client.store.get(remotePage.id)).toBeUndefined()
230
+
231
+ await tick()
232
+ expect(client.store.get(remotePage.id)).toEqual(remotePage)
233
+
234
+ // and the first (full) db write includes them rather than overwriting them
235
+ client.store.put([PageRecordType.create({ name: 'local', index: 'a1' as IndexKey })])
236
+ await tick()
237
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
238
+ expect(client.db.storeSnapshot.mock.calls[0][0].snapshot[remotePage.id]).toEqual(remotePage)
239
+ })
240
+
241
+ test('closing the client persists changes that are still queued', async () => {
242
+ const { client, tick } = testClient()
243
+ await tick()
244
+ client.store.put([PageRecordType.create({ name: 'test', index: 'a0' as IndexKey })])
245
+ expect(client.db.storeSnapshot).not.toHaveBeenCalled()
246
+
247
+ // close before the throttled persist fires
248
+ client.close()
249
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
250
+ })
251
+
252
+ test('closing the client while a persist is in flight still persists edits queued during the write', async () => {
253
+ const idbOperationResult = promiseWithResolve<void>()
254
+ const { client, tick } = testClient()
255
+ client.db.storeSnapshot.mockImplementationOnce(() => idbOperationResult)
256
+ const closeDb = vi.spyOn(client.db, 'close')
257
+
258
+ await tick()
259
+ client.store.put([PageRecordType.create({ name: 'test', index: 'a0' as IndexKey })])
260
+ await tick()
261
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
262
+
263
+ // an edit made while the first write is still in flight, then unmount
264
+ const page = PageRecordType.create({ name: 'test2', index: 'a1' as IndexKey })
265
+ client.store.put([page])
266
+ client.close()
267
+ expect(client.db.storeChanges).not.toHaveBeenCalled()
268
+ expect(closeDb).not.toHaveBeenCalled()
269
+
270
+ idbOperationResult.resolve()
271
+ await tick()
272
+ expect(client.db.storeChanges).toHaveBeenCalledTimes(1)
273
+ expect(client.db.storeChanges.mock.calls[0][0].changes.added[page.id]).toEqual(page)
274
+ expect(closeDb).toHaveBeenCalledTimes(1)
275
+ })
276
+
277
+ test('closing the client with nothing queued does not write to the db', async () => {
278
+ const { client, tick } = testClient()
279
+ await tick()
280
+ client.close()
281
+ expect(client.db.storeSnapshot).not.toHaveBeenCalled()
282
+ expect(client.db.storeChanges).not.toHaveBeenCalled()
283
+ })
284
+
217
285
  test('pagehide and visibilitychange listeners are removed when the client closes', async () => {
218
286
  const removeWindowListener = vi.spyOn(window, 'removeEventListener')
219
287
  const removeDocumentListener = vi.spyOn(document, 'removeEventListener')
@@ -228,3 +296,171 @@ test('pagehide and visibilitychange listeners are removed when the client closes
228
296
  removeDocumentListener.mockRestore()
229
297
  }
230
298
  })
299
+
300
+ test('closing the client before it has loaded does not write to the db', async () => {
301
+ const { client, tick } = testClient()
302
+ client.close()
303
+ await tick()
304
+ expect(client.db.storeSnapshot).not.toHaveBeenCalled()
305
+ expect(client.db.storeChanges).not.toHaveBeenCalled()
306
+ })
307
+
308
+ test('closing flushes changes that have not reached the next animation frame', async () => {
309
+ const { client, tick } = testClient()
310
+ await tick()
311
+ const page = PageRecordType.create({ name: 'last frame', index: 'a0' as IndexKey })
312
+ vi.stubGlobal('__FORCE_RAF_IN_TESTS__', true)
313
+ try {
314
+ client.store.put([page])
315
+ client.close()
316
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
317
+ expect(client.db.storeSnapshot.mock.calls[0][0].snapshot[page.id]).toEqual(page)
318
+ } finally {
319
+ vi.unstubAllGlobals()
320
+ }
321
+ })
322
+
323
+ test('buffered schema announcements cannot persist before the remaining buffered diffs', async () => {
324
+ const { client, channel, tick } = testClient()
325
+ const page = PageRecordType.create({ name: 'remote', index: 'a0' as IndexKey })
326
+ const schema = client.store.schema.serialize()
327
+ channel.onmessage?.({
328
+ data: {
329
+ type: 'announce',
330
+ schema: { ...schema, sequences: { ...schema.sequences, 'com.tldraw.page': 0 } },
331
+ },
332
+ } as MessageEvent)
333
+ channel.onmessage?.({
334
+ data: {
335
+ type: 'diff',
336
+ storeId: 'other-tab',
337
+ schema: client.serializedSchema,
338
+ changes: { added: { [page.id]: page }, updated: {}, removed: {} },
339
+ },
340
+ } as MessageEvent)
341
+ await tick()
342
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
343
+ expect(client.db.storeSnapshot.mock.calls[0][0].snapshot[page.id]).toEqual(page)
344
+ client.close()
345
+ })
346
+
347
+ test('closing before load cancels a persist scheduled by an early edit', async () => {
348
+ const load = promiseWithResolve<Awaited<ReturnType<LocalIndexedDb['load']>>>()
349
+ const loadMock = vi.spyOn(LocalIndexedDb.prototype, 'load').mockImplementationOnce(() => load)
350
+ try {
351
+ const { client, tick } = testClient()
352
+ client.store.put([PageRecordType.create({ name: 'early', index: 'a0' as IndexKey })])
353
+ client.close()
354
+ load.resolve({ records: [], schema: undefined, sessionStateSnapshot: undefined })
355
+ await tick()
356
+ expect(client.db.storeSnapshot).not.toHaveBeenCalled()
357
+ expect(client.db.storeChanges).not.toHaveBeenCalled()
358
+ } finally {
359
+ loadMock.mockRestore()
360
+ }
361
+ })
362
+
363
+ test.each(['close flush', 'in-flight write'] as const)(
364
+ 'a failed %s after close logs the error without disrupting the current page',
365
+ async (when) => {
366
+ const { client, tick } = testClient()
367
+ await tick()
368
+ const write = promiseWithResolve<void>()
369
+ client.db.storeSnapshot.mockImplementationOnce(() => write)
370
+ const error = new Error('write failed')
371
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})
372
+ const alert = vi.spyOn(window, 'alert').mockImplementation(() => {})
373
+ try {
374
+ client.store.put([PageRecordType.create({ name: 'last edit', index: 'a0' as IndexKey })])
375
+ if (when === 'in-flight write') await tick()
376
+ client.close()
377
+ write.reject(error)
378
+ await tick()
379
+ expect(log).toHaveBeenCalledWith('failed to store changes in indexed db', error)
380
+ expect(alert).not.toHaveBeenCalled()
381
+ expect(reloadMock).not.toHaveBeenCalled()
382
+ } finally {
383
+ log.mockRestore()
384
+ alert.mockRestore()
385
+ }
386
+ }
387
+ )
388
+
389
+ test('closing with no queued changes cancels a failed-write retry', async () => {
390
+ const { client, tick } = testClient()
391
+ await tick()
392
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})
393
+ const alert = vi.spyOn(window, 'alert').mockImplementation(() => {})
394
+ try {
395
+ client.db.storeSnapshot.mockRejectedValueOnce(new Error('first write failed'))
396
+ client.store.put([PageRecordType.create({ name: 'retry', index: 'a0' as IndexKey })])
397
+ await tick()
398
+ expect(reloadMock).toHaveBeenCalledTimes(1)
399
+ client.close()
400
+ await vi.advanceTimersByTimeAsync(10_000)
401
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
402
+ } finally {
403
+ log.mockRestore()
404
+ alert.mockRestore()
405
+ }
406
+ })
407
+
408
+ test('a schema mismatch does not try to refresh without a window', async () => {
409
+ const { client, channel, tick } = testClient()
410
+ await tick()
411
+ vi.advanceTimersByTime(10_000)
412
+ vi.stubGlobal('window', undefined)
413
+ try {
414
+ expect(() =>
415
+ channel.onmessage?.({
416
+ data: {
417
+ type: 'announce',
418
+ schema: {
419
+ ...client.serializedSchema,
420
+ schemaVersion: client.serializedSchema.schemaVersion + 1,
421
+ },
422
+ },
423
+ } as MessageEvent)
424
+ ).not.toThrow()
425
+ } finally {
426
+ vi.unstubAllGlobals()
427
+ client.close()
428
+ }
429
+ })
430
+
431
+ test('onLoad can close the client without losing buffered remote changes', async () => {
432
+ const { client, channel, onLoad, tick } = testClient()
433
+ const page = PageRecordType.create({ name: 'remote', index: 'a0' as IndexKey })
434
+ channel.onmessage?.({
435
+ data: {
436
+ type: 'diff',
437
+ storeId: 'other-tab',
438
+ schema: client.serializedSchema,
439
+ changes: { added: { [page.id]: page }, updated: {}, removed: {} },
440
+ },
441
+ } as MessageEvent)
442
+ onLoad.mockImplementation(() => {
443
+ client.store.put([PageRecordType.create({ name: 'local', index: 'a1' as IndexKey })])
444
+ client.close()
445
+ })
446
+ await tick()
447
+ expect(client.db.storeSnapshot.mock.calls[0][0].snapshot[page.id]).toEqual(page)
448
+ })
449
+
450
+ test('a buffered newer schema reports a load error without announcing a successful load', async () => {
451
+ const { client, channel, onLoad, onLoadError, tick } = testClient()
452
+ channel.onmessage?.({
453
+ data: {
454
+ type: 'announce',
455
+ schema: {
456
+ ...client.serializedSchema,
457
+ schemaVersion: client.serializedSchema.schemaVersion + 1,
458
+ },
459
+ },
460
+ } as MessageEvent)
461
+ await tick()
462
+ expect(onLoadError).toHaveBeenCalledTimes(1)
463
+ expect(onLoad).not.toHaveBeenCalled()
464
+ client.close()
465
+ expect(client.db.storeSnapshot).not.toHaveBeenCalled()
466
+ })