@tldraw/editor 5.2.0-next.a6104dd18d03 → 5.2.0-next.b0c9cf86de67

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 (89) hide show
  1. package/README.md +6 -0
  2. package/dist-cjs/index.d.ts +42 -4
  3. package/dist-cjs/index.js +2 -1
  4. package/dist-cjs/index.js.map +2 -2
  5. package/dist-cjs/lib/components/MenuClickCapture.js +8 -5
  6. package/dist-cjs/lib/components/MenuClickCapture.js.map +2 -2
  7. package/dist-cjs/lib/editor/Editor.js +74 -41
  8. package/dist-cjs/lib/editor/Editor.js.map +2 -2
  9. package/dist-cjs/lib/editor/managers/CollaboratorsManager/CollaboratorsManager.js +2 -2
  10. package/dist-cjs/lib/editor/managers/CollaboratorsManager/CollaboratorsManager.js.map +2 -2
  11. package/dist-cjs/lib/editor/managers/HistoryManager/HistoryManager.js +24 -2
  12. package/dist-cjs/lib/editor/managers/HistoryManager/HistoryManager.js.map +2 -2
  13. package/dist-cjs/lib/editor/managers/InputsManager/InputsManager.js +14 -3
  14. package/dist-cjs/lib/editor/managers/InputsManager/InputsManager.js.map +2 -2
  15. package/dist-cjs/lib/editor/managers/SpatialIndexManager/SpatialIndexManager.js +4 -2
  16. package/dist-cjs/lib/editor/managers/SpatialIndexManager/SpatialIndexManager.js.map +2 -2
  17. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js +7 -3
  18. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js.map +2 -2
  19. package/dist-cjs/lib/editor/managers/TickManager/TickManager.js +0 -1
  20. package/dist-cjs/lib/editor/managers/TickManager/TickManager.js.map +2 -2
  21. package/dist-cjs/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.js +15 -2
  22. package/dist-cjs/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.js.map +2 -2
  23. package/dist-cjs/lib/editor/tools/BaseBoxShapeTool/children/Pointing.js +3 -0
  24. package/dist-cjs/lib/editor/tools/BaseBoxShapeTool/children/Pointing.js.map +2 -2
  25. package/dist-cjs/lib/hooks/useCanvasEvents.js +14 -7
  26. package/dist-cjs/lib/hooks/useCanvasEvents.js.map +2 -2
  27. package/dist-cjs/lib/hooks/usePresence.js.map +2 -2
  28. package/dist-cjs/lib/utils/getPointerInfo.js +2 -1
  29. package/dist-cjs/lib/utils/getPointerInfo.js.map +2 -2
  30. package/dist-cjs/lib/utils/pointer.js +32 -0
  31. package/dist-cjs/lib/utils/pointer.js.map +7 -0
  32. package/dist-cjs/version.js +3 -3
  33. package/dist-cjs/version.js.map +1 -1
  34. package/dist-esm/index.d.mts +42 -4
  35. package/dist-esm/index.mjs +4 -2
  36. package/dist-esm/index.mjs.map +2 -2
  37. package/dist-esm/lib/components/MenuClickCapture.mjs +8 -5
  38. package/dist-esm/lib/components/MenuClickCapture.mjs.map +2 -2
  39. package/dist-esm/lib/editor/Editor.mjs +74 -41
  40. package/dist-esm/lib/editor/Editor.mjs.map +2 -2
  41. package/dist-esm/lib/editor/managers/CollaboratorsManager/CollaboratorsManager.mjs +2 -2
  42. package/dist-esm/lib/editor/managers/CollaboratorsManager/CollaboratorsManager.mjs.map +2 -2
  43. package/dist-esm/lib/editor/managers/HistoryManager/HistoryManager.mjs +24 -2
  44. package/dist-esm/lib/editor/managers/HistoryManager/HistoryManager.mjs.map +2 -2
  45. package/dist-esm/lib/editor/managers/InputsManager/InputsManager.mjs +14 -3
  46. package/dist-esm/lib/editor/managers/InputsManager/InputsManager.mjs.map +2 -2
  47. package/dist-esm/lib/editor/managers/SpatialIndexManager/SpatialIndexManager.mjs +4 -2
  48. package/dist-esm/lib/editor/managers/SpatialIndexManager/SpatialIndexManager.mjs.map +2 -2
  49. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs +7 -3
  50. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs.map +2 -2
  51. package/dist-esm/lib/editor/managers/TickManager/TickManager.mjs +0 -1
  52. package/dist-esm/lib/editor/managers/TickManager/TickManager.mjs.map +2 -2
  53. package/dist-esm/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.mjs +15 -2
  54. package/dist-esm/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.mjs.map +2 -2
  55. package/dist-esm/lib/editor/tools/BaseBoxShapeTool/children/Pointing.mjs +3 -0
  56. package/dist-esm/lib/editor/tools/BaseBoxShapeTool/children/Pointing.mjs.map +2 -2
  57. package/dist-esm/lib/hooks/useCanvasEvents.mjs +14 -7
  58. package/dist-esm/lib/hooks/useCanvasEvents.mjs.map +2 -2
  59. package/dist-esm/lib/hooks/usePresence.mjs.map +2 -2
  60. package/dist-esm/lib/utils/getPointerInfo.mjs +2 -1
  61. package/dist-esm/lib/utils/getPointerInfo.mjs.map +2 -2
  62. package/dist-esm/lib/utils/pointer.mjs +12 -0
  63. package/dist-esm/lib/utils/pointer.mjs.map +7 -0
  64. package/dist-esm/version.mjs +3 -3
  65. package/dist-esm/version.mjs.map +1 -1
  66. package/editor.css +3 -3
  67. package/package.json +7 -7
  68. package/src/index.ts +1 -0
  69. package/src/lib/components/MenuClickCapture.tsx +8 -4
  70. package/src/lib/editor/Editor.ts +91 -50
  71. package/src/lib/editor/managers/CollaboratorsManager/CollaboratorsManager.test.ts +31 -18
  72. package/src/lib/editor/managers/CollaboratorsManager/CollaboratorsManager.ts +2 -2
  73. package/src/lib/editor/managers/HistoryManager/HistoryManager.test.ts +32 -0
  74. package/src/lib/editor/managers/HistoryManager/HistoryManager.ts +34 -4
  75. package/src/lib/editor/managers/InputsManager/InputsManager.test.ts +61 -0
  76. package/src/lib/editor/managers/InputsManager/InputsManager.ts +16 -4
  77. package/src/lib/editor/managers/SpatialIndexManager/SpatialIndexManager.ts +9 -2
  78. package/src/lib/editor/managers/TextManager/TextManager.ts +17 -2
  79. package/src/lib/editor/managers/TickManager/TickManager.test.ts +0 -40
  80. package/src/lib/editor/managers/TickManager/TickManager.ts +0 -1
  81. package/src/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.test.ts +12 -2
  82. package/src/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.ts +27 -2
  83. package/src/lib/editor/tools/BaseBoxShapeTool/children/Pointing.ts +4 -0
  84. package/src/lib/hooks/useCanvasEvents.ts +19 -12
  85. package/src/lib/hooks/usePresence.ts +2 -2
  86. package/src/lib/utils/getPointerInfo.ts +2 -1
  87. package/src/lib/utils/pointer.test.ts +48 -0
  88. package/src/lib/utils/pointer.ts +18 -0
  89. package/src/version.ts +3 -3
@@ -6,6 +6,7 @@ import { useEditor } from '../hooks/useEditor'
6
6
  import { Vec } from '../primitives/Vec'
7
7
  import { releasePointerCapture, setPointerCapture } from '../utils/dom'
8
8
  import { getPointerInfo } from '../utils/getPointerInfo'
9
+ import { getPointerEventButton } from '../utils/pointer'
9
10
 
10
11
  /**
11
12
  * When a menu is open, this component prevents the user from interacting with the canvas.
@@ -68,18 +69,19 @@ export function MenuClickCapture() {
68
69
 
69
70
  const handlePointerDown = useCallback(
70
71
  (e: PointerEvent) => {
71
- if (e.button !== 0 && e.button !== 2) return
72
+ const button = getPointerEventButton(e)
73
+ if (button !== 0 && button !== 2) return
72
74
 
73
75
  flushSync(() => setIsPointing(true))
74
76
  setPointerCapture(e.currentTarget, e)
75
77
  rPointerState.current = {
76
78
  isDown: true,
77
79
  isDragging: false,
78
- button: e.button,
80
+ button,
79
81
  start: new Vec(e.clientX, e.clientY),
80
82
  }
81
83
 
82
- if (e.button === 2) {
84
+ if (button === 2) {
83
85
  if (!editor.options.rightClickPanning) {
84
86
  // Right-click panning off: close the open menu and swallow the native
85
87
  // contextmenu that would otherwise briefly open a new one (causing a flash).
@@ -141,13 +143,15 @@ export function MenuClickCapture() {
141
143
 
142
144
  const handlePointerUp = useCallback(
143
145
  (e: PointerEvent) => {
144
- const isStaticRightClick = e.button === 2 && !rPointerState.current.isDragging
146
+ const isStaticRightClick =
147
+ rPointerState.current.button === 2 && !rPointerState.current.isDragging
145
148
 
146
149
  editor.dispatch({
147
150
  type: 'pointer',
148
151
  target: 'canvas',
149
152
  name: 'pointer_up',
150
153
  ...getPointerInfo(editor, e),
154
+ button: rPointerState.current.button === 2 ? 2 : getPointerEventButton(e),
151
155
  })
152
156
 
153
157
  if (isStaticRightClick && editor.options.rightClickPanning) {
@@ -409,9 +409,6 @@ export class Editor extends EventEmitter<TLEventMap> {
409
409
  this._tickManager = new TickManager(this)
410
410
  this.disposables.add(() => this._tickManager.dispose())
411
411
  this.disposables.add(() => {
412
- // Reset camera state to 'idle' so the store isn't left stuck at 'moving'
413
- // when tick events stop (e.g. React strict mode disposes while camera is moving)
414
- this.off('tick', this._decayCameraStateTimeout)
415
412
  this._setCameraState('idle')
416
413
  })
417
414
 
@@ -419,6 +416,7 @@ export class Editor extends EventEmitter<TLEventMap> {
419
416
  this.disposables.add(() => this.fonts.dispose())
420
417
 
421
418
  this.inputs = new InputsManager(this)
419
+ this.disposables.add(() => this.inputs.dispose())
422
420
  this.performance = new PerformanceManager(this)
423
421
  this.disposables.add(() => this.performance.dispose())
424
422
  this.collaborators = new CollaboratorsManager(this)
@@ -1179,6 +1177,7 @@ export class Editor extends EventEmitter<TLEventMap> {
1179
1177
  this.store.dispose()
1180
1178
  this.isDisposed = true
1181
1179
  this.emit('dispose')
1180
+ this.removeAllListeners()
1182
1181
  }
1183
1182
 
1184
1183
  /* ------------------ Themes (shadowing the theme manager) ------------------ */
@@ -1551,6 +1550,15 @@ export class Editor extends EventEmitter<TLEventMap> {
1551
1550
  return this.history.getMarkIdMatching(idSubstring)
1552
1551
  }
1553
1552
 
1553
+ /**
1554
+ * Whether the editor is currently replaying history (i.e. an undo or redo is being applied).
1555
+ *
1556
+ * @internal
1557
+ */
1558
+ isReplayingHistory(): boolean {
1559
+ return this.history.isReplaying()
1560
+ }
1561
+
1554
1562
  /**
1555
1563
  * Coalesces all changes since the given mark into a single change, removing any intermediate marks.
1556
1564
  *
@@ -3068,8 +3076,8 @@ export class Editor extends EventEmitter<TLEventMap> {
3068
3076
  return baseCamera
3069
3077
  }
3070
3078
 
3071
- private _getFollowingPresence(targetUserId: string | null) {
3072
- const visited = [this.user.getId()]
3079
+ private _getFollowingPresence(targetUserId: TLUserId | null) {
3080
+ const visited = [this.user.getRecordId()]
3073
3081
  const collaborators = this.getCollaborators()
3074
3082
  let leaderPresence = null as null | TLInstancePresence
3075
3083
  while (targetUserId && !visited.includes(targetUserId)) {
@@ -4078,7 +4086,7 @@ export class Editor extends EventEmitter<TLEventMap> {
4078
4086
  * @param opts - The camera move options.
4079
4087
  * @public
4080
4088
  */
4081
- zoomToUser(userId: string, opts: TLCameraMoveOptions = { animation: { duration: 500 } }): this {
4089
+ zoomToUser(userId: TLUserId, opts: TLCameraMoveOptions = { animation: { duration: 500 } }): this {
4082
4090
  const presence = this.getCollaborators().find((c) => c.userId === userId)
4083
4091
 
4084
4092
  if (!presence) return this
@@ -4450,11 +4458,11 @@ export class Editor extends EventEmitter<TLEventMap> {
4450
4458
  *
4451
4459
  * @public
4452
4460
  */
4453
- startFollowingUser(userId: string): this {
4461
+ startFollowingUser(userId: TLUserId): this {
4454
4462
  // if we were already following someone, stop following them
4455
4463
  this.stopFollowingUser()
4456
4464
 
4457
- const thisUserId = this.user.getId()
4465
+ const thisUserId = this.user.getExternalId()
4458
4466
 
4459
4467
  if (!thisUserId) {
4460
4468
  console.warn('You should set the userId for the current instance before following a user')
@@ -8102,32 +8110,53 @@ export class Editor extends EventEmitter<TLEventMap> {
8102
8110
  * @public
8103
8111
  */
8104
8112
  resizeShape(shape: TLShapeId | TLShape, scale: VecLike, opts: TLResizeShapeOptions = {}): this {
8113
+ const partial = this.getResizeShapePartial(shape, scale, opts)
8114
+ if (partial) this.updateShapes([partial])
8115
+ return this
8116
+ }
8117
+
8118
+ /**
8119
+ * Get the update for a resized shape without committing it to the store. Interactions that
8120
+ * resize many shapes at once use this to collect all of the updates and commit them in a
8121
+ * single batch. Returns null when there is nothing to update.
8122
+ *
8123
+ * Shapes that are rotated out of alignment with the scale axis cannot be resized with a
8124
+ * single update; those shapes are resized immediately (as `resizeShape` would do) and null
8125
+ * is returned.
8126
+ *
8127
+ * @internal
8128
+ */
8129
+ getResizeShapePartial(
8130
+ shape: TLShapeId | TLShape,
8131
+ scale: VecLike,
8132
+ opts: TLResizeShapeOptions = {}
8133
+ ): TLShapePartial | null {
8105
8134
  const id = typeof shape === 'string' ? shape : shape.id
8106
- if (this.getIsReadonly()) return this
8135
+ if (this.getIsReadonly()) return null
8107
8136
 
8108
8137
  if (!Number.isFinite(scale.x)) scale = new Vec(1, scale.y)
8109
8138
  if (!Number.isFinite(scale.y)) scale = new Vec(scale.x, 1)
8110
8139
 
8111
8140
  const initialShape = opts.initialShape ?? this.getShape(id)
8112
- if (!initialShape) return this
8141
+ if (!initialShape) return null
8113
8142
 
8114
8143
  const scaleOrigin = opts.scaleOrigin ?? this.getShapePageBounds(id)?.center
8115
- if (!scaleOrigin) return this
8144
+ if (!scaleOrigin) return null
8116
8145
 
8117
8146
  const pageTransform = opts.initialPageTransform
8118
8147
  ? Mat.Cast(opts.initialPageTransform)
8119
8148
  : this.getShapePageTransform(id)
8120
- if (!pageTransform) return this
8149
+ if (!pageTransform) return null
8121
8150
 
8122
8151
  const pageRotation = pageTransform.rotation()
8123
8152
 
8124
- if (pageRotation == null) return this
8153
+ if (pageRotation == null) return null
8125
8154
 
8126
8155
  const scaleAxisRotation = opts.scaleAxisRotation ?? pageRotation
8127
8156
 
8128
8157
  const initialBounds = opts.initialBounds ?? this.getShapeGeometry(id).bounds
8129
8158
 
8130
- if (!initialBounds) return this
8159
+ if (!initialBounds) return null
8131
8160
 
8132
8161
  const isAspectRatioLocked =
8133
8162
  opts.isAspectRatioLocked ?? this.getShapeUtil(initialShape).isAspectRatioLocked(initialShape)
@@ -8137,7 +8166,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8137
8166
  // from whichever axis is being scaled the least, to avoid the shape getting bigger
8138
8167
  // than the bounds of the selection
8139
8168
  // const minScale = Math.min(Math.abs(scale.x), Math.abs(scale.y))
8140
- return this._resizeUnalignedShape(id, scale, {
8169
+ this._resizeUnalignedShape(id, scale, {
8141
8170
  ...opts,
8142
8171
  initialBounds,
8143
8172
  scaleOrigin,
@@ -8146,6 +8175,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8146
8175
  isAspectRatioLocked,
8147
8176
  initialShape,
8148
8177
  })
8178
+ return null
8149
8179
  }
8150
8180
 
8151
8181
  const util = this.getShapeUtil(initialShape)
@@ -8158,7 +8188,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8158
8188
  }
8159
8189
  }
8160
8190
 
8161
- let didResize = false
8191
+ let workingShape: TLShape | null = null
8162
8192
 
8163
8193
  if (util.onResize && util.canResize(initialShape)) {
8164
8194
  // get the model changes from the shape util
@@ -8190,7 +8220,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8190
8220
  // need to adjust the shape's x and y points in case the parent has moved since start of resizing
8191
8221
  const { x, y } = this.getPointInParentSpace(initialShape.id, initialPagePoint)
8192
8222
 
8193
- let workingShape = initialShape
8223
+ workingShape = initialShape
8194
8224
  if (!opts.skipStartAndEndCallbacks) {
8195
8225
  workingShape = applyPartialToRecordWithProps(
8196
8226
  initialShape,
@@ -8212,10 +8242,6 @@ export class Editor extends EventEmitter<TLEventMap> {
8212
8242
  }
8213
8243
  )
8214
8244
 
8215
- if (resizedShape) {
8216
- didResize = true
8217
- }
8218
-
8219
8245
  workingShape = applyPartialToRecordWithProps(workingShape, {
8220
8246
  id,
8221
8247
  type: initialShape.type as any,
@@ -8231,40 +8257,47 @@ export class Editor extends EventEmitter<TLEventMap> {
8231
8257
  )
8232
8258
  }
8233
8259
 
8234
- this.updateShapes([workingShape])
8260
+ if (resizedShape) {
8261
+ return workingShape
8262
+ }
8235
8263
  }
8236
8264
 
8237
- if (!didResize) {
8238
- // reposition shape (rather than resizing it) based on where its resized center would be
8265
+ // the shape was not resized by its util, so reposition it (rather than resizing it)
8266
+ // based on where its resized center would be
8239
8267
 
8240
- const initialPageCenter = Mat.applyToPoint(pageTransform, initialBounds.center)
8241
- // get the model changes from the shape util
8242
- const newPageCenter = this._scalePagePoint(
8243
- initialPageCenter,
8244
- scaleOrigin,
8245
- scale,
8246
- scaleAxisRotation
8247
- )
8268
+ const initialPageCenter = Mat.applyToPoint(pageTransform, initialBounds.center)
8269
+ // get the model changes from the shape util
8270
+ const newPageCenter = this._scalePagePoint(
8271
+ initialPageCenter,
8272
+ scaleOrigin,
8273
+ scale,
8274
+ scaleAxisRotation
8275
+ )
8248
8276
 
8249
- const initialPageCenterInParentSpace = this.getPointInParentSpace(
8250
- initialShape.id,
8251
- initialPageCenter
8252
- )
8253
- const newPageCenterInParentSpace = this.getPointInParentSpace(initialShape.id, newPageCenter)
8277
+ const initialPageCenterInParentSpace = this.getPointInParentSpace(
8278
+ initialShape.id,
8279
+ initialPageCenter
8280
+ )
8281
+ const newPageCenterInParentSpace = this.getPointInParentSpace(initialShape.id, newPageCenter)
8254
8282
 
8255
- const delta = Vec.Sub(newPageCenterInParentSpace, initialPageCenterInParentSpace)
8256
- // apply the changes to the model
8257
- this.updateShapes([
8258
- {
8259
- id,
8260
- type: initialShape.type as any,
8261
- x: initialShape.x + delta.x,
8262
- y: initialShape.y + delta.y,
8263
- },
8264
- ])
8283
+ const delta = Vec.Sub(newPageCenterInParentSpace, initialPageCenterInParentSpace)
8284
+
8285
+ if (workingShape) {
8286
+ // the util's onResize ran but returned no change; keep the working update (which may
8287
+ // include changes from onResizeStart / onResizeEnd) and reposition the shape
8288
+ return {
8289
+ ...workingShape,
8290
+ x: initialShape.x + delta.x,
8291
+ y: initialShape.y + delta.y,
8292
+ }
8265
8293
  }
8266
8294
 
8267
- return this
8295
+ return {
8296
+ id,
8297
+ type: initialShape.type as any,
8298
+ x: initialShape.x + delta.x,
8299
+ y: initialShape.y + delta.y,
8300
+ }
8268
8301
  }
8269
8302
 
8270
8303
  /** @internal */
@@ -11191,7 +11224,12 @@ export class Editor extends EventEmitter<TLEventMap> {
11191
11224
  inputs.setIsDragging(false)
11192
11225
 
11193
11226
  // If pen mode is off but we're not already in pen mode, turn that on
11194
- if (!isPenMode && isPen) this.updateInstanceState({ isPenMode: true })
11227
+ if (!isPenMode && isPen) {
11228
+ this.updateInstanceState({ isPenMode: true })
11229
+ // Once pen mode is on, touch input is ignored, so we discard the
11230
+ // in-progress touch interaction .
11231
+ this.interrupt()
11232
+ }
11195
11233
 
11196
11234
  // On devices with erasers (like the Surface Pen or Wacom Pen), button 5 is the eraser
11197
11235
  if (info.button === STYLUS_ERASER_BUTTON) {
@@ -11341,7 +11379,10 @@ export class Editor extends EventEmitter<TLEventMap> {
11341
11379
  // Don't pass right-click panning events to the state chart
11342
11380
  // as it causes unintended shape selection on release
11343
11381
  if (slideSpeed > 0) {
11344
- this.slideCamera({ speed: slideSpeed, direction: slideDirection })
11382
+ this.slideCamera({
11383
+ speed: slideSpeed,
11384
+ direction: { x: slideDirection.x, y: slideDirection.y, z: 0 },
11385
+ })
11345
11386
  }
11346
11387
  this._selectedShapeIdsAtPointerDown = []
11347
11388
  this._didCaptureSelectionAtPointerDown = false
@@ -1,11 +1,17 @@
1
- import { PageRecordType, type TLInstancePresence } from '@tldraw/tlschema'
1
+ import {
2
+ PageRecordType,
3
+ createUserId,
4
+ type TLInstancePresence,
5
+ type TLUserId,
6
+ } from '@tldraw/tlschema'
2
7
  import { vi } from 'vitest'
8
+ import { createTLStore } from '../../../config/createTLStore'
3
9
  import type { Editor } from '../../Editor'
4
10
  import { CollaboratorsManager } from './CollaboratorsManager'
5
11
 
6
12
  const currentPageId = PageRecordType.createId('page')
7
13
 
8
- function createPresence(userId: string): TLInstancePresence {
14
+ function createPresence(userId: TLUserId): TLInstancePresence {
9
15
  return {
10
16
  typeName: 'instance_presence',
11
17
  id: `instance_presence:${userId}` as TLInstancePresence['id'],
@@ -34,6 +40,9 @@ function createEditor(presences: TLInstancePresence[] = []) {
34
40
  }))
35
41
  const userGetId = vi.fn(() => 'current-user')
36
42
 
43
+ const store = createTLStore()
44
+ store.put(presences)
45
+
37
46
  const editor = {
38
47
  options: {
39
48
  collaboratorCheckIntervalMs: 1000,
@@ -45,14 +54,9 @@ function createEditor(presences: TLInstancePresence[] = []) {
45
54
  },
46
55
  user: {
47
56
  getId: userGetId,
57
+ getRecordId: () => createUserId(userGetId()),
48
58
  },
49
- store: {
50
- query: {
51
- records: vi.fn(() => ({
52
- get: () => presences,
53
- })),
54
- },
55
- },
59
+ store,
56
60
  getInstanceState,
57
61
  getCurrentPageId: vi.fn(() => currentPageId),
58
62
  } as unknown as Editor
@@ -88,10 +92,19 @@ describe(CollaboratorsManager, () => {
88
92
  expect(setInterval).toHaveBeenCalledTimes(1)
89
93
  })
90
94
 
95
+ it("excludes the local user's own other sessions", () => {
96
+ const ownSession = createPresence(createUserId('current-user'))
97
+ const peer = createPresence(createUserId('peer'))
98
+ const { editor } = createEditor([ownSession, peer])
99
+ const manager = new CollaboratorsManager(editor)
100
+
101
+ expect(manager.getCollaborators()).toEqual([peer])
102
+ })
103
+
91
104
  it('reads instance state once when filtering visible collaborators', () => {
92
105
  const { editor, getInstanceState } = createEditor([
93
- createPresence('user-1'),
94
- createPresence('user-2'),
106
+ createPresence(createUserId('user-1')),
107
+ createPresence(createUserId('user-2')),
95
108
  ])
96
109
  const manager = new CollaboratorsManager(editor)
97
110
 
@@ -101,9 +114,9 @@ describe(CollaboratorsManager, () => {
101
114
  })
102
115
 
103
116
  it('hides idle collaborators that are following us', () => {
104
- const presence = createPresence('peer')
117
+ const presence = createPresence(createUserId('peer'))
105
118
  presence.lastActivityTimestamp = Date.now() - 4000
106
- presence.followingUserId = 'current-user'
119
+ presence.followingUserId = createUserId('current-user')
107
120
  const { editor } = createEditor([presence])
108
121
  const manager = new CollaboratorsManager(editor)
109
122
 
@@ -111,9 +124,9 @@ describe(CollaboratorsManager, () => {
111
124
  })
112
125
 
113
126
  it('shows idle collaborators that are following us when they have a chat message', () => {
114
- const presence = createPresence('peer')
127
+ const presence = createPresence(createUserId('peer'))
115
128
  presence.lastActivityTimestamp = Date.now() - 4000
116
- presence.followingUserId = 'current-user'
129
+ presence.followingUserId = createUserId('current-user')
117
130
  presence.chatMessage = 'hi'
118
131
  const { editor } = createEditor([presence])
119
132
  const manager = new CollaboratorsManager(editor)
@@ -122,7 +135,7 @@ describe(CollaboratorsManager, () => {
122
135
  })
123
136
 
124
137
  it('shows idle collaborators that are not following us', () => {
125
- const presence = createPresence('peer')
138
+ const presence = createPresence(createUserId('peer'))
126
139
  presence.lastActivityTimestamp = Date.now() - 4000
127
140
  const { editor } = createEditor([presence])
128
141
  const manager = new CollaboratorsManager(editor)
@@ -134,9 +147,9 @@ describe(CollaboratorsManager, () => {
134
147
  // A peer who has joined but not moved their pointer broadcasts the default
135
148
  // `lastActivityTimestamp` of 0. They should still be treated as active so
136
149
  // they appear in the people menu / face pile. See issue #9017.
137
- const zero = createPresence('zero')
150
+ const zero = createPresence(createUserId('zero'))
138
151
  zero.lastActivityTimestamp = 0
139
- const nullish = createPresence('nullish')
152
+ const nullish = createPresence(createUserId('nullish'))
140
153
  nullish.lastActivityTimestamp = null
141
154
  const { editor } = createEditor([zero, nullish])
142
155
  const manager = new CollaboratorsManager(editor)
@@ -37,7 +37,7 @@ export class CollaboratorsManager {
37
37
  @computed
38
38
  private _getCollaboratorsQuery() {
39
39
  return this.editor.store.query.records('instance_presence', () => ({
40
- userId: { neq: this.editor.user.getId() },
40
+ userId: { neq: this.editor.user.getRecordId() },
41
41
  }))
42
42
  }
43
43
 
@@ -88,7 +88,7 @@ export class CollaboratorsManager {
88
88
  if (!collaborators.length) return EMPTY_ARRAY
89
89
 
90
90
  const { followingUserId, highlightedUserIds } = this.editor.getInstanceState()
91
- const currentUserId = this.editor.user.getId()
91
+ const currentUserId = this.editor.user.getRecordId()
92
92
 
93
93
  return collaborators.filter((presence) => {
94
94
  const { lastActivityTimestamp, userId, chatMessage } = presence
@@ -584,6 +584,38 @@ describe('HistoryManager getters and utilities', () => {
584
584
  store.update(ids.a, (s) => ({ ...s, value: 2 }))
585
585
  expect(manager.getNumRedos()).toBe(0)
586
586
  })
587
+
588
+ it('should only report replaying while undoing or redoing', () => {
589
+ const replayStates: boolean[] = []
590
+ const dispose = store.addHistoryInterceptor(() => {
591
+ replayStates.push(manager.isReplaying())
592
+ })
593
+
594
+ store.update(ids.a, (s) => ({ ...s, value: 1 }))
595
+ expect(replayStates).toEqual([false])
596
+
597
+ replayStates.length = 0
598
+ manager.undo()
599
+ expect(replayStates).toEqual([true])
600
+ expect(manager.isReplaying()).toBe(false)
601
+
602
+ replayStates.length = 0
603
+ manager.redo()
604
+ expect(replayStates).toEqual([true])
605
+ expect(manager.isReplaying()).toBe(false)
606
+
607
+ replayStates.length = 0
608
+ manager.batch(
609
+ () => {
610
+ store.update(ids.a, (s) => ({ ...s, value: 2 }))
611
+ },
612
+ { history: 'ignore' }
613
+ )
614
+ expect(replayStates).toEqual([false])
615
+ expect(manager.isReplaying()).toBe(false)
616
+
617
+ dispose()
618
+ })
587
619
  })
588
620
 
589
621
  describe('getMarkIdMatching', () => {
@@ -48,7 +48,11 @@ export class HistoryManager<R extends UnknownRecord> {
48
48
  switch (this.state) {
49
49
  case HistoryRecorderState.Recording:
50
50
  this.pendingDiff.apply(entry.changes)
51
- this.stacks.update(({ undos }) => ({ undos, redos: stack() }))
51
+ // this interceptor runs for every store change, so skip the update when the
52
+ // redo stack is already empty
53
+ if (this.stacks.get().redos.length > 0) {
54
+ this.stacks.update(({ undos }) => ({ undos, redos: stack() }))
55
+ }
52
56
  break
53
57
  case HistoryRecorderState.RecordingPreserveRedoStack:
54
58
  this.pendingDiff.apply(entry.changes)
@@ -79,6 +83,14 @@ export class HistoryManager<R extends UnknownRecord> {
79
83
  return this.stacks.get().redos.length
80
84
  }
81
85
 
86
+ /** @internal */
87
+ private _isReplaying = false
88
+
89
+ /** @internal */
90
+ isReplaying() {
91
+ return this._isReplaying
92
+ }
93
+
82
94
  /** @internal */
83
95
  _isInBatch = false
84
96
 
@@ -115,7 +127,9 @@ export class HistoryManager<R extends UnknownRecord> {
115
127
  // History
116
128
  _undo({ pushToRedoStack, toMark = undefined }: { pushToRedoStack: boolean; toMark?: string }) {
117
129
  const previousState = this.state
130
+ const previousIsReplaying = this._isReplaying
118
131
  this.state = HistoryRecorderState.Paused
132
+ this._isReplaying = true
119
133
  try {
120
134
  let { undos, redos } = this.stacks.get()
121
135
 
@@ -176,11 +190,11 @@ export class HistoryManager<R extends UnknownRecord> {
176
190
  this.pendingDiff.restore(pendingDiff)
177
191
  return this
178
192
  }
179
-
180
193
  this.store.applyDiff(diffToUndo, { ignoreEphemeralKeys: true })
181
194
  this.store.ensureStoreIsUsable()
182
195
  this.stacks.set({ undos, redos })
183
196
  } finally {
197
+ this._isReplaying = previousIsReplaying
184
198
  this.state = previousState
185
199
  }
186
200
 
@@ -195,7 +209,9 @@ export class HistoryManager<R extends UnknownRecord> {
195
209
 
196
210
  redo() {
197
211
  const previousState = this.state
212
+ const previousIsReplaying = this._isReplaying
198
213
  this.state = HistoryRecorderState.Paused
214
+ this._isReplaying = true
199
215
  try {
200
216
  this.flushPendingDiff()
201
217
 
@@ -224,11 +240,11 @@ export class HistoryManager<R extends UnknownRecord> {
224
240
  break
225
241
  }
226
242
  }
227
-
228
243
  this.store.applyDiff(diffToRedo, { ignoreEphemeralKeys: true })
229
244
  this.store.ensureStoreIsUsable()
230
245
  this.stacks.set({ undos, redos })
231
246
  } finally {
247
+ this._isReplaying = previousIsReplaying
232
248
  this.state = previousState
233
249
  }
234
250
 
@@ -349,7 +365,16 @@ class PendingDiff<R extends UnknownRecord> {
349
365
 
350
366
  apply(diff: RecordsDiff<R>) {
351
367
  squashRecordDiffsMutable(this.diff, [diff])
352
- this.isEmptyAtom.set(isRecordsDiffEmpty(this.diff))
368
+ // Recomputing emptiness from the accumulated diff is O(N) (for-in over a
369
+ // dictionary-mode object pays an O(N) key-collection prologue), and this runs on
370
+ // every history interceptor call — e.g. every input tick while resizing many
371
+ // shapes. Updates can never cancel out existing entries during a squash, so the
372
+ // full recompute is only needed when the incoming diff adds or removes records.
373
+ if (hasAnyKey(diff.added) || hasAnyKey(diff.removed)) {
374
+ this.isEmptyAtom.set(isRecordsDiffEmpty(this.diff))
375
+ } else if (this.isEmptyAtom.__unsafe__getWithoutCapture()) {
376
+ this.isEmptyAtom.set(!hasAnyKey(diff.updated))
377
+ }
353
378
  }
354
379
 
355
380
  debug() {
@@ -357,6 +382,11 @@ class PendingDiff<R extends UnknownRecord> {
357
382
  }
358
383
  }
359
384
 
385
+ function hasAnyKey(obj: object) {
386
+ for (const _ in obj) return true
387
+ return false
388
+ }
389
+
360
390
  type Stack<T> = StackItem<T> | EmptyStackItem<T>
361
391
 
362
392
  function stack<T>(): Stack<T> {
@@ -0,0 +1,61 @@
1
+ import { createTLStore } from '../../../config/createTLStore'
2
+ import { Editor } from '../../Editor'
3
+
4
+ function createTestEditor() {
5
+ const store = createTLStore({})
6
+ store.ensureStoreIsUsable()
7
+ return new Editor({
8
+ store,
9
+ bindingUtils: [],
10
+ shapeUtils: [],
11
+ getContainer: () => document.createElement('div'),
12
+ tools: [],
13
+ })
14
+ }
15
+
16
+ describe('InputsManager', () => {
17
+ let editor: Editor
18
+
19
+ beforeEach(() => {
20
+ editor = createTestEditor()
21
+ })
22
+
23
+ afterEach(() => {
24
+ editor.dispose()
25
+ })
26
+
27
+ it('updates pointer velocity on frame events', () => {
28
+ const point = editor.inputs.getCurrentScreenPoint()
29
+ point.x = 0
30
+ point.y = 0
31
+ editor.emit('frame', 16)
32
+
33
+ point.x = 100
34
+ point.y = 0
35
+ editor.emit('frame', 16)
36
+
37
+ expect(editor.inputs.getPointerVelocity().len()).toBeGreaterThan(0)
38
+ })
39
+
40
+ it('stops updating pointer velocity after dispose', () => {
41
+ const point = editor.inputs.getCurrentScreenPoint()
42
+ point.x = 0
43
+ point.y = 0
44
+ editor.emit('frame', 16)
45
+
46
+ point.x = 100
47
+ point.y = 0
48
+ editor.emit('frame', 16)
49
+
50
+ const velocityBeforeDispose = editor.inputs.getPointerVelocity().clone()
51
+ expect(velocityBeforeDispose.len()).toBeGreaterThan(0)
52
+
53
+ editor.inputs.dispose()
54
+
55
+ point.x = 200
56
+ point.y = 0
57
+ editor.emit('frame', 16)
58
+
59
+ expect(editor.inputs.getPointerVelocity()).toEqual(velocityBeforeDispose)
60
+ })
61
+ })