@tldraw/editor 5.5.0-next.f9308d324e1c → 5.6.0-canary.5bfc37740468

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 (203) hide show
  1. package/dist-cjs/index.d.ts +49 -23
  2. package/dist-cjs/index.js +1 -1
  3. package/dist-cjs/index.js.map +2 -2
  4. package/dist-cjs/lib/TldrawEditor.js +16 -12
  5. package/dist-cjs/lib/TldrawEditor.js.map +2 -2
  6. package/dist-cjs/lib/components/MenuClickCapture.js +42 -3
  7. package/dist-cjs/lib/components/MenuClickCapture.js.map +2 -2
  8. package/dist-cjs/lib/components/default-components/DefaultCanvas.js +5 -1
  9. package/dist-cjs/lib/components/default-components/DefaultCanvas.js.map +2 -2
  10. package/dist-cjs/lib/components/default-components/DefaultErrorFallback.js +2 -5
  11. package/dist-cjs/lib/components/default-components/DefaultErrorFallback.js.map +3 -3
  12. package/dist-cjs/lib/components/default-components/DefaultSpinner.js.map +2 -2
  13. package/dist-cjs/lib/editor/Editor.js +183 -185
  14. package/dist-cjs/lib/editor/Editor.js.map +3 -3
  15. package/dist-cjs/lib/editor/derivations/bindingsIndex.js +2 -0
  16. package/dist-cjs/lib/editor/derivations/bindingsIndex.js.map +2 -2
  17. package/dist-cjs/lib/editor/managers/ClickManager/ClickManager.js +3 -2
  18. package/dist-cjs/lib/editor/managers/ClickManager/ClickManager.js.map +2 -2
  19. package/dist-cjs/lib/editor/managers/EditorManager.js +11 -2
  20. package/dist-cjs/lib/editor/managers/EditorManager.js.map +2 -2
  21. package/dist-cjs/lib/editor/managers/PerformanceManager/PerformanceManager.js +49 -63
  22. package/dist-cjs/lib/editor/managers/PerformanceManager/PerformanceManager.js.map +2 -2
  23. package/dist-cjs/lib/editor/managers/ScribbleManager/ScribbleManager.js +1 -1
  24. package/dist-cjs/lib/editor/managers/ScribbleManager/ScribbleManager.js.map +2 -2
  25. package/dist-cjs/lib/editor/managers/SnapManager/BoundsSnaps.js +24 -24
  26. package/dist-cjs/lib/editor/managers/SnapManager/BoundsSnaps.js.map +2 -2
  27. package/dist-cjs/lib/editor/managers/SnapManager/HandleSnaps.js +7 -1
  28. package/dist-cjs/lib/editor/managers/SnapManager/HandleSnaps.js.map +2 -2
  29. package/dist-cjs/lib/editor/managers/SnapManager/SnapManager.js +4 -3
  30. package/dist-cjs/lib/editor/managers/SnapManager/SnapManager.js.map +2 -2
  31. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js +4 -4
  32. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js.map +2 -2
  33. package/dist-cjs/lib/editor/shapes/group/GroupShapeUtil.js +14 -6
  34. package/dist-cjs/lib/editor/shapes/group/GroupShapeUtil.js.map +3 -3
  35. package/dist-cjs/lib/editor/shapes/shared/resizeBox.js +21 -16
  36. package/dist-cjs/lib/editor/shapes/shared/resizeBox.js.map +2 -2
  37. package/dist-cjs/lib/editor/types/external-content.js.map +1 -1
  38. package/dist-cjs/lib/exports/ExportDelay.js +10 -2
  39. package/dist-cjs/lib/exports/ExportDelay.js.map +2 -2
  40. package/dist-cjs/lib/exports/FontEmbedder.js +25 -11
  41. package/dist-cjs/lib/exports/FontEmbedder.js.map +2 -2
  42. package/dist-cjs/lib/exports/StyleEmbedder.js +9 -4
  43. package/dist-cjs/lib/exports/StyleEmbedder.js.map +2 -2
  44. package/dist-cjs/lib/exports/fetchCache.js +3 -0
  45. package/dist-cjs/lib/exports/fetchCache.js.map +2 -2
  46. package/dist-cjs/lib/exports/getSvgAsImage.js +10 -4
  47. package/dist-cjs/lib/exports/getSvgAsImage.js.map +2 -2
  48. package/dist-cjs/lib/exports/getSvgJsx.js +18 -9
  49. package/dist-cjs/lib/exports/getSvgJsx.js.map +2 -2
  50. package/dist-cjs/lib/exports/parseCss.js +1 -1
  51. package/dist-cjs/lib/exports/parseCss.js.map +1 -1
  52. package/dist-cjs/lib/hooks/EditorComponentsContext.js.map +2 -2
  53. package/dist-cjs/lib/hooks/useCanvasEvents.js +24 -0
  54. package/dist-cjs/lib/hooks/useCanvasEvents.js.map +2 -2
  55. package/dist-cjs/lib/hooks/useCursor.js +12 -8
  56. package/dist-cjs/lib/hooks/useCursor.js.map +2 -2
  57. package/dist-cjs/lib/hooks/useIdentity.js +6 -2
  58. package/dist-cjs/lib/hooks/useIdentity.js.map +3 -3
  59. package/dist-cjs/lib/license/LicenseManager.js +9 -1
  60. package/dist-cjs/lib/license/LicenseManager.js.map +2 -2
  61. package/dist-cjs/lib/license/LicenseProvider.js +12 -4
  62. package/dist-cjs/lib/license/LicenseProvider.js.map +2 -2
  63. package/dist-cjs/lib/utils/debug-flags.js +0 -6
  64. package/dist-cjs/lib/utils/debug-flags.js.map +2 -2
  65. package/dist-cjs/lib/utils/deepLinks.js +2 -1
  66. package/dist-cjs/lib/utils/deepLinks.js.map +2 -2
  67. package/dist-cjs/lib/utils/sync/LocalIndexedDb.js +32 -25
  68. package/dist-cjs/lib/utils/sync/LocalIndexedDb.js.map +2 -2
  69. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js +88 -40
  70. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js.map +2 -2
  71. package/dist-cjs/version.js +3 -3
  72. package/dist-cjs/version.js.map +1 -1
  73. package/dist-esm/index.d.mts +49 -23
  74. package/dist-esm/index.mjs +4 -2
  75. package/dist-esm/index.mjs.map +2 -2
  76. package/dist-esm/lib/TldrawEditor.mjs +17 -13
  77. package/dist-esm/lib/TldrawEditor.mjs.map +2 -2
  78. package/dist-esm/lib/components/MenuClickCapture.mjs +42 -3
  79. package/dist-esm/lib/components/MenuClickCapture.mjs.map +2 -2
  80. package/dist-esm/lib/components/default-components/DefaultCanvas.mjs +5 -1
  81. package/dist-esm/lib/components/default-components/DefaultCanvas.mjs.map +2 -2
  82. package/dist-esm/lib/components/default-components/DefaultErrorFallback.mjs +2 -5
  83. package/dist-esm/lib/components/default-components/DefaultErrorFallback.mjs.map +3 -3
  84. package/dist-esm/lib/components/default-components/DefaultSpinner.mjs.map +2 -2
  85. package/dist-esm/lib/editor/Editor.mjs +185 -186
  86. package/dist-esm/lib/editor/Editor.mjs.map +3 -3
  87. package/dist-esm/lib/editor/derivations/bindingsIndex.mjs +2 -0
  88. package/dist-esm/lib/editor/derivations/bindingsIndex.mjs.map +2 -2
  89. package/dist-esm/lib/editor/managers/ClickManager/ClickManager.mjs +3 -2
  90. package/dist-esm/lib/editor/managers/ClickManager/ClickManager.mjs.map +2 -2
  91. package/dist-esm/lib/editor/managers/EditorManager.mjs +11 -2
  92. package/dist-esm/lib/editor/managers/EditorManager.mjs.map +2 -2
  93. package/dist-esm/lib/editor/managers/PerformanceManager/PerformanceManager.mjs +49 -63
  94. package/dist-esm/lib/editor/managers/PerformanceManager/PerformanceManager.mjs.map +2 -2
  95. package/dist-esm/lib/editor/managers/ScribbleManager/ScribbleManager.mjs +1 -1
  96. package/dist-esm/lib/editor/managers/ScribbleManager/ScribbleManager.mjs.map +2 -2
  97. package/dist-esm/lib/editor/managers/SnapManager/BoundsSnaps.mjs +24 -24
  98. package/dist-esm/lib/editor/managers/SnapManager/BoundsSnaps.mjs.map +2 -2
  99. package/dist-esm/lib/editor/managers/SnapManager/HandleSnaps.mjs +7 -1
  100. package/dist-esm/lib/editor/managers/SnapManager/HandleSnaps.mjs.map +2 -2
  101. package/dist-esm/lib/editor/managers/SnapManager/SnapManager.mjs +4 -3
  102. package/dist-esm/lib/editor/managers/SnapManager/SnapManager.mjs.map +2 -2
  103. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs +4 -4
  104. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs.map +2 -2
  105. package/dist-esm/lib/editor/shapes/group/GroupShapeUtil.mjs +14 -6
  106. package/dist-esm/lib/editor/shapes/group/GroupShapeUtil.mjs.map +3 -3
  107. package/dist-esm/lib/editor/shapes/shared/resizeBox.mjs +21 -16
  108. package/dist-esm/lib/editor/shapes/shared/resizeBox.mjs.map +2 -2
  109. package/dist-esm/lib/exports/ExportDelay.mjs +11 -3
  110. package/dist-esm/lib/exports/ExportDelay.mjs.map +2 -2
  111. package/dist-esm/lib/exports/FontEmbedder.mjs +25 -11
  112. package/dist-esm/lib/exports/FontEmbedder.mjs.map +2 -2
  113. package/dist-esm/lib/exports/StyleEmbedder.mjs +9 -4
  114. package/dist-esm/lib/exports/StyleEmbedder.mjs.map +2 -2
  115. package/dist-esm/lib/exports/fetchCache.mjs +3 -0
  116. package/dist-esm/lib/exports/fetchCache.mjs.map +2 -2
  117. package/dist-esm/lib/exports/getSvgAsImage.mjs +10 -4
  118. package/dist-esm/lib/exports/getSvgAsImage.mjs.map +2 -2
  119. package/dist-esm/lib/exports/getSvgJsx.mjs +18 -9
  120. package/dist-esm/lib/exports/getSvgJsx.mjs.map +2 -2
  121. package/dist-esm/lib/exports/parseCss.mjs +1 -1
  122. package/dist-esm/lib/exports/parseCss.mjs.map +1 -1
  123. package/dist-esm/lib/hooks/EditorComponentsContext.mjs.map +2 -2
  124. package/dist-esm/lib/hooks/useCanvasEvents.mjs +24 -0
  125. package/dist-esm/lib/hooks/useCanvasEvents.mjs.map +2 -2
  126. package/dist-esm/lib/hooks/useCursor.mjs +12 -8
  127. package/dist-esm/lib/hooks/useCursor.mjs.map +2 -2
  128. package/dist-esm/lib/hooks/useIdentity.mjs +7 -3
  129. package/dist-esm/lib/hooks/useIdentity.mjs.map +3 -3
  130. package/dist-esm/lib/license/LicenseManager.mjs +9 -1
  131. package/dist-esm/lib/license/LicenseManager.mjs.map +2 -2
  132. package/dist-esm/lib/license/LicenseProvider.mjs +13 -5
  133. package/dist-esm/lib/license/LicenseProvider.mjs.map +2 -2
  134. package/dist-esm/lib/utils/debug-flags.mjs +0 -6
  135. package/dist-esm/lib/utils/debug-flags.mjs.map +2 -2
  136. package/dist-esm/lib/utils/deepLinks.mjs +2 -1
  137. package/dist-esm/lib/utils/deepLinks.mjs.map +2 -2
  138. package/dist-esm/lib/utils/sync/LocalIndexedDb.mjs +32 -25
  139. package/dist-esm/lib/utils/sync/LocalIndexedDb.mjs.map +2 -2
  140. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs +89 -41
  141. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs.map +2 -2
  142. package/dist-esm/version.mjs +3 -3
  143. package/dist-esm/version.mjs.map +1 -1
  144. package/editor.css +9 -1
  145. package/package.json +18 -23
  146. package/src/index.ts +5 -1
  147. package/src/lib/TldrawEditor.tsx +35 -21
  148. package/src/lib/components/MenuClickCapture.tsx +55 -4
  149. package/src/lib/components/default-components/DefaultCanvas.tsx +7 -1
  150. package/src/lib/components/default-components/DefaultErrorFallback.tsx +13 -5
  151. package/src/lib/components/default-components/DefaultSpinner.tsx +4 -1
  152. package/src/lib/editor/Editor.test.ts +65 -0
  153. package/src/lib/editor/Editor.ts +299 -303
  154. package/src/lib/editor/derivations/bindingsIndex.ts +3 -0
  155. package/src/lib/editor/managers/ClickManager/ClickManager.test.ts +1 -0
  156. package/src/lib/editor/managers/ClickManager/ClickManager.ts +3 -2
  157. package/src/lib/editor/managers/EditorManager.test.ts +32 -1
  158. package/src/lib/editor/managers/EditorManager.ts +15 -3
  159. package/src/lib/editor/managers/PerformanceManager/PerformanceManager.test.ts +80 -0
  160. package/src/lib/editor/managers/PerformanceManager/PerformanceManager.ts +54 -81
  161. package/src/lib/editor/managers/ScribbleManager/ScribbleManager.ts +1 -1
  162. package/src/lib/editor/managers/SnapManager/BoundsSnaps.ts +32 -36
  163. package/src/lib/editor/managers/SnapManager/HandleSnaps.ts +13 -2
  164. package/src/lib/editor/managers/SnapManager/SnapManager.test.ts +13 -0
  165. package/src/lib/editor/managers/SnapManager/SnapManager.ts +6 -4
  166. package/src/lib/editor/managers/TextManager/TextManager.test.ts +74 -0
  167. package/src/lib/editor/managers/TextManager/TextManager.ts +6 -5
  168. package/src/lib/editor/shapes/group/GroupShapeUtil.tsx +23 -8
  169. package/src/lib/editor/shapes/shared/resizeBox.ts +21 -16
  170. package/src/lib/editor/types/external-content.ts +5 -0
  171. package/src/lib/exports/ExportDelay.tsx +16 -4
  172. package/src/lib/exports/FontEmbedder.test.ts +99 -0
  173. package/src/lib/exports/FontEmbedder.ts +32 -11
  174. package/src/lib/exports/StyleEmbedder.ts +13 -4
  175. package/src/lib/exports/fetchCache.test.ts +22 -0
  176. package/src/lib/exports/fetchCache.ts +4 -0
  177. package/src/lib/exports/getSvgAsImage.ts +13 -5
  178. package/src/lib/exports/getSvgJsx.test.ts +43 -1
  179. package/src/lib/exports/getSvgJsx.tsx +28 -16
  180. package/src/lib/exports/parseCss.test.ts +4 -0
  181. package/src/lib/exports/parseCss.ts +2 -2
  182. package/src/lib/hooks/EditorComponentsContext.tsx +2 -1
  183. package/src/lib/hooks/useCanvasEvents.ts +42 -0
  184. package/src/lib/hooks/useCursor.ts +14 -7
  185. package/src/lib/hooks/useIdentity.tsx +12 -1
  186. package/src/lib/license/LicenseManager.ts +13 -1
  187. package/src/lib/license/LicenseProvider.test.tsx +76 -0
  188. package/src/lib/license/LicenseProvider.tsx +19 -5
  189. package/src/lib/test/preserveFocus.test.tsx +81 -0
  190. package/src/lib/test/useCursor.test.tsx +36 -0
  191. package/src/lib/utils/debug-flags.ts +0 -6
  192. package/src/lib/utils/deepLinks.test.ts +15 -0
  193. package/src/lib/utils/deepLinks.ts +8 -3
  194. package/src/lib/utils/sync/LocalIndexedDb.test.ts +121 -1
  195. package/src/lib/utils/sync/LocalIndexedDb.ts +41 -28
  196. package/src/lib/utils/sync/TLLocalSyncClient.test.ts +330 -1
  197. package/src/lib/utils/sync/TLLocalSyncClient.ts +129 -55
  198. package/src/version.ts +3 -3
  199. package/dist-cjs/lib/primitives/geometry/geometry.bench.js +0 -133
  200. package/dist-cjs/lib/primitives/geometry/geometry.bench.js.map +0 -7
  201. package/dist-esm/lib/primitives/geometry/geometry.bench.mjs +0 -132
  202. package/dist-esm/lib/primitives/geometry/geometry.bench.mjs.map +0 -7
  203. package/src/lib/primitives/geometry/geometry.bench.ts +0 -179
@@ -81,6 +81,21 @@ describe('parseDeepLinkString', () => {
81
81
  expect(() => parseDeepLinkString('v')).toThrow('Invalid deep link string')
82
82
  })
83
83
 
84
+ it('throws on a viewport link with no area', () => {
85
+ expect(() => parseDeepLinkString('v0.0.0.0')).toThrow('Invalid deep link string')
86
+ expect(() => parseDeepLinkString('v100.100.0.200')).toThrow('Invalid deep link string')
87
+ expect(() => parseDeepLinkString('v100.100.200.0')).toThrow('Invalid deep link string')
88
+ expect(() => parseDeepLinkString('v100.100.-200.-100')).toThrow('Invalid deep link string')
89
+ })
90
+
91
+ it('accepts a viewport link positioned at the origin', () => {
92
+ expect(parseDeepLinkString('v0.0.200.100')).toEqual({
93
+ type: 'viewport',
94
+ bounds: new Box(0, 0, 200, 100),
95
+ pageId: undefined,
96
+ })
97
+ })
98
+
84
99
  it('throws on an unknown link type', () => {
85
100
  expect(() => parseDeepLinkString('xabc')).toThrow('Invalid deep link string')
86
101
  })
@@ -74,9 +74,14 @@ export function parseDeepLinkString(deepLinkString: string): TLDeepLink {
74
74
  case 'v': {
75
75
  const [x, y, w, h, pageId] = deepLinkString.slice(1).split('.')
76
76
  const bounds = new Box(Number(x), Number(y), Number(w), Number(h))
77
- // Number('abc') is NaN rather than an error, so without this check a malformed
78
- // viewport link would bypass the caller's fallback and park the camera at the origin
79
- if (![bounds.x, bounds.y, bounds.w, bounds.h].every(Number.isFinite)) {
77
+ // Number('abc') is NaN rather than an error, and a box with no area parses cleanly but
78
+ // can only be zoomed to by clamping to max zoom at its corner. Both bypass the caller's
79
+ // fallback and park the camera at the origin, so both count as an invalid link here.
80
+ const isUsableViewport =
81
+ [bounds.x, bounds.y, bounds.w, bounds.h].every(Number.isFinite) &&
82
+ bounds.w > 0 &&
83
+ bounds.h > 0
84
+ if (!isUsableViewport) {
80
85
  throw Error('Invalid deep link string')
81
86
  }
82
87
  return {
@@ -1,5 +1,5 @@
1
1
  import { createTLSchema } from '@tldraw/tlschema'
2
- import { openDB } from 'idb'
2
+ import { deleteDB, openDB } from 'idb'
3
3
  import { vi } from 'vitest'
4
4
  import { hardReset } from './hardReset'
5
5
  import { getAllIndexDbNames, LocalIndexedDb } from './LocalIndexedDb'
@@ -10,6 +10,7 @@ describe('LocalIndexedDb', () => {
10
10
  vi.useRealTimers()
11
11
  })
12
12
  afterEach(async () => {
13
+ vi.restoreAllMocks()
13
14
  await hardReset({ shouldReload: false })
14
15
  })
15
16
  describe('#storeSnapshot', () => {
@@ -106,6 +107,34 @@ describe('LocalIndexedDb', () => {
106
107
  })
107
108
  })
108
109
 
110
+ it('commits a write that is still in flight when the db is closed', async () => {
111
+ const db = new LocalIndexedDb('test-0')
112
+ const write = db.storeSnapshot({ schema, snapshot: { 'shape:1': { id: 'shape:1' } } })
113
+ await db.close()
114
+ await write
115
+
116
+ const reopened = new LocalIndexedDb('test-0')
117
+ expect((await reopened.load())?.records).toEqual([{ id: 'shape:1' }])
118
+ await reopened.close()
119
+ })
120
+
121
+ it('rejects a transaction that aborts after its requests succeeded while closing', async () => {
122
+ const db = new LocalIndexedDb('test-0')
123
+ let closing: Promise<void> | undefined
124
+ // A commit can fail after every request succeeded, so the request promises cannot report it.
125
+ // @ts-expect-error Exercise the transaction boundary directly to inject a commit failure.
126
+ const write = db.tx('readwrite', ['records'], async (tx) => {
127
+ await tx.objectStore('records').put({ id: 'shape:1' }, 'shape:1')
128
+ closing = db.close()
129
+ tx.abort()
130
+ })
131
+ try {
132
+ await expect(write).rejects.toMatchObject({ name: 'AbortError' })
133
+ } finally {
134
+ await closing
135
+ }
136
+ })
137
+
109
138
  describe('#storeChanges', () => {
110
139
  it('allows merging changes into an existing store', async () => {
111
140
  const db = new LocalIndexedDb('test-0')
@@ -174,6 +203,72 @@ describe('LocalIndexedDb', () => {
174
203
  })
175
204
  })
176
205
 
206
+ describe('#pruneSessions', () => {
207
+ it('keeps the 10 most recent session rows and the current session', async () => {
208
+ const db = new LocalIndexedDb('test-0')
209
+ let now = 1000
210
+ vi.spyOn(Date, 'now').mockImplementation(() => now++)
211
+
212
+ // the current session is the oldest row of 14
213
+ const sessionIds = ['current', ...Array.from({ length: 13 }, (_, i) => `other-${i}`)]
214
+ for (const sessionId of sessionIds) {
215
+ await db.storeChanges({
216
+ schema,
217
+ changes: { added: {}, updated: {}, removed: {} },
218
+ sessionId,
219
+ sessionStateSnapshot: { sessionId } as any,
220
+ })
221
+ }
222
+
223
+ await db.pruneSessions({ keepSessionId: 'current' })
224
+
225
+ const remaining = await Promise.all(
226
+ sessionIds.map(async (sessionId) => [
227
+ sessionId,
228
+ ((await db.load({ sessionId })).sessionStateSnapshot as any)?.sessionId === sessionId,
229
+ ])
230
+ )
231
+ expect(Object.fromEntries(remaining)).toEqual({
232
+ current: true,
233
+ 'other-0': false,
234
+ 'other-1': false,
235
+ 'other-2': false,
236
+ 'other-3': true,
237
+ 'other-4': true,
238
+ 'other-5': true,
239
+ 'other-6': true,
240
+ 'other-7': true,
241
+ 'other-8': true,
242
+ 'other-9': true,
243
+ 'other-10': true,
244
+ 'other-11': true,
245
+ 'other-12': true,
246
+ })
247
+
248
+ await db.close()
249
+ })
250
+
251
+ it('is a no-op when there are at most 10 rows', async () => {
252
+ const db = new LocalIndexedDb('test-0')
253
+ for (let i = 0; i < 10; i++) {
254
+ await db.storeChanges({
255
+ schema,
256
+ changes: { added: {}, updated: {}, removed: {} },
257
+ sessionId: `session-${i}`,
258
+ sessionStateSnapshot: { i } as any,
259
+ })
260
+ }
261
+
262
+ await db.pruneSessions()
263
+
264
+ for (let i = 0; i < 10; i++) {
265
+ expect((await db.load({ sessionId: `session-${i}` })).sessionStateSnapshot).toEqual({ i })
266
+ }
267
+
268
+ await db.close()
269
+ })
270
+ })
271
+
177
272
  it('migrates legacy asset storage into the new format', async () => {
178
273
  const legacyAssetsDb = await openDB('TLDRAW_ASSET_STORE_v1test-0', 1, {
179
274
  upgrade(database) {
@@ -239,4 +334,29 @@ describe('LocalIndexedDb', () => {
239
334
  (await window.indexedDB.databases()).find((db) => db.name === 'TLDRAW_ASSET_STORE_v1test-0')
240
335
  ).toBeUndefined()
241
336
  })
337
+
338
+ it('closes its connection so another tab can delete the database', async () => {
339
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
340
+ const db = new LocalIndexedDb('test-0')
341
+ await db.storeSnapshot({ schema, snapshot: {} })
342
+
343
+ // Simulates a hard reset from another tab. Without the blocking handler this never
344
+ // resolves because our open connection blocks the delete.
345
+ let timeout: ReturnType<typeof setTimeout>
346
+ const result = await Promise.race([
347
+ deleteDB('TLDRAW_DOCUMENT_v2test-0').then(() => 'deleted'),
348
+ new Promise<string>((resolve) => {
349
+ timeout = setTimeout(() => resolve('blocked'), 1000)
350
+ }),
351
+ ])
352
+ clearTimeout(timeout!)
353
+ expect(result).toBe('deleted')
354
+ expect(warn).toHaveBeenCalledWith(
355
+ 'Closing TLDRAW_DOCUMENT_v2test-0 so another tab can delete or upgrade it'
356
+ )
357
+ warn.mockRestore()
358
+
359
+ // the next write on the closed connection surfaces as an error rather than hanging
360
+ await expect(db.storeSnapshot({ schema, snapshot: {} })).rejects.toThrow()
361
+ })
242
362
  })
@@ -9,6 +9,9 @@ const STORE_PREFIX = 'TLDRAW_DOCUMENT_v2'
9
9
  const LEGACY_ASSET_STORE_PREFIX = 'TLDRAW_ASSET_STORE_v1'
10
10
  const dbNameIndexKey = 'TLDRAW_DB_NAME_INDEX_v2'
11
11
 
12
+ /** How many session state rows (one per tab) to keep per document when pruning. */
13
+ const MAX_SESSION_STATE_ROWS = 10
14
+
12
15
  /** @internal */
13
16
  export const Table = {
14
17
  Records: 'records',
@@ -25,7 +28,7 @@ async function openLocalDb(persistenceKey: string) {
25
28
 
26
29
  addDbName(storeId)
27
30
 
28
- return await openDB<StoreName>(storeId, 4, {
31
+ const db = await openDB<StoreName>(storeId, 4, {
29
32
  upgrade(database) {
30
33
  if (!database.objectStoreNames.contains(Table.Records)) {
31
34
  database.createObjectStore(Table.Records)
@@ -40,7 +43,16 @@ async function openLocalDb(persistenceKey: string) {
40
43
  database.createObjectStore(Table.Assets)
41
44
  }
42
45
  },
46
+ // Another tab is deleting (hard reset) or upgrading this database. Its request waits
47
+ // until every open connection closes, so holding ours would stall it indefinitely.
48
+ // Closing here lets it proceed; this tab's next write then fails and goes through
49
+ // the write-failure alert-and-reload path.
50
+ blocking() {
51
+ console.warn(`Closing ${storeId} so another tab can delete or upgrade it`)
52
+ db.close()
53
+ },
43
54
  })
55
+ return db
44
56
  }
45
57
 
46
58
  async function migrateLegacyAssetDbIfNeeded(persistenceKey: string) {
@@ -141,26 +153,22 @@ export class LocalIndexedDb {
141
153
  assert(!this.isClosed, 'db is closed')
142
154
  const db = await this.getDb()
143
155
  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
- })
156
+ // Commit failures may arrive before the callback finishes; observe them immediately
157
+ // while preserving the rejection for the await below.
158
+ const done = tx.done
159
+ done.catch(noop)
152
160
  try {
153
161
  return await cb(tx)
154
162
  } finally {
155
- if (!this.isClosed) {
156
- await done
157
- } else {
158
- tx.abort()
159
- }
163
+ // let the transaction commit even if close() was called meanwhile, otherwise a
164
+ // persist racing an unmount is silently rolled back
165
+ await done
160
166
  }
161
167
  })()
162
168
  this.pendingTransactionSet.add(txPromise)
163
- txPromise.finally(() => this.pendingTransactionSet.delete(txPromise))
169
+ // not `.finally()`: the promise it returns would re-reject with nobody observing it
170
+ const cleanup = () => this.pendingTransactionSet.delete(txPromise)
171
+ txPromise.then(cleanup, cleanup)
164
172
  return txPromise
165
173
  }
166
174
 
@@ -208,17 +216,19 @@ export class LocalIndexedDb {
208
216
  const schemaStore = tx.objectStore(Table.Schema)
209
217
  const sessionStateStore = tx.objectStore(Table.SessionState)
210
218
 
219
+ const requests: Promise<unknown>[] = []
211
220
  for (const [id, record] of Object.entries(changes.added)) {
212
- await recordsStore.put(record, id)
221
+ requests.push(recordsStore.put(record, id))
213
222
  }
214
223
 
215
224
  for (const [_prev, updated] of Object.values(changes.updated)) {
216
- await recordsStore.put(updated, updated.id)
225
+ requests.push(recordsStore.put(updated, updated.id))
217
226
  }
218
227
 
219
228
  for (const id of Object.keys(changes.removed)) {
220
- await recordsStore.delete(id)
229
+ requests.push(recordsStore.delete(id))
221
230
  }
231
+ await Promise.all(requests)
222
232
 
223
233
  schemaStore.put(schema.serialize(), Table.Schema)
224
234
  if (sessionStateSnapshot && sessionId) {
@@ -254,9 +264,9 @@ export class LocalIndexedDb {
254
264
 
255
265
  await recordsStore.clear()
256
266
 
257
- for (const [id, record] of Object.entries(snapshot)) {
258
- await recordsStore.put(record, id)
259
- }
267
+ await Promise.all(
268
+ Object.entries(snapshot).map(([id, record]) => recordsStore.put(record, id))
269
+ )
260
270
 
261
271
  schemaStore.put(schema.serialize(), Table.Schema)
262
272
 
@@ -275,15 +285,18 @@ export class LocalIndexedDb {
275
285
  })
276
286
  }
277
287
 
278
- async pruneSessions() {
288
+ /**
289
+ * Drop all but the most recently updated session state rows. The row for `keepSessionId` is never
290
+ * deleted: it may be an old row that this tab restored its state from and has not rewritten yet,
291
+ * and deleting it would make a later reload fall back to another tab's session state.
292
+ */
293
+ async pruneSessions({ keepSessionId }: { keepSessionId?: string } = {}) {
279
294
  await this.tx('readwrite', [Table.SessionState], async (tx) => {
280
295
  const sessionStateStore = tx.objectStore(Table.SessionState)
281
- const all = (await sessionStateStore.getAll()).sort((a, b) => a.updatedAt - b.updatedAt)
282
- if (all.length < 10) {
283
- await tx.done
284
- return
285
- }
286
- const toDelete = all.slice(0, all.length - 10)
296
+ const all = ((await sessionStateStore.getAll()) as SessionStateSnapshotRow[])
297
+ .filter((row) => row.id !== keepSessionId)
298
+ .sort((a, b) => a.updatedAt - b.updatedAt)
299
+ const toDelete = all.slice(0, Math.max(0, all.length - MAX_SESSION_STATE_ROWS))
287
300
  for (const { id } of toDelete) {
288
301
  await sessionStateStore.delete(id)
289
302
  }
@@ -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 {
@@ -38,9 +39,12 @@ function testClient(channel = new BroadcastChannelMock('test')) {
38
39
 
39
40
  client.db.storeSnapshot = vi.fn(() => Promise.resolve())
40
41
  client.db.storeChanges = vi.fn(() => Promise.resolve())
42
+ client.db.pruneSessions = vi.fn(() => Promise.resolve())
41
43
 
42
44
  return {
43
- client: client as { db: { storeSnapshot: Mock; storeChanges: Mock } } & typeof client,
45
+ client: client as {
46
+ db: { storeSnapshot: Mock; storeChanges: Mock; pruneSessions: Mock }
47
+ } & typeof client,
44
48
  store,
45
49
  onLoad,
46
50
  onLoadError,
@@ -83,6 +87,23 @@ test('the client connects on instantiation, announcing its schema', async () =>
83
87
  expect(msg).toMatchObject({ type: 'announce', schema: {} })
84
88
  })
85
89
 
90
+ test('the client prunes stale session state rows after loading, keeping its own', async () => {
91
+ const { client, onLoad, tick } = testClient()
92
+ expect(client.db.pruneSessions).not.toHaveBeenCalled()
93
+ await tick()
94
+ expect(onLoad).toHaveBeenCalledTimes(1)
95
+ expect(client.db.pruneSessions).toHaveBeenCalledTimes(1)
96
+ expect(client.db.pruneSessions).toHaveBeenCalledWith({ keepSessionId: client.sessionId })
97
+ })
98
+
99
+ test('a failed session prune does not fail the load', async () => {
100
+ const { client, onLoad, onLoadError, tick } = testClient()
101
+ client.db.pruneSessions.mockImplementation(() => Promise.reject(new Error('nope')))
102
+ await tick()
103
+ expect(onLoad).toHaveBeenCalledTimes(1)
104
+ expect(onLoadError).not.toHaveBeenCalled()
105
+ })
106
+
86
107
  test('when a client receives an announce with a newer schema version it reloads itself', async () => {
87
108
  const { client, channel, onLoadError, tick } = testClient()
88
109
  await tick()
@@ -214,6 +235,73 @@ test('pagehide does not write before the initial load has completed', async () =
214
235
  expect(client.db.storeChanges).not.toHaveBeenCalled()
215
236
  })
216
237
 
238
+ test('diffs received while the client is still loading are applied once it has loaded', async () => {
239
+ const { client, channel, tick } = testClient()
240
+ const remotePage = PageRecordType.create({ name: 'remote', index: 'a0' as IndexKey })
241
+ channel.onmessage?.({
242
+ data: {
243
+ type: 'diff',
244
+ storeId: 'other-tab',
245
+ schema: client.serializedSchema,
246
+ changes: { added: { [remotePage.id]: remotePage }, updated: {}, removed: {} },
247
+ },
248
+ } as any)
249
+ expect(client.store.get(remotePage.id)).toBeUndefined()
250
+
251
+ await tick()
252
+ expect(client.store.get(remotePage.id)).toEqual(remotePage)
253
+
254
+ // and the first (full) db write includes them rather than overwriting them
255
+ client.store.put([PageRecordType.create({ name: 'local', index: 'a1' as IndexKey })])
256
+ await tick()
257
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
258
+ expect(client.db.storeSnapshot.mock.calls[0][0].snapshot[remotePage.id]).toEqual(remotePage)
259
+ })
260
+
261
+ test('closing the client persists changes that are still queued', async () => {
262
+ const { client, tick } = testClient()
263
+ await tick()
264
+ client.store.put([PageRecordType.create({ name: 'test', index: 'a0' as IndexKey })])
265
+ expect(client.db.storeSnapshot).not.toHaveBeenCalled()
266
+
267
+ // close before the throttled persist fires
268
+ client.close()
269
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
270
+ })
271
+
272
+ test('closing the client while a persist is in flight still persists edits queued during the write', async () => {
273
+ const idbOperationResult = promiseWithResolve<void>()
274
+ const { client, tick } = testClient()
275
+ client.db.storeSnapshot.mockImplementationOnce(() => idbOperationResult)
276
+ const closeDb = vi.spyOn(client.db, 'close')
277
+
278
+ await tick()
279
+ client.store.put([PageRecordType.create({ name: 'test', index: 'a0' as IndexKey })])
280
+ await tick()
281
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
282
+
283
+ // an edit made while the first write is still in flight, then unmount
284
+ const page = PageRecordType.create({ name: 'test2', index: 'a1' as IndexKey })
285
+ client.store.put([page])
286
+ client.close()
287
+ expect(client.db.storeChanges).not.toHaveBeenCalled()
288
+ expect(closeDb).not.toHaveBeenCalled()
289
+
290
+ idbOperationResult.resolve()
291
+ await tick()
292
+ expect(client.db.storeChanges).toHaveBeenCalledTimes(1)
293
+ expect(client.db.storeChanges.mock.calls[0][0].changes.added[page.id]).toEqual(page)
294
+ expect(closeDb).toHaveBeenCalledTimes(1)
295
+ })
296
+
297
+ test('closing the client with nothing queued does not write to the db', async () => {
298
+ const { client, tick } = testClient()
299
+ await tick()
300
+ client.close()
301
+ expect(client.db.storeSnapshot).not.toHaveBeenCalled()
302
+ expect(client.db.storeChanges).not.toHaveBeenCalled()
303
+ })
304
+
217
305
  test('pagehide and visibilitychange listeners are removed when the client closes', async () => {
218
306
  const removeWindowListener = vi.spyOn(window, 'removeEventListener')
219
307
  const removeDocumentListener = vi.spyOn(document, 'removeEventListener')
@@ -228,3 +316,244 @@ test('pagehide and visibilitychange listeners are removed when the client closes
228
316
  removeDocumentListener.mockRestore()
229
317
  }
230
318
  })
319
+
320
+ test('closing the client before it has loaded does not write to the db', async () => {
321
+ const { client, tick } = testClient()
322
+ client.close()
323
+ await tick()
324
+ expect(client.db.storeSnapshot).not.toHaveBeenCalled()
325
+ expect(client.db.storeChanges).not.toHaveBeenCalled()
326
+ })
327
+
328
+ test('closing flushes changes that have not reached the next animation frame', async () => {
329
+ const { client, tick } = testClient()
330
+ await tick()
331
+ const page = PageRecordType.create({ name: 'last frame', index: 'a0' as IndexKey })
332
+ vi.stubGlobal('__FORCE_RAF_IN_TESTS__', true)
333
+ try {
334
+ client.store.put([page])
335
+ client.close()
336
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
337
+ expect(client.db.storeSnapshot.mock.calls[0][0].snapshot[page.id]).toEqual(page)
338
+ } finally {
339
+ vi.unstubAllGlobals()
340
+ }
341
+ })
342
+
343
+ test('buffered schema announcements cannot persist before the remaining buffered diffs', async () => {
344
+ const { client, channel, tick } = testClient()
345
+ const page = PageRecordType.create({ name: 'remote', index: 'a0' as IndexKey })
346
+ const schema = client.store.schema.serialize()
347
+ channel.onmessage?.({
348
+ data: {
349
+ type: 'announce',
350
+ schema: { ...schema, sequences: { ...schema.sequences, 'com.tldraw.page': 0 } },
351
+ },
352
+ } as MessageEvent)
353
+ channel.onmessage?.({
354
+ data: {
355
+ type: 'diff',
356
+ storeId: 'other-tab',
357
+ schema: client.serializedSchema,
358
+ changes: { added: { [page.id]: page }, updated: {}, removed: {} },
359
+ },
360
+ } as MessageEvent)
361
+ await tick()
362
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
363
+ expect(client.db.storeSnapshot.mock.calls[0][0].snapshot[page.id]).toEqual(page)
364
+ client.close()
365
+ })
366
+
367
+ test('closing before load cancels a persist scheduled by an early edit', async () => {
368
+ const load = promiseWithResolve<Awaited<ReturnType<LocalIndexedDb['load']>>>()
369
+ const loadMock = vi.spyOn(LocalIndexedDb.prototype, 'load').mockImplementationOnce(() => load)
370
+ try {
371
+ const { client, tick } = testClient()
372
+ client.store.put([PageRecordType.create({ name: 'early', index: 'a0' as IndexKey })])
373
+ client.close()
374
+ load.resolve({ records: [], schema: undefined, sessionStateSnapshot: undefined })
375
+ await tick()
376
+ expect(client.db.storeSnapshot).not.toHaveBeenCalled()
377
+ expect(client.db.storeChanges).not.toHaveBeenCalled()
378
+ } finally {
379
+ loadMock.mockRestore()
380
+ }
381
+ })
382
+
383
+ test.each(['close flush', 'in-flight write'] as const)(
384
+ 'a failed %s after close logs the error without disrupting the current page',
385
+ async (when) => {
386
+ const { client, tick } = testClient()
387
+ await tick()
388
+ const write = promiseWithResolve<void>()
389
+ client.db.storeSnapshot.mockImplementationOnce(() => write)
390
+ const error = new Error('write failed')
391
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})
392
+ const alert = vi.spyOn(window, 'alert').mockImplementation(() => {})
393
+ try {
394
+ client.store.put([PageRecordType.create({ name: 'last edit', index: 'a0' as IndexKey })])
395
+ if (when === 'in-flight write') await tick()
396
+ client.close()
397
+ write.reject(error)
398
+ await tick()
399
+ expect(log).toHaveBeenCalledWith('failed to store changes in indexed db', error)
400
+ expect(alert).not.toHaveBeenCalled()
401
+ expect(reloadMock).not.toHaveBeenCalled()
402
+ } finally {
403
+ log.mockRestore()
404
+ alert.mockRestore()
405
+ }
406
+ }
407
+ )
408
+
409
+ test('closing with no queued changes cancels a failed-write retry', async () => {
410
+ const { client, tick } = testClient()
411
+ await tick()
412
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})
413
+ const alert = vi.spyOn(window, 'alert').mockImplementation(() => {})
414
+ try {
415
+ client.db.storeSnapshot.mockRejectedValueOnce(new Error('first write failed'))
416
+ client.store.put([PageRecordType.create({ name: 'retry', index: 'a0' as IndexKey })])
417
+ await tick()
418
+ expect(reloadMock).toHaveBeenCalledTimes(1)
419
+ client.close()
420
+ await vi.advanceTimersByTimeAsync(10_000)
421
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1)
422
+ } finally {
423
+ log.mockRestore()
424
+ alert.mockRestore()
425
+ }
426
+ })
427
+
428
+ test('a schema mismatch does not try to refresh without a window', async () => {
429
+ const { client, channel, tick } = testClient()
430
+ await tick()
431
+ vi.advanceTimersByTime(10_000)
432
+ vi.stubGlobal('window', undefined)
433
+ try {
434
+ expect(() =>
435
+ channel.onmessage?.({
436
+ data: {
437
+ type: 'announce',
438
+ schema: {
439
+ ...client.serializedSchema,
440
+ schemaVersion: client.serializedSchema.schemaVersion + 1,
441
+ },
442
+ },
443
+ } as MessageEvent)
444
+ ).not.toThrow()
445
+ } finally {
446
+ vi.unstubAllGlobals()
447
+ client.close()
448
+ }
449
+ })
450
+
451
+ test('onLoad can close the client without losing buffered remote changes', async () => {
452
+ const { client, channel, onLoad, tick } = testClient()
453
+ const page = PageRecordType.create({ name: 'remote', index: 'a0' as IndexKey })
454
+ channel.onmessage?.({
455
+ data: {
456
+ type: 'diff',
457
+ storeId: 'other-tab',
458
+ schema: client.serializedSchema,
459
+ changes: { added: { [page.id]: page }, updated: {}, removed: {} },
460
+ },
461
+ } as MessageEvent)
462
+ onLoad.mockImplementation(() => {
463
+ client.store.put([PageRecordType.create({ name: 'local', index: 'a1' as IndexKey })])
464
+ client.close()
465
+ })
466
+ await tick()
467
+ expect(client.db.storeSnapshot.mock.calls[0][0].snapshot[page.id]).toEqual(page)
468
+ })
469
+
470
+ test('a buffered newer schema reports a load error without announcing a successful load', async () => {
471
+ const { client, channel, onLoad, onLoadError, tick } = testClient()
472
+ channel.onmessage?.({
473
+ data: {
474
+ type: 'announce',
475
+ schema: {
476
+ ...client.serializedSchema,
477
+ schemaVersion: client.serializedSchema.schemaVersion + 1,
478
+ },
479
+ },
480
+ } as MessageEvent)
481
+ await tick()
482
+ expect(onLoadError).toHaveBeenCalledTimes(1)
483
+ expect(onLoad).not.toHaveBeenCalled()
484
+ client.close()
485
+ expect(client.db.storeSnapshot).not.toHaveBeenCalled()
486
+ })
487
+
488
+ test('a client created on the same key while a closed client is still flushing waits for that flush', async () => {
489
+ const inFlightWrite = promiseWithResolve<void>()
490
+ const { client, tick } = testClient()
491
+ client.db.storeSnapshot.mockImplementationOnce(() => inFlightWrite)
492
+ await tick()
493
+ client.store.put([PageRecordType.create({ name: 'first', index: 'a0' as IndexKey })])
494
+ await tick()
495
+ expect(client.db.storeSnapshot).toHaveBeenCalledTimes(1) // still in flight
496
+ client.store.put([PageRecordType.create({ name: 'during write', index: 'a1' as IndexKey })])
497
+ client.close()
498
+
499
+ // remount on the same key while the old client is still flushing
500
+ const loadSpy = vi.spyOn(LocalIndexedDb.prototype, 'load')
501
+ const next = testClient()
502
+ await tick()
503
+ // reading now would miss the queued edit, then erase it on the first write
504
+ expect(loadSpy).not.toHaveBeenCalled()
505
+ expect(next.onLoad).not.toHaveBeenCalled()
506
+
507
+ inFlightWrite.resolve()
508
+ await tick()
509
+ expect(client.db.storeChanges).toHaveBeenCalledTimes(1)
510
+ for (let i = 0; i < 20; i++) await Promise.resolve()
511
+ await next.tick()
512
+ expect(loadSpy).toHaveBeenCalledTimes(1)
513
+ expect(next.onLoad).toHaveBeenCalledTimes(1)
514
+ loadSpy.mockRestore()
515
+ })
516
+
517
+ test('two clients closing on the same key flush in order', async () => {
518
+ const writes: string[] = []
519
+ const inFlightWrite = promiseWithResolve<void>()
520
+
521
+ const a = testClient()
522
+ const b = testClient()
523
+ await a.tick()
524
+ await b.tick()
525
+ // hold a's first write in flight
526
+ a.client.db.storeSnapshot.mockImplementation(() => {
527
+ writes.push('a')
528
+ return inFlightWrite
529
+ })
530
+ a.client.db.storeChanges.mockImplementation(() => {
531
+ writes.push('a')
532
+ return Promise.resolve()
533
+ })
534
+ b.client.db.storeSnapshot.mockImplementation(() => {
535
+ writes.push('b')
536
+ return Promise.resolve()
537
+ })
538
+ b.client.db.storeChanges.mockImplementation(() => {
539
+ writes.push('b')
540
+ return Promise.resolve()
541
+ })
542
+
543
+ a.client.store.put([PageRecordType.create({ name: 'a1', index: 'a0' as IndexKey })])
544
+ await a.tick()
545
+ expect(writes).toEqual(['a']) // in flight
546
+ a.client.store.put([PageRecordType.create({ name: 'a2', index: 'a1' as IndexKey })])
547
+ a.client.close()
548
+
549
+ b.client.store.put([PageRecordType.create({ name: 'b1', index: 'a2' as IndexKey })])
550
+ b.client.close()
551
+ await b.tick()
552
+ // b's snapshot landing first would lose a's queued changes
553
+ expect(writes).toEqual(['a'])
554
+
555
+ inFlightWrite.resolve()
556
+ await a.tick()
557
+ await b.tick()
558
+ expect(writes).toEqual(['a', 'a', 'b'])
559
+ })