@tldraw/editor 5.4.0-next.ef99ab47e5ce → 5.5.0-canary.3870eea2f0fd

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 (288) hide show
  1. package/dist-cjs/index.d.ts +119 -49
  2. package/dist-cjs/index.js +4 -1
  3. package/dist-cjs/index.js.map +2 -2
  4. package/dist-cjs/lib/TldrawEditor.js +7 -2
  5. package/dist-cjs/lib/TldrawEditor.js.map +2 -2
  6. package/dist-cjs/lib/components/MenuClickCapture.js +6 -8
  7. package/dist-cjs/lib/components/MenuClickCapture.js.map +2 -2
  8. package/dist-cjs/lib/components/default-components/CanvasOverlays.js +1 -3
  9. package/dist-cjs/lib/components/default-components/CanvasOverlays.js.map +2 -2
  10. package/dist-cjs/lib/components/default-components/DefaultErrorFallback.js +1 -1
  11. package/dist-cjs/lib/components/default-components/DefaultErrorFallback.js.map +1 -1
  12. package/dist-cjs/lib/config/TLUserPreferences.js +6 -2
  13. package/dist-cjs/lib/config/TLUserPreferences.js.map +2 -2
  14. package/dist-cjs/lib/config/createTLStore.js +1 -1
  15. package/dist-cjs/lib/config/createTLStore.js.map +2 -2
  16. package/dist-cjs/lib/constants.js +2 -0
  17. package/dist-cjs/lib/constants.js.map +2 -2
  18. package/dist-cjs/lib/editor/Editor.js +184 -296
  19. package/dist-cjs/lib/editor/Editor.js.map +2 -2
  20. package/dist-cjs/lib/editor/derivations/shapeIdsInCurrentPage.js +7 -3
  21. package/dist-cjs/lib/editor/derivations/shapeIdsInCurrentPage.js.map +2 -2
  22. package/dist-cjs/lib/editor/managers/ClickManager/ClickManager.js +3 -3
  23. package/dist-cjs/lib/editor/managers/ClickManager/ClickManager.js.map +2 -2
  24. package/dist-cjs/lib/editor/managers/CollaboratorsManager/CollaboratorsManager.js +8 -8
  25. package/dist-cjs/lib/editor/managers/CollaboratorsManager/CollaboratorsManager.js.map +2 -2
  26. package/dist-cjs/lib/editor/managers/EdgeScrollManager/EdgeScrollManager.js +10 -6
  27. package/dist-cjs/lib/editor/managers/EdgeScrollManager/EdgeScrollManager.js.map +2 -2
  28. package/dist-cjs/lib/editor/managers/FontManager/FontManager.js +2 -1
  29. package/dist-cjs/lib/editor/managers/FontManager/FontManager.js.map +2 -2
  30. package/dist-cjs/lib/editor/managers/InputsManager/InputsManager.js +79 -6
  31. package/dist-cjs/lib/editor/managers/InputsManager/InputsManager.js.map +2 -2
  32. package/dist-cjs/lib/editor/managers/ScribbleManager/ScribbleManager.js +7 -0
  33. package/dist-cjs/lib/editor/managers/ScribbleManager/ScribbleManager.js.map +2 -2
  34. package/dist-cjs/lib/editor/managers/SnapManager/BoundsSnaps.js +0 -2
  35. package/dist-cjs/lib/editor/managers/SnapManager/BoundsSnaps.js.map +2 -2
  36. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js +1 -2
  37. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js.map +2 -2
  38. package/dist-cjs/lib/editor/managers/ThemeManager/ThemeManager.js +7 -3
  39. package/dist-cjs/lib/editor/managers/ThemeManager/ThemeManager.js.map +2 -2
  40. package/dist-cjs/lib/editor/managers/TickManager/TickManager.js +6 -3
  41. package/dist-cjs/lib/editor/managers/TickManager/TickManager.js.map +2 -2
  42. package/dist-cjs/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.js +12 -1
  43. package/dist-cjs/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.js.map +2 -2
  44. package/dist-cjs/lib/editor/overlays/OverlayManager.js +3 -7
  45. package/dist-cjs/lib/editor/overlays/OverlayManager.js.map +2 -2
  46. package/dist-cjs/lib/editor/overlays/strokeShapeIndicators.js +0 -1
  47. package/dist-cjs/lib/editor/overlays/strokeShapeIndicators.js.map +2 -2
  48. package/dist-cjs/lib/editor/shapes/BaseFrameLikeShapeUtil.js +3 -1
  49. package/dist-cjs/lib/editor/shapes/BaseFrameLikeShapeUtil.js.map +2 -2
  50. package/dist-cjs/lib/editor/shapes/shared/getPerfectDashProps.js +1 -0
  51. package/dist-cjs/lib/editor/shapes/shared/getPerfectDashProps.js.map +2 -2
  52. package/dist-cjs/lib/editor/tools/BaseBoxShapeTool/children/Pointing.js +1 -1
  53. package/dist-cjs/lib/editor/tools/BaseBoxShapeTool/children/Pointing.js.map +2 -2
  54. package/dist-cjs/lib/editor/tools/StateNode.js +3 -2
  55. package/dist-cjs/lib/editor/tools/StateNode.js.map +2 -2
  56. package/dist-cjs/lib/globals/editors.js +57 -0
  57. package/dist-cjs/lib/globals/editors.js.map +7 -0
  58. package/dist-cjs/lib/globals/menus.js +9 -4
  59. package/dist-cjs/lib/globals/menus.js.map +2 -2
  60. package/dist-cjs/lib/hooks/useCanvasEvents.js +2 -0
  61. package/dist-cjs/lib/hooks/useCanvasEvents.js.map +2 -2
  62. package/dist-cjs/lib/hooks/useDocumentEvents.js +39 -9
  63. package/dist-cjs/lib/hooks/useDocumentEvents.js.map +2 -2
  64. package/dist-cjs/lib/hooks/useLocalStore.js +10 -6
  65. package/dist-cjs/lib/hooks/useLocalStore.js.map +2 -2
  66. package/dist-cjs/lib/hooks/usePassThroughWheelEvents.js +1 -0
  67. package/dist-cjs/lib/hooks/usePassThroughWheelEvents.js.map +2 -2
  68. package/dist-cjs/lib/hooks/usePeerIds.js +2 -1
  69. package/dist-cjs/lib/hooks/usePeerIds.js.map +2 -2
  70. package/dist-cjs/lib/license/LicenseManager.js +9 -2
  71. package/dist-cjs/lib/license/LicenseManager.js.map +2 -2
  72. package/dist-cjs/lib/license/LicenseProvider.js +16 -3
  73. package/dist-cjs/lib/license/LicenseProvider.js.map +2 -2
  74. package/dist-cjs/lib/license/useLicenseManagerState.js +5 -4
  75. package/dist-cjs/lib/license/useLicenseManagerState.js.map +2 -2
  76. package/dist-cjs/lib/primitives/Box.js +2 -1
  77. package/dist-cjs/lib/primitives/Box.js.map +2 -2
  78. package/dist-cjs/lib/primitives/Vec.js +4 -3
  79. package/dist-cjs/lib/primitives/Vec.js.map +2 -2
  80. package/dist-cjs/lib/primitives/geometry/Arc2d.js +1 -1
  81. package/dist-cjs/lib/primitives/geometry/Arc2d.js.map +2 -2
  82. package/dist-cjs/lib/primitives/geometry/CubicBezier2d.js +1 -1
  83. package/dist-cjs/lib/primitives/geometry/CubicBezier2d.js.map +2 -2
  84. package/dist-cjs/lib/primitives/geometry/Edge2d.js +1 -1
  85. package/dist-cjs/lib/primitives/geometry/Edge2d.js.map +2 -2
  86. package/dist-cjs/lib/primitives/geometry/Group2d.js +71 -26
  87. package/dist-cjs/lib/primitives/geometry/Group2d.js.map +2 -2
  88. package/dist-cjs/lib/primitives/geometry/Point2d.js +1 -1
  89. package/dist-cjs/lib/primitives/geometry/Point2d.js.map +2 -2
  90. package/dist-cjs/lib/primitives/utils.js +2 -1
  91. package/dist-cjs/lib/primitives/utils.js.map +2 -2
  92. package/dist-cjs/lib/utils/deepLinks.js +5 -1
  93. package/dist-cjs/lib/utils/deepLinks.js.map +2 -2
  94. package/dist-cjs/lib/utils/normalizeWheel.js +2 -0
  95. package/dist-cjs/lib/utils/normalizeWheel.js.map +2 -2
  96. package/dist-cjs/lib/utils/rotation.js +1 -9
  97. package/dist-cjs/lib/utils/rotation.js.map +2 -2
  98. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js +17 -0
  99. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js.map +2 -2
  100. package/dist-cjs/lib/utils/sync/alerts.js +1 -1
  101. package/dist-cjs/lib/utils/sync/alerts.js.map +1 -1
  102. package/dist-cjs/version.js +3 -3
  103. package/dist-cjs/version.js.map +1 -1
  104. package/dist-esm/index.d.mts +119 -49
  105. package/dist-esm/index.mjs +9 -2
  106. package/dist-esm/index.mjs.map +2 -2
  107. package/dist-esm/lib/TldrawEditor.mjs +9 -4
  108. package/dist-esm/lib/TldrawEditor.mjs.map +2 -2
  109. package/dist-esm/lib/components/MenuClickCapture.mjs +6 -8
  110. package/dist-esm/lib/components/MenuClickCapture.mjs.map +2 -2
  111. package/dist-esm/lib/components/default-components/CanvasOverlays.mjs +1 -3
  112. package/dist-esm/lib/components/default-components/CanvasOverlays.mjs.map +2 -2
  113. package/dist-esm/lib/components/default-components/DefaultErrorFallback.mjs +1 -1
  114. package/dist-esm/lib/components/default-components/DefaultErrorFallback.mjs.map +1 -1
  115. package/dist-esm/lib/config/TLUserPreferences.mjs +6 -2
  116. package/dist-esm/lib/config/TLUserPreferences.mjs.map +2 -2
  117. package/dist-esm/lib/config/createTLStore.mjs +1 -1
  118. package/dist-esm/lib/config/createTLStore.mjs.map +2 -2
  119. package/dist-esm/lib/constants.mjs +2 -0
  120. package/dist-esm/lib/constants.mjs.map +2 -2
  121. package/dist-esm/lib/editor/Editor.mjs +193 -297
  122. package/dist-esm/lib/editor/Editor.mjs.map +2 -2
  123. package/dist-esm/lib/editor/derivations/shapeIdsInCurrentPage.mjs +7 -3
  124. package/dist-esm/lib/editor/derivations/shapeIdsInCurrentPage.mjs.map +2 -2
  125. package/dist-esm/lib/editor/managers/ClickManager/ClickManager.mjs +3 -3
  126. package/dist-esm/lib/editor/managers/ClickManager/ClickManager.mjs.map +2 -2
  127. package/dist-esm/lib/editor/managers/CollaboratorsManager/CollaboratorsManager.mjs +9 -9
  128. package/dist-esm/lib/editor/managers/CollaboratorsManager/CollaboratorsManager.mjs.map +2 -2
  129. package/dist-esm/lib/editor/managers/EdgeScrollManager/EdgeScrollManager.mjs +10 -6
  130. package/dist-esm/lib/editor/managers/EdgeScrollManager/EdgeScrollManager.mjs.map +2 -2
  131. package/dist-esm/lib/editor/managers/FontManager/FontManager.mjs +2 -1
  132. package/dist-esm/lib/editor/managers/FontManager/FontManager.mjs.map +2 -2
  133. package/dist-esm/lib/editor/managers/InputsManager/InputsManager.mjs +81 -8
  134. package/dist-esm/lib/editor/managers/InputsManager/InputsManager.mjs.map +2 -2
  135. package/dist-esm/lib/editor/managers/ScribbleManager/ScribbleManager.mjs +7 -0
  136. package/dist-esm/lib/editor/managers/ScribbleManager/ScribbleManager.mjs.map +2 -2
  137. package/dist-esm/lib/editor/managers/SnapManager/BoundsSnaps.mjs +0 -2
  138. package/dist-esm/lib/editor/managers/SnapManager/BoundsSnaps.mjs.map +2 -2
  139. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs +2 -3
  140. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs.map +2 -2
  141. package/dist-esm/lib/editor/managers/ThemeManager/ThemeManager.mjs +7 -3
  142. package/dist-esm/lib/editor/managers/ThemeManager/ThemeManager.mjs.map +2 -2
  143. package/dist-esm/lib/editor/managers/TickManager/TickManager.mjs +6 -3
  144. package/dist-esm/lib/editor/managers/TickManager/TickManager.mjs.map +2 -2
  145. package/dist-esm/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.mjs +12 -1
  146. package/dist-esm/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.mjs.map +2 -2
  147. package/dist-esm/lib/editor/overlays/OverlayManager.mjs +3 -7
  148. package/dist-esm/lib/editor/overlays/OverlayManager.mjs.map +2 -2
  149. package/dist-esm/lib/editor/overlays/strokeShapeIndicators.mjs +0 -1
  150. package/dist-esm/lib/editor/overlays/strokeShapeIndicators.mjs.map +2 -2
  151. package/dist-esm/lib/editor/shapes/BaseFrameLikeShapeUtil.mjs +3 -1
  152. package/dist-esm/lib/editor/shapes/BaseFrameLikeShapeUtil.mjs.map +2 -2
  153. package/dist-esm/lib/editor/shapes/shared/getPerfectDashProps.mjs +1 -0
  154. package/dist-esm/lib/editor/shapes/shared/getPerfectDashProps.mjs.map +2 -2
  155. package/dist-esm/lib/editor/tools/BaseBoxShapeTool/children/Pointing.mjs +1 -1
  156. package/dist-esm/lib/editor/tools/BaseBoxShapeTool/children/Pointing.mjs.map +2 -2
  157. package/dist-esm/lib/editor/tools/StateNode.mjs +3 -2
  158. package/dist-esm/lib/editor/tools/StateNode.mjs.map +2 -2
  159. package/dist-esm/lib/globals/editors.mjs +37 -0
  160. package/dist-esm/lib/globals/editors.mjs.map +7 -0
  161. package/dist-esm/lib/globals/menus.mjs +9 -4
  162. package/dist-esm/lib/globals/menus.mjs.map +2 -2
  163. package/dist-esm/lib/hooks/useCanvasEvents.mjs +2 -0
  164. package/dist-esm/lib/hooks/useCanvasEvents.mjs.map +2 -2
  165. package/dist-esm/lib/hooks/useDocumentEvents.mjs +40 -10
  166. package/dist-esm/lib/hooks/useDocumentEvents.mjs.map +2 -2
  167. package/dist-esm/lib/hooks/useLocalStore.mjs +11 -7
  168. package/dist-esm/lib/hooks/useLocalStore.mjs.map +2 -2
  169. package/dist-esm/lib/hooks/usePassThroughWheelEvents.mjs +1 -0
  170. package/dist-esm/lib/hooks/usePassThroughWheelEvents.mjs.map +2 -2
  171. package/dist-esm/lib/hooks/usePeerIds.mjs +2 -1
  172. package/dist-esm/lib/hooks/usePeerIds.mjs.map +2 -2
  173. package/dist-esm/lib/license/LicenseManager.mjs +9 -2
  174. package/dist-esm/lib/license/LicenseManager.mjs.map +2 -2
  175. package/dist-esm/lib/license/LicenseProvider.mjs +16 -3
  176. package/dist-esm/lib/license/LicenseProvider.mjs.map +2 -2
  177. package/dist-esm/lib/license/useLicenseManagerState.mjs +5 -4
  178. package/dist-esm/lib/license/useLicenseManagerState.mjs.map +2 -2
  179. package/dist-esm/lib/primitives/Box.mjs +2 -1
  180. package/dist-esm/lib/primitives/Box.mjs.map +2 -2
  181. package/dist-esm/lib/primitives/Vec.mjs +4 -3
  182. package/dist-esm/lib/primitives/Vec.mjs.map +2 -2
  183. package/dist-esm/lib/primitives/geometry/Arc2d.mjs +1 -1
  184. package/dist-esm/lib/primitives/geometry/Arc2d.mjs.map +2 -2
  185. package/dist-esm/lib/primitives/geometry/CubicBezier2d.mjs +1 -1
  186. package/dist-esm/lib/primitives/geometry/CubicBezier2d.mjs.map +2 -2
  187. package/dist-esm/lib/primitives/geometry/Edge2d.mjs +1 -1
  188. package/dist-esm/lib/primitives/geometry/Edge2d.mjs.map +2 -2
  189. package/dist-esm/lib/primitives/geometry/Group2d.mjs +75 -27
  190. package/dist-esm/lib/primitives/geometry/Group2d.mjs.map +2 -2
  191. package/dist-esm/lib/primitives/geometry/Point2d.mjs +1 -1
  192. package/dist-esm/lib/primitives/geometry/Point2d.mjs.map +2 -2
  193. package/dist-esm/lib/primitives/utils.mjs +2 -1
  194. package/dist-esm/lib/primitives/utils.mjs.map +2 -2
  195. package/dist-esm/lib/utils/deepLinks.mjs +5 -1
  196. package/dist-esm/lib/utils/deepLinks.mjs.map +2 -2
  197. package/dist-esm/lib/utils/normalizeWheel.mjs +2 -0
  198. package/dist-esm/lib/utils/normalizeWheel.mjs.map +2 -2
  199. package/dist-esm/lib/utils/rotation.mjs +1 -9
  200. package/dist-esm/lib/utils/rotation.mjs.map +2 -2
  201. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs +17 -0
  202. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs.map +2 -2
  203. package/dist-esm/lib/utils/sync/alerts.mjs +1 -1
  204. package/dist-esm/lib/utils/sync/alerts.mjs.map +1 -1
  205. package/dist-esm/version.mjs +3 -3
  206. package/dist-esm/version.mjs.map +1 -1
  207. package/package.json +13 -7
  208. package/src/index.ts +6 -1
  209. package/src/lib/TldrawEditor.tsx +16 -4
  210. package/src/lib/components/MenuClickCapture.tsx +19 -18
  211. package/src/lib/components/default-components/CanvasOverlays.tsx +1 -3
  212. package/src/lib/components/default-components/DefaultErrorFallback.tsx +1 -1
  213. package/src/lib/config/TLUserPreferences.test.ts +18 -1
  214. package/src/lib/config/TLUserPreferences.ts +8 -4
  215. package/src/lib/config/createTLStore.ts +1 -1
  216. package/src/lib/constants.ts +8 -0
  217. package/src/lib/editor/Editor.ts +273 -386
  218. package/src/lib/editor/derivations/shapeIdsInCurrentPage.ts +7 -3
  219. package/src/lib/editor/managers/ClickManager/ClickManager.ts +5 -3
  220. package/src/lib/editor/managers/CollaboratorsManager/CollaboratorsManager.ts +9 -9
  221. package/src/lib/editor/managers/EdgeScrollManager/EdgeScrollManager.test.ts +35 -4
  222. package/src/lib/editor/managers/EdgeScrollManager/EdgeScrollManager.ts +13 -7
  223. package/src/lib/editor/managers/FontManager/FontManager.ts +2 -1
  224. package/src/lib/editor/managers/InputsManager/InputsManager.test.ts +199 -3
  225. package/src/lib/editor/managers/InputsManager/InputsManager.ts +128 -9
  226. package/src/lib/editor/managers/ScribbleManager/ScribbleManager.ts +12 -1
  227. package/src/lib/editor/managers/SnapManager/BoundsSnaps.ts +0 -2
  228. package/src/lib/editor/managers/TextManager/TextManager.ts +2 -6
  229. package/src/lib/editor/managers/ThemeManager/ThemeManager.test.ts +53 -0
  230. package/src/lib/editor/managers/ThemeManager/ThemeManager.ts +9 -3
  231. package/src/lib/editor/managers/TickManager/TickManager.test.ts +13 -0
  232. package/src/lib/editor/managers/TickManager/TickManager.ts +9 -3
  233. package/src/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.test.ts +64 -3
  234. package/src/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.ts +18 -1
  235. package/src/lib/editor/overlays/OverlayManager.ts +3 -7
  236. package/src/lib/editor/overlays/strokeShapeIndicators.ts +0 -1
  237. package/src/lib/editor/shapes/BaseFrameLikeShapeUtil.tsx +5 -1
  238. package/src/lib/editor/shapes/shared/getPerfectDashProps.ts +3 -0
  239. package/src/lib/editor/tools/BaseBoxShapeTool/children/Pointing.ts +4 -1
  240. package/src/lib/editor/tools/StateNode.test.ts +64 -0
  241. package/src/lib/editor/tools/StateNode.ts +12 -2
  242. package/src/lib/globals/editors.test.ts +76 -0
  243. package/src/lib/globals/editors.ts +53 -0
  244. package/src/lib/globals/menus.test.ts +33 -0
  245. package/src/lib/globals/menus.ts +11 -4
  246. package/src/lib/hooks/useCanvasEvents.ts +2 -0
  247. package/src/lib/hooks/useDocumentEvents.ts +60 -16
  248. package/src/lib/hooks/useLocalStore.ts +16 -8
  249. package/src/lib/hooks/usePassThroughWheelEvents.ts +3 -0
  250. package/src/lib/hooks/usePeerIds.ts +2 -1
  251. package/src/lib/license/LicenseManager.test.ts +160 -0
  252. package/src/lib/license/LicenseManager.ts +13 -4
  253. package/src/lib/license/LicenseProvider.tsx +24 -3
  254. package/src/lib/license/useLicenseManagerState.ts +8 -6
  255. package/src/lib/primitives/Box.test.ts +9 -1
  256. package/src/lib/primitives/Box.ts +3 -1
  257. package/src/lib/primitives/Vec.test.ts +10 -0
  258. package/src/lib/primitives/Vec.ts +4 -4
  259. package/src/lib/primitives/geometry/Arc2d.test.ts +235 -3
  260. package/src/lib/primitives/geometry/Arc2d.ts +1 -1
  261. package/src/lib/primitives/geometry/CubicBezier2d.test.ts +186 -3
  262. package/src/lib/primitives/geometry/CubicBezier2d.ts +1 -1
  263. package/src/lib/primitives/geometry/CubicSpline2d.test.ts +160 -3
  264. package/src/lib/primitives/geometry/Edge2d.test.ts +21 -3
  265. package/src/lib/primitives/geometry/Edge2d.ts +1 -1
  266. package/src/lib/primitives/geometry/Ellipse2d.test.ts +243 -3
  267. package/src/lib/primitives/geometry/Geometry2d.test.ts +553 -1
  268. package/src/lib/primitives/geometry/Group2d.test.ts +419 -3
  269. package/src/lib/primitives/geometry/Group2d.ts +81 -34
  270. package/src/lib/primitives/geometry/Point2d.test.ts +14 -3
  271. package/src/lib/primitives/geometry/Point2d.ts +1 -1
  272. package/src/lib/primitives/geometry/Polyline2d.test.ts +207 -0
  273. package/src/lib/primitives/geometry/Stadium2d.test.ts +191 -3
  274. package/src/lib/primitives/utils.test.ts +10 -1
  275. package/src/lib/primitives/utils.ts +4 -1
  276. package/src/lib/test/useCanvasEvents.test.tsx +74 -0
  277. package/src/lib/test/useDocumentEvents.test.tsx +107 -0
  278. package/src/lib/test/usePassThroughWheelEvents.test.tsx +25 -2
  279. package/src/lib/utils/deepLinks.test.ts +15 -0
  280. package/src/lib/utils/deepLinks.ts +7 -1
  281. package/src/lib/utils/normalizeWheel.test.ts +39 -0
  282. package/src/lib/utils/normalizeWheel.ts +6 -0
  283. package/src/lib/utils/rotation.ts +4 -12
  284. package/src/lib/utils/sync/TLLocalSyncClient.test.ts +56 -0
  285. package/src/lib/utils/sync/TLLocalSyncClient.ts +24 -0
  286. package/src/lib/utils/sync/alerts.ts +1 -1
  287. package/src/version.ts +3 -3
  288. package/src/lib/primitives/geometry/Polyline.test.ts +0 -5
@@ -72,6 +72,7 @@ import {
72
72
  Result,
73
73
  ZERO_INDEX_KEY,
74
74
  annotateError,
75
+ areArraysShallowEqual,
75
76
  assert,
76
77
  assertExists,
77
78
  bind,
@@ -109,6 +110,7 @@ import {
109
110
  import {
110
111
  DEFAULT_ANIMATION_OPTIONS,
111
112
  DEFAULT_CAMERA_OPTIONS,
113
+ FRAME_MS_60HZ,
112
114
  INTERNAL_POINTER_IDS,
113
115
  LEFT_MOUSE_BUTTON,
114
116
  MIDDLE_MOUSE_BUTTON,
@@ -118,8 +120,10 @@ import {
118
120
  import { getOwnerWindow } from '../exports/domUtils'
119
121
  import { exportToSvg } from '../exports/exportToSvg'
120
122
  import { getSvgAsImageWithOptions, trimSvgToContent } from '../exports/getSvgAsImage'
123
+ import { registerMountedEditor, unregisterMountedEditor } from '../globals/editors'
121
124
  import { tlmenus } from '../globals/menus'
122
125
  import { tltime } from '../globals/time'
126
+ import { LicenseManager } from '../license/LicenseManager'
123
127
  import { TldrawOptions, defaultTldrawOptions } from '../options'
124
128
  import { Box, BoxLike } from '../primitives/Box'
125
129
  import { EASINGS } from '../primitives/easings'
@@ -127,7 +131,13 @@ import { Geometry2d } from '../primitives/geometry/Geometry2d'
127
131
  import { Group2d } from '../primitives/geometry/Group2d'
128
132
  import { intersectPolygonPolygon } from '../primitives/intersect'
129
133
  import { Mat, MatLike } from '../primitives/Mat'
130
- import { PI, approximately, areAnglesCompatible, clamp, pointInPolygon } from '../primitives/utils'
134
+ import {
135
+ HALF_PI,
136
+ approximately,
137
+ areAnglesCompatible,
138
+ clamp,
139
+ pointInPolygon,
140
+ } from '../primitives/utils'
131
141
  import { Vec, VecLike } from '../primitives/Vec'
132
142
  import { areShapesContentEqual } from '../utils/areShapesContentEqual'
133
143
  import { dataUrlToFile } from '../utils/assets'
@@ -185,6 +195,7 @@ import { TLHistoryBatchOptions } from './types/history-types'
185
195
  import {
186
196
  OptionalKeys,
187
197
  RequiredKeys,
198
+ TLCameraConstraints,
188
199
  TLCameraMoveOptions,
189
200
  TLCameraOptions,
190
201
  TLGetShapeAtPointOptions,
@@ -543,6 +554,14 @@ export class Editor extends EventEmitter<TLEventMap> {
543
554
  nextPageState.editingShapeId = null
544
555
  }
545
556
 
557
+ if (
558
+ prevPageState.croppingShapeId &&
559
+ shapesNoLongerInPage.has(prevPageState.croppingShapeId)
560
+ ) {
561
+ if (!nextPageState) nextPageState = { ...prevPageState }
562
+ nextPageState.croppingShapeId = null
563
+ }
564
+
546
565
  const hintingShapeIds = prevPageState.hintingShapeIds.filter(
547
566
  (id) => !shapesNoLongerInPage.has(id)
548
567
  )
@@ -828,10 +847,11 @@ export class Editor extends EventEmitter<TLEventMap> {
828
847
 
829
848
  if (prev?.selectedShapeIds !== next?.selectedShapeIds) {
830
849
  // ensure that descendants and ancestors are not selected at the same time
850
+ const selectedShapeIds = new Set(next.selectedShapeIds)
831
851
  const filtered = next.selectedShapeIds.filter((id) => {
832
852
  let parentId = this.getShape(id)?.parentId
833
853
  while (isShapeId(parentId)) {
834
- if (next.selectedShapeIds.includes(parentId)) {
854
+ if (selectedShapeIds.has(parentId)) {
835
855
  return false
836
856
  }
837
857
  parentId = this.getShape(parentId)?.parentId
@@ -918,10 +938,12 @@ export class Editor extends EventEmitter<TLEventMap> {
918
938
 
919
939
  this.on('mount', () => {
920
940
  this._isMounted.set(true)
941
+ registerMountedEditor(this)
921
942
  })
922
943
 
923
944
  this.on('unmount', () => {
924
945
  this._isMounted.set(false)
946
+ unregisterMountedEditor(this)
925
947
  })
926
948
 
927
949
  this.timers.requestAnimationFrame(() => {
@@ -934,7 +956,11 @@ export class Editor extends EventEmitter<TLEventMap> {
934
956
  const mode = this.store.props.collaboration.mode
935
957
  this.disposables.add(
936
958
  react('update collaboration mode', () => {
937
- this.store.put([{ ...this.getInstanceState(), isReadonly: mode.get() === 'readonly' }])
959
+ const isReadonly = mode.get() === 'readonly'
960
+ // only track `mode`, and keep the sync out of the user's undo history
961
+ unsafe__withoutCapture(() =>
962
+ this._updateInstanceState({ isReadonly }, { history: 'ignore' })
963
+ )
938
964
  })
939
965
  )
940
966
  }
@@ -973,6 +999,15 @@ export class Editor extends EventEmitter<TLEventMap> {
973
999
 
974
1000
  readonly options: TldrawOptions
975
1001
 
1002
+ /**
1003
+ * The license manager whose feature flags apply to this editor. Assigned by `<TldrawEditor />`
1004
+ * when it creates the editor, so that UI rendered outside the editor tree can resolve the
1005
+ * editor's license through the editor instance. Undefined for editors created directly.
1006
+ *
1007
+ * @internal
1008
+ */
1009
+ licenseManager?: LicenseManager
1010
+
976
1011
  readonly contextId = uniqueId()
977
1012
 
978
1013
  /**
@@ -1209,6 +1244,9 @@ export class Editor extends EventEmitter<TLEventMap> {
1209
1244
  if (this._isMounted.get()) {
1210
1245
  this.emit('unmount')
1211
1246
  }
1247
+ // The unmount listener above normally handles this; unregister again in case a listener
1248
+ // threw or was removed, so a disposed editor never lingers in `tleditors`.
1249
+ unregisterMountedEditor(this)
1212
1250
 
1213
1251
  // Stop any in-progress camera animations and following before
1214
1252
  // running disposables, so their cleanup listeners fire first
@@ -1374,7 +1412,8 @@ export class Editor extends EventEmitter<TLEventMap> {
1374
1412
  getShapeUtil(arg: string | { type: string }) {
1375
1413
  const type = typeof arg === 'string' ? arg : arg.type
1376
1414
  const shapeUtil = getOwnProperty(this.shapeUtils, type)
1377
- assert(shapeUtil, `No shape util found for type "${type}"`)
1415
+ // hot path: avoid building the message (and the assert wrapper) on every successful call
1416
+ if (!shapeUtil) throw new Error(`No shape util found for type "${type}"`)
1378
1417
  return shapeUtil
1379
1418
  }
1380
1419
 
@@ -2265,8 +2304,11 @@ export class Editor extends EventEmitter<TLEventMap> {
2265
2304
  const shapeIds = readingOrderShapes.map((shape) => shape.id)
2266
2305
 
2267
2306
  const currentIndex = currentShapeId ? shapeIds.indexOf(currentShapeId) : -1
2307
+ // With no current index, stepping from -1 makes 'prev' land one shape
2308
+ // before the last; seed it from 0 so it wraps to the last shape. See #10559.
2309
+ const startIndex = currentIndex === -1 && direction === 'prev' ? 0 : currentIndex
2268
2310
  const adjacentIndex =
2269
- (currentIndex + (direction === 'next' ? 1 : -1) + shapeIds.length) % shapeIds.length
2311
+ (startIndex + (direction === 'next' ? 1 : -1) + shapeIds.length) % shapeIds.length
2270
2312
  adjacentShapeId = shapeIds[adjacentIndex]
2271
2313
  } else {
2272
2314
  if (!currentShapeId) return
@@ -2451,9 +2493,9 @@ export class Editor extends EventEmitter<TLEventMap> {
2451
2493
  const selectedShapes = this.getSelectedShapes()
2452
2494
  if (!selectedShapes.length) return
2453
2495
  const selectedShape = selectedShapes[0]
2454
- const children = this.getSortedChildIdsForParent(selectedShape.id)
2455
- .map((id) => this.getShape(id))
2456
- .filter((i) => i) as TLShape[]
2496
+ const children = compact(
2497
+ this.getSortedChildIdsForParent(selectedShape.id).map((id) => this.getShape(id))
2498
+ )
2457
2499
  const sortedChildren = this._getShapesInReadingOrder(children)
2458
2500
  if (sortedChildren.length === 0) return
2459
2501
  this._selectShapesAndZoom([sortedChildren[0].id])
@@ -2554,20 +2596,14 @@ export class Editor extends EventEmitter<TLEventMap> {
2554
2596
  * @internal
2555
2597
  */
2556
2598
  getShapesSharedRotation(shapeIds: TLShapeId[]) {
2557
- let foundFirst = false // annoying but we can't use an i===0 check because we need to skip over undefineds
2558
2599
  let rotation = 0
2559
2600
  for (let i = 0, n = shapeIds.length; i < n; i++) {
2560
- const pageTransform = this.getShapePageTransform(shapeIds[i])
2561
- if (!pageTransform) continue
2562
- if (foundFirst) {
2563
- if (pageTransform.rotation() !== rotation) {
2564
- // There are at least 2 different rotations, so the common rotation is zero
2565
- return 0
2566
- }
2567
- } else {
2568
- // First rotation found
2569
- foundFirst = true
2570
- rotation = pageTransform.rotation()
2601
+ const pageRotation = this.getShapePageTransform(shapeIds[i]).rotation()
2602
+ if (i === 0) {
2603
+ rotation = pageRotation
2604
+ } else if (pageRotation !== rotation) {
2605
+ // There are at least 2 different rotations, so the common rotation is zero
2606
+ return 0
2571
2607
  }
2572
2608
  }
2573
2609
 
@@ -2599,7 +2635,7 @@ export class Editor extends EventEmitter<TLEventMap> {
2599
2635
 
2600
2636
  if (shapeIds.length === 1) {
2601
2637
  const bounds = this.getShapeGeometry(shapeIds[0]).bounds.clone()
2602
- const pageTransform = this.getShapePageTransform(shapeIds[0])!
2638
+ const pageTransform = this.getShapePageTransform(shapeIds[0])
2603
2639
  bounds.point = pageTransform.applyToPoint(bounds.point)
2604
2640
  return bounds
2605
2641
  }
@@ -2607,11 +2643,9 @@ export class Editor extends EventEmitter<TLEventMap> {
2607
2643
  // need to 'un-rotate' all the outlines of the existing nodes so we can fit them inside a box
2608
2644
  const boxFromRotatedVertices = Box.FromPoints(
2609
2645
  shapeIds
2610
- .flatMap((id) => {
2611
- const pageTransform = this.getShapePageTransform(id)
2612
- if (!pageTransform) return []
2613
- return pageTransform.applyToPoints(this.getShapeGeometry(id).bounds.corners)
2614
- })
2646
+ .flatMap((id) =>
2647
+ this.getShapePageTransform(id).applyToPoints(this.getShapeGeometry(id).bounds.corners)
2648
+ )
2615
2649
  .map((p) => p.rot(-selectionRotation))
2616
2650
  )
2617
2651
  // now position box so that it's top-left corner is in the right place
@@ -2638,9 +2672,16 @@ export class Editor extends EventEmitter<TLEventMap> {
2638
2672
  @computed getSelectionRotatedScreenBounds(): Box | undefined {
2639
2673
  const bounds = this.getSelectionRotatedPageBounds()
2640
2674
  if (!bounds) return undefined
2641
- const { x, y } = this.pageToScreen(bounds.point)
2642
- const zoom = this.getZoomLevel()
2643
- return new Box(x, y, bounds.width * zoom, bounds.height * zoom)
2675
+ // Don't use pageToScreen here: it reads the screen bounds without capturing them, so this
2676
+ // computed would never invalidate when the container moves
2677
+ const screenBounds = this.getViewportScreenBounds()
2678
+ const { x: cx, y: cy, z: zoom } = this.getCamera()
2679
+ return new Box(
2680
+ (bounds.x + cx) * zoom + screenBounds.x,
2681
+ (bounds.y + cy) * zoom + screenBounds.y,
2682
+ bounds.width * zoom,
2683
+ bounds.height * zoom
2684
+ )
2644
2685
  }
2645
2686
 
2646
2687
  // Focus Group
@@ -2780,57 +2821,38 @@ export class Editor extends EventEmitter<TLEventMap> {
2780
2821
  setEditingShape(shape: TLShapeId | TLShape | null): this {
2781
2822
  const id = typeof shape === 'string' ? shape : (shape?.id ?? null)
2782
2823
 
2783
- if (!id) {
2784
- // setting the editing shape to null
2824
+ // id was provided but the next editing shape was not editable or didn't exist, so do nothing
2825
+ if (id && !this.canEditShape(id)) return this
2826
+
2827
+ this.run(() => {
2828
+ // Clean up the previous editing shape. This runs outside the history-ignored batch below,
2829
+ // otherwise document changes made by onEditEnd (e.g. deleting an empty text shape) are
2830
+ // never recorded and leave a phantom undo entry whose redo resurrects the shape.
2831
+ const prevEditingShapeId = this.getEditingShapeId()
2832
+ if (prevEditingShapeId) {
2833
+ const prevEditingShape = this.getShape(prevEditingShapeId)
2834
+ if (prevEditingShape) {
2835
+ this.getShapeUtil(prevEditingShape).onEditEnd?.(prevEditingShape)
2836
+ }
2837
+ }
2838
+
2785
2839
  this.run(
2786
2840
  () => {
2787
- // Clean up the previous editing shape
2788
- const prevEditingShapeId = this.getEditingShapeId()
2789
- if (prevEditingShapeId) {
2790
- const prevEditingShape = this.getShape(prevEditingShapeId)
2791
- if (prevEditingShape) {
2792
- this.getShapeUtil(prevEditingShape).onEditEnd?.(prevEditingShape)
2793
- }
2794
- }
2795
-
2796
2841
  // Clean up the editing shape state and rich text editor
2797
2842
  this._updateCurrentPageState({ editingShapeId: null })
2798
2843
  this._currentRichTextEditor.set(null)
2799
- },
2800
- { history: 'ignore' }
2801
- )
2802
2844
 
2803
- return this
2804
- }
2845
+ if (!id) return
2805
2846
 
2806
- // id was provided but the next editing shape was not editable or didn't exist, so do nothing
2807
- if (!this.canEditShape(id)) return this
2847
+ this.select(id)
2848
+ this._updateCurrentPageState({ editingShapeId: id })
2808
2849
 
2809
- // id was provided and the next editing shape is editable, so set the rich text editor to null
2810
- this.run(
2811
- () => {
2812
- // Clean up the previous editing shape
2813
- const prevEditingShapeId = this.getEditingShapeId()
2814
- if (prevEditingShapeId) {
2815
- const prevEditingShape = this.getShape(prevEditingShapeId)
2816
- if (prevEditingShape) {
2817
- this.getShapeUtil(prevEditingShape).onEditEnd?.(prevEditingShape)
2818
- }
2819
- }
2820
-
2821
- // Clean up the editing shape state and rich text editor
2822
- this._updateCurrentPageState({ editingShapeId: null })
2823
- this._currentRichTextEditor.set(null)
2824
-
2825
- // Set the new editing shape
2826
- this.select(id)
2827
- this._updateCurrentPageState({ editingShapeId: id })
2828
-
2829
- const nextEditingShape = this.getShape(id)! // shape should be there because canEditShape checked it. Possible small chance that onEditEnd deleted it?
2830
- this.getShapeUtil(nextEditingShape).onEditStart?.(nextEditingShape)
2831
- },
2832
- { history: 'ignore' }
2833
- )
2850
+ const nextEditingShape = this.getShape(id)! // shape should be there because canEditShape checked it. Possible small chance that onEditEnd deleted it?
2851
+ this.getShapeUtil(nextEditingShape).onEditStart?.(nextEditingShape)
2852
+ },
2853
+ { history: 'ignore' }
2854
+ )
2855
+ })
2834
2856
 
2835
2857
  return this
2836
2858
  }
@@ -2995,26 +3017,17 @@ export class Editor extends EventEmitter<TLEventMap> {
2995
3017
  * @public
2996
3018
  */
2997
3019
  setErasingShapes(shapes: TLShapeId[] | TLShape[]): this {
3020
+ // copy before sorting: the caller may pass a store-owned (frozen) array
2998
3021
  const ids =
2999
3022
  typeof shapes[0] === 'string'
3000
- ? (shapes as TLShapeId[])
3023
+ ? (shapes as TLShapeId[]).slice()
3001
3024
  : (shapes as TLShape[]).map((shape) => shape.id)
3002
3025
  ids.sort() // sort the incoming ids
3003
3026
  const erasingShapeIds = this.getErasingShapeIds()
3004
3027
  this.run(
3005
3028
  () => {
3006
- if (ids.length === erasingShapeIds.length) {
3007
- // if the new ids are the same length as the current ids, they might be the same.
3008
- // presuming the current ids are also sorted, check each item to see if it's the same;
3009
- // if we find any unequal, then we know the new ids are different.
3010
- for (let i = 0; i < ids.length; i++) {
3011
- if (ids[i] !== erasingShapeIds[i]) {
3012
- this._updateCurrentPageState({ erasingShapeIds: ids })
3013
- break
3014
- }
3015
- }
3016
- } else {
3017
- // if the ids are a different length, then we know they're different.
3029
+ // the current ids are also sorted, so a shallow comparison tells us whether they changed
3030
+ if (!areArraysShallowEqual(ids, erasingShapeIds)) {
3018
3031
  this._updateCurrentPageState({ erasingShapeIds: ids })
3019
3032
  }
3020
3033
  },
@@ -3051,6 +3064,7 @@ export class Editor extends EventEmitter<TLEventMap> {
3051
3064
  if (!_shape) return false
3052
3065
  const util = this.getShapeUtil(_shape)
3053
3066
  if (!util.canCrop(_shape)) return false
3067
+ if (this.getIsReadonly()) return false
3054
3068
  if (this.isShapeOrAncestorLocked(_shape)) return false
3055
3069
  return true
3056
3070
  }
@@ -3130,11 +3144,13 @@ export class Editor extends EventEmitter<TLEventMap> {
3130
3144
  const collaborators = this.getCollaborators()
3131
3145
  let leaderPresence = null as null | TLInstancePresence
3132
3146
  while (targetUserId && !visited.includes(targetUserId)) {
3133
- leaderPresence = collaborators.find((c) => c.userId === targetUserId) ?? null
3134
- targetUserId = leaderPresence?.followingUserId ?? null
3135
- if (leaderPresence) {
3136
- visited.push(leaderPresence.userId)
3137
- }
3147
+ const nextPresence = collaborators.find((c) => c.userId === targetUserId)
3148
+ // Stop at the last resolvable presence, otherwise a leader whose own leader has left
3149
+ // (or whose presence hasn't arrived yet) can't be followed at all
3150
+ if (!nextPresence) break
3151
+ leaderPresence = nextPresence
3152
+ targetUserId = nextPresence.followingUserId ?? null
3153
+ visited.push(nextPresence.userId)
3138
3154
  }
3139
3155
  return leaderPresence
3140
3156
  }
@@ -3252,44 +3268,7 @@ export class Editor extends EventEmitter<TLEventMap> {
3252
3268
  *
3253
3269
  * @public */
3254
3270
  getInitialZoom() {
3255
- const cameraOptions = this.getCameraOptions()
3256
- // If no camera constraints are provided, the default zoom is 100%
3257
- if (!cameraOptions.constraints) return 1
3258
-
3259
- // When defaultZoom is default, the default zoom is 100%
3260
- if (cameraOptions.constraints.initialZoom === 'default') return 1
3261
-
3262
- const { zx, zy } = getCameraFitXFitY(this, cameraOptions)
3263
-
3264
- switch (cameraOptions.constraints.initialZoom) {
3265
- case 'fit-min': {
3266
- return Math.max(zx, zy)
3267
- }
3268
- case 'fit-max': {
3269
- return Math.min(zx, zy)
3270
- }
3271
- case 'fit-x': {
3272
- return zx
3273
- }
3274
- case 'fit-y': {
3275
- return zy
3276
- }
3277
- case 'fit-min-100': {
3278
- return Math.min(1, Math.max(zx, zy))
3279
- }
3280
- case 'fit-max-100': {
3281
- return Math.min(1, Math.min(zx, zy))
3282
- }
3283
- case 'fit-x-100': {
3284
- return Math.min(1, zx)
3285
- }
3286
- case 'fit-y-100': {
3287
- return Math.min(1, zy)
3288
- }
3289
- default: {
3290
- throw exhaustiveSwitchError(cameraOptions.constraints.initialZoom)
3291
- }
3292
- }
3271
+ return this._getFitZoom(this.getCameraOptions().constraints?.initialZoom ?? 'default')
3293
3272
  }
3294
3273
 
3295
3274
  /**
@@ -3302,16 +3281,16 @@ export class Editor extends EventEmitter<TLEventMap> {
3302
3281
  *
3303
3282
  * @public */
3304
3283
  getBaseZoom() {
3305
- const cameraOptions = this.getCameraOptions()
3306
- // If no camera constraints are provided, the default zoom is 100%
3307
- if (!cameraOptions.constraints) return 1
3284
+ return this._getFitZoom(this.getCameraOptions().constraints?.baseZoom ?? 'default')
3285
+ }
3308
3286
 
3309
- // When defaultZoom is default, the default zoom is 100%
3310
- if (cameraOptions.constraints.baseZoom === 'default') return 1
3287
+ private _getFitZoom(fit: TLCameraConstraints['initialZoom']): number {
3288
+ const cameraOptions = this.getCameraOptions()
3289
+ if (!cameraOptions.constraints || fit === 'default') return 1
3311
3290
 
3312
3291
  const { zx, zy } = getCameraFitXFitY(this, cameraOptions)
3313
3292
 
3314
- switch (cameraOptions.constraints.baseZoom) {
3293
+ switch (fit) {
3315
3294
  case 'fit-min': {
3316
3295
  return Math.max(zx, zy)
3317
3296
  }
@@ -3337,7 +3316,7 @@ export class Editor extends EventEmitter<TLEventMap> {
3337
3316
  return Math.min(1, zy)
3338
3317
  }
3339
3318
  default: {
3340
- throw exhaustiveSwitchError(cameraOptions.constraints.baseZoom)
3319
+ throw exhaustiveSwitchError(fit)
3341
3320
  }
3342
3321
  }
3343
3322
  }
@@ -3374,7 +3353,9 @@ export class Editor extends EventEmitter<TLEventMap> {
3374
3353
  ...this._cameraOptions.__unsafe__getWithoutCapture(),
3375
3354
  ...opts,
3376
3355
  })
3377
- if (next.zoomSteps?.length < 1) next.zoomSteps = [1]
3356
+ // `undefined < 1` is false, so an explicit `zoomSteps: undefined` would otherwise get through
3357
+ // and make every later camera move throw
3358
+ if (!next.zoomSteps || next.zoomSteps.length < 1) next.zoomSteps = [1]
3378
3359
  this._cameraOptions.set(next)
3379
3360
  this.setCamera(this.getCamera())
3380
3361
  return this
@@ -3420,8 +3401,8 @@ export class Editor extends EventEmitter<TLEventMap> {
3420
3401
  const { constraints } = cameraOptions
3421
3402
 
3422
3403
  // Clamp padding to half the viewport size on either dimension
3423
- const py = Math.min(constraints.padding.y, vsb.w / 2)
3424
- const px = Math.min(constraints.padding.x, vsb.h / 2)
3404
+ const px = Math.min(constraints.padding.x, vsb.w / 2)
3405
+ const py = Math.min(constraints.padding.y, vsb.h / 2)
3425
3406
 
3426
3407
  // Expand the bounds by the padding
3427
3408
  const bounds = Box.From(cameraOptions.constraints.bounds)
@@ -3490,14 +3471,14 @@ export class Editor extends EventEmitter<TLEventMap> {
3490
3471
  }
3491
3472
  case 'inside': {
3492
3473
  // When below fit zoom, constrain the camera so that the bounds stay completely within the viewport
3493
- if (z < zx) x = clamp(x, minX, (vsb.w - px) / z - bounds.w)
3474
+ if (z < zx) x = clamp(x, minX, (vsb.w - px) / z - bounds.w - bounds.x)
3494
3475
  // When above fit zoom, keep the bounds within padding distance of the viewport edge
3495
3476
  else x = clamp(x, minX + freeW, minX)
3496
3477
  break
3497
3478
  }
3498
3479
  case 'outside': {
3499
3480
  // Constrain the camera so that the bounds never leaves the viewport
3500
- x = clamp(x, px / z - bounds.w, (vsb.w - px) / z)
3481
+ x = clamp(x, px / z - bounds.w - bounds.x, (vsb.w - px) / z - bounds.x)
3501
3482
  break
3502
3483
  }
3503
3484
  case 'free': {
@@ -3522,12 +3503,12 @@ export class Editor extends EventEmitter<TLEventMap> {
3522
3503
  break
3523
3504
  }
3524
3505
  case 'inside': {
3525
- if (z < zy) y = clamp(y, minY, (vsb.h - py) / z - bounds.h)
3506
+ if (z < zy) y = clamp(y, minY, (vsb.h - py) / z - bounds.h - bounds.y)
3526
3507
  else y = clamp(y, minY + freeH, minY)
3527
3508
  break
3528
3509
  }
3529
3510
  case 'outside': {
3530
- y = clamp(y, py / z - bounds.h, (vsb.h - py) / z)
3511
+ y = clamp(y, py / z - bounds.h - bounds.y, (vsb.h - py) / z - bounds.y)
3531
3512
  break
3532
3513
  }
3533
3514
  case 'free': {
@@ -3982,9 +3963,9 @@ export class Editor extends EventEmitter<TLEventMap> {
3982
3963
  const remaining = duration - elapsed
3983
3964
  const t = easing(1 - remaining / duration)
3984
3965
 
3985
- const left = start.minX + (end.minX - start.minX) * t
3986
- const top = start.minY + (end.minY - start.minY) * t
3987
- const right = start.maxX + (end.maxX - start.maxX) * t
3966
+ const left = lerp(start.minX, end.minX, t)
3967
+ const top = lerp(start.minY, end.minY, t)
3968
+ const right = lerp(start.maxX, end.maxX, t)
3988
3969
 
3989
3970
  this._setCamera(new Vec(-left, -top, this.getViewportScreenBounds().width / (right - left)), {
3990
3971
  force: true,
@@ -4099,17 +4080,18 @@ export class Editor extends EventEmitter<TLEventMap> {
4099
4080
  let newCy = cy + dy
4100
4081
  let newCz = cz
4101
4082
 
4102
- // animate zoom if z direction is passed in
4083
+ // animate zoom if z direction is passed in. Use an exponential factor so that a single
4084
+ // long frame can't drive the zoom to zero or negative (which would give NaN coordinates)
4103
4085
  if (dirZ !== 0) {
4104
- newCz = cz * (1 + dirZ * currentSpeed * elapsed)
4086
+ newCz = cz * Math.exp(dirZ * currentSpeed * elapsed)
4105
4087
  // Adjust x/y to keep the viewport center fixed while zooming
4106
4088
  const center = this.getViewportScreenCenter()
4107
4089
  newCx += center.x / newCz - center.x / cz
4108
4090
  newCy += center.y / newCz - center.y / cz
4109
4091
  }
4110
4092
 
4111
- // Apply friction
4112
- currentSpeed *= 1 - friction
4093
+ // Apply friction per unit of elapsed time, not per tick, or a 120 Hz display decays twice as fast
4094
+ currentSpeed *= (1 - friction) ** (elapsed / FRAME_MS_60HZ)
4113
4095
  if (currentSpeed < speedThreshold) {
4114
4096
  cancel()
4115
4097
  } else {
@@ -4686,7 +4668,7 @@ export class Editor extends EventEmitter<TLEventMap> {
4686
4668
  let nextIndex = this.options.maxShapesPerPage * 2
4687
4669
  let nextBackgroundIndex = this.options.maxShapesPerPage
4688
4670
 
4689
- const erasingShapeIds = this.getErasingShapeIds()
4671
+ const erasingShapeIds = new Set(this.getErasingShapeIds())
4690
4672
 
4691
4673
  const addShapeById = (id: TLShapeId, opacity: number, isAncestorErasing: boolean) => {
4692
4674
  const shape = this.getShape(id)
@@ -4694,7 +4676,7 @@ export class Editor extends EventEmitter<TLEventMap> {
4694
4676
 
4695
4677
  if (this.isShapeHidden(shape)) {
4696
4678
  // process children just in case they are overriding the hidden state
4697
- const isErasing = isAncestorErasing || erasingShapeIds.includes(id)
4679
+ const isErasing = isAncestorErasing || erasingShapeIds.has(id)
4698
4680
  for (const childId of this.getSortedChildIdsForParent(id)) {
4699
4681
  addShapeById(childId, opacity, isErasing)
4700
4682
  }
@@ -4706,7 +4688,7 @@ export class Editor extends EventEmitter<TLEventMap> {
4706
4688
  const util = this.getShapeUtil(shape)
4707
4689
 
4708
4690
  if (useEditorState) {
4709
- isShapeErasing = !isAncestorErasing && erasingShapeIds.includes(id)
4691
+ isShapeErasing = !isAncestorErasing && erasingShapeIds.has(id)
4710
4692
  if (isShapeErasing) {
4711
4693
  opacity *= 0.32
4712
4694
  }
@@ -5465,11 +5447,8 @@ export class Editor extends EventEmitter<TLEventMap> {
5465
5447
  /** @internal */
5466
5448
  @computed private _getShapePageBoundsCache(): ComputedCache<Box, TLShape> {
5467
5449
  return this.store.createComputedCache<Box, TLShape>('pageBoundsCache', (shape) => {
5468
- const pageTransform = this.getShapePageTransform(shape)
5469
- if (!pageTransform) return undefined
5470
-
5471
5450
  return Box.FromPoints(
5472
- pageTransform.applyToPoints(this.getShapeGeometry(shape).boundsVertices)
5451
+ this.getShapePageTransform(shape).applyToPoints(this.getShapeGeometry(shape).boundsVertices)
5473
5452
  )
5474
5453
  })
5475
5454
  }
@@ -5608,7 +5587,13 @@ export class Editor extends EventEmitter<TLEventMap> {
5608
5587
  if (pageMask) {
5609
5588
  if (pageMask.length === 0) return undefined
5610
5589
  const { corners } = pageBounds
5611
- if (corners.every((p, i) => p && Vec.Equals(p, pageMask[i]))) return pageBounds.clone()
5590
+ // the mask may have fewer than four points (e.g. a triangular clip path)
5591
+ if (
5592
+ pageMask.length === corners.length &&
5593
+ corners.every((p, i) => Vec.Equals(p, pageMask[i]))
5594
+ ) {
5595
+ return pageBounds.clone()
5596
+ }
5612
5597
  const intersection = intersectPolygonPolygon(pageMask, corners)
5613
5598
  if (!intersection) return
5614
5599
  return Box.FromPoints(intersection)
@@ -5862,6 +5847,7 @@ export class Editor extends EventEmitter<TLEventMap> {
5862
5847
  const margin = this.options.hitTestMargin / this.getZoomLevel()
5863
5848
  const sortedShapes = this.getCurrentPageShapesSorted()
5864
5849
 
5850
+ // iterate from the top (highest z-index) to find the top-most matching shape
5865
5851
  for (let i = sortedShapes.length - 1; i >= 0; i--) {
5866
5852
  const shape = sortedShapes[i]
5867
5853
  if (shape.type === 'group') continue
@@ -5911,44 +5897,43 @@ export class Editor extends EventEmitter<TLEventMap> {
5911
5897
  const searchMargin = Math.max(innerMargin, outerMargin, this.getHitTestMargin())
5912
5898
  const candidateIds = this._spatialIndex.getShapeIdsAtPoint(point, searchMargin)
5913
5899
 
5914
- const shapesToCheck = (
5915
- opts.renderingOnly
5916
- ? this.getCurrentPageRenderingShapesSorted()
5917
- : this.getCurrentPageShapesSorted()
5918
- ).filter((shape) => {
5919
- // Frame-like shapes have labels positioned above the shape (outside bounds), so always include them
5920
- if (!candidateIds.has(shape.id) && !this.isShapeFrameLike(shape)) return false
5900
+ const shapesToCheck = opts.renderingOnly
5901
+ ? this.getCurrentPageRenderingShapesSorted()
5902
+ : this.getCurrentPageShapesSorted()
5921
5903
 
5904
+ for (let i = shapesToCheck.length - 1; i >= 0; i--) {
5905
+ const shape = shapesToCheck[i]
5906
+ // Frame-like shapes have labels positioned above the shape (outside bounds), so always include them
5907
+ if (!candidateIds.has(shape.id) && !this.isShapeFrameLike(shape)) continue
5922
5908
  if (
5923
5909
  (shape.isLocked && !hitLocked) ||
5924
5910
  this.isShapeHidden(shape) ||
5925
5911
  this.isShapeOfType(shape, 'group')
5926
- )
5927
- return false
5912
+ ) {
5913
+ continue
5914
+ }
5928
5915
  const pageMask = this.getShapeMask(shape)
5929
- if (pageMask && !pointInPolygon(point, pageMask)) return false
5930
- if (filter && !filter(shape)) return false
5931
- return true
5932
- })
5916
+ if (pageMask && !pointInPolygon(point, pageMask)) continue
5917
+ if (filter && !filter(shape)) continue
5933
5918
 
5934
- for (let i = shapesToCheck.length - 1; i >= 0; i--) {
5935
- const shape = shapesToCheck[i]
5936
5919
  const geometry = this.getShapeGeometry(shape)
5937
5920
  const isGroup = geometry instanceof Group2d
5938
5921
 
5939
5922
  const pointInShapeSpace = this.getPointInShapeSpace(shape, point)
5940
5923
 
5941
- // Check labels first
5924
+ // Check labels first. Only group geometries can carry a label child; a frame-like
5925
+ // shape util may still return a plain geometry.
5942
5926
  const shapeUtil = this.getShapeUtil(shape)
5943
5927
  const isShapeFrameLike = this.isShapeFrameLike(shape)
5944
5928
  if (
5945
- isShapeFrameLike ||
5946
- ((this.isShapeOfType(shape, 'note') ||
5947
- this.isShapeOfType(shape, 'arrow') ||
5948
- (this.isShapeOfType(shape, 'geo') && shape.props.fill === 'none')) &&
5949
- shapeUtil.getText(shape)?.trim())
5929
+ isGroup &&
5930
+ (isShapeFrameLike ||
5931
+ ((this.isShapeOfType(shape, 'note') ||
5932
+ this.isShapeOfType(shape, 'arrow') ||
5933
+ (this.isShapeOfType(shape, 'geo') && shape.props.fill === 'none')) &&
5934
+ shapeUtil.getText(shape)?.trim()))
5950
5935
  ) {
5951
- for (const childGeometry of (geometry as Group2d).children) {
5936
+ for (const childGeometry of geometry.children) {
5952
5937
  if (childGeometry.isLabel && childGeometry.isPointInBounds(pointInShapeSpace)) {
5953
5938
  return shape
5954
5939
  }
@@ -6114,15 +6099,18 @@ export class Editor extends EventEmitter<TLEventMap> {
6114
6099
  const margin = opts.margin ?? 0
6115
6100
  const candidateIds = this._spatialIndex.getShapeIdsAtPoint(point, margin)
6116
6101
 
6117
- // Get all page shapes in z-index order and filter to candidates that pass isPointInShape
6118
- // Frame-like shapes are always checked because their labels can be outside their bounds
6119
- return this.getCurrentPageShapesSorted()
6120
- .filter((shape) => {
6121
- if (this.isShapeHidden(shape)) return false
6122
- if (!candidateIds.has(shape.id) && !this.isShapeFrameLike(shape)) return false
6123
- return this.isPointInShape(shape, point, opts)
6124
- })
6125
- .reverse()
6102
+ // Get all page shapes in z-index order and filter to candidates that pass isPointInShape.
6103
+ // Frame-like shapes are always checked because their labels can be outside their bounds.
6104
+ // Iterate backwards so the result is pre-sorted in reverse z-index order (top-most first).
6105
+ const sorted = this.getCurrentPageShapesSorted()
6106
+ const result: TLShape[] = []
6107
+ for (let i = sorted.length - 1; i >= 0; i--) {
6108
+ const shape = sorted[i]
6109
+ if (this.isShapeHidden(shape)) continue
6110
+ if (!candidateIds.has(shape.id) && !this.isShapeFrameLike(shape)) continue
6111
+ if (this.isPointInShape(shape, point, opts)) result.push(shape)
6112
+ }
6113
+ return result
6126
6114
  }
6127
6115
 
6128
6116
  /**
@@ -6222,9 +6210,7 @@ export class Editor extends EventEmitter<TLEventMap> {
6222
6210
  if (!freshShape) return new Vec(0, 0)
6223
6211
  if (isPageId(freshShape.parentId)) return Vec.From(point)
6224
6212
 
6225
- const parentTransform = this.getShapePageTransform(freshShape.parentId)
6226
- if (!parentTransform) return Vec.From(point)
6227
- return parentTransform.clone().invert().applyToPoint(point)
6213
+ return this.getShapePageTransform(freshShape.parentId).clone().invert().applyToPoint(point)
6228
6214
  }
6229
6215
 
6230
6216
  /**
@@ -6391,26 +6377,7 @@ export class Editor extends EventEmitter<TLEventMap> {
6391
6377
  * @public
6392
6378
  */
6393
6379
  isShapeInPage(shape: TLShape | TLShapeId, pageId = this.getCurrentPageId()): boolean {
6394
- const id = typeof shape === 'string' ? shape : shape.id
6395
- const shapeToCheck = this.getShape(id)
6396
- if (!shapeToCheck) return false
6397
-
6398
- let shapeIsInPage = false
6399
-
6400
- if (shapeToCheck.parentId === pageId) {
6401
- shapeIsInPage = true
6402
- } else {
6403
- let parent = this.getShape(shapeToCheck.parentId)
6404
- isInPageSearch: while (parent) {
6405
- if (parent.parentId === pageId) {
6406
- shapeIsInPage = true
6407
- break isInPageSearch
6408
- }
6409
- parent = this.getShape(parent.parentId)
6410
- }
6411
- }
6412
-
6413
- return shapeIsInPage
6380
+ return this.getAncestorPageId(shape) === pageId
6414
6381
  }
6415
6382
 
6416
6383
  /**
@@ -6521,13 +6488,8 @@ export class Editor extends EventEmitter<TLEventMap> {
6521
6488
  for (let i = 0; i < shapesToReparent.length; i++) {
6522
6489
  const shape = shapesToReparent[i]
6523
6490
 
6524
- const pageTransform = this.getShapePageTransform(shape)!
6525
- if (!pageTransform) continue
6526
-
6527
- const pagePoint = pageTransform.point()
6528
- if (!pagePoint) continue
6529
-
6530
- const newPoint = invertedParentTransform.applyToPoint(pagePoint)
6491
+ const pageTransform = this.getShapePageTransform(shape)
6492
+ const newPoint = invertedParentTransform.applyToPoint(pageTransform.point())
6531
6493
  const newRotation = pageTransform.rotation() - parentPageRotation
6532
6494
 
6533
6495
  if (shape.id === parentId) {
@@ -6628,7 +6590,7 @@ export class Editor extends EventEmitter<TLEventMap> {
6628
6590
  */
6629
6591
  getShapeAndDescendantIds(ids: TLShapeId[]): Set<TLShapeId> {
6630
6592
  const shapeIds = new Set<TLShapeId>()
6631
- for (const shape of ids.map((id) => this.getShape(id)!).sort(sortByIndex)) {
6593
+ for (const shape of compact(ids.map((id) => this.getShape(id))).sort(sortByIndex)) {
6632
6594
  shapeIds.add(shape.id)
6633
6595
  this.visitDescendants(shape, (descendantId) => {
6634
6596
  shapeIds.add(descendantId)
@@ -6652,6 +6614,9 @@ export class Editor extends EventEmitter<TLEventMap> {
6652
6614
  const draggingShapes = compact(droppingShapes.map((s) => this.getShape(s))).filter(
6653
6615
  (s) => !s.isLocked && !this.isShapeHidden(s)
6654
6616
  )
6617
+ // Descendants of the dragged shapes can't be the target, otherwise dragging a frame out of
6618
+ // its parent reports a nested child as the target and the parent never sees the drag leave
6619
+ const excludedIds = this.getShapeAndDescendantIds(draggingShapes.map((s) => s.id))
6655
6620
 
6656
6621
  const maybeDraggingOverShapes = this.getShapesAtPoint(point, {
6657
6622
  hitInside: true,
@@ -6661,7 +6626,7 @@ export class Editor extends EventEmitter<TLEventMap> {
6661
6626
  !droppingShapes.includes(s) &&
6662
6627
  !s.isLocked &&
6663
6628
  !this.isShapeHidden(s) &&
6664
- !draggingShapes.includes(s)
6629
+ !excludedIds.has(s.id)
6665
6630
  )
6666
6631
 
6667
6632
  for (const maybeDraggingOverShape of maybeDraggingOverShapes) {
@@ -7035,8 +7000,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7035
7000
  for (const id of ids) {
7036
7001
  const shape = this.getShape(id)!
7037
7002
  const localDelta = Vec.From(offset)
7038
- const parentTransform = this.getShapeParentTransform(shape)
7039
- if (parentTransform) localDelta.rot(-parentTransform.rotation())
7003
+ localDelta.rot(-this.getShapeParentTransform(shape).rotation())
7040
7004
 
7041
7005
  changes.push(this.getChangesToTranslateShape(shape, localDelta.add(shape)))
7042
7006
  }
@@ -7106,7 +7070,13 @@ export class Editor extends EventEmitter<TLEventMap> {
7106
7070
  let ox = 0
7107
7071
  let oy = 0
7108
7072
 
7109
- if (offset && initialIds.has(originalId)) {
7073
+ // Only offset the roots of the duplicated tree: a descendant that was also passed in
7074
+ // follows its duplicated parent, so offsetting it too would move it twice
7075
+ if (
7076
+ offset &&
7077
+ initialIds.has(originalId) &&
7078
+ !shapeIdSet.has(originalShape.parentId as TLShapeId)
7079
+ ) {
7110
7080
  const parentTransform = this.getShapeParentTransform(originalShape)
7111
7081
  const vec = new Vec(offset.x, offset.y).rot(-parentTransform!.rotation())
7112
7082
  ox = vec.x
@@ -7272,27 +7242,17 @@ export class Editor extends EventEmitter<TLEventMap> {
7272
7242
 
7273
7243
  if (this.getIsReadonly() || ids.length === 0) return this
7274
7244
 
7275
- let allLocked = true,
7276
- allUnlocked = true
7245
+ let allLocked = true
7277
7246
  const shapesToToggle: TLShape[] = []
7278
7247
  for (const id of ids) {
7279
7248
  const shape = this.getShape(id)
7280
7249
  if (shape) {
7281
7250
  shapesToToggle.push(shape)
7282
- if (shape.isLocked) {
7283
- allUnlocked = false
7284
- } else {
7285
- allLocked = false
7286
- }
7251
+ if (!shape.isLocked) allLocked = false
7287
7252
  }
7288
7253
  }
7289
7254
  this.run(() => {
7290
- if (allUnlocked) {
7291
- this.updateShapes(
7292
- shapesToToggle.map((shape) => ({ id: shape.id, type: shape.type, isLocked: true }))
7293
- )
7294
- this.setSelectedShapes([])
7295
- } else if (allLocked) {
7255
+ if (allLocked) {
7296
7256
  this.updateShapes(
7297
7257
  shapesToToggle.map((shape) => ({ id: shape.id, type: shape.type, isLocked: false }))
7298
7258
  )
@@ -7300,6 +7260,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7300
7260
  this.updateShapes(
7301
7261
  shapesToToggle.map((shape) => ({ id: shape.id, type: shape.type, isLocked: true }))
7302
7262
  )
7263
+ this.setSelectedShapes([])
7303
7264
  }
7304
7265
  })
7305
7266
 
@@ -7439,9 +7400,12 @@ export class Editor extends EventEmitter<TLEventMap> {
7439
7400
 
7440
7401
  // optionally filter to axis-aligned shapes (rotation is a multiple of 90 degrees)
7441
7402
  if (opts?.filterAxisAligned) {
7442
- freshShapes = freshShapes.filter(
7443
- (s) => this.getShapePageTransform(s)?.rotation() % (PI / 2) === 0
7444
- )
7403
+ freshShapes = freshShapes.filter((s) => {
7404
+ // Page rotations come back through atan2 on a composed matrix, so a 270° shape can land
7405
+ // a hair either side of the multiple; an exact === 0 check drops it
7406
+ const remainder = Math.abs(this.getShapePageTransform(s).rotation() % HALF_PI)
7407
+ return Math.min(remainder, HALF_PI - remainder) < 1e-9
7408
+ })
7445
7409
  }
7446
7410
 
7447
7411
  const clusters: { shapes: TLShape[]; pageBounds: Box }[] = []
@@ -7662,13 +7626,14 @@ export class Editor extends EventEmitter<TLEventMap> {
7662
7626
 
7663
7627
  let shapeGap: number = 0
7664
7628
 
7629
+ // Stack in spatial order rather than input (z) order, otherwise shapes swap places
7630
+ shapeClustersToStack.sort((a, b) => a.pageBounds[min] - b.pageBounds[min])
7631
+
7665
7632
  if (_gap === 0) {
7666
7633
  // note: this is not used in the current tldraw.com; there we use a specified stack
7667
7634
 
7668
7635
  const gaps: Record<number, number> = {}
7669
7636
 
7670
- shapeClustersToStack.sort((a, b) => a.pageBounds[min] - b.pageBounds[min])
7671
-
7672
7637
  // Collect all of the gaps between shapes. We want to find
7673
7638
  // patterns (equal gaps between shapes) and use the most common
7674
7639
  // one as the gap for all of the shapes.
@@ -7721,8 +7686,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7721
7686
  // todo: ensure that the parent isn't being aligned together with its children
7722
7687
  const parent = this.getShapeParent(shape)
7723
7688
  if (parent) {
7724
- const parentTransform = this.getShapePageTransform(parent)
7725
- if (parentTransform) shapeDelta.rot(-parentTransform.rotation())
7689
+ shapeDelta.rot(-this.getShapePageTransform(parent).rotation())
7726
7690
  }
7727
7691
 
7728
7692
  shapeDelta.add(shape) // add the shape's x and y to the delta
@@ -7772,10 +7736,11 @@ export class Editor extends EventEmitter<TLEventMap> {
7772
7736
 
7773
7737
  const maxWidth = commonBounds.width
7774
7738
 
7775
- // sort the shape clusters by width and then height, descending
7739
+ // sort the shape clusters by width and then height, descending: potpack fills each row's
7740
+ // right-hand space with the shapes that follow, so they must be no taller than the row
7776
7741
  shapeClustersToPack
7777
- .sort((a, b) => a.pageBounds.width - b.pageBounds.width)
7778
- .sort((a, b) => a.pageBounds.height - b.pageBounds.height)
7742
+ .sort((a, b) => b.pageBounds.width - a.pageBounds.width)
7743
+ .sort((a, b) => b.pageBounds.height - a.pageBounds.height)
7779
7744
 
7780
7745
  // Start with is (sort of) the square of the area
7781
7746
  const startWidth = Math.max(Math.ceil(Math.sqrt(area / 0.95)), maxWidth)
@@ -7845,8 +7810,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7845
7810
 
7846
7811
  const parent = this.getShapeParent(shape)
7847
7812
  if (parent) {
7848
- const parentTransform = this.getShapeParentTransform(shape)
7849
- if (parentTransform) shapeDelta.rot(-parentTransform.rotation())
7813
+ shapeDelta.rot(-this.getShapeParentTransform(shape).rotation())
7850
7814
  }
7851
7815
 
7852
7816
  shapeDelta.add(shape)
@@ -7936,8 +7900,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7936
7900
  // todo: ensure that the parent isn't being aligned together with its children
7937
7901
  const parent = this.getShapeParent(shape)
7938
7902
  if (parent) {
7939
- const parentTransform = this.getShapePageTransform(parent)
7940
- if (parentTransform) shapeDelta.rot(-parentTransform.rotation())
7903
+ shapeDelta.rot(-this.getShapePageTransform(parent).rotation())
7941
7904
  }
7942
7905
 
7943
7906
  shapeDelta.add(shape) // add the shape's x and y to the delta
@@ -8037,8 +8000,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8037
8000
  // todo: ensure that the parent isn't being aligned together with its children
8038
8001
  const parent = this.getShapeParent(shape)
8039
8002
  if (parent) {
8040
- const parentTransform = this.getShapePageTransform(parent)
8041
- if (parentTransform) shapeDelta.rot(-parentTransform.rotation())
8003
+ shapeDelta.rot(-this.getShapePageTransform(parent).rotation())
8042
8004
  }
8043
8005
 
8044
8006
  shapeDelta.add(shape) // add the shape's x and y to the delta
@@ -8106,8 +8068,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8106
8068
  for (const shape of shapes) {
8107
8069
  // First translate
8108
8070
  const shapeLocalOffset = localOffset.clone()
8109
- const parentTransform = this.getShapeParentTransform(shape)
8110
- if (parentTransform) shapeLocalOffset.rot(-parentTransform.rotation())
8071
+ shapeLocalOffset.rot(-this.getShapeParentTransform(shape).rotation())
8111
8072
  shapeLocalOffset.add(shape)
8112
8073
  const changes = this.getChangesToTranslateShape(shape, shapeLocalOffset)
8113
8074
  this.updateShape(changes)
@@ -8178,8 +8139,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8178
8139
  for (const shape of shapes) {
8179
8140
  // First translate
8180
8141
  const shapeLocalOffset = localOffset.clone()
8181
- const parentTransform = this.getShapeParentTransform(shape)
8182
- if (parentTransform) shapeLocalOffset.rot(-parentTransform.rotation())
8142
+ shapeLocalOffset.rot(-this.getShapeParentTransform(shape).rotation())
8183
8143
  shapeLocalOffset.add(shape)
8184
8144
  const changes = this.getChangesToTranslateShape(shape, shapeLocalOffset)
8185
8145
  this.updateShape(changes)
@@ -8243,12 +8203,9 @@ export class Editor extends EventEmitter<TLEventMap> {
8243
8203
  const pageTransform = opts.initialPageTransform
8244
8204
  ? Mat.Cast(opts.initialPageTransform)
8245
8205
  : this.getShapePageTransform(id)
8246
- if (!pageTransform) return null
8247
8206
 
8248
8207
  const pageRotation = pageTransform.rotation()
8249
8208
 
8250
- if (pageRotation == null) return null
8251
-
8252
8209
  const scaleAxisRotation = opts.scaleAxisRotation ?? pageRotation
8253
8210
 
8254
8211
  const initialBounds = opts.initialBounds ?? this.getShapeGeometry(id).bounds
@@ -8485,7 +8442,7 @@ export class Editor extends EventEmitter<TLEventMap> {
8485
8442
  )
8486
8443
 
8487
8444
  // now calculate how far away the shape is from where it needs to be
8488
- const pageTransform = this.getShapePageTransform(id)!
8445
+ const pageTransform = this.getShapePageTransform(id)
8489
8446
  // We need to use the local bounds center transformed to page space, not the axis-aligned
8490
8447
  // page bounds center. This is because the page bounds are axis-aligned and their center
8491
8448
  // changes when the rotation changes, but we want to use the same reference point as
@@ -8493,7 +8450,6 @@ export class Editor extends EventEmitter<TLEventMap> {
8493
8450
  const currentLocalBounds = this.getShapeGeometry(id).bounds
8494
8451
  const currentPageCenter = Mat.applyToPoint(pageTransform, currentLocalBounds.center)
8495
8452
  const shapePageTransformOrigin = pageTransform.point()
8496
- if (!currentPageCenter || !shapePageTransformOrigin) return this
8497
8453
  const pageDelta = Vec.Sub(postScaleShapePageCenter, currentPageCenter)
8498
8454
 
8499
8455
  // and finally figure out what the shape's new position should be
@@ -8881,10 +8837,10 @@ export class Editor extends EventEmitter<TLEventMap> {
8881
8837
 
8882
8838
  updates.push({
8883
8839
  ...end,
8884
- x: start.x + (end.x - start.x) * t,
8885
- y: start.y + (end.y - start.y) * t,
8886
- opacity: start.opacity + (end.opacity - start.opacity) * t,
8887
- rotation: start.rotation + (end.rotation - start.rotation) * t,
8840
+ x: lerp(start.x, end.x, t),
8841
+ y: lerp(start.y, end.y, t),
8842
+ opacity: lerp(start.opacity, end.opacity, t),
8843
+ rotation: lerp(start.rotation, end.rotation, t),
8888
8844
  props: this.getShapeUtil(end).getInterpolatedProps?.(start, end, t) ?? end.props,
8889
8845
  })
8890
8846
  }
@@ -9100,7 +9056,7 @@ export class Editor extends EventEmitter<TLEventMap> {
9100
9056
  * @public
9101
9057
  */
9102
9058
  updateShapes<T extends TLShape>(partials: (TLShapePartial<T> | null | undefined)[]) {
9103
- const compactedPartials: TLShapePartial<T>[] = Array(partials.length)
9059
+ const compactedPartials: TLShapePartial<T>[] = []
9104
9060
 
9105
9061
  for (let i = 0, n = partials.length; i < n; i++) {
9106
9062
  const partial = partials[i]
@@ -9246,26 +9202,25 @@ export class Editor extends EventEmitter<TLEventMap> {
9246
9202
  /* --------------------- Styles --------------------- */
9247
9203
 
9248
9204
  /**
9249
- * Get all the current styles among the users selected shapes
9205
+ * Groups have no styles of their own: a style read or write on a selection applies to the
9206
+ * non-group shapes beneath each group, however deeply nested. Returns those shapes.
9250
9207
  *
9251
9208
  * @internal
9252
9209
  */
9253
- private _extractSharedStyles(shape: TLShape, sharedStyleMap: SharedStyleMap) {
9254
- if (this.isShapeOfType(shape, 'group')) {
9255
- // For groups, ignore the styles of the group shape and instead include the styles of the
9256
- // group's children. These are the shapes that would have their styles changed if the
9257
- // user called `setStyle` on the current selection.
9258
- const childIds = this._parentIdsToChildIds.get()[shape.id]
9259
- if (!childIds) return
9260
-
9261
- for (let i = 0, n = childIds.length; i < n; i++) {
9262
- this._extractSharedStyles(this.getShape(childIds[i])!, sharedStyleMap)
9263
- }
9264
- } else {
9265
- for (const [style, propKey] of this.styleProps[shape.type]) {
9266
- sharedStyleMap.applyValue(style, getOwnProperty(shape.props, propKey))
9210
+ private _getStyleableShapes(shapes: TLShape[]): TLShape[] {
9211
+ const result: TLShape[] = []
9212
+ const visit = (shape: TLShape) => {
9213
+ if (this.isShapeOfType(shape, 'group')) {
9214
+ for (const childId of this.getSortedChildIdsForParent(shape.id)) {
9215
+ const child = this.getShape(childId)
9216
+ if (child) visit(child)
9217
+ }
9218
+ } else {
9219
+ result.push(shape)
9267
9220
  }
9268
9221
  }
9222
+ for (const shape of shapes) visit(shape)
9223
+ return result
9269
9224
  }
9270
9225
 
9271
9226
  /**
@@ -9275,11 +9230,11 @@ export class Editor extends EventEmitter<TLEventMap> {
9275
9230
  */
9276
9231
  @computed
9277
9232
  private _getSelectionSharedStyles(): ReadonlySharedStyleMap {
9278
- const selectedShapes = this.getSelectedShapes()
9279
-
9280
9233
  const sharedStyles = new SharedStyleMap()
9281
- for (const selectedShape of selectedShapes) {
9282
- this._extractSharedStyles(selectedShape, sharedStyles)
9234
+ for (const shape of this._getStyleableShapes(this.getSelectedShapes())) {
9235
+ for (const [style, propKey] of this.styleProps[shape.type]) {
9236
+ sharedStyles.applyValue(style, getOwnProperty(shape.props, propKey))
9237
+ }
9283
9238
  }
9284
9239
 
9285
9240
  return sharedStyles
@@ -9337,18 +9292,8 @@ export class Editor extends EventEmitter<TLEventMap> {
9337
9292
  if (!currentTool) return styles
9338
9293
 
9339
9294
  if (currentTool.shapeType) {
9340
- if (
9341
- currentTool.shapeType === 'frame' &&
9342
- !(this.getShapeUtil('frame')!.options as any).showColors
9343
- ) {
9344
- for (const style of this.styleProps[currentTool.shapeType].keys()) {
9345
- if (style.id === 'tldraw:color') continue
9346
- styles.applyValue(style, this.getStyleForNextShape(style))
9347
- }
9348
- } else {
9349
- for (const style of this.styleProps[currentTool.shapeType].keys()) {
9350
- styles.applyValue(style, this.getStyleForNextShape(style))
9351
- }
9295
+ for (const style of this.styleProps[currentTool.shapeType].keys()) {
9296
+ styles.applyValue(style, this.getStyleForNextShape(style))
9352
9297
  }
9353
9298
  }
9354
9299
 
@@ -9364,27 +9309,8 @@ export class Editor extends EventEmitter<TLEventMap> {
9364
9309
  */
9365
9310
  @computed getSharedOpacity(): SharedStyle<number> {
9366
9311
  if (this.isIn('select') && this.getSelectedShapeIds().length > 0) {
9367
- const shapesToCheck: TLShape[] = []
9368
- const addShape = (shapeId: TLShapeId) => {
9369
- const shape = this.getShape(shapeId)
9370
- if (!shape) return
9371
- // For groups, ignore the opacity of the group shape and instead include
9372
- // the opacity of the group's children. These are the shapes that would have
9373
- // their opacity changed if the user called `setOpacity` on the current selection.
9374
- if (this.isShapeOfType(shape, 'group')) {
9375
- for (const childId of this.getSortedChildIdsForParent(shape.id)) {
9376
- addShape(childId)
9377
- }
9378
- } else {
9379
- shapesToCheck.push(shape)
9380
- }
9381
- }
9382
- for (const shapeId of this.getSelectedShapeIds()) {
9383
- addShape(shapeId)
9384
- }
9385
-
9386
9312
  let opacity: number | null = null
9387
- for (const shape of shapesToCheck) {
9313
+ for (const shape of this._getStyleableShapes(this.getSelectedShapes())) {
9388
9314
  if (opacity === null) {
9389
9315
  opacity = shape.opacity
9390
9316
  } else if (opacity !== shape.opacity) {
@@ -9427,33 +9353,12 @@ export class Editor extends EventEmitter<TLEventMap> {
9427
9353
  const selectedShapes = this.getSelectedShapes()
9428
9354
 
9429
9355
  if (selectedShapes.length > 0) {
9430
- const shapesToUpdate: TLShape[] = []
9431
-
9432
- // We can have many deep levels of grouped shape
9433
- // Making a recursive function to look through all the levels
9434
- const addShapeById = (shape: TLShape) => {
9435
- if (this.isShapeOfType(shape, 'group')) {
9436
- const childIds = this.getSortedChildIdsForParent(shape)
9437
- for (const childId of childIds) {
9438
- addShapeById(this.getShape(childId)!)
9439
- }
9440
- } else {
9441
- shapesToUpdate.push(shape)
9442
- }
9443
- }
9444
-
9445
- for (const id of selectedShapes) {
9446
- addShapeById(id)
9447
- }
9448
-
9449
9356
  this.updateShapes(
9450
- shapesToUpdate.map((shape) => {
9451
- return {
9452
- id: shape.id,
9453
- type: shape.type,
9454
- opacity,
9455
- }
9456
- })
9357
+ this._getStyleableShapes(selectedShapes).map((shape) => ({
9358
+ id: shape.id,
9359
+ type: shape.type,
9360
+ opacity,
9361
+ }))
9457
9362
  )
9458
9363
  }
9459
9364
 
@@ -9507,43 +9412,19 @@ export class Editor extends EventEmitter<TLEventMap> {
9507
9412
  const selectedShapes = this.getSelectedShapes()
9508
9413
 
9509
9414
  if (selectedShapes.length > 0) {
9510
- const updates: {
9511
- util: ShapeUtil
9512
- originalShape: TLShape
9513
- updatePartial: TLShapePartial
9514
- }[] = []
9515
-
9516
- // We can have many deep levels of grouped shape
9517
- // Making a recursive function to look through all the levels
9518
- const addShapeById = (shape: TLShape) => {
9519
- if (this.isShapeOfType(shape, 'group')) {
9520
- const childIds = this.getSortedChildIdsForParent(shape.id)
9521
- for (const childId of childIds) {
9522
- addShapeById(this.getShape(childId)!)
9523
- }
9524
- } else {
9525
- const util = this.getShapeUtil(shape)
9526
- const stylePropKey = this.styleProps[shape.type].get(style)
9527
- if (stylePropKey) {
9528
- const shapePartial: TLShapePartial = {
9529
- id: shape.id,
9530
- type: shape.type,
9531
- props: { [stylePropKey]: value },
9532
- }
9533
- updates.push({
9534
- util,
9535
- originalShape: shape,
9536
- updatePartial: shapePartial,
9537
- })
9538
- }
9415
+ const updates: TLShapePartial[] = []
9416
+ for (const shape of this._getStyleableShapes(selectedShapes)) {
9417
+ const stylePropKey = this.styleProps[shape.type].get(style)
9418
+ if (stylePropKey) {
9419
+ updates.push({
9420
+ id: shape.id,
9421
+ type: shape.type,
9422
+ props: { [stylePropKey]: value },
9423
+ })
9539
9424
  }
9540
9425
  }
9541
9426
 
9542
- for (const shape of selectedShapes) {
9543
- addShapeById(shape)
9544
- }
9545
-
9546
- this.updateShapes(updates.map(({ updatePartial }) => updatePartial))
9427
+ this.updateShapes(updates)
9547
9428
  }
9548
9429
 
9549
9430
  return this
@@ -10075,7 +9956,6 @@ export class Editor extends EventEmitter<TLEventMap> {
10075
9956
  if (shapeIdMap.has(newShape.parentId)) {
10076
9957
  newShape.parentId = shapeIdMap.get(oldShape.parentId)!
10077
9958
  } else {
10078
- rootShapeIds.push(newShape.id)
10079
9959
  // newShape.parentId = pasteParentId
10080
9960
  newShape.index = index
10081
9961
  index = getIndexAbove(index)
@@ -10118,10 +9998,14 @@ export class Editor extends EventEmitter<TLEventMap> {
10118
9998
  (asset.type === 'video' && asset.props.src?.startsWith('data:video'))
10119
9999
  ) {
10120
10000
  // it's src is a base64 image or video; we need to create a new asset without the src,
10121
- // then create a new asset from the original src. So we save a copy of the original asset,
10122
- // then delete the src from the original asset.
10123
- assetsToUpdate.push(structuredClone(asset as TLImageAsset | TLVideoAsset))
10124
- asset.props.src = null
10001
+ // then create a new asset from the original src. So we keep the original asset for the
10002
+ // upload and create a copy with its src removed. Copy rather than mutate: when no
10003
+ // migration applies, migrateStoreSnapshot hands back the caller's own record objects.
10004
+ assetsToUpdate.push(asset as TLImageAsset | TLVideoAsset)
10005
+ const assetWithoutSrc = structuredClone(asset as TLImageAsset | TLVideoAsset)
10006
+ assetWithoutSrc.props.src = null
10007
+ assetsToCreate.push(assetWithoutSrc)
10008
+ continue
10125
10009
  }
10126
10010
 
10127
10011
  // Add the asset to the list of assets to create
@@ -11116,7 +11000,10 @@ export class Editor extends EventEmitter<TLEventMap> {
11116
11000
  if (info.name === 'cancel' || info.name === 'complete') {
11117
11001
  this.inputs.setIsDragging(false)
11118
11002
 
11119
- if (this.inputs.getIsPanning()) {
11003
+ // A pan owned by a held spacebar outlives the cancelled interaction;
11004
+ // key_up ends it. Otherwise Escape mid-pan stops the camera until
11005
+ // the user releases and re-presses Space (#10446).
11006
+ if (this.inputs.getIsPanning() && !this.inputs.keys.has('Space')) {
11120
11007
  this.inputs.setIsPanning(false)
11121
11008
  this.inputs.setIsSpacebarPanning(false)
11122
11009
  this.setCursor({ type: this._prevCursor, rotation: 0 })
@@ -11870,10 +11757,10 @@ function withIsolatedShapes<T>(
11870
11757
 
11871
11758
  function getCameraFitXFitY(editor: Editor, cameraOptions: TLCameraOptions) {
11872
11759
  if (!cameraOptions.constraints) throw Error('Should have constraints here')
11873
- const {
11874
- padding: { x: px, y: py },
11875
- } = cameraOptions.constraints
11876
11760
  const vsb = editor.getViewportScreenBounds()
11761
+ // Clamp padding to half the viewport size on either dimension, as getConstrainedCamera does
11762
+ const px = Math.min(cameraOptions.constraints.padding.x, vsb.w / 2)
11763
+ const py = Math.min(cameraOptions.constraints.padding.y, vsb.h / 2)
11877
11764
  const bounds = Box.From(cameraOptions.constraints.bounds)
11878
11765
  const zx = (vsb.w - px * 2) / bounds.w
11879
11766
  const zy = (vsb.h - py * 2) / bounds.h