@tldraw/editor 5.5.0-next.b6a9f7cd7be2 → 5.5.0-next.c91b2de0a423

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 (96) hide show
  1. package/dist-cjs/index.d.ts +47 -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.map +2 -2
  5. package/dist-cjs/lib/components/default-components/DefaultCanvas.js +5 -1
  6. package/dist-cjs/lib/components/default-components/DefaultCanvas.js.map +2 -2
  7. package/dist-cjs/lib/components/default-components/DefaultErrorFallback.js +2 -5
  8. package/dist-cjs/lib/components/default-components/DefaultErrorFallback.js.map +3 -3
  9. package/dist-cjs/lib/components/default-components/DefaultSpinner.js.map +2 -2
  10. package/dist-cjs/lib/editor/Editor.js +24 -26
  11. package/dist-cjs/lib/editor/Editor.js.map +2 -2
  12. package/dist-cjs/lib/editor/managers/ClickManager/ClickManager.js +3 -2
  13. package/dist-cjs/lib/editor/managers/ClickManager/ClickManager.js.map +2 -2
  14. package/dist-cjs/lib/editor/managers/EditorManager.js +11 -2
  15. package/dist-cjs/lib/editor/managers/EditorManager.js.map +2 -2
  16. package/dist-cjs/lib/editor/managers/PerformanceManager/PerformanceManager.js +49 -63
  17. package/dist-cjs/lib/editor/managers/PerformanceManager/PerformanceManager.js.map +2 -2
  18. package/dist-cjs/lib/editor/managers/ScribbleManager/ScribbleManager.js +1 -1
  19. package/dist-cjs/lib/editor/managers/ScribbleManager/ScribbleManager.js.map +2 -2
  20. package/dist-cjs/lib/editor/managers/SnapManager/BoundsSnaps.js +24 -24
  21. package/dist-cjs/lib/editor/managers/SnapManager/BoundsSnaps.js.map +2 -2
  22. package/dist-cjs/lib/editor/managers/SnapManager/HandleSnaps.js +7 -1
  23. package/dist-cjs/lib/editor/managers/SnapManager/HandleSnaps.js.map +2 -2
  24. package/dist-cjs/lib/editor/managers/SnapManager/SnapManager.js +4 -3
  25. package/dist-cjs/lib/editor/managers/SnapManager/SnapManager.js.map +2 -2
  26. package/dist-cjs/lib/editor/types/external-content.js.map +1 -1
  27. package/dist-cjs/lib/hooks/EditorComponentsContext.js.map +2 -2
  28. package/dist-cjs/lib/utils/debug-flags.js +0 -6
  29. package/dist-cjs/lib/utils/debug-flags.js.map +2 -2
  30. package/dist-cjs/lib/utils/sync/LocalIndexedDb.js +19 -8
  31. package/dist-cjs/lib/utils/sync/LocalIndexedDb.js.map +2 -2
  32. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js +3 -0
  33. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js.map +2 -2
  34. package/dist-cjs/version.js +3 -3
  35. package/dist-cjs/version.js.map +1 -1
  36. package/dist-esm/index.d.mts +47 -23
  37. package/dist-esm/index.mjs +4 -2
  38. package/dist-esm/index.mjs.map +2 -2
  39. package/dist-esm/lib/TldrawEditor.mjs.map +2 -2
  40. package/dist-esm/lib/components/default-components/DefaultCanvas.mjs +5 -1
  41. package/dist-esm/lib/components/default-components/DefaultCanvas.mjs.map +2 -2
  42. package/dist-esm/lib/components/default-components/DefaultErrorFallback.mjs +2 -5
  43. package/dist-esm/lib/components/default-components/DefaultErrorFallback.mjs.map +3 -3
  44. package/dist-esm/lib/components/default-components/DefaultSpinner.mjs.map +2 -2
  45. package/dist-esm/lib/editor/Editor.mjs +24 -26
  46. package/dist-esm/lib/editor/Editor.mjs.map +2 -2
  47. package/dist-esm/lib/editor/managers/ClickManager/ClickManager.mjs +3 -2
  48. package/dist-esm/lib/editor/managers/ClickManager/ClickManager.mjs.map +2 -2
  49. package/dist-esm/lib/editor/managers/EditorManager.mjs +11 -2
  50. package/dist-esm/lib/editor/managers/EditorManager.mjs.map +2 -2
  51. package/dist-esm/lib/editor/managers/PerformanceManager/PerformanceManager.mjs +49 -63
  52. package/dist-esm/lib/editor/managers/PerformanceManager/PerformanceManager.mjs.map +2 -2
  53. package/dist-esm/lib/editor/managers/ScribbleManager/ScribbleManager.mjs +1 -1
  54. package/dist-esm/lib/editor/managers/ScribbleManager/ScribbleManager.mjs.map +2 -2
  55. package/dist-esm/lib/editor/managers/SnapManager/BoundsSnaps.mjs +24 -24
  56. package/dist-esm/lib/editor/managers/SnapManager/BoundsSnaps.mjs.map +2 -2
  57. package/dist-esm/lib/editor/managers/SnapManager/HandleSnaps.mjs +7 -1
  58. package/dist-esm/lib/editor/managers/SnapManager/HandleSnaps.mjs.map +2 -2
  59. package/dist-esm/lib/editor/managers/SnapManager/SnapManager.mjs +4 -3
  60. package/dist-esm/lib/editor/managers/SnapManager/SnapManager.mjs.map +2 -2
  61. package/dist-esm/lib/hooks/EditorComponentsContext.mjs.map +2 -2
  62. package/dist-esm/lib/utils/debug-flags.mjs +0 -6
  63. package/dist-esm/lib/utils/debug-flags.mjs.map +2 -2
  64. package/dist-esm/lib/utils/sync/LocalIndexedDb.mjs +19 -8
  65. package/dist-esm/lib/utils/sync/LocalIndexedDb.mjs.map +2 -2
  66. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs +3 -0
  67. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs.map +2 -2
  68. package/dist-esm/version.mjs +3 -3
  69. package/dist-esm/version.mjs.map +1 -1
  70. package/package.json +7 -7
  71. package/src/index.ts +5 -1
  72. package/src/lib/TldrawEditor.tsx +8 -6
  73. package/src/lib/components/default-components/DefaultCanvas.tsx +7 -1
  74. package/src/lib/components/default-components/DefaultErrorFallback.tsx +13 -5
  75. package/src/lib/components/default-components/DefaultSpinner.tsx +4 -1
  76. package/src/lib/editor/Editor.test.ts +45 -0
  77. package/src/lib/editor/Editor.ts +40 -35
  78. package/src/lib/editor/managers/ClickManager/ClickManager.test.ts +1 -0
  79. package/src/lib/editor/managers/ClickManager/ClickManager.ts +3 -2
  80. package/src/lib/editor/managers/EditorManager.test.ts +32 -1
  81. package/src/lib/editor/managers/EditorManager.ts +15 -3
  82. package/src/lib/editor/managers/PerformanceManager/PerformanceManager.test.ts +80 -0
  83. package/src/lib/editor/managers/PerformanceManager/PerformanceManager.ts +54 -81
  84. package/src/lib/editor/managers/ScribbleManager/ScribbleManager.ts +1 -1
  85. package/src/lib/editor/managers/SnapManager/BoundsSnaps.ts +32 -36
  86. package/src/lib/editor/managers/SnapManager/HandleSnaps.ts +13 -2
  87. package/src/lib/editor/managers/SnapManager/SnapManager.test.ts +13 -0
  88. package/src/lib/editor/managers/SnapManager/SnapManager.ts +6 -4
  89. package/src/lib/editor/types/external-content.ts +5 -0
  90. package/src/lib/hooks/EditorComponentsContext.tsx +2 -1
  91. package/src/lib/utils/debug-flags.ts +0 -6
  92. package/src/lib/utils/sync/LocalIndexedDb.test.ts +93 -1
  93. package/src/lib/utils/sync/LocalIndexedDb.ts +23 -8
  94. package/src/lib/utils/sync/TLLocalSyncClient.test.ts +21 -1
  95. package/src/lib/utils/sync/TLLocalSyncClient.ts +6 -0
  96. package/src/version.ts +3 -3
@@ -1,7 +1,7 @@
1
1
  import type { TLRecord, TLShapeId } from '@tldraw/tlschema'
2
2
  import { bind } from '@tldraw/utils'
3
3
  import EventEmitter from 'eventemitter3'
4
- import type { Editor } from '../../Editor'
4
+ import { EditorManager } from '../EditorManager'
5
5
  import type {
6
6
  TLCameraEndPerfEvent,
7
7
  TLCameraStartPerfEvent,
@@ -14,6 +14,9 @@ import type {
14
14
  TLUndoRedoPerfEvent,
15
15
  } from './perf-types'
16
16
 
17
+ // The editor listeners and observer that are attached only while a subscriber needs them
18
+ type LazyListener = 'frame' | 'loaf' | 'shapes-created' | 'shapes-updated' | 'shapes-deleted'
19
+
17
20
  function percentile(sorted: number[], p: number): number {
18
21
  const idx = Math.ceil(p * sorted.length) - 1
19
22
  return sorted[Math.max(0, idx)]
@@ -71,12 +74,10 @@ function toLoafEntry(entry: PerformanceEntry): TLPerfLongAnimationFrame | null {
71
74
  *
72
75
  * @public
73
76
  */
74
- export class PerformanceManager {
77
+ export class PerformanceManager extends EditorManager {
75
78
  /** @internal */
76
79
  readonly emitter = new EventEmitter<TLPerfEventMap>()
77
80
 
78
- private editor: Editor
79
-
80
81
  // Active interaction tracking
81
82
  private activeInteraction: {
82
83
  name: string
@@ -96,18 +97,8 @@ export class PerformanceManager {
96
97
  loafEntries: TLPerfLongAnimationFrame[]
97
98
  } | null = null
98
99
 
99
- // Lazy listener cleanup functions
100
- private frameCleanup: (() => void) | null = null
101
- private shapeCreatedCleanup: (() => void) | null = null
102
- private shapeEditedCleanup: (() => void) | null = null
103
- private shapeDeletedCleanup: (() => void) | null = null
104
-
105
- // LoAF observer
106
- private loafObserver: PerformanceObserver | null = null
107
-
108
- constructor(editor: Editor) {
109
- this.editor = editor
110
- }
100
+ // Cleanups for whatever is currently attached, keyed so a detach unregisters only its own
101
+ private readonly lazyCleanups = new Map<LazyListener, () => void>()
111
102
 
112
103
  /**
113
104
  * Subscribe to a performance event. Returns an unsubscribe function.
@@ -158,19 +149,12 @@ export class PerformanceManager {
158
149
 
159
150
  /** @internal */
160
151
  dispose() {
161
- if (this.activeCamera?.timeout) clearTimeout(this.activeCamera.timeout)
152
+ if (this.activeCamera?.timeout) this.editor.timers.clearTimeout(this.activeCamera.timeout)
162
153
  this.activeInteraction = null
163
154
  this.activeCamera = null
164
- this.frameCleanup?.()
165
- this.frameCleanup = null
166
- this.shapeCreatedCleanup?.()
167
- this.shapeCreatedCleanup = null
168
- this.shapeEditedCleanup?.()
169
- this.shapeEditedCleanup = null
170
- this.shapeDeletedCleanup?.()
171
- this.shapeDeletedCleanup = null
172
- this._stopLoafObserver()
155
+ this.lazyCleanups.clear()
173
156
  this.emitter.removeAllListeners()
157
+ super.dispose()
174
158
  }
175
159
 
176
160
  // --- Internal notification methods ---
@@ -259,7 +243,7 @@ export class PerformanceManager {
259
243
  if (this.activeCamera) {
260
244
  // Extend existing camera session
261
245
  if (this.activeCamera.timeout) {
262
- clearTimeout(this.activeCamera.timeout)
246
+ this.editor.timers.clearTimeout(this.activeCamera.timeout)
263
247
  }
264
248
  // If type changed, end old and start new
265
249
  if (this.activeCamera.type !== type) {
@@ -313,7 +297,7 @@ export class PerformanceManager {
313
297
  const camera = this.activeCamera
314
298
  if (!camera) return
315
299
  this.activeCamera = null
316
- if (camera.timeout) clearTimeout(camera.timeout)
300
+ if (camera.timeout) this.editor.timers.clearTimeout(camera.timeout)
317
301
 
318
302
  if (this.emitter.listenerCount('camera-end') === 0) return
319
303
 
@@ -444,7 +428,7 @@ export class PerformanceManager {
444
428
  return
445
429
  }
446
430
 
447
- this.loafObserver = new PerformanceObserver((list) => {
431
+ const observer = new PerformanceObserver((list) => {
448
432
  const isInteractionActive = this.activeInteraction !== null
449
433
  const isCameraActive = this.activeCamera !== null
450
434
 
@@ -463,14 +447,11 @@ export class PerformanceManager {
463
447
  }
464
448
  })
465
449
 
466
- this.loafObserver.observe({ type: 'long-animation-frame', buffered: false })
467
- }
468
-
469
- private _stopLoafObserver() {
470
- if (this.loafObserver) {
471
- this.loafObserver.disconnect()
472
- this.loafObserver = null
473
- }
450
+ observer.observe({ type: 'long-animation-frame', buffered: false })
451
+ this.lazyCleanups.set(
452
+ 'loaf',
453
+ this.register(() => observer.disconnect())
454
+ )
474
455
  }
475
456
 
476
457
  // --- Lazy listener management ---
@@ -495,7 +476,7 @@ export class PerformanceManager {
495
476
  private _maybeAttachLazyListeners(event: keyof TLPerfEventMap) {
496
477
  // Frame listener needed for frame event + interaction/camera frame time tracking
497
478
  if (
498
- !this.frameCleanup &&
479
+ !this.lazyCleanups.has('frame') &&
499
480
  (event === 'frame' ||
500
481
  event === 'interaction-start' ||
501
482
  event === 'interaction-end' ||
@@ -503,81 +484,73 @@ export class PerformanceManager {
503
484
  event === 'camera-end')
504
485
  ) {
505
486
  if (this._needsFrameListener()) {
506
- this.editor.on('frame', this._onFrame)
507
- this.frameCleanup = () => this.editor.off('frame', this._onFrame)
487
+ this.lazyCleanups.set('frame', this.addEditorEvent('frame', this._onFrame))
508
488
  }
509
489
  }
510
490
 
511
491
  // LoAF observer needed when interaction-end or camera-end listeners exist
512
- if (!this.loafObserver && (event === 'interaction-end' || event === 'camera-end')) {
492
+ if (!this.lazyCleanups.has('loaf') && (event === 'interaction-end' || event === 'camera-end')) {
513
493
  if (this._needsLoafObserver()) {
514
494
  this._startLoafObserver()
515
495
  }
516
496
  }
517
497
 
518
- if (!this.shapeCreatedCleanup && event === 'shapes-created') {
519
- this.editor.on('created-shapes', this._onShapesCreated)
520
- this.shapeCreatedCleanup = () => this.editor.off('created-shapes', this._onShapesCreated)
498
+ if (!this.lazyCleanups.has('shapes-created') && event === 'shapes-created') {
499
+ this.lazyCleanups.set(
500
+ 'shapes-created',
501
+ this.addEditorEvent('created-shapes', this._onShapesCreated)
502
+ )
521
503
  }
522
504
 
523
- if (!this.shapeEditedCleanup && event === 'shapes-updated') {
524
- this.editor.on('edited-shapes', this._onShapesEdited)
525
- this.shapeEditedCleanup = () => this.editor.off('edited-shapes', this._onShapesEdited)
505
+ if (!this.lazyCleanups.has('shapes-updated') && event === 'shapes-updated') {
506
+ this.lazyCleanups.set(
507
+ 'shapes-updated',
508
+ this.addEditorEvent('edited-shapes', this._onShapesEdited)
509
+ )
526
510
  }
527
511
 
528
- if (!this.shapeDeletedCleanup && event === 'shapes-deleted') {
529
- this.editor.on('deleted-shapes', this._onShapesDeleted)
530
- this.shapeDeletedCleanup = () => this.editor.off('deleted-shapes', this._onShapesDeleted)
512
+ if (!this.lazyCleanups.has('shapes-deleted') && event === 'shapes-deleted') {
513
+ this.lazyCleanups.set(
514
+ 'shapes-deleted',
515
+ this.addEditorEvent('deleted-shapes', this._onShapesDeleted)
516
+ )
531
517
  }
532
518
  }
533
519
 
534
520
  private _maybeDetachLazyListeners(event: keyof TLPerfEventMap) {
535
521
  if (
536
- this.frameCleanup &&
537
522
  (event === 'frame' ||
538
523
  event === 'interaction-start' ||
539
524
  event === 'interaction-end' ||
540
525
  event === 'camera-start' ||
541
- event === 'camera-end')
526
+ event === 'camera-end') &&
527
+ !this._needsFrameListener()
542
528
  ) {
543
- if (!this._needsFrameListener()) {
544
- this.frameCleanup()
545
- this.frameCleanup = null
546
- }
529
+ this._detachLazy('frame')
547
530
  }
548
531
 
549
532
  // Stop LoAF observer when no longer needed
550
- if (this.loafObserver && (event === 'interaction-end' || event === 'camera-end')) {
551
- if (!this._needsLoafObserver()) {
552
- this._stopLoafObserver()
553
- }
533
+ if ((event === 'interaction-end' || event === 'camera-end') && !this._needsLoafObserver()) {
534
+ this._detachLazy('loaf')
554
535
  }
555
536
 
556
- if (
557
- this.shapeCreatedCleanup &&
558
- event === 'shapes-created' &&
559
- this.emitter.listenerCount('shapes-created') === 0
560
- ) {
561
- this.shapeCreatedCleanup()
562
- this.shapeCreatedCleanup = null
537
+ if (event === 'shapes-created' && this.emitter.listenerCount('shapes-created') === 0) {
538
+ this._detachLazy('shapes-created')
563
539
  }
564
540
 
565
- if (
566
- this.shapeEditedCleanup &&
567
- event === 'shapes-updated' &&
568
- this.emitter.listenerCount('shapes-updated') === 0
569
- ) {
570
- this.shapeEditedCleanup()
571
- this.shapeEditedCleanup = null
541
+ if (event === 'shapes-updated' && this.emitter.listenerCount('shapes-updated') === 0) {
542
+ this._detachLazy('shapes-updated')
572
543
  }
573
544
 
574
- if (
575
- this.shapeDeletedCleanup &&
576
- event === 'shapes-deleted' &&
577
- this.emitter.listenerCount('shapes-deleted') === 0
578
- ) {
579
- this.shapeDeletedCleanup()
580
- this.shapeDeletedCleanup = null
545
+ if (event === 'shapes-deleted' && this.emitter.listenerCount('shapes-deleted') === 0) {
546
+ this._detachLazy('shapes-deleted')
581
547
  }
582
548
  }
549
+
550
+ private _detachLazy(key: LazyListener) {
551
+ const cleanup = this.lazyCleanups.get(key)
552
+ if (!cleanup) return
553
+ this.unregister(cleanup)
554
+ this.lazyCleanups.delete(key)
555
+ }
583
556
  }
@@ -409,7 +409,7 @@ export class ScribbleManager {
409
409
 
410
410
  private clearIdleTimeout(session: Session): void {
411
411
  if (session.idleTimeoutHandle !== undefined) {
412
- clearTimeout(session.idleTimeoutHandle)
412
+ this.editor.timers.clearTimeout(session.idleTimeoutHandle)
413
413
  session.idleTimeoutHandle = undefined
414
414
  }
415
415
  }
@@ -159,6 +159,22 @@ function findAdjacentGaps(
159
159
  return matches
160
160
  }
161
161
 
162
+ // Adjacent evenly spaced items produce many center snaps whose gaps cover the
163
+ // same breadth; only the smallest such gap needs showing, so find the one a new
164
+ // gap would be redundant with. Touching breadths don't count as overlapping.
165
+ function findOverlappingCenterSnap(snaps: NearestSnap[], gap: Gap) {
166
+ return snaps.find(
167
+ (snap): snap is Extract<NearestSnap, { type: 'gap_center' }> =>
168
+ snap.type === 'gap_center' &&
169
+ rangesOverlap(
170
+ gap.breadthIntersection[0],
171
+ gap.breadthIntersection[1],
172
+ snap.gap.breadthIntersection[0],
173
+ snap.gap.breadthIntersection[1]
174
+ )
175
+ )
176
+ }
177
+
162
178
  function dedupeGapSnaps(snaps: Array<Extract<SnapIndicator, { type: 'gaps' }>>) {
163
179
  // sort by descending order of number of gaps
164
180
  snaps.sort((a, b) => b.gaps.length - a.gaps.length)
@@ -597,9 +613,8 @@ export class BoundsSnaps {
597
613
  // which are closest to it in each axis
598
614
  for (const thisSnapPoint of selectionSnapPoints) {
599
615
  for (const otherSnapPoint of otherNodeSnapPoints) {
600
- const offset = Vec.Sub(thisSnapPoint, otherSnapPoint)
601
- const offsetX = Math.abs(offset.x)
602
- const offsetY = Math.abs(offset.y)
616
+ const offsetX = Math.abs(thisSnapPoint.x - otherSnapPoint.x)
617
+ const offsetY = Math.abs(thisSnapPoint.y - otherSnapPoint.y)
603
618
 
604
619
  if (round(offsetX) <= round(minOffset.x)) {
605
620
  if (round(offsetX) < round(minOffset.x)) {
@@ -718,23 +733,14 @@ export class BoundsSnaps {
718
733
  // │ │
719
734
  // └─────────┘
720
735
 
721
- const otherCenterSnap = nearestSnapsX.find(({ type }) => type === 'gap_center') as
722
- | Extract<NearestSnap, { type: 'gap_center' }>
723
- | undefined
724
-
725
- const gapBreadthsOverlap =
726
- otherCenterSnap &&
727
- rangeIntersection(
728
- gap.breadthIntersection[0],
729
- gap.breadthIntersection[1],
730
- otherCenterSnap.gap.breadthIntersection[0],
731
- otherCenterSnap.gap.breadthIntersection[1]
732
- )
736
+ const overlappingCenterSnap = findOverlappingCenterSnap(nearestSnapsX, gap)
733
737
 
734
- // if there is another center snap and it's bigger than this one, and it overlaps with this one, replace it
735
- if (otherCenterSnap && otherCenterSnap.gap.length > gap.length && gapBreadthsOverlap) {
736
- nearestSnapsX[nearestSnapsX.indexOf(otherCenterSnap)] = snap
737
- } else if (!otherCenterSnap || !gapBreadthsOverlap) {
738
+ // if there is another center snap that overlaps with this one, keep only the smaller gap
739
+ if (overlappingCenterSnap) {
740
+ if (overlappingCenterSnap.gap.length > gap.length) {
741
+ nearestSnapsX[nearestSnapsX.indexOf(overlappingCenterSnap)] = snap
742
+ }
743
+ } else {
738
744
  nearestSnapsX.push(snap)
739
745
  }
740
746
  }
@@ -853,26 +859,16 @@ export class BoundsSnaps {
853
859
  // │ │
854
860
  // └─────────┘
855
861
 
856
- const otherCenterSnap = nearestSnapsY.find(({ type }) => type === 'gap_center') as
857
- | Extract<NearestSnap, { type: 'gap_center' }>
858
- | undefined
859
-
860
- const gapBreadthsOverlap =
861
- otherCenterSnap &&
862
- rangesOverlap(
863
- otherCenterSnap.gap.breadthIntersection[0],
864
- otherCenterSnap.gap.breadthIntersection[1],
865
- gap.breadthIntersection[0],
866
- gap.breadthIntersection[1]
867
- )
862
+ const overlappingCenterSnap = findOverlappingCenterSnap(nearestSnapsY, gap)
868
863
 
869
- // if there is another center snap and it's bigger than this one, and it overlaps with this one, replace it
870
- if (otherCenterSnap && otherCenterSnap.gap.length > gap.length && gapBreadthsOverlap) {
871
- nearestSnapsY[nearestSnapsY.indexOf(otherCenterSnap)] = snap
872
- } else if (!otherCenterSnap || !gapBreadthsOverlap) {
864
+ // if there is another center snap that overlaps with this one, keep only the smaller gap
865
+ if (overlappingCenterSnap) {
866
+ if (overlappingCenterSnap.gap.length > gap.length) {
867
+ nearestSnapsY[nearestSnapsY.indexOf(overlappingCenterSnap)] = snap
868
+ }
869
+ } else {
873
870
  nearestSnapsY.push(snap)
874
871
  }
875
- continue
876
872
  }
877
873
 
878
874
  // check for duplication top match
@@ -1,7 +1,8 @@
1
1
  import { computed } from '@tldraw/state'
2
2
  import { TLHandle, TLShape, TLShapeId, VecModel } from '@tldraw/tlschema'
3
3
  import { assertExists, uniqueId } from '@tldraw/utils'
4
- import { Geometry2d } from '../../../primitives/geometry/Geometry2d'
4
+ import { Geometry2d, Geometry2dFilters } from '../../../primitives/geometry/Geometry2d'
5
+ import { Group2d } from '../../../primitives/geometry/Group2d'
5
6
  import { Vec } from '../../../primitives/Vec'
6
7
  import type { Editor } from '../../Editor'
7
8
  import type { PointsSnapIndicator, SnapData, SnapManager } from './SnapManager'
@@ -156,11 +157,21 @@ export class HandleSnaps {
156
157
  let minDistanceForOutline = snapThreshold
157
158
  let nearestPointOnOutline: Vec | null = null
158
159
 
160
+ // Labels and internal detail (a note's label, a geo check mark) are not outlines
161
+ // to snap to. Group2d.nearestPoint throws when the filter leaves no child, so
162
+ // skip those groups.
163
+ const filters = Geometry2dFilters.EXCLUDE_NON_STANDARD
159
164
  for (const { shapeId, outline } of this.iterateSnapOutlines(currentShapeId, handle)) {
165
+ if (
166
+ outline instanceof Group2d &&
167
+ outline.children.every((child) => child.isExcludedByFilter(filters))
168
+ ) {
169
+ continue
170
+ }
160
171
  const shapePageTransform = assertExists(this.editor.getShapePageTransform(shapeId))
161
172
  const pointInShapeSpace = this.editor.getPointInShapeSpace(shapeId, handleInPageSpace)
162
173
 
163
- const nearestShapePointInShapeSpace = outline.nearestPoint(pointInShapeSpace)
174
+ const nearestShapePointInShapeSpace = outline.nearestPoint(pointInShapeSpace, filters)
164
175
  const nearestInPageSpace = shapePageTransform.applyToPoint(nearestShapePointInShapeSpace)
165
176
 
166
177
  if (Vec.DistMin(handleInPageSpace, nearestInPageSpace, minDistanceForOutline)) {
@@ -78,6 +78,7 @@ describe('SnapManager', () => {
78
78
  getShapePageBounds: vi.fn(),
79
79
  isShapeOfType: vi.fn(),
80
80
  isShapeFrameLike: vi.fn(() => false),
81
+ isShapeHidden: vi.fn(() => false),
81
82
  } as any
82
83
 
83
84
  editor.getShapeUtil.mockReturnValue({
@@ -337,6 +338,18 @@ describe('SnapManager', () => {
337
338
  expect(result.has(shapeId)).toBe(false)
338
339
  })
339
340
 
341
+ it('should exclude hidden shapes', () => {
342
+ const shapeId = createShapeId('shape1')
343
+
344
+ editor.getSortedChildIdsForParent.mockReturnValue([shapeId])
345
+ editor.getShape.mockReturnValue(createMockShape(shapeId) as any)
346
+ editor.getShapePageBounds.mockReturnValue(new Box(10, 10, 50, 50))
347
+ editor.isShapeHidden.mockReturnValue(true)
348
+
349
+ const result = snapManager.getSnappableShapes()
350
+ expect(result.has(shapeId)).toBe(false)
351
+ })
352
+
340
353
  it('should exclude shapes outside viewport bounds', () => {
341
354
  const shapeId = createShapeId('shape1')
342
355
  const shape = createMockShape(shapeId)
@@ -65,21 +65,21 @@ export class SnapManager {
65
65
  @computed getSnappableShapes(): Set<TLShapeId> {
66
66
  const { editor } = this
67
67
  const renderingBounds = editor.getViewportPageBounds()
68
- const selectedShapeIds = editor.getSelectedShapeIds()
68
+ const selectedShapeIds = new Set(editor.getSelectedShapeIds())
69
69
 
70
70
  const snappableShapes: Set<TLShapeId> = new Set()
71
71
 
72
72
  const collectSnappableShapesFromParent = (parentId: TLParentId) => {
73
73
  if (isShapeId(parentId)) {
74
74
  const parent = editor.getShape(parentId)
75
- if (parent && editor.isShapeFrameLike(parent)) {
75
+ if (parent && editor.isShapeFrameLike(parent) && !editor.isShapeHidden(parent)) {
76
76
  snappableShapes.add(parentId)
77
77
  }
78
78
  }
79
79
  const sortedChildIds = editor.getSortedChildIdsForParent(parentId)
80
80
  for (const childId of sortedChildIds) {
81
81
  // Skip any selected ids
82
- if (selectedShapeIds.includes(childId)) continue
82
+ if (selectedShapeIds.has(childId)) continue
83
83
  const childShape = editor.getShape(childId)
84
84
  if (!childShape) continue
85
85
  const util = editor.getShapeUtil(childShape)
@@ -88,11 +88,13 @@ export class SnapManager {
88
88
  // Only consider shapes if they're inside of the viewport page bounds
89
89
  const pageBounds = editor.getShapePageBounds(childId)
90
90
  if (!(pageBounds && renderingBounds.includes(pageBounds))) continue
91
- // Snap to children of groups but not group itself
91
+ // Snap to children of groups but not group itself. A hidden group's
92
+ // children may still override to visible, so recurse before the check.
92
93
  if (editor.isShapeOfType(childShape, 'group')) {
93
94
  collectSnappableShapesFromParent(childId)
94
95
  continue
95
96
  }
97
+ if (editor.isShapeHidden(childShape)) continue
96
98
  snappableShapes.add(childId)
97
99
  }
98
100
  }
@@ -73,6 +73,11 @@ export interface TLFileReplaceExternalContent extends TLBaseExternalContent {
73
73
  export interface TLUrlExternalContent extends TLBaseExternalContent {
74
74
  type: 'url'
75
75
  url: string
76
+ /**
77
+ * A shape to set the url on, instead of creating a bookmark or an embed. The shape must have a
78
+ * `url` prop; the clipboard sets this when a link is pasted with one such shape selected.
79
+ */
80
+ shapeId?: TLShapeId
76
81
  }
77
82
 
78
83
  /** @public */
@@ -5,6 +5,7 @@ import type { TLErrorFallbackComponent } from '../components/default-components/
5
5
  import type { TLGridProps } from '../components/default-components/DefaultGrid'
6
6
  import type { TLShapeErrorFallbackComponent } from '../components/default-components/DefaultShapeErrorFallback'
7
7
  import type { TLShapeWrapperProps } from '../components/default-components/DefaultShapeWrapper'
8
+ import type { TLSpinnerProps } from '../components/default-components/DefaultSpinner'
8
9
 
9
10
  /** @public */
10
11
  export interface TLEditorComponents {
@@ -16,7 +17,7 @@ export interface TLEditorComponents {
16
17
  LoadingScreen?: ComponentType | null
17
18
  OnTheCanvas?: ComponentType | null
18
19
  ShapeWrapper?: ComponentType<TLShapeWrapperProps & RefAttributes<HTMLDivElement>> | null
19
- Spinner?: ComponentType<React.SVGProps<SVGSVGElement>> | null
20
+ Spinner?: ComponentType<TLSpinnerProps> | null
20
21
  SvgDefs?: ComponentType | null
21
22
 
22
23
  // These will always have defaults
@@ -43,12 +43,6 @@ export const debugFlags = {
43
43
  throwToBlob: createDebugValue('throwToBlob', {
44
44
  defaults: { all: false },
45
45
  }),
46
- reconnectOnPing: createDebugValue('reconnectOnPing', {
47
- defaults: { all: false },
48
- }),
49
- debugCursors: createDebugValue('debugCursors', {
50
- defaults: { all: false },
51
- }),
52
46
  forceSrgb: createDebugValue('forceSrgbColors', { defaults: { all: false } }),
53
47
  debugGeometry: createDebugValue('debugGeometry', { defaults: { all: false } }),
54
48
  hideShapes: createDebugValue('hideShapes', { defaults: { all: false } }),
@@ -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', () => {
@@ -202,6 +203,72 @@ describe('LocalIndexedDb', () => {
202
203
  })
203
204
  })
204
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
+
205
272
  it('migrates legacy asset storage into the new format', async () => {
206
273
  const legacyAssetsDb = await openDB('TLDRAW_ASSET_STORE_v1test-0', 1, {
207
274
  upgrade(database) {
@@ -267,4 +334,29 @@ describe('LocalIndexedDb', () => {
267
334
  (await window.indexedDB.databases()).find((db) => db.name === 'TLDRAW_ASSET_STORE_v1test-0')
268
335
  ).toBeUndefined()
269
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
+ })
270
362
  })