@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
@@ -137,6 +137,7 @@ import {
137
137
  areAnglesCompatible,
138
138
  clamp,
139
139
  pointInPolygon,
140
+ shortAngleDist,
140
141
  } from '../primitives/utils'
141
142
  import { Vec, VecLike } from '../primitives/Vec'
142
143
  import { areShapesContentEqual } from '../utils/areShapesContentEqual'
@@ -341,6 +342,11 @@ export interface TLRenderingShape {
341
342
 
342
343
  const RENDERING_SHAPES_SORT_CACHE_THRESHOLD = 100
343
344
 
345
+ const AXIS = {
346
+ horizontal: { val: 'x', min: 'minX', max: 'maxX', dim: 'width' },
347
+ vertical: { val: 'y', min: 'minY', max: 'maxY', dim: 'height' },
348
+ } as const
349
+
344
350
  /** @public */
345
351
  export class Editor extends EventEmitter<TLEventMap> {
346
352
  readonly id = uniqueId()
@@ -753,7 +759,9 @@ export class Editor extends EventEmitter<TLEventMap> {
753
759
  }
754
760
 
755
761
  if (deleteBindingIds.length) {
756
- this.deleteBindings(deleteBindingIds)
762
+ // straight to the store: this cleanup must run even when deleteBindings would
763
+ // refuse (readonly), e.g. for a deletion that arrived from a remote peer
764
+ this.store.remove(deleteBindingIds)
757
765
  }
758
766
  },
759
767
  },
@@ -1970,6 +1978,7 @@ export class Editor extends EventEmitter<TLEventMap> {
1970
1978
  * @public
1971
1979
  **/
1972
1980
  updateDocumentSettings(settings: Partial<TLDocument>): this {
1981
+ if (this.getIsReadonly()) return this
1973
1982
  this.run(
1974
1983
  () => {
1975
1984
  this.store.put([{ ...this.getDocumentSettings(), ...settings }])
@@ -2005,7 +2014,7 @@ export class Editor extends EventEmitter<TLEventMap> {
2005
2014
  this._updateInstanceState(partial, { history: 'ignore', ...historyOptions })
2006
2015
 
2007
2016
  if (partial.isChangingStyle !== undefined) {
2008
- clearTimeout(this._isChangingStyleTimeout)
2017
+ this.timers.clearTimeout(this._isChangingStyleTimeout)
2009
2018
  if (partial.isChangingStyle === true) {
2010
2019
  // If we've set to true, set a new reset timeout to change the value back to false after 1 seconds
2011
2020
  this._isChangingStyleTimeout = this.timers.setTimeout(() => {
@@ -2197,10 +2206,7 @@ export class Editor extends EventEmitter<TLEventMap> {
2197
2206
  * @public
2198
2207
  */
2199
2208
  select(...shapes: TLShapeId[] | TLShape[]): this {
2200
- const ids =
2201
- typeof shapes[0] === 'string'
2202
- ? (shapes as TLShapeId[])
2203
- : (shapes as TLShape[]).map((shape) => shape.id)
2209
+ const ids = toShapeIds(shapes)
2204
2210
  this.setSelectedShapes(ids)
2205
2211
  return this
2206
2212
  }
@@ -2216,10 +2222,7 @@ export class Editor extends EventEmitter<TLEventMap> {
2216
2222
  * @public
2217
2223
  */
2218
2224
  deselect(...shapes: TLShapeId[] | TLShape[]): this {
2219
- const ids =
2220
- typeof shapes[0] === 'string'
2221
- ? (shapes as TLShapeId[])
2222
- : (shapes as TLShape[]).map((shape) => shape.id)
2225
+ const ids = toShapeIds(shapes)
2223
2226
  const selectedShapeIds = this.getSelectedShapeIds()
2224
2227
  if (selectedShapeIds.length > 0 && ids.length > 0) {
2225
2228
  this.setSelectedShapes(selectedShapeIds.filter((id) => !ids.includes(id)))
@@ -2264,10 +2267,11 @@ export class Editor extends EventEmitter<TLEventMap> {
2264
2267
  parentToSelectWithinId = this.getCurrentPageId()
2265
2268
  }
2266
2269
 
2267
- // Select all the unlocked shapes within the parent
2270
+ // Select all the unlocked shapes within the parent. Only the shape's own lock matters here:
2271
+ // selecting inside a locked frame or group is allowed, mutating is not.
2268
2272
  const ids = this.getSortedChildIdsForParent(parentToSelectWithinId)
2269
2273
  if (ids.length <= 0) return this
2270
- this.setSelectedShapes(this._getUnlockedShapeIds(ids))
2274
+ this.setSelectedShapes(ids.filter((id) => !this.getShape(id)?.isLocked))
2271
2275
  return this
2272
2276
  }
2273
2277
 
@@ -2288,12 +2292,14 @@ export class Editor extends EventEmitter<TLEventMap> {
2288
2292
  firstParentId &&
2289
2293
  selectedShapeIds.every((shapeId) => this.getShape(shapeId)?.parentId === firstParentId) &&
2290
2294
  !isPageId(firstParentId)
2291
- const filteredShapes = isSelectedWithinContainer
2292
- ? this.getCurrentPageShapes().filter((shape) => shape.parentId === firstParentId)
2293
- : this.getCurrentPageShapes().filter((shape) => isPageId(shape.parentId))
2294
- const readingOrderShapes = isSelectedWithinContainer
2295
- ? this._getShapesInReadingOrder(filteredShapes)
2296
- : this.getCurrentPageShapesInReadingOrder()
2295
+ // Locked shapes (and children of locked containers) can't be selected by clicking or
2296
+ // select all, so traversal skips them too
2297
+ const filteredShapes = this.getCurrentPageShapes().filter(
2298
+ (shape) =>
2299
+ !this.isShapeOrAncestorLocked(shape) &&
2300
+ (isSelectedWithinContainer ? shape.parentId === firstParentId : isPageId(shape.parentId))
2301
+ )
2302
+ const readingOrderShapes = this._getShapesInReadingOrder(filteredShapes)
2297
2303
  const currentShapeId: TLShapeId | undefined =
2298
2304
  selectedShapeIds.length === 1
2299
2305
  ? selectedShapeIds[0]
@@ -2302,6 +2308,9 @@ export class Editor extends EventEmitter<TLEventMap> {
2302
2308
  let adjacentShapeId: TLShapeId
2303
2309
  if (direction === 'next' || direction === 'prev') {
2304
2310
  const shapeIds = readingOrderShapes.map((shape) => shape.id)
2311
+ // Every candidate can be filtered out (e.g. a locked shape is selected and nothing
2312
+ // else is unlocked); indexing an empty list would hand getShape undefined
2313
+ if (shapeIds.length === 0) return
2305
2314
 
2306
2315
  const currentIndex = currentShapeId ? shapeIds.indexOf(currentShapeId) : -1
2307
2316
  // With no current index, stepping from -1 makes 'prev' land one shape
@@ -2450,8 +2459,9 @@ export class Editor extends EventEmitter<TLEventMap> {
2450
2459
 
2451
2460
  // Ok, now score that subset of shapes.
2452
2461
  const lowestScoringShape = minBy(shapesInDirection, ({ center }) => {
2453
- // Distance is the primary weighting factor.
2454
- const distance = Vec.Dist2(currentCenter, center)
2462
+ // Linear, not squared: the off-axis and diagonal penalties below are page units too, and
2463
+ // squared distance swamps them, so a nearer diagonal shape beats an aligned one.
2464
+ const distance = Vec.Dist(currentCenter, center)
2455
2465
 
2456
2466
  // Distance along the primary axis.
2457
2467
  const dirProp = ['left', 'right'].includes(direction) ? 'x' : 'y'
@@ -2461,9 +2471,11 @@ export class Editor extends EventEmitter<TLEventMap> {
2461
2471
  const offProp = ['left', 'right'].includes(direction) ? 'y' : 'x'
2462
2472
  const offAxisDeviation = Math.abs(center[offProp] - currentCenter[offProp])
2463
2473
 
2464
- // Angle in degrees
2465
- const angle = Math.abs(Vec.Angle(currentCenter, center) * (180 / Math.PI))
2466
- const angleDeviation = Math.abs(angle - directionToAngle[direction])
2474
+ // atan2 gives -180..180, so 'up' is -90; normalize to 0..360 to match 270, and wrap the
2475
+ // deviation so that 350 is 10 away from 'right' (0), not 350.
2476
+ const angle = (Vec.Angle(currentCenter, center) * (180 / Math.PI) + 360) % 360
2477
+ const rawAngleDeviation = Math.abs(angle - directionToAngle[direction])
2478
+ const angleDeviation = Math.min(rawAngleDeviation, 360 - rawAngleDeviation)
2467
2479
 
2468
2480
  // Calculate final score (lower is better).
2469
2481
  // Weight factors to prioritize:
@@ -2968,10 +2980,7 @@ export class Editor extends EventEmitter<TLEventMap> {
2968
2980
  * @public
2969
2981
  */
2970
2982
  setHintingShapes(shapes: TLShapeId[] | TLShape[]): this {
2971
- const ids =
2972
- typeof shapes[0] === 'string'
2973
- ? (shapes as TLShapeId[])
2974
- : (shapes as TLShape[]).map((shape) => shape.id)
2983
+ const ids = toShapeIds(shapes)
2975
2984
  // always ephemeral
2976
2985
  this.run(
2977
2986
  () => {
@@ -3018,10 +3027,7 @@ export class Editor extends EventEmitter<TLEventMap> {
3018
3027
  */
3019
3028
  setErasingShapes(shapes: TLShapeId[] | TLShape[]): this {
3020
3029
  // copy before sorting: the caller may pass a store-owned (frozen) array
3021
- const ids =
3022
- typeof shapes[0] === 'string'
3023
- ? (shapes as TLShapeId[]).slice()
3024
- : (shapes as TLShape[]).map((shape) => shape.id)
3030
+ const ids = toShapeIds(shapes).slice()
3025
3031
  ids.sort() // sort the incoming ids
3026
3032
  const erasingShapeIds = this.getErasingShapeIds()
3027
3033
  this.run(
@@ -3595,6 +3601,20 @@ export class Editor extends EventEmitter<TLEventMap> {
3595
3601
  const { isLocked } = this._cameraOptions.__unsafe__getWithoutCapture()
3596
3602
  if (isLocked && !opts?.force) return this
3597
3603
 
3604
+ // Resolve the zoom before building the Vec: Vec.Cast would default a missing z to 1,
3605
+ // and a missing z should keep the current zoom level instead
3606
+ const _point = new Vec(point.x, point.y, point.z ?? this.getZoomLevel())
3607
+
3608
+ // Reject non-finite values before anything else, so the call is a no-op rather than a
3609
+ // partial one. An animated move writes the camera from a 'tick' listener, and a listener
3610
+ // that throws stops TickManager scheduling the next frame, which kills every frame-driven
3611
+ // behavior for the rest of the session instead of surfacing the error to the caller.
3612
+ if (!Number.isFinite(_point.x) || !Number.isFinite(_point.y) || !Number.isFinite(_point.z)) {
3613
+ throw Error(
3614
+ `Editor.setCamera: expected finite values, got (${_point.x}, ${_point.y}, ${_point.z}).`
3615
+ )
3616
+ }
3617
+
3598
3618
  // Stop any camera animations
3599
3619
  this.stopCameraAnimation()
3600
3620
 
@@ -3603,12 +3623,6 @@ export class Editor extends EventEmitter<TLEventMap> {
3603
3623
  this.stopFollowingUser()
3604
3624
  }
3605
3625
 
3606
- const _point = Vec.Cast(point)
3607
-
3608
- if (!Number.isFinite(_point.x)) _point.x = 0
3609
- if (!Number.isFinite(_point.y)) _point.y = 0
3610
- if (_point.z === undefined || !Number.isFinite(_point.z)) point.z = this.getZoomLevel()
3611
-
3612
3626
  const camera = this.getConstrainedCamera(_point, opts)
3613
3627
 
3614
3628
  if (opts?.animation) {
@@ -3943,6 +3957,7 @@ export class Editor extends EventEmitter<TLEventMap> {
3943
3957
  easing(t: number): number
3944
3958
  start: Box
3945
3959
  end: Box
3960
+ opts: TLCameraMoveOptions
3946
3961
  }
3947
3962
 
3948
3963
  /** @internal */
@@ -3951,12 +3966,17 @@ export class Editor extends EventEmitter<TLEventMap> {
3951
3966
 
3952
3967
  this._viewportAnimation.elapsed += ms
3953
3968
 
3954
- const { elapsed, easing, duration, start, end } = this._viewportAnimation
3969
+ const { elapsed, easing, duration, start, end, opts } = this._viewportAnimation
3955
3970
 
3956
3971
  if (elapsed > duration) {
3957
3972
  this.off('tick', this._animateViewport)
3958
3973
  this._viewportAnimation = null
3959
- this._setCamera(new Vec(-end.x, -end.y, this.getViewportScreenBounds().width / end.width))
3974
+ // Forward the caller's options, otherwise a forced move to a position outside the
3975
+ // constraints animates there and then snaps back on this last frame
3976
+ this._setCamera(
3977
+ new Vec(-end.x, -end.y, this.getViewportScreenBounds().width / end.width),
3978
+ opts
3979
+ )
3960
3980
  return
3961
3981
  }
3962
3982
 
@@ -4010,6 +4030,7 @@ export class Editor extends EventEmitter<TLEventMap> {
4010
4030
  easing,
4011
4031
  start: viewportPageBounds.clone(),
4012
4032
  end: targetViewportPage.clone(),
4033
+ opts: rest,
4013
4034
  }
4014
4035
 
4015
4036
  // If we ever get a "stop-camera-animation" event, we stop
@@ -4134,6 +4155,7 @@ export class Editor extends EventEmitter<TLEventMap> {
4134
4155
  // If we're not on the same page, move to the page they're on
4135
4156
  const isOnSamePage = presence.currentPageId === this.getCurrentPageId()
4136
4157
  if (!isOnSamePage) {
4158
+ this.markHistoryStoppingPoint('change-page')
4137
4159
  this.setCurrentPage(presence.currentPageId)
4138
4160
  }
4139
4161
 
@@ -5101,7 +5123,11 @@ export class Editor extends EventEmitter<TLEventMap> {
5101
5123
  const freshPage = this.getPage(id) // get the most recent version of the page anyway
5102
5124
  if (!freshPage) return this
5103
5125
 
5104
- const prevCamera = { ...this.getCamera() }
5126
+ // Read the source page's own camera rather than getCamera(), which is the
5127
+ // current page's and is wrong when duplicating a page that isn't being viewed
5128
+ const prevCamera = {
5129
+ ...(this.store.get(CameraRecordType.createId(freshPage.id)) ?? this.getCamera()),
5130
+ }
5105
5131
  const content = this.getContentFromCurrentPage(this.getSortedChildIdsForParent(freshPage.id))
5106
5132
 
5107
5133
  this.run(() => {
@@ -5116,8 +5142,9 @@ export class Editor extends EventEmitter<TLEventMap> {
5116
5142
  this.setCamera(prevCamera)
5117
5143
 
5118
5144
  if (content) {
5119
- // If we had content on the previous page, put it on the new page
5120
- return this.putContentOntoCurrentPage(content)
5145
+ // Without preservePosition the paste rule recenters off-screen content
5146
+ // in the viewport, so the copy's layout would not match the original
5147
+ return this.putContentOntoCurrentPage(content, { preservePosition: true })
5121
5148
  }
5122
5149
  })
5123
5150
 
@@ -5231,7 +5258,10 @@ export class Editor extends EventEmitter<TLEventMap> {
5231
5258
 
5232
5259
  this.run(
5233
5260
  () => {
5234
- this.store.props.assets.remove?.(ids)
5261
+ // the asset store's remove is async; surface failures instead of leaving an unhandled rejection
5262
+ Promise.resolve(this.store.props.assets.remove?.(ids)).catch((err) =>
5263
+ console.error('Error while removing assets from the asset store:', err)
5264
+ )
5235
5265
  this.store.remove(ids)
5236
5266
  },
5237
5267
  { history: 'ignore' }
@@ -5693,10 +5723,7 @@ export class Editor extends EventEmitter<TLEventMap> {
5693
5723
  return
5694
5724
  }
5695
5725
 
5696
- const ids =
5697
- typeof shapes[0] === 'string'
5698
- ? (shapes as TLShapeId[])
5699
- : (shapes as TLShape[]).map((s) => s.id)
5726
+ const ids = toShapeIds(shapes)
5700
5727
  const freshShapes = compact(ids.map((id) => this.getShape(id)))
5701
5728
 
5702
5729
  if (freshShapes.length === 1) {
@@ -5844,14 +5871,16 @@ export class Editor extends EventEmitter<TLEventMap> {
5844
5871
  */
5845
5872
  getSelectedShapeAtPoint(point: VecLike): TLShape | undefined {
5846
5873
  const selectedShapeIds = this.getSelectedShapeIds()
5847
- const margin = this.options.hitTestMargin / this.getZoomLevel()
5874
+ if (selectedShapeIds.length === 0) return undefined
5875
+ const selectedShapeIdSet = new Set(selectedShapeIds)
5876
+ const margin = this.getHitTestMargin()
5848
5877
  const sortedShapes = this.getCurrentPageShapesSorted()
5849
5878
 
5850
5879
  // iterate from the top (highest z-index) to find the top-most matching shape
5851
5880
  for (let i = sortedShapes.length - 1; i >= 0; i--) {
5852
5881
  const shape = sortedShapes[i]
5853
5882
  if (shape.type === 'group') continue
5854
- if (!selectedShapeIds.includes(shape.id)) continue
5883
+ if (!selectedShapeIdSet.has(shape.id)) continue
5855
5884
  if (
5856
5885
  this.getShapeGeometry(shape).hitTestPoint(
5857
5886
  this.getPointInShapeSpace(shape, point),
@@ -6022,9 +6051,6 @@ export class Editor extends EventEmitter<TLEventMap> {
6022
6051
  // other hits would be occluded by the shape.
6023
6052
  return inMarginClosestToEdgeHit || shape
6024
6053
  } else {
6025
- // If the shape is bigger than the viewport, then skip it.
6026
- if (this.getShapePageBounds(shape)!.contains(viewportPageBounds)) continue
6027
-
6028
6054
  // If we're close to the edge of the shape, and if it's the closest edge among
6029
6055
  // all the edges that we've gotten close to so far, then we will want to hit the
6030
6056
  // shape unless we hit something else or closer in later iterations.
@@ -6045,6 +6071,10 @@ export class Editor extends EventEmitter<TLEventMap> {
6045
6071
  inMarginClosestToEdgeHit = shape
6046
6072
  }
6047
6073
  } else if (!inMarginClosestToEdgeHit) {
6074
+ // If the shape is bigger than the viewport, then skip it. (Only here: its
6075
+ // edges should still be hittable within the margin.)
6076
+ if (this.getShapePageBounds(shape)!.contains(viewportPageBounds)) continue
6077
+
6048
6078
  // If we're not within margin distance to any edge, and if the
6049
6079
  // shape is hollow, then we want to hit the shape with the
6050
6080
  // smallest area. (There's a bug here with self-intersecting
@@ -6063,6 +6093,11 @@ export class Editor extends EventEmitter<TLEventMap> {
6063
6093
  // If the distance is less than the margin, return the shape as the hit.
6064
6094
  // Use the editor's configurable hit test margin.
6065
6095
  if (distance < this.getHitTestMargin()) {
6096
+ // An edge we already hit (above this shape) that is at least as close still wins,
6097
+ // matching the closest-edge rule used for hollow shapes
6098
+ if (inMarginClosestToEdgeHit && inMarginClosestToEdgeDistance <= distance) {
6099
+ return inMarginClosestToEdgeHit
6100
+ }
6066
6101
  return shape
6067
6102
  }
6068
6103
  }
@@ -6427,8 +6462,7 @@ export class Editor extends EventEmitter<TLEventMap> {
6427
6462
  * @public
6428
6463
  */
6429
6464
  reparentShapes(shapes: TLShapeId[] | TLShape[], parentId: TLParentId, insertIndex?: IndexKey) {
6430
- const ids =
6431
- typeof shapes[0] === 'string' ? (shapes as TLShapeId[]) : shapes.map((s) => (s as TLShape).id)
6465
+ const ids = toShapeIds(shapes)
6432
6466
  if (ids.length === 0) return this
6433
6467
 
6434
6468
  const changes: TLShapePartial[] = []
@@ -6777,6 +6811,8 @@ export class Editor extends EventEmitter<TLEventMap> {
6777
6811
  * binding, but the `type`, `toId`, and `fromId` must all be provided.
6778
6812
  */
6779
6813
  createBindings<B extends TLBinding = TLBinding>(partials: TLBindingCreate<B>[]) {
6814
+ if (this.getIsReadonly()) return this
6815
+
6780
6816
  const bindings: TLBinding[] = []
6781
6817
  for (const partial of partials) {
6782
6818
  const fromShape = this.getShape(partial.fromId)
@@ -6816,6 +6852,8 @@ export class Editor extends EventEmitter<TLEventMap> {
6816
6852
  * binding is skipped. The changes from the partial are merged into the existing record.
6817
6853
  */
6818
6854
  updateBindings(partials: (TLBindingUpdate | null | undefined)[]) {
6855
+ if (this.getIsReadonly()) return this
6856
+
6819
6857
  const updated: TLBinding[] = []
6820
6858
 
6821
6859
  for (const partial of partials) {
@@ -6853,6 +6891,17 @@ export class Editor extends EventEmitter<TLEventMap> {
6853
6891
  * Delete several bindings by their IDs. If a binding ID doesn't exist, it's ignored.
6854
6892
  */
6855
6893
  deleteBindings(bindings: (TLBinding | TLBindingId)[], { isolateShapes = false } = {}) {
6894
+ if (this.getIsReadonly()) return this
6895
+ return this._deleteBindings(bindings, { isolateShapes })
6896
+ }
6897
+
6898
+ /**
6899
+ * Unguarded so that withIsolatedShapes can transiently isolate shapes for copy and export in
6900
+ * readonly mode; the public deleteBindings is what readonly blocks.
6901
+ *
6902
+ * @internal
6903
+ */
6904
+ _deleteBindings(bindings: (TLBinding | TLBindingId)[], { isolateShapes = false } = {}) {
6856
6905
  const ids = bindings.map((binding) => (typeof binding === 'string' ? binding : binding.id))
6857
6906
  if (isolateShapes) {
6858
6907
  this.store.atomic(() => {
@@ -6927,10 +6976,7 @@ export class Editor extends EventEmitter<TLEventMap> {
6927
6976
  delta: number,
6928
6977
  opts?: { center?: VecLike }
6929
6978
  ): this {
6930
- const ids =
6931
- typeof shapes[0] === 'string'
6932
- ? (shapes as TLShapeId[])
6933
- : (shapes as TLShape[]).map((s) => s.id)
6979
+ const ids = toShapeIds(shapes)
6934
6980
 
6935
6981
  if (ids.length <= 0) return this
6936
6982
 
@@ -6977,6 +7023,15 @@ export class Editor extends EventEmitter<TLEventMap> {
6977
7023
  return workingShape
6978
7024
  }
6979
7025
 
7026
+ // Counter-rotates the page-space delta into the parent's space; without that a child of a rotated
7027
+ // frame or group would move along its parent's axes instead of the page's.
7028
+ // todo: a shape laid out together with its own parent moves twice, once with the parent and once
7029
+ // on its own; the layout commands should skip shapes whose ancestors are also being laid out
7030
+ private getChangesToTranslateShapeByPageDelta(shape: TLShape, pageDelta: VecLike): TLShape {
7031
+ const localDelta = Vec.From(pageDelta).rot(-this.getShapeParentTransform(shape).rotation())
7032
+ return this.getChangesToTranslateShape(shape, localDelta.add(shape))
7033
+ }
7034
+
6980
7035
  /**
6981
7036
  * Move shapes by a delta.
6982
7037
  *
@@ -6989,20 +7044,14 @@ export class Editor extends EventEmitter<TLEventMap> {
6989
7044
  * @param offset - The offset to apply to the shapes.
6990
7045
  */
6991
7046
  nudgeShapes(shapes: TLShapeId[] | TLShape[], offset: VecLike): this {
6992
- const ids =
6993
- typeof shapes[0] === 'string'
6994
- ? (shapes as TLShapeId[])
6995
- : (shapes as TLShape[]).map((s) => s.id)
7047
+ const ids = toShapeIds(shapes)
6996
7048
 
6997
7049
  if (ids.length <= 0) return this
6998
7050
  const changes: TLShapePartial[] = []
6999
7051
 
7000
7052
  for (const id of ids) {
7001
7053
  const shape = this.getShape(id)!
7002
- const localDelta = Vec.From(offset)
7003
- localDelta.rot(-this.getShapeParentTransform(shape).rotation())
7004
-
7005
- changes.push(this.getChangesToTranslateShape(shape, localDelta.add(shape)))
7054
+ changes.push(this.getChangesToTranslateShapeByPageDelta(shape, offset))
7006
7055
  }
7007
7056
 
7008
7057
  this.updateShapes(changes)
@@ -7026,10 +7075,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7026
7075
  */
7027
7076
  duplicateShapes(shapes: TLShapeId[] | TLShape[], offset?: VecLike): this {
7028
7077
  this.run(() => {
7029
- const _ids =
7030
- typeof shapes[0] === 'string'
7031
- ? (shapes as TLShapeId[])
7032
- : (shapes as TLShape[]).map((s) => s.id)
7078
+ const _ids = toShapeIds(shapes)
7033
7079
 
7034
7080
  const ids = this._shouldIgnoreShapeLock ? _ids : this._getUnlockedShapeIds(_ids)
7035
7081
  if (ids.length <= 0) return this
@@ -7171,10 +7217,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7171
7217
  * @public
7172
7218
  */
7173
7219
  moveShapesToPage(shapes: TLShapeId[] | TLShape[], pageId: TLPageId): this {
7174
- const ids =
7175
- typeof shapes[0] === 'string'
7176
- ? (shapes as TLShapeId[])
7177
- : (shapes as TLShape[]).map((s) => s.id)
7220
+ const ids = toShapeIds(shapes)
7178
7221
 
7179
7222
  if (ids.length === 0) return this
7180
7223
  if (this.getIsReadonly()) return this
@@ -7235,10 +7278,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7235
7278
  * @public
7236
7279
  */
7237
7280
  toggleLock(shapes: TLShapeId[] | TLShape[]): this {
7238
- const ids =
7239
- typeof shapes[0] === 'string'
7240
- ? (shapes as TLShapeId[])
7241
- : (shapes as TLShape[]).map((s) => s.id)
7281
+ const ids = toShapeIds(shapes)
7242
7282
 
7243
7283
  if (this.getIsReadonly() || ids.length === 0) return this
7244
7284
 
@@ -7281,11 +7321,8 @@ export class Editor extends EventEmitter<TLEventMap> {
7281
7321
  * @public
7282
7322
  */
7283
7323
  sendToBack(shapes: TLShapeId[] | TLShape[]): this {
7284
- const ids =
7285
- typeof shapes[0] === 'string'
7286
- ? (shapes as TLShapeId[])
7287
- : (shapes as TLShape[]).map((s) => s.id)
7288
- const changes = getReorderingShapesChanges(this, 'toBack', ids as TLShapeId[], {
7324
+ const ids = toShapeIds(shapes)
7325
+ const changes = getReorderingShapesChanges(this, 'toBack', ids, {
7289
7326
  considerAllShapes: true,
7290
7327
  })
7291
7328
  if (changes) this.updateShapes(changes)
@@ -7315,11 +7352,8 @@ export class Editor extends EventEmitter<TLEventMap> {
7315
7352
  * @public
7316
7353
  */
7317
7354
  sendBackward(shapes: TLShapeId[] | TLShape[], opts: { considerAllShapes?: boolean } = {}): this {
7318
- const ids =
7319
- typeof shapes[0] === 'string'
7320
- ? (shapes as TLShapeId[])
7321
- : (shapes as TLShape[]).map((s) => s.id)
7322
- const changes = getReorderingShapesChanges(this, 'backward', ids as TLShapeId[], opts)
7355
+ const ids = toShapeIds(shapes)
7356
+ const changes = getReorderingShapesChanges(this, 'backward', ids, opts)
7323
7357
  if (changes) this.updateShapes(changes)
7324
7358
  return this
7325
7359
  }
@@ -7347,11 +7381,8 @@ export class Editor extends EventEmitter<TLEventMap> {
7347
7381
  * @public
7348
7382
  */
7349
7383
  bringForward(shapes: TLShapeId[] | TLShape[], opts: { considerAllShapes?: boolean } = {}): this {
7350
- const ids =
7351
- typeof shapes[0] === 'string'
7352
- ? (shapes as TLShapeId[])
7353
- : (shapes as TLShape[]).map((s) => s.id)
7354
- const changes = getReorderingShapesChanges(this, 'forward', ids as TLShapeId[], opts)
7384
+ const ids = toShapeIds(shapes)
7385
+ const changes = getReorderingShapesChanges(this, 'forward', ids, opts)
7355
7386
  if (changes) this.updateShapes(changes)
7356
7387
  return this
7357
7388
  }
@@ -7370,11 +7401,8 @@ export class Editor extends EventEmitter<TLEventMap> {
7370
7401
  * @public
7371
7402
  */
7372
7403
  bringToFront(shapes: TLShapeId[] | TLShape[]): this {
7373
- const ids =
7374
- typeof shapes[0] === 'string'
7375
- ? (shapes as TLShapeId[])
7376
- : (shapes as TLShape[]).map((s) => s.id)
7377
- const changes = getReorderingShapesChanges(this, 'toFront', ids as TLShapeId[])
7404
+ const ids = toShapeIds(shapes)
7405
+ const changes = getReorderingShapesChanges(this, 'toFront', ids)
7378
7406
  if (changes) this.updateShapes(changes)
7379
7407
  return this
7380
7408
  }
@@ -7390,10 +7418,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7390
7418
  type: TLShapeUtilCanBeLaidOutOpts['type'],
7391
7419
  opts?: { filterAxisAligned?: boolean }
7392
7420
  ): { clusters: { shapes: TLShape[]; pageBounds: Box }[]; allBounds: Box[] } {
7393
- const ids =
7394
- typeof shapes[0] === 'string'
7395
- ? (shapes as TLShapeId[])
7396
- : (shapes as TLShape[]).map((s) => s.id)
7421
+ const ids = toShapeIds(shapes)
7397
7422
 
7398
7423
  // always fresh shapes
7399
7424
  let freshShapes = compact(ids.map((id) => this.getShape(id)))
@@ -7431,8 +7456,10 @@ export class Editor extends EventEmitter<TLEventMap> {
7431
7456
  const shapesMovingTogether = [shape]
7432
7457
  const boundsOfShapesMovingTogether: Box[] = [shapePageBounds]
7433
7458
 
7459
+ // Seed with bindings in both directions, otherwise an arrow visited before the shapes it
7460
+ // binds ends up in a cluster of its own and the result depends on input order
7434
7461
  this.collectShapesViaArrowBindings({
7435
- bindings: this.getBindingsToShape(shape.id, 'arrow'),
7462
+ bindings: this.getBindingsInvolvingShape(shape.id, 'arrow'),
7436
7463
  initialShapes: freshShapes,
7437
7464
  resultShapes: shapesMovingTogether,
7438
7465
  resultBounds: boundsOfShapesMovingTogether,
@@ -7501,10 +7528,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7501
7528
  flipShapes(shapes: TLShapeId[] | TLShape[], operation: 'horizontal' | 'vertical'): this {
7502
7529
  if (this.getIsReadonly()) return this
7503
7530
 
7504
- const ids =
7505
- typeof shapes[0] === 'string'
7506
- ? (shapes as TLShapeId[])
7507
- : (shapes as TLShape[]).map((s) => s.id)
7531
+ const ids = toShapeIds(shapes)
7508
7532
 
7509
7533
  // Collect a greedy list of shapes to flip
7510
7534
  const shapesToFlipFirstPass = compact(ids.map((id) => this.getShape(id)))
@@ -7607,22 +7631,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7607
7631
  const len = shapeClustersToStack.length
7608
7632
  if ((_gap === 0 && len < 3) || len < 2) return this
7609
7633
 
7610
- let val: 'x' | 'y'
7611
- let min: 'minX' | 'minY'
7612
- let max: 'maxX' | 'maxY'
7613
- let dim: 'width' | 'height'
7614
-
7615
- if (operation === 'horizontal') {
7616
- val = 'x'
7617
- min = 'minX'
7618
- max = 'maxX'
7619
- dim = 'width'
7620
- } else {
7621
- val = 'y'
7622
- min = 'minY'
7623
- max = 'maxY'
7624
- dim = 'height'
7625
- }
7634
+ const { val, min, max, dim } = AXIS[operation]
7626
7635
 
7627
7636
  let shapeGap: number = 0
7628
7637
 
@@ -7680,17 +7689,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7680
7689
  delta[val] = v + shapeGap - pageBounds[val]
7681
7690
 
7682
7691
  for (const shape of shapes) {
7683
- const shapeDelta = delta.clone()
7684
-
7685
- // If the shape has another shape as its parent, and if the parent has a rotation, we need to rotate the counter-rotate delta
7686
- // todo: ensure that the parent isn't being aligned together with its children
7687
- const parent = this.getShapeParent(shape)
7688
- if (parent) {
7689
- shapeDelta.rot(-this.getShapePageTransform(parent).rotation())
7690
- }
7691
-
7692
- shapeDelta.add(shape) // add the shape's x and y to the delta
7693
- changes.push(this.getChangesToTranslateShape(shape, shapeDelta))
7692
+ changes.push(this.getChangesToTranslateShapeByPageDelta(shape, delta))
7694
7693
  }
7695
7694
 
7696
7695
  v += pageBounds[dim] + shapeGap
@@ -7806,15 +7805,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7806
7805
  const delta = Vec.Sub(nextPageBounds.point, pageBounds.point).add(centerDelta)
7807
7806
 
7808
7807
  for (const shape of shapes) {
7809
- const shapeDelta = delta.clone()
7810
-
7811
- const parent = this.getShapeParent(shape)
7812
- if (parent) {
7813
- shapeDelta.rot(-this.getShapeParentTransform(shape).rotation())
7814
- }
7815
-
7816
- shapeDelta.add(shape)
7817
- changes.push(this.getChangesToTranslateShape(shape, shapeDelta))
7808
+ changes.push(this.getChangesToTranslateShapeByPageDelta(shape, delta))
7818
7809
  }
7819
7810
  }
7820
7811
 
@@ -7894,17 +7885,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7894
7885
  }
7895
7886
 
7896
7887
  for (const shape of shapes) {
7897
- const shapeDelta = delta.clone()
7898
-
7899
- // If the shape has another shape as its parent, and if the parent has a rotation, we need to rotate the counter-rotate delta
7900
- // todo: ensure that the parent isn't being aligned together with its children
7901
- const parent = this.getShapeParent(shape)
7902
- if (parent) {
7903
- shapeDelta.rot(-this.getShapePageTransform(parent).rotation())
7904
- }
7905
-
7906
- shapeDelta.add(shape) // add the shape's x and y to the delta
7907
- changes.push(this.getChangesToTranslateShape(shape, shapeDelta))
7888
+ changes.push(this.getChangesToTranslateShapeByPageDelta(shape, delta))
7908
7889
  }
7909
7890
  })
7910
7891
 
@@ -7933,22 +7914,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7933
7914
 
7934
7915
  if (shapeClustersToDistribute.length < 3) return this
7935
7916
 
7936
- let val: 'x' | 'y'
7937
- let min: 'minX' | 'minY'
7938
- let max: 'maxX' | 'maxY'
7939
- let dim: 'width' | 'height'
7940
-
7941
- if (operation === 'horizontal') {
7942
- val = 'x'
7943
- min = 'minX'
7944
- max = 'maxX'
7945
- dim = 'width'
7946
- } else {
7947
- val = 'y'
7948
- min = 'minY'
7949
- max = 'maxY'
7950
- dim = 'height'
7951
- }
7917
+ const { val, min, max, dim } = AXIS[operation]
7952
7918
  const changes: TLShapePartial[] = []
7953
7919
 
7954
7920
  const first = shapeClustersToDistribute.sort((a, b) => a.pageBounds[min] - b.pageBounds[min])[0]
@@ -7957,10 +7923,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7957
7923
  // If the first shape group is also the last shape group, distribute without it
7958
7924
  if (first === last) {
7959
7925
  const excludedShapeIds = new Set(first.shapes.map((s) => s.id))
7960
- const ids =
7961
- typeof shapes[0] === 'string'
7962
- ? (shapes as TLShapeId[])
7963
- : (shapes as TLShape[]).map((s) => s.id)
7926
+ const ids = toShapeIds(shapes)
7964
7927
  return this.distributeShapes(
7965
7928
  ids.filter((id) => !excludedShapeIds.has(id)),
7966
7929
  operation
@@ -7994,17 +7957,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7994
7957
  }
7995
7958
 
7996
7959
  for (const shape of shapes) {
7997
- const shapeDelta = delta.clone()
7998
-
7999
- // If the shape has another shape as its parent, and if the parent has a rotation, we need to rotate the counter-rotate delta
8000
- // todo: ensure that the parent isn't being aligned together with its children
8001
- const parent = this.getShapeParent(shape)
8002
- if (parent) {
8003
- shapeDelta.rot(-this.getShapePageTransform(parent).rotation())
8004
- }
8005
-
8006
- shapeDelta.add(shape) // add the shape's x and y to the delta
8007
- changes.push(this.getChangesToTranslateShape(shape, shapeDelta))
7960
+ changes.push(this.getChangesToTranslateShapeByPageDelta(shape, delta))
8008
7961
  }
8009
7962
 
8010
7963
  v += pageBounds[dim] + gap
@@ -8040,24 +7993,12 @@ export class Editor extends EventEmitter<TLEventMap> {
8040
7993
  if (shapeClustersToStretch.length < 2) return this
8041
7994
 
8042
7995
  const commonBounds = Box.Common(allBounds)
8043
- let val: 'x' | 'y'
8044
- let min: 'minX' | 'minY'
8045
- let dim: 'width' | 'height'
8046
-
8047
- if (operation === 'horizontal') {
8048
- val = 'x'
8049
- min = 'minX'
8050
- dim = 'width'
8051
- } else {
8052
- val = 'y'
8053
- min = 'minY'
8054
- dim = 'height'
8055
- }
7996
+ const { val, min, dim } = AXIS[operation]
8056
7997
 
8057
7998
  this.run(() => {
8058
7999
  shapeClustersToStretch.forEach(({ shapes, pageBounds }) => {
8059
- const localOffset = new Vec()
8060
- localOffset[val] = commonBounds[min] - pageBounds[min]
8000
+ const pageOffset = new Vec()
8001
+ pageOffset[val] = commonBounds[min] - pageBounds[min]
8061
8002
 
8062
8003
  const scaleOrigin = pageBounds.center.clone()
8063
8004
  scaleOrigin[val] = commonBounds[min]
@@ -8067,11 +8008,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8067
8008
 
8068
8009
  for (const shape of shapes) {
8069
8010
  // First translate
8070
- const shapeLocalOffset = localOffset.clone()
8071
- shapeLocalOffset.rot(-this.getShapeParentTransform(shape).rotation())
8072
- shapeLocalOffset.add(shape)
8073
- const changes = this.getChangesToTranslateShape(shape, shapeLocalOffset)
8074
- this.updateShape(changes)
8011
+ this.updateShape(this.getChangesToTranslateShapeByPageDelta(shape, pageOffset))
8075
8012
 
8076
8013
  // Then resize
8077
8014
  this.resizeShape(shape.id, scale, {
@@ -8124,7 +8061,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8124
8061
  const scale = new Vec(scaleX, scaleY)
8125
8062
 
8126
8063
  shapeClusters.forEach(({ shapes, pageBounds }) => {
8127
- const localOffset = new Vec(
8064
+ const pageOffset = new Vec(
8128
8065
  targetBounds.minX -
8129
8066
  commonBounds.minX +
8130
8067
  (pageBounds.minX - commonBounds.minX) * (scaleX - 1),
@@ -8138,11 +8075,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8138
8075
 
8139
8076
  for (const shape of shapes) {
8140
8077
  // First translate
8141
- const shapeLocalOffset = localOffset.clone()
8142
- shapeLocalOffset.rot(-this.getShapeParentTransform(shape).rotation())
8143
- shapeLocalOffset.add(shape)
8144
- const changes = this.getChangesToTranslateShape(shape, shapeLocalOffset)
8145
- this.updateShape(changes)
8078
+ this.updateShape(this.getChangesToTranslateShapeByPageDelta(shape, pageOffset))
8146
8079
 
8147
8080
  // Then resize
8148
8081
  this.resizeShape(shape.id, scale, {
@@ -8386,6 +8319,9 @@ export class Editor extends EventEmitter<TLEventMap> {
8386
8319
  initialShape: TLShape
8387
8320
  isAspectRatioLocked: boolean
8388
8321
  initialPageTransform: MatLike
8322
+ dragHandle?: TLResizeHandle
8323
+ mode?: TLResizeMode
8324
+ skipStartAndEndCallbacks?: boolean
8389
8325
  }
8390
8326
  ) {
8391
8327
  const { type } = options.initialShape
@@ -8410,19 +8346,39 @@ export class Editor extends EventEmitter<TLEventMap> {
8410
8346
  initialBounds: options.initialBounds,
8411
8347
  isAspectRatioLocked: options.isAspectRatioLocked,
8412
8348
  initialPageTransform: options.initialPageTransform,
8349
+ dragHandle: options.dragHandle,
8350
+ mode: options.mode,
8351
+ // this is one frame of the same resize, not a new one, so don't fire start/end again
8352
+ skipStartAndEndCallbacks: options.skipStartAndEndCallbacks,
8413
8353
  })
8414
8354
 
8415
8355
  // then if the shape is flipped in one axis only, we need to apply an extra rotation
8416
8356
  // to make sure the shape is mirrored correctly
8417
8357
  if (Math.sign(scale.x) * Math.sign(scale.y) < 0) {
8418
- // We need to compute the new local rotation that will result in the negated page rotation.
8419
- // For a shape with local rotation `localRot` and parent page rotation `parentRot`:
8358
+ // Mirroring across an axis at angle `axisRot` maps a page rotation `pageRot` to
8359
+ // `2 * axisRot - pageRot`. For a shape with local rotation `localRot` whose parent had
8360
+ // page rotation `parentRot` when the resize began:
8420
8361
  // - pageRot = parentRot + localRot
8421
- // - newPageRot = -pageRot (we want to negate the page rotation)
8422
- // - newPageRot = parentRot + newLocalRot (parent hasn't changed)
8423
- // - Therefore: newLocalRot = -pageRot - parentRot = -(parentRot + localRot) - parentRot = -localRot - 2*parentRot
8362
+ // - newPageRot = 2 * axisRot - pageRot
8363
+ // - newPageRot = (parentRot + parentDelta) + newLocalRot
8364
+ // - Therefore: newLocalRot = 2 * axisRot - localRot - 2 * parentRot - parentDelta
8365
+ // `parentDelta` is how far the parent has rotated since the resize began. Nested resizes
8366
+ // commit ancestors before descendants, so an unaligned parent may itself have been
8367
+ // flipped by the time its child gets here; reading the parent's current rotation as if
8368
+ // it were the initial one would then double-count that flip.
8424
8369
  const parentRotation = this.getShapeParentTransform(id).rotation()
8425
- const rotation = -options.initialShape.rotation - 2 * parentRotation
8370
+ // take the shortest arc so the stored rotation doesn't drift by 2π when the parent
8371
+ // hasn't moved and the initial page rotation happens to be wrapped
8372
+ const parentDelta = shortAngleDist(
8373
+ Mat.Cast(options.initialPageTransform).rotation() - options.initialShape.rotation,
8374
+ parentRotation
8375
+ )
8376
+ const initialParentRotation = parentRotation - parentDelta
8377
+ const rotation =
8378
+ 2 * options.scaleAxisRotation -
8379
+ options.initialShape.rotation -
8380
+ 2 * initialParentRotation -
8381
+ parentDelta
8426
8382
  this.updateShapes([{ id, type, rotation }])
8427
8383
  }
8428
8384
 
@@ -8787,6 +8743,11 @@ export class Editor extends EventEmitter<TLEventMap> {
8787
8743
 
8788
8744
  const animations: ShapeAnimation[] = []
8789
8745
 
8746
+ // Snapshot the lock override now: when this animation is started inside
8747
+ // editor.run(..., { ignoreShapeLock: true }), run() restores the flag before any tick
8748
+ // fires, so the final updateShapes below would refuse the locked shape and strand it
8749
+ const ignoreShapeLock = this._shouldIgnoreShapeLock
8750
+
8790
8751
  let partial: TLShapePartial | null | undefined, result: ShapeAnimation
8791
8752
  for (let i = 0, n = partials.length; i < n; i++) {
8792
8753
  partial = partials[i]
@@ -8795,6 +8756,14 @@ export class Editor extends EventEmitter<TLEventMap> {
8795
8756
  const shape = this.getShape(partial.id)!
8796
8757
  if (!shape) continue
8797
8758
 
8759
+ // Apply the same lock rule as updateShapes up front: the intermediate frames go through
8760
+ // _updateShapes, which doesn't check locks, so a locked shape would otherwise be moved by
8761
+ // every frame but the last and end up stranded at the penultimate one
8762
+ const unlocks = shape.isLocked && Object.hasOwn(partial, 'isLocked') && !partial.isLocked
8763
+ if (!ignoreShapeLock && !unlocks && this.isShapeOrAncestorLocked(shape)) {
8764
+ continue
8765
+ }
8766
+
8798
8767
  result = {
8799
8768
  start: structuredClone(shape),
8800
8769
  end: applyPartialToRecordWithProps(structuredClone(shape), partial),
@@ -8815,7 +8784,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8815
8784
  if (partialsToUpdate.length) {
8816
8785
  // the regular update shapes also removes the shape from
8817
8786
  // the animating shapes set
8818
- this.updateShapes(partialsToUpdate)
8787
+ this.run(() => this.updateShapes(partialsToUpdate), { ignoreShapeLock })
8819
8788
  }
8820
8789
 
8821
8790
  this.off('tick', handleTick)
@@ -8882,18 +8851,16 @@ export class Editor extends EventEmitter<TLEventMap> {
8882
8851
  }
8883
8852
  if (this.getIsReadonly()) return this
8884
8853
 
8885
- const ids =
8886
- typeof shapes[0] === 'string'
8887
- ? (shapes as TLShapeId[])
8888
- : (shapes.map((s) => (s as TLShape).id) as TLShapeId[])
8889
-
8890
- if (ids.length <= 1) return this
8854
+ const ids = toShapeIds(shapes)
8891
8855
 
8892
8856
  const shapesToGroup = compact(
8893
8857
  (this._shouldIgnoreShapeLock ? ids : this._getUnlockedShapeIds(ids)).map((id) =>
8894
8858
  this.getShape(id)
8895
8859
  )
8896
8860
  )
8861
+ // Re-check after the lock filter: Box.Common of nothing is not a valid box and would throw
8862
+ if (shapesToGroup.length <= 1) return this
8863
+
8897
8864
  const sortedShapeIds = shapesToGroup.sort(sortByIndex).map((s) => s.id)
8898
8865
  const childBounds = compact(shapesToGroup.map((shape) => this.getShapePageBounds(shape)))
8899
8866
  const pageBounds = Box.Common(childBounds)
@@ -8906,11 +8873,15 @@ export class Editor extends EventEmitter<TLEventMap> {
8906
8873
 
8907
8874
  const parentId = this.findCommonAncestor(shapesToGroup) ?? this.getCurrentPageId()
8908
8875
 
8909
- // Only group when the select tool is active
8910
- if (this.getCurrentToolId() !== 'select') return this
8876
+ // createShapes bails out when the page is full, so check first; otherwise the shapes get
8877
+ // reparented into a group that was never created and vanish from the page
8878
+ if (!this.canCreateShapes([groupId])) {
8879
+ alertMaxShapes(this)
8880
+ return this
8881
+ }
8911
8882
 
8912
- // If not already in idle, cancel the current interaction (get back to idle)
8913
- if (!this.isIn('select.idle')) {
8883
+ // If the select tool is mid-interaction, cancel it (get back to idle) before grouping
8884
+ if (this.isIn('select') && !this.isIn('select.idle')) {
8914
8885
  this.cancel()
8915
8886
  }
8916
8887
 
@@ -8964,10 +8935,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8964
8935
  if (this.getIsReadonly()) return this
8965
8936
 
8966
8937
  const { select = true } = opts
8967
- const ids =
8968
- typeof shapes[0] === 'string'
8969
- ? (shapes as TLShapeId[])
8970
- : (shapes as TLShape[]).map((s) => s.id)
8938
+ const ids = toShapeIds(shapes)
8971
8939
 
8972
8940
  const shapesToUngroup = compact(
8973
8941
  (this._shouldIgnoreShapeLock ? ids : this._getUnlockedShapeIds(ids)).map((id) =>
@@ -8977,9 +8945,8 @@ export class Editor extends EventEmitter<TLEventMap> {
8977
8945
 
8978
8946
  if (shapesToUngroup.length === 0) return this
8979
8947
 
8980
- // todo: the editor shouldn't know about the select tool, move to group / ungroup actions
8981
- if (this.getCurrentToolId() !== 'select') return this
8982
- if (!this.isIn('select.idle')) {
8948
+ // If the select tool is mid-interaction, cancel it (get back to idle) before ungrouping
8949
+ if (this.isIn('select') && !this.isIn('select.idle')) {
8983
8950
  this.cancel()
8984
8951
  }
8985
8952
 
@@ -9002,10 +8969,12 @@ export class Editor extends EventEmitter<TLEventMap> {
9002
8969
  if (groups.length === 0) return this
9003
8970
 
9004
8971
  this.run(() => {
9005
- let group: TLGroupShape
9006
-
9007
8972
  for (let i = 0, n = groups.length; i < n; i++) {
9008
- group = groups[i]
8973
+ // Re-read the group: ungrouping an outer group earlier in this loop reparents the
8974
+ // inner ones, and the stale parentId would send their children into a group that's
8975
+ // about to be deleted
8976
+ const group = this.getShape<TLGroupShape>(groups[i].id)
8977
+ if (!group) continue
9009
8978
  const childIds = this.getSortedChildIdsForParent(group.id)
9010
8979
 
9011
8980
  for (let j = 0, n = childIds.length; j < n; j++) {
@@ -9132,7 +9101,9 @@ export class Editor extends EventEmitter<TLEventMap> {
9132
9101
 
9133
9102
  /** @internal */
9134
9103
  private _getUnlockedShapeIds(ids: TLShapeId[]): TLShapeId[] {
9135
- return ids.filter((id) => !this.getShape(id)?.isLocked)
9104
+ // Match updateShapes, which also refuses shapes under a locked ancestor; otherwise a child
9105
+ // of a locked frame can't be moved but can still be deleted or duplicated
9106
+ return ids.filter((id) => !this.isShapeOrAncestorLocked(id))
9136
9107
  }
9137
9108
 
9138
9109
  /**
@@ -9156,8 +9127,7 @@ export class Editor extends EventEmitter<TLEventMap> {
9156
9127
  throw Error('Editor.deleteShapes: must provide an array of shapes or shapeIds')
9157
9128
  }
9158
9129
 
9159
- const shapeIds =
9160
- typeof _ids[0] === 'string' ? (_ids as TLShapeId[]) : (_ids as TLShape[]).map((s) => s.id)
9130
+ const shapeIds = toShapeIds(_ids)
9161
9131
 
9162
9132
  // Normally we don't want to delete locked shapes, but if the force option is set, we'll delete them anyway
9163
9133
  const shapeIdsToDelete = this._shouldIgnoreShapeLock
@@ -9631,10 +9601,7 @@ export class Editor extends EventEmitter<TLEventMap> {
9631
9601
  */
9632
9602
  getContentFromCurrentPage(shapes: TLShapeId[] | TLShape[]): TLContent | undefined {
9633
9603
  // todo: make this work with any page, not just the current page
9634
- const ids =
9635
- typeof shapes[0] === 'string'
9636
- ? (shapes as TLShapeId[])
9637
- : (shapes as TLShape[]).map((s) => s.id)
9604
+ const ids = toShapeIds(shapes)
9638
9605
 
9639
9606
  if (!ids) return
9640
9607
  if (ids.length === 0) return
@@ -9721,21 +9688,34 @@ export class Editor extends EventEmitter<TLEventMap> {
9721
9688
  !asset.props.src?.startsWith('data:video') &&
9722
9689
  !asset.props.src?.startsWith('http')
9723
9690
  ) {
9724
- const assetWithDataUrl = structuredClone(asset as TLImageAsset | TLVideoAsset)
9725
- const objectUrl = await this.store.props.assets.resolve(asset, {
9726
- screenScale: 1,
9727
- steppedScreenScale: 1,
9728
- dpr: 1,
9729
- networkEffectiveType: null,
9730
- shouldResolveToOriginal: true,
9731
- })
9732
- assetWithDataUrl.props.src = await FileHelpers.blobToDataUrl(
9733
- await fetch(objectUrl!).then((r) => r.blob())
9734
- )
9735
- assets.push(assetWithDataUrl)
9736
- } else {
9737
- assets.push(asset)
9691
+ // If the asset can't be inlined (unresolvable src, fetch failure), fall through and
9692
+ // keep the original record; dropping it leaves the pasted shapes pointing at an
9693
+ // asset that doesn't exist
9694
+ try {
9695
+ const objectUrl = await this.store.props.assets.resolve(asset, {
9696
+ screenScale: 1,
9697
+ steppedScreenScale: 1,
9698
+ dpr: 1,
9699
+ networkEffectiveType: null,
9700
+ shouldResolveToOriginal: true,
9701
+ })
9702
+ if (objectUrl) {
9703
+ // fetch resolves on 4xx/5xx, so without this check a 404 error page would be
9704
+ // inlined as a data:text/html src
9705
+ const response = await fetch(objectUrl)
9706
+ if (response.ok) {
9707
+ const assetWithDataUrl = structuredClone(asset as TLImageAsset | TLVideoAsset)
9708
+ assetWithDataUrl.props.src = await FileHelpers.blobToDataUrl(await response.blob())
9709
+ assets.push(assetWithDataUrl)
9710
+ return
9711
+ }
9712
+ console.warn(`Could not inline asset ${asset.id}: fetch returned ${response.status}`)
9713
+ }
9714
+ } catch (err) {
9715
+ console.warn(`Could not inline asset ${asset.id}`, err)
9716
+ }
9738
9717
  }
9718
+ assets.push(asset)
9739
9719
  })
9740
9720
  )
9741
9721
  content.assets = assets
@@ -10157,12 +10137,7 @@ export class Editor extends EventEmitter<TLEventMap> {
10157
10137
  * @public
10158
10138
  */
10159
10139
  async getSvgElement(shapes: TLShapeId[] | TLShape[], opts: TLSvgExportOptions = {}) {
10160
- const ids =
10161
- shapes.length === 0
10162
- ? this.getCurrentPageShapeIdsSorted()
10163
- : typeof shapes[0] === 'string'
10164
- ? (shapes as TLShapeId[])
10165
- : (shapes as TLShape[]).map((s) => s.id)
10140
+ const ids = shapes.length === 0 ? this.getCurrentPageShapeIdsSorted() : toShapeIds(shapes)
10166
10141
 
10167
10142
  if (ids.length === 0) return undefined
10168
10143
 
@@ -10851,22 +10826,22 @@ export class Editor extends EventEmitter<TLEventMap> {
10851
10826
  const releaseMeta = this._metaKeyTimeout !== -1
10852
10827
 
10853
10828
  if (releaseShift) {
10854
- clearTimeout(this._shiftKeyTimeout)
10829
+ this.timers.clearTimeout(this._shiftKeyTimeout)
10855
10830
  this._shiftKeyTimeout = -1
10856
10831
  this.inputs.setShiftKey(false)
10857
10832
  }
10858
10833
  if (releaseAlt) {
10859
- clearTimeout(this._altKeyTimeout)
10834
+ this.timers.clearTimeout(this._altKeyTimeout)
10860
10835
  this._altKeyTimeout = -1
10861
10836
  this.inputs.setAltKey(false)
10862
10837
  }
10863
10838
  if (releaseCtrl) {
10864
- clearTimeout(this._ctrlKeyTimeout)
10839
+ this.timers.clearTimeout(this._ctrlKeyTimeout)
10865
10840
  this._ctrlKeyTimeout = -1
10866
10841
  this.inputs.setCtrlKey(false)
10867
10842
  }
10868
10843
  if (releaseMeta) {
10869
- clearTimeout(this._metaKeyTimeout)
10844
+ this.timers.clearTimeout(this._metaKeyTimeout)
10870
10845
  this._metaKeyTimeout = -1
10871
10846
  this.inputs.setMetaKey(false)
10872
10847
  }
@@ -11016,7 +10991,7 @@ export class Editor extends EventEmitter<TLEventMap> {
11016
10991
  }
11017
10992
 
11018
10993
  if (info.shiftKey) {
11019
- clearTimeout(this._shiftKeyTimeout)
10994
+ this.timers.clearTimeout(this._shiftKeyTimeout)
11020
10995
  this._shiftKeyTimeout = -1
11021
10996
  inputs.setShiftKey(true)
11022
10997
  } else if (!info.shiftKey && inputs.getShiftKey() && this._shiftKeyTimeout === -1) {
@@ -11024,7 +10999,7 @@ export class Editor extends EventEmitter<TLEventMap> {
11024
10999
  }
11025
11000
 
11026
11001
  if (info.altKey) {
11027
- clearTimeout(this._altKeyTimeout)
11002
+ this.timers.clearTimeout(this._altKeyTimeout)
11028
11003
  this._altKeyTimeout = -1
11029
11004
  inputs.setAltKey(true)
11030
11005
  } else if (!info.altKey && inputs.getAltKey() && this._altKeyTimeout === -1) {
@@ -11032,7 +11007,7 @@ export class Editor extends EventEmitter<TLEventMap> {
11032
11007
  }
11033
11008
 
11034
11009
  if (info.ctrlKey) {
11035
- clearTimeout(this._ctrlKeyTimeout)
11010
+ this.timers.clearTimeout(this._ctrlKeyTimeout)
11036
11011
  this._ctrlKeyTimeout = -1
11037
11012
  inputs.setCtrlKey(true)
11038
11013
  } else if (!info.ctrlKey && inputs.getCtrlKey() && this._ctrlKeyTimeout === -1) {
@@ -11042,7 +11017,7 @@ export class Editor extends EventEmitter<TLEventMap> {
11042
11017
  if (info.metaKey && info.name !== 'key_up') {
11043
11018
  // Unlike the other modifiers, the native metaKey property is still true on keyup.
11044
11019
  // If we don't have this guard, then the metakey will be left true without the timeout.
11045
- clearTimeout(this._metaKeyTimeout)
11020
+ this.timers.clearTimeout(this._metaKeyTimeout)
11046
11021
  this._metaKeyTimeout = -1
11047
11022
  inputs.setMetaKey(true)
11048
11023
  } else if (!info.metaKey && inputs.getMetaKey() && this._metaKeyTimeout === -1) {
@@ -11059,8 +11034,7 @@ export class Editor extends EventEmitter<TLEventMap> {
11059
11034
 
11060
11035
  switch (type) {
11061
11036
  case 'pinch': {
11062
- if (cameraOptions.isLocked) return
11063
- clearTimeout(this._longPressTimeout)
11037
+ this.timers.clearTimeout(this._longPressTimeout)
11064
11038
  this.inputs.updateFromEvent(info)
11065
11039
 
11066
11040
  switch (info.name) {
@@ -11097,6 +11071,9 @@ export class Editor extends EventEmitter<TLEventMap> {
11097
11071
  }
11098
11072
  case 'pinch': {
11099
11073
  if (!inputs.getIsPinching()) return
11074
+ // Lock the zoom, not the gesture: skipping pinch_start would send the fingers'
11075
+ // pointer events to the tool, and skipping pinch_end would leave isPinching stuck.
11076
+ if (cameraOptions.isLocked) return
11100
11077
 
11101
11078
  const {
11102
11079
  point: { z = 1 },
@@ -11170,8 +11147,9 @@ export class Editor extends EventEmitter<TLEventMap> {
11170
11147
  let wheelBehavior = cameraOptions.wheelBehavior
11171
11148
  const inputMode = this.user.getUserPreferences().inputMode
11172
11149
 
11173
- // If the user has set their input mode preference, then use that to determine the wheel behavior
11174
- if (inputMode !== null) {
11150
+ // The user's input mode preference picks between pan and zoom, but it must not
11151
+ // re-enable a wheel the app disabled with `wheelBehavior: 'none'`.
11152
+ if (inputMode !== null && wheelBehavior !== 'none') {
11175
11153
  wheelBehavior = inputMode === 'trackpad' ? 'pan' : 'zoom'
11176
11154
  }
11177
11155
 
@@ -11245,15 +11223,18 @@ export class Editor extends EventEmitter<TLEventMap> {
11245
11223
  // Ignore pointer events while we're pinching
11246
11224
  if (inputs.getIsPinching()) return
11247
11225
 
11248
- this.inputs.updateFromEvent(info)
11249
11226
  const { isPen } = info
11250
11227
  const { isPenMode } = instanceState
11251
11228
 
11229
+ // In pen mode, reject non-pen input (a resting palm) before it touches any
11230
+ // state: otherwise updateFromEvent moves the origin point out from under the
11231
+ // pen's drag, and a palm pointer_up clears the pen's isPointing/isDragging.
11232
+ if (isPenMode && !isPen) return
11233
+
11234
+ this.inputs.updateFromEvent(info)
11235
+
11252
11236
  switch (info.name) {
11253
11237
  case 'pointer_down': {
11254
- // If we're in pen mode and the input is not a pen type, then stop here
11255
- if (isPenMode && !isPen) return
11256
-
11257
11238
  // A pointer down starts a new interaction, so flush any modifier that's
11258
11239
  // still lingering in its release-debounce window: treat it as released now.
11259
11240
  this._releaseDebouncedModifiers()
@@ -11295,6 +11276,10 @@ export class Editor extends EventEmitter<TLEventMap> {
11295
11276
  inputs.setIsPointing(true)
11296
11277
  inputs.setIsDragging(false)
11297
11278
 
11279
+ // A camera still animating under a held pointer would shift the page
11280
+ // point past the drag threshold and turn a click into a drag (#10706)
11281
+ this.stopCameraAnimation()
11282
+
11298
11283
  // If pen mode is off, turn it on for direct-display pen input only (e.g. Apple
11299
11284
  // Pencil on an iPad or a Surface Pen on a touchscreen). Indirect desktop tablet
11300
11285
  // styluses still draw as pens, but should not auto-enable pen mode.
@@ -11305,8 +11290,10 @@ export class Editor extends EventEmitter<TLEventMap> {
11305
11290
  this.interrupt()
11306
11291
  }
11307
11292
 
11308
- // On devices with erasers (like the Surface Pen or Wacom Pen), button 5 is the eraser
11309
- if (info.button === STYLUS_ERASER_BUTTON) {
11293
+ // On devices with erasers (like the Surface Pen or Wacom Pen), button 5 is the eraser.
11294
+ // Guarded on the eraser tool existing: the bare editor can be configured without
11295
+ // it, and an unguarded transition would throw and crash the editor.
11296
+ if (info.button === STYLUS_ERASER_BUTTON && this.getStateDescendant('eraser')) {
11310
11297
  this._restoreToolId = this.getCurrentToolId()
11311
11298
  this.complete()
11312
11299
  this.setCurrentTool('eraser')
@@ -11316,10 +11303,10 @@ export class Editor extends EventEmitter<TLEventMap> {
11316
11303
  this._prevCursor = this.getInstanceState().cursor.type
11317
11304
  }
11318
11305
  this.inputs.setIsPanning(true)
11319
- clearTimeout(this._longPressTimeout)
11306
+ this.timers.clearTimeout(this._longPressTimeout)
11320
11307
  } else if (info.button === RIGHT_MOUSE_BUTTON && this.options.rightClickPanning) {
11321
11308
  this.inputs.setIsRightPointing(true)
11322
- clearTimeout(this._longPressTimeout)
11309
+ this.timers.clearTimeout(this._longPressTimeout)
11323
11310
  return this
11324
11311
  }
11325
11312
 
@@ -11334,9 +11321,6 @@ export class Editor extends EventEmitter<TLEventMap> {
11334
11321
  break
11335
11322
  }
11336
11323
  case 'pointer_move': {
11337
- // If the user is in pen mode, but the pointer is not a pen, stop here.
11338
- if (!isPen && isPenMode) return
11339
-
11340
11324
  const { x: cx, y: cy, z: cz } = unsafe__withoutCapture(() => this.getCamera())
11341
11325
 
11342
11326
  // Right-click pointing: waiting to see if this becomes a drag
@@ -11387,7 +11371,7 @@ export class Editor extends EventEmitter<TLEventMap> {
11387
11371
  ) {
11388
11372
  // Start dragging
11389
11373
  inputs.setIsDragging(true)
11390
- clearTimeout(this._longPressTimeout)
11374
+ this.timers.clearTimeout(this._longPressTimeout)
11391
11375
  }
11392
11376
  break
11393
11377
  }
@@ -11395,13 +11379,10 @@ export class Editor extends EventEmitter<TLEventMap> {
11395
11379
  // Stop dragging / pointing
11396
11380
  inputs.setIsDragging(false)
11397
11381
  inputs.setIsPointing(false)
11398
- clearTimeout(this._longPressTimeout)
11382
+ this.timers.clearTimeout(this._longPressTimeout)
11399
11383
  // Remove the button from the buttons set
11400
11384
  inputs.buttons.delete(info.button)
11401
11385
 
11402
- // If we're in pen mode and we're not using a pen, stop here
11403
- if (instanceState.isPenMode && !isPen) return
11404
-
11405
11386
  // Right-click pointing ended without dragging—this is a static
11406
11387
  // right-click, so let it through to the state chart as right_click.
11407
11388
  // Check isPanning first: if we transitioned to panning, isRightPointing
@@ -11471,7 +11452,7 @@ export class Editor extends EventEmitter<TLEventMap> {
11471
11452
  })
11472
11453
  }
11473
11454
  } else {
11474
- if (info.button === STYLUS_ERASER_BUTTON) {
11455
+ if (info.button === STYLUS_ERASER_BUTTON && this.getStateDescendant('eraser')) {
11475
11456
  // If we were erasing with a stylus button, restore the tool we were using before we started erasing
11476
11457
  this.complete()
11477
11458
  this.setCurrentTool(this._restoreToolId)
@@ -11489,9 +11470,11 @@ export class Editor extends EventEmitter<TLEventMap> {
11489
11470
  break
11490
11471
  }
11491
11472
  case 'keyboard': {
11492
- // please, please
11493
- if (info.key === 'ShiftRight') info.key = 'ShiftLeft'
11494
- if (info.key === 'AltRight') info.key = 'AltLeft'
11473
+ // Left and right modifier keys are the same key to us. `inputs.keys` stores
11474
+ // `code`, so normalize that: a `ShiftRight` left as-is would never match the
11475
+ // `ShiftLeft` that nudging checks or that `_releaseShiftKey` clears.
11476
+ if (info.code === 'ShiftRight') info.code = 'ShiftLeft'
11477
+ if (info.code === 'AltRight') info.code = 'AltLeft'
11495
11478
  if (info.code === 'ControlRight') info.code = 'ControlLeft'
11496
11479
  if (info.code === 'MetaRight') info.code = 'MetaLeft'
11497
11480
 
@@ -11509,7 +11492,7 @@ export class Editor extends EventEmitter<TLEventMap> {
11509
11492
 
11510
11493
  this.inputs.setIsPanning(true)
11511
11494
  this.inputs.setIsSpacebarPanning(true)
11512
- clearTimeout(this._longPressTimeout)
11495
+ this.timers.clearTimeout(this._longPressTimeout)
11513
11496
  this.setCursor({
11514
11497
  type: this.inputs.getIsPointing() ? 'grabbing' : 'grab',
11515
11498
  rotation: 0,
@@ -11537,7 +11520,8 @@ export class Editor extends EventEmitter<TLEventMap> {
11537
11520
  }
11538
11521
  }
11539
11522
 
11540
- if (offset) {
11523
+ // `_animateToViewport` bypasses `setCamera`, so honor the lock here.
11524
+ if (offset && !cameraOptions.isLocked) {
11541
11525
  const bounds = this.getViewportPageBounds()
11542
11526
  const next = bounds.clone().translate(offset.mulV({ x: bounds.w, y: bounds.h }))
11543
11527
  this._animateToViewport(next, { animation: { duration: 320 } })
@@ -11599,9 +11583,11 @@ export class Editor extends EventEmitter<TLEventMap> {
11599
11583
  this.setCurrentTool('select')
11600
11584
  }
11601
11585
 
11602
- // If a left click pointer event, send the event to the click manager.
11586
+ // Send the event to the click manager. In pen mode only pen clicks count; otherwise
11587
+ // every pointer does, including an indirect tablet stylus (a pen that never enables
11588
+ // pen mode), which would otherwise never produce double-click events.
11603
11589
  const { isPenMode } = this.store.unsafeGetWithoutCapture(TLINSTANCE_ID)!
11604
- if (info.isPen === isPenMode) {
11590
+ if (!isPenMode || info.isPen) {
11605
11591
  // The click manager may return a new event, i.e. a double click event
11606
11592
  // depending on the event coming in and its own state. If the event has
11607
11593
  // changed then hand both events to the statechart
@@ -11633,7 +11619,7 @@ export class Editor extends EventEmitter<TLEventMap> {
11633
11619
  private maybeTrackPerformance(name: string) {
11634
11620
  if (debugFlags.measurePerformance.get()) {
11635
11621
  if (this.performanceTracker.isStarted()) {
11636
- clearTimeout(this.performanceTrackerTimeout)
11622
+ this.timers.clearTimeout(this.performanceTrackerTimeout)
11637
11623
  } else {
11638
11624
  this.performanceTracker.start(name)
11639
11625
  }
@@ -11697,6 +11683,16 @@ function pushShapeWithDescendants(editor: Editor, id: TLShapeId, result: TLShape
11697
11683
  }
11698
11684
  }
11699
11685
 
11686
+ /**
11687
+ * When `shapes` already holds ids this returns that same array, not a copy, so a caller that
11688
+ * mutates the result (for example to sort it) must copy it first.
11689
+ */
11690
+ function toShapeIds(shapes: TLShapeId[] | TLShape[]): TLShapeId[] {
11691
+ return typeof shapes[0] === 'string'
11692
+ ? (shapes as TLShapeId[])
11693
+ : (shapes as TLShape[]).map((shape) => shape.id)
11694
+ }
11695
+
11700
11696
  /**
11701
11697
  * Run `callback` in a world where all bindings from the shapes in `shapeIds` to shapes not in
11702
11698
  * `shapeIds` are removed. This is useful when you want to duplicate/copy shapes without worrying
@@ -11734,7 +11730,7 @@ function withIsolatedShapes<T>(
11734
11730
  }
11735
11731
  }
11736
11732
 
11737
- editor.deleteBindings([...bindingsToRemove], { isolateShapes: true })
11733
+ editor._deleteBindings([...bindingsToRemove], { isolateShapes: true })
11738
11734
 
11739
11735
  try {
11740
11736
  result = Result.ok(callback(bindingsWithBoth))