@tldraw/commenting 5.3.0-internal.c5c7f1d817d0 → 5.3.0-next.030bf6014f04

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 (328) hide show
  1. package/README.md +0 -2
  2. package/commenting.css +1059 -257
  3. package/dist-cjs/canvas/anchor-lifecycle.js +148 -0
  4. package/dist-cjs/canvas/anchor-lifecycle.js.map +7 -0
  5. package/dist-cjs/canvas/canvas-events.js +35 -0
  6. package/dist-cjs/canvas/canvas-events.js.map +7 -0
  7. package/dist-cjs/canvas/cluster-badge.js +121 -0
  8. package/dist-cjs/canvas/cluster-badge.js.map +7 -0
  9. package/dist-cjs/canvas/cluster-fade.js +85 -0
  10. package/dist-cjs/canvas/cluster-fade.js.map +7 -0
  11. package/dist-cjs/canvas/cluster-input.js +53 -3
  12. package/dist-cjs/canvas/cluster-input.js.map +2 -2
  13. package/dist-cjs/canvas/cluster-model.js +252 -0
  14. package/dist-cjs/canvas/cluster-model.js.map +7 -0
  15. package/dist-cjs/canvas/comment-drafts.js +54 -0
  16. package/dist-cjs/canvas/comment-drafts.js.map +7 -0
  17. package/dist-cjs/canvas/comment-mutations.js +152 -0
  18. package/dist-cjs/canvas/comment-mutations.js.map +7 -0
  19. package/dist-cjs/canvas/comment-reactions.js +160 -0
  20. package/dist-cjs/canvas/comment-reactions.js.map +7 -0
  21. package/dist-cjs/canvas/comment-render.js +9 -6
  22. package/dist-cjs/canvas/comment-render.js.map +2 -2
  23. package/dist-cjs/canvas/comment-store.js +19 -9
  24. package/dist-cjs/canvas/comment-store.js.map +2 -2
  25. package/dist-cjs/canvas/comment-tool.js +63 -14
  26. package/dist-cjs/canvas/comment-tool.js.map +2 -2
  27. package/dist-cjs/canvas/comments-filter-menu.js +17 -37
  28. package/dist-cjs/canvas/comments-filter-menu.js.map +2 -2
  29. package/dist-cjs/canvas/comments-overflow-menu.js +25 -22
  30. package/dist-cjs/canvas/comments-overflow-menu.js.map +2 -2
  31. package/dist-cjs/canvas/comments-overlay.js +150 -1003
  32. package/dist-cjs/canvas/comments-overlay.js.map +3 -3
  33. package/dist-cjs/canvas/comments-sidebar.js +48 -40
  34. package/dist-cjs/canvas/comments-sidebar.js.map +2 -2
  35. package/dist-cjs/canvas/comments-visibility-toggle.js +45 -0
  36. package/dist-cjs/canvas/comments-visibility-toggle.js.map +7 -0
  37. package/dist-cjs/canvas/context.js +17 -0
  38. package/dist-cjs/canvas/context.js.map +7 -0
  39. package/dist-cjs/canvas/hooks.js +28 -3
  40. package/dist-cjs/canvas/hooks.js.map +2 -2
  41. package/dist-cjs/canvas/license.js.map +1 -1
  42. package/dist-cjs/canvas/mobile-placement.js +91 -0
  43. package/dist-cjs/canvas/mobile-placement.js.map +7 -0
  44. package/dist-cjs/canvas/options.js +57 -2
  45. package/dist-cjs/canvas/options.js.map +2 -2
  46. package/dist-cjs/canvas/pending-composer.js +134 -0
  47. package/dist-cjs/canvas/pending-composer.js.map +7 -0
  48. package/dist-cjs/canvas/pin-stacking.js +81 -0
  49. package/dist-cjs/canvas/pin-stacking.js.map +7 -0
  50. package/dist-cjs/canvas/region-box.js +113 -0
  51. package/dist-cjs/canvas/region-box.js.map +7 -0
  52. package/dist-cjs/canvas/sidebar-filters.js +2 -2
  53. package/dist-cjs/canvas/sidebar-filters.js.map +2 -2
  54. package/dist-cjs/canvas/state.js +28 -14
  55. package/dist-cjs/canvas/state.js.map +2 -2
  56. package/dist-cjs/canvas/thread-pin.js +304 -0
  57. package/dist-cjs/canvas/thread-pin.js.map +7 -0
  58. package/dist-cjs/canvas/thread-preview.js +177 -0
  59. package/dist-cjs/canvas/thread-preview.js.map +7 -0
  60. package/dist-cjs/canvas/thread-stack.js +199 -0
  61. package/dist-cjs/canvas/thread-stack.js.map +7 -0
  62. package/dist-cjs/canvas/thread-state.js +82 -21
  63. package/dist-cjs/canvas/thread-state.js.map +2 -2
  64. package/dist-cjs/canvas/thread-view.js +450 -0
  65. package/dist-cjs/canvas/thread-view.js.map +7 -0
  66. package/dist-cjs/clustering/computeClusterTable.js +6 -6
  67. package/dist-cjs/clustering/computeClusterTable.js.map +2 -2
  68. package/dist-cjs/clustering/replay.js +89 -22
  69. package/dist-cjs/clustering/replay.js.map +3 -3
  70. package/dist-cjs/clustering/runtime.js +27 -20
  71. package/dist-cjs/clustering/runtime.js.map +2 -2
  72. package/dist-cjs/clustering/types.js.map +1 -1
  73. package/dist-cjs/index.d.ts +904 -373
  74. package/dist-cjs/index.js +52 -28
  75. package/dist-cjs/index.js.map +2 -2
  76. package/dist-cjs/ui/byline.js +8 -4
  77. package/dist-cjs/ui/byline.js.map +2 -2
  78. package/dist-cjs/ui/comment-card.js +12 -5
  79. package/dist-cjs/ui/comment-card.js.map +2 -2
  80. package/dist-cjs/ui/comment-composer.js +99 -20
  81. package/dist-cjs/ui/comment-composer.js.map +2 -2
  82. package/dist-cjs/ui/comment-pin.js +7 -2
  83. package/dist-cjs/ui/comment-pin.js.map +2 -2
  84. package/dist-cjs/ui/comment-thread.js +4 -2
  85. package/dist-cjs/ui/comment-thread.js.map +2 -2
  86. package/dist-cjs/ui/comments-list.js +32 -33
  87. package/dist-cjs/ui/comments-list.js.map +2 -2
  88. package/dist-cjs/ui/count-badge.js +3 -2
  89. package/dist-cjs/ui/count-badge.js.map +2 -2
  90. package/dist-cjs/ui/emoji-picker.js +54 -0
  91. package/dist-cjs/ui/emoji-picker.js.map +7 -0
  92. package/dist-cjs/ui/format-time.js +16 -1
  93. package/dist-cjs/ui/format-time.js.map +2 -2
  94. package/dist-cjs/ui/icons.js +115 -0
  95. package/dist-cjs/ui/icons.js.map +7 -0
  96. package/dist-cjs/ui/reaction-picker.js +71 -0
  97. package/dist-cjs/ui/reaction-picker.js.map +7 -0
  98. package/dist-cjs/ui/reaction.js +51 -6
  99. package/dist-cjs/ui/reaction.js.map +2 -2
  100. package/dist-cjs/ui/reactions.js +20 -15
  101. package/dist-cjs/ui/reactions.js.map +2 -2
  102. package/dist-cjs/ui/{mention.js → reply-count.js} +9 -11
  103. package/dist-cjs/ui/reply-count.js.map +7 -0
  104. package/dist-cjs/ui/send-button.js +13 -1
  105. package/dist-cjs/ui/send-button.js.map +2 -2
  106. package/dist-cjs/ui/{comment-text.js → visual-viewport.js} +12 -9
  107. package/dist-cjs/ui/visual-viewport.js.map +7 -0
  108. package/dist-esm/canvas/anchor-lifecycle.mjs +128 -0
  109. package/dist-esm/canvas/anchor-lifecycle.mjs.map +7 -0
  110. package/dist-esm/canvas/canvas-events.mjs +15 -0
  111. package/dist-esm/canvas/canvas-events.mjs.map +7 -0
  112. package/dist-esm/canvas/cluster-badge.mjs +106 -0
  113. package/dist-esm/canvas/cluster-badge.mjs.map +7 -0
  114. package/dist-esm/canvas/cluster-fade.mjs +65 -0
  115. package/dist-esm/canvas/cluster-fade.mjs.map +7 -0
  116. package/dist-esm/canvas/cluster-input.mjs +54 -4
  117. package/dist-esm/canvas/cluster-input.mjs.map +2 -2
  118. package/dist-esm/canvas/cluster-model.mjs +236 -0
  119. package/dist-esm/canvas/cluster-model.mjs.map +7 -0
  120. package/dist-esm/canvas/comment-drafts.mjs +34 -0
  121. package/dist-esm/canvas/comment-drafts.mjs.map +7 -0
  122. package/dist-esm/canvas/comment-mutations.mjs +132 -0
  123. package/dist-esm/canvas/comment-mutations.mjs.map +7 -0
  124. package/dist-esm/canvas/comment-reactions.mjs +145 -0
  125. package/dist-esm/canvas/comment-reactions.mjs.map +7 -0
  126. package/dist-esm/canvas/comment-render.mjs +10 -7
  127. package/dist-esm/canvas/comment-render.mjs.map +2 -2
  128. package/dist-esm/canvas/comment-store.mjs +19 -9
  129. package/dist-esm/canvas/comment-store.mjs.map +2 -2
  130. package/dist-esm/canvas/comment-tool.mjs +66 -17
  131. package/dist-esm/canvas/comment-tool.mjs.map +2 -2
  132. package/dist-esm/canvas/comments-filter-menu.mjs +17 -36
  133. package/dist-esm/canvas/comments-filter-menu.mjs.map +2 -2
  134. package/dist-esm/canvas/comments-overflow-menu.mjs +27 -22
  135. package/dist-esm/canvas/comments-overflow-menu.mjs.map +2 -2
  136. package/dist-esm/canvas/comments-overlay.mjs +156 -1024
  137. package/dist-esm/canvas/comments-overlay.mjs.map +3 -3
  138. package/dist-esm/canvas/comments-sidebar.mjs +52 -45
  139. package/dist-esm/canvas/comments-sidebar.mjs.map +2 -2
  140. package/dist-esm/canvas/comments-visibility-toggle.mjs +25 -0
  141. package/dist-esm/canvas/comments-visibility-toggle.mjs.map +7 -0
  142. package/dist-esm/canvas/context.mjs +1 -0
  143. package/dist-esm/canvas/context.mjs.map +7 -0
  144. package/dist-esm/canvas/hooks.mjs +35 -5
  145. package/dist-esm/canvas/hooks.mjs.map +2 -2
  146. package/dist-esm/canvas/license.mjs.map +1 -1
  147. package/dist-esm/canvas/mobile-placement.mjs +71 -0
  148. package/dist-esm/canvas/mobile-placement.mjs.map +7 -0
  149. package/dist-esm/canvas/options.mjs +59 -3
  150. package/dist-esm/canvas/options.mjs.map +2 -2
  151. package/dist-esm/canvas/pending-composer.mjs +126 -0
  152. package/dist-esm/canvas/pending-composer.mjs.map +7 -0
  153. package/dist-esm/canvas/pin-stacking.mjs +61 -0
  154. package/dist-esm/canvas/pin-stacking.mjs.map +7 -0
  155. package/dist-esm/canvas/region-box.mjs +93 -0
  156. package/dist-esm/canvas/region-box.mjs.map +7 -0
  157. package/dist-esm/canvas/sidebar-filters.mjs +2 -2
  158. package/dist-esm/canvas/sidebar-filters.mjs.map +2 -2
  159. package/dist-esm/canvas/state.mjs +29 -19
  160. package/dist-esm/canvas/state.mjs.map +2 -2
  161. package/dist-esm/canvas/thread-pin.mjs +310 -0
  162. package/dist-esm/canvas/thread-pin.mjs.map +7 -0
  163. package/dist-esm/canvas/thread-preview.mjs +163 -0
  164. package/dist-esm/canvas/thread-preview.mjs.map +7 -0
  165. package/dist-esm/canvas/thread-stack.mjs +189 -0
  166. package/dist-esm/canvas/thread-stack.mjs.map +7 -0
  167. package/dist-esm/canvas/thread-state.mjs +86 -22
  168. package/dist-esm/canvas/thread-state.mjs.map +2 -2
  169. package/dist-esm/canvas/thread-view.mjs +461 -0
  170. package/dist-esm/canvas/thread-view.mjs.map +7 -0
  171. package/dist-esm/clustering/computeClusterTable.mjs +6 -6
  172. package/dist-esm/clustering/computeClusterTable.mjs.map +2 -2
  173. package/dist-esm/clustering/replay.mjs +89 -22
  174. package/dist-esm/clustering/replay.mjs.map +3 -3
  175. package/dist-esm/clustering/runtime.mjs +27 -20
  176. package/dist-esm/clustering/runtime.mjs.map +2 -2
  177. package/dist-esm/index.d.mts +904 -373
  178. package/dist-esm/index.mjs +102 -43
  179. package/dist-esm/index.mjs.map +2 -2
  180. package/dist-esm/ui/byline.mjs +9 -5
  181. package/dist-esm/ui/byline.mjs.map +2 -2
  182. package/dist-esm/ui/comment-card.mjs +12 -5
  183. package/dist-esm/ui/comment-card.mjs.map +2 -2
  184. package/dist-esm/ui/comment-composer.mjs +109 -19
  185. package/dist-esm/ui/comment-composer.mjs.map +2 -2
  186. package/dist-esm/ui/comment-pin.mjs +7 -2
  187. package/dist-esm/ui/comment-pin.mjs.map +2 -2
  188. package/dist-esm/ui/comment-thread.mjs +4 -2
  189. package/dist-esm/ui/comment-thread.mjs.map +2 -2
  190. package/dist-esm/ui/comments-list.mjs +48 -47
  191. package/dist-esm/ui/comments-list.mjs.map +2 -2
  192. package/dist-esm/ui/count-badge.mjs +3 -2
  193. package/dist-esm/ui/count-badge.mjs.map +2 -2
  194. package/dist-esm/ui/emoji-picker.mjs +34 -0
  195. package/dist-esm/ui/emoji-picker.mjs.map +7 -0
  196. package/dist-esm/ui/format-time.mjs +16 -1
  197. package/dist-esm/ui/format-time.mjs.map +2 -2
  198. package/dist-esm/ui/icons.mjs +95 -0
  199. package/dist-esm/ui/icons.mjs.map +7 -0
  200. package/dist-esm/ui/reaction-picker.mjs +59 -0
  201. package/dist-esm/ui/reaction-picker.mjs.map +7 -0
  202. package/dist-esm/ui/reaction.mjs +52 -7
  203. package/dist-esm/ui/reaction.mjs.map +2 -2
  204. package/dist-esm/ui/reactions.mjs +21 -16
  205. package/dist-esm/ui/reactions.mjs.map +2 -2
  206. package/dist-esm/ui/reply-count.mjs +9 -0
  207. package/dist-esm/ui/reply-count.mjs.map +7 -0
  208. package/dist-esm/ui/send-button.mjs +13 -1
  209. package/dist-esm/ui/send-button.mjs.map +2 -2
  210. package/dist-esm/ui/visual-viewport.mjs +12 -0
  211. package/dist-esm/ui/visual-viewport.mjs.map +7 -0
  212. package/package.json +6 -6
  213. package/src/canvas/anchor-lifecycle.test.ts +290 -0
  214. package/src/canvas/anchor-lifecycle.ts +191 -0
  215. package/src/canvas/canvas-events.ts +18 -0
  216. package/src/canvas/canvas.css +444 -35
  217. package/src/canvas/cluster-badge.tsx +133 -0
  218. package/src/canvas/cluster-fade.ts +102 -0
  219. package/src/canvas/cluster-input.test.ts +178 -36
  220. package/src/canvas/cluster-input.ts +95 -9
  221. package/src/canvas/cluster-model.ts +378 -0
  222. package/src/canvas/comment-drafts.test.ts +55 -0
  223. package/src/canvas/comment-drafts.ts +46 -0
  224. package/src/canvas/comment-mutations.test.ts +452 -0
  225. package/src/canvas/comment-mutations.ts +299 -0
  226. package/src/canvas/comment-reactions.test.ts +154 -0
  227. package/src/canvas/comment-reactions.tsx +246 -0
  228. package/src/canvas/comment-render.ts +17 -13
  229. package/src/canvas/comment-store.ts +68 -33
  230. package/src/canvas/comment-tool.test.ts +162 -0
  231. package/src/canvas/comment-tool.tsx +103 -25
  232. package/src/canvas/comments-filter-menu.tsx +20 -36
  233. package/src/canvas/comments-overflow-menu.tsx +15 -17
  234. package/src/canvas/comments-overlay.tsx +251 -1401
  235. package/src/canvas/comments-sidebar.test.ts +45 -0
  236. package/src/canvas/comments-sidebar.tsx +111 -72
  237. package/src/canvas/comments-visibility-toggle.tsx +25 -0
  238. package/src/canvas/context.ts +48 -0
  239. package/src/canvas/hooks.test.ts +94 -0
  240. package/src/canvas/hooks.ts +66 -11
  241. package/src/canvas/license.ts +1 -1
  242. package/src/canvas/mobile-placement.ts +115 -0
  243. package/src/canvas/options.test.ts +176 -4
  244. package/src/canvas/options.ts +276 -18
  245. package/src/canvas/pending-composer.tsx +157 -0
  246. package/src/canvas/pin-stacking.test.ts +224 -0
  247. package/src/canvas/pin-stacking.ts +103 -0
  248. package/src/canvas/region-box.tsx +124 -0
  249. package/src/canvas/sidebar-filters.ts +4 -3
  250. package/src/canvas/state.ts +88 -39
  251. package/src/canvas/thread-pin.tsx +418 -0
  252. package/src/canvas/thread-preview.test.ts +91 -0
  253. package/src/canvas/thread-preview.tsx +294 -0
  254. package/src/canvas/thread-stack.tsx +242 -0
  255. package/src/canvas/thread-state.test.ts +260 -0
  256. package/src/canvas/thread-state.ts +171 -37
  257. package/src/canvas/thread-view.test.ts +72 -0
  258. package/src/canvas/thread-view.tsx +614 -0
  259. package/src/clustering/computeClusterTable.test.ts +24 -23
  260. package/src/clustering/computeClusterTable.ts +17 -8
  261. package/src/clustering/replay.test.ts +0 -7
  262. package/src/clustering/replay.ts +131 -32
  263. package/src/clustering/runtime.test.ts +84 -6
  264. package/src/clustering/runtime.ts +52 -44
  265. package/src/clustering/schedule.test.ts +0 -6
  266. package/src/clustering/screen-offsets.test.ts +171 -0
  267. package/src/clustering/types.ts +19 -9
  268. package/src/index.ts +91 -42
  269. package/src/ui/byline.tsx +20 -8
  270. package/src/ui/comment-card.tsx +17 -7
  271. package/src/ui/comment-composer.tsx +146 -43
  272. package/src/ui/comment-pin.tsx +9 -2
  273. package/src/ui/comment-thread.tsx +6 -1
  274. package/src/ui/comments-list.test.ts +31 -0
  275. package/src/ui/comments-list.tsx +69 -38
  276. package/src/ui/comments.css +505 -222
  277. package/src/ui/count-badge.tsx +9 -2
  278. package/src/ui/emoji-picker.test.ts +25 -0
  279. package/src/ui/emoji-picker.tsx +76 -0
  280. package/src/ui/format-time.test.ts +69 -0
  281. package/src/ui/format-time.ts +27 -2
  282. package/src/ui/icons.tsx +116 -0
  283. package/src/ui/reaction-picker.tsx +102 -0
  284. package/src/ui/reaction.tsx +123 -7
  285. package/src/ui/reactions.tsx +68 -13
  286. package/src/ui/reply-count.ts +16 -0
  287. package/src/ui/send-button.tsx +13 -3
  288. package/src/ui/visual-viewport.test.ts +36 -0
  289. package/src/ui/visual-viewport.ts +27 -0
  290. package/dist-cjs/canvas/region-options.js +0 -49
  291. package/dist-cjs/canvas/region-options.js.map +0 -7
  292. package/dist-cjs/ui/avatar.js +0 -51
  293. package/dist-cjs/ui/avatar.js.map +0 -7
  294. package/dist-cjs/ui/comment-mention.js +0 -42
  295. package/dist-cjs/ui/comment-mention.js.map +0 -7
  296. package/dist-cjs/ui/comment-text.js.map +0 -7
  297. package/dist-cjs/ui/mention-list.js +0 -70
  298. package/dist-cjs/ui/mention-list.js.map +0 -7
  299. package/dist-cjs/ui/mention-suggestion.js +0 -206
  300. package/dist-cjs/ui/mention-suggestion.js.map +0 -7
  301. package/dist-cjs/ui/mention.js.map +0 -7
  302. package/dist-cjs/ui/render-markdown.js +0 -63
  303. package/dist-cjs/ui/render-markdown.js.map +0 -7
  304. package/dist-esm/canvas/region-options.mjs +0 -29
  305. package/dist-esm/canvas/region-options.mjs.map +0 -7
  306. package/dist-esm/ui/avatar.mjs +0 -31
  307. package/dist-esm/ui/avatar.mjs.map +0 -7
  308. package/dist-esm/ui/comment-mention.mjs +0 -22
  309. package/dist-esm/ui/comment-mention.mjs.map +0 -7
  310. package/dist-esm/ui/comment-text.mjs +0 -9
  311. package/dist-esm/ui/comment-text.mjs.map +0 -7
  312. package/dist-esm/ui/mention-list.mjs +0 -50
  313. package/dist-esm/ui/mention-list.mjs.map +0 -7
  314. package/dist-esm/ui/mention-suggestion.mjs +0 -186
  315. package/dist-esm/ui/mention-suggestion.mjs.map +0 -7
  316. package/dist-esm/ui/mention.mjs +0 -11
  317. package/dist-esm/ui/mention.mjs.map +0 -7
  318. package/dist-esm/ui/render-markdown.mjs +0 -45
  319. package/dist-esm/ui/render-markdown.mjs.map +0 -7
  320. package/src/canvas/region-options.ts +0 -57
  321. package/src/ui/avatar.tsx +0 -38
  322. package/src/ui/comment-mention.ts +0 -47
  323. package/src/ui/comment-text.tsx +0 -12
  324. package/src/ui/mention-list.tsx +0 -106
  325. package/src/ui/mention-suggestion.test.ts +0 -18
  326. package/src/ui/mention-suggestion.tsx +0 -285
  327. package/src/ui/mention.tsx +0 -9
  328. package/src/ui/render-markdown.tsx +0 -72
@@ -1,416 +1,197 @@
1
+ import { isMentionPickerOpen } from '@tldraw/mentions'
2
+ import { Fragment, ReactNode, useCallback, useEffect, useMemo, useRef } from 'react'
3
+ import { EditorPortal, TLCommentThread, useEditor, useValue } from 'tldraw'
4
+ import type { ClusterNode } from '../clustering/types'
5
+ import { registerCommentAnchorLifecycle } from './anchor-lifecycle'
6
+ import { ClusterBadge } from './cluster-badge'
7
+ import { clusterFadeClassName } from './cluster-fade'
1
8
  import {
2
- memo,
3
- type CSSProperties,
4
- type PointerEvent as ReactPointerEvent,
5
- ReactNode,
6
- useCallback,
7
- useEffect,
8
- useMemo,
9
- useRef,
10
- useState,
11
- } from 'react'
12
- import { createPortal } from 'react-dom'
13
- import {
14
- type BoxModel,
15
- createComment,
16
- createCommentThread,
17
- Editor,
18
- getFirstCharacter,
19
- react,
20
- TLComment,
21
- TLCommentId,
22
- TLCommentThread,
23
- TLRichText,
24
- TldrawUiIcon,
25
- useContainer,
26
- useEditor,
27
- usePassThroughMouseOverEvents,
28
- usePassThroughWheelEvents,
29
- useTranslation,
30
- useValue,
31
- VecLike,
32
- } from 'tldraw'
33
- import { computeClusterTable } from '../clustering/computeClusterTable'
34
- import { type ClusterRuntime, createClusterRuntime } from '../clustering/runtime'
35
- import type { ClusterNode, ClusterTable, MergeEvent } from '../clustering/types'
36
- import { CommentCard, CommentCardProps } from '../ui/comment-card'
37
- import { CommentComposer } from '../ui/comment-composer'
38
- import { EMPTY_COMMENT, isCommentEmpty } from '../ui/comment-extensions'
39
- import { CommentPin } from '../ui/comment-pin'
40
- import { CommentThread } from '../ui/comment-thread'
41
- import { CountBadge } from '../ui/count-badge'
42
- import { MentionMember } from '../ui/mention-list'
43
- import { isMentionPickerOpen } from '../ui/mention-suggestion'
44
- import { collectClusterLeaves } from './cluster-input'
45
- import { CommentBody } from './comment-body'
46
- import { UNKNOWN_AUTHOR } from './comment-render'
47
- import { getCommentRecord, putCommentRecords, removeCommentRecords } from './comment-store'
48
- import { PendingComment } from './comment-tool'
49
- import { useCommentThreads, useThreadComments } from './hooks'
9
+ CLUSTER_EXPAND_ZOOM_MS,
10
+ revealThreadPin,
11
+ useClusterModel,
12
+ zoomToClusterSplit,
13
+ } from './cluster-model'
14
+ import { getCommentRecord } from './comment-store'
15
+ import { type CommentingContext } from './context'
16
+ import { useCommentThreads } from './hooks'
50
17
  import { useCommentingEnabled } from './license'
51
- import {
52
- type CommentingComponents,
53
- type CommentingOptions,
54
- getCommentingOptions,
55
- useCommentingOptions,
56
- } from './options'
57
- import {
58
- DEFAULT_REGION_COMMENT_OPTIONS,
59
- RegionCommentOptions,
60
- setRegionCommentOptions,
61
- } from './region-options'
18
+ import { useCanComment, useCommentingOptions } from './options'
19
+ import { PendingComposer } from './pending-composer'
20
+ import { computePinStacks, isOpenStackKeyLive, pinStacksEqual } from './pin-stacking'
21
+ import { RegionBox, RegionDraftBox } from './region-box'
62
22
  import {
63
23
  commentsHidden,
64
- commitCommentMutation,
24
+ openStackId,
65
25
  openThreadId,
66
26
  pendingComment,
67
- regionDraft,
27
+ revealThreadRequest,
28
+ sidebarFilters,
68
29
  toggleCommentsHidden,
69
30
  usePendingComment,
70
31
  } from './state'
71
- import { anchorPagePoint, regionPinPoint, shapeAnchorAt } from './thread-state'
32
+ import { ThreadPin } from './thread-pin'
33
+ import { ThreadStackPin } from './thread-stack'
34
+
35
+ /**
36
+ * The host wiring for {@link CanvasComments} — see {@link CommentingContext}, which the sidebar
37
+ * takes the same fields from.
38
+ *
39
+ * @public
40
+ */
41
+ export type CanvasCommentsProps = CommentingContext
72
42
 
73
43
  /**
74
44
  * A ready-to-use comments layer for a tldraw canvas: pins each thread at its anchor, opens a
75
45
  * thread popover (with a reply composer) on click, and shows a composer where the comment tool
76
46
  * placed a new thread. Reads/writes comment records straight from `editor.store`.
77
47
  *
78
- * It's meant as the batteries-included default — every visible piece is a lever (the `CommentBody`
79
- * and `PinContent` slots on `CommentTool.configure({ components })`), and the pieces it composes
80
- * (`CommentPin`, `CommentThread`, `CommentComposer`, the hooks, the tool) are all exported, so a
81
- * consumer can rebuild this from parts instead.
82
- * @public
48
+ * It's the batteries-included default: every visible piece is a slot on
49
+ * `CommentTool.configure({ components })`, and the pieces it composes (`CommentPin`,
50
+ * `CommentThread`, `CommentComposer`, the hooks, the tool) are all exported, so a consumer can
51
+ * rebuild it from parts instead. The host wiring is the {@link CommentingContext}, which
52
+ * `CanvasCommentsSidebar` takes too.
53
+ *
54
+ * @public @react
83
55
  */
84
- export interface CanvasCommentsProps {
85
- /** The signed-in user's id, or null for a read-only viewer. Only a signed-in user composes. */
86
- currentUserId: string | null
87
- /** Map an author id to a display name, or `undefined` when the id can't be named. */
88
- resolveName(id: string): string | undefined
89
- /** Called after any comment (a new thread's first comment, or a reply) is posted. */
90
- onPostComment?(comment: TLComment): void
91
- /** Whether a comment is unread for the current user (return true for unread). */
92
- isCommentUnread?(commentId: TLCommentId): boolean
93
- /**
94
- * Called for each unread comment shown to the user in an open thread popover, so hosts can
95
- * record a read receipt. Needs `isCommentUnread` to know what's unread.
96
- */
97
- onCommentRead?(commentId: TLCommentId): void
98
- /** Resolve the members matching an `@`-query in the composers (sync or async). */
99
- getMentionSuggestions?(query: string): MentionMember[] | Promise<MentionMember[]>
100
- /** Override a mention-picker row's content. */
101
- renderMentionSuggestion?(member: MentionMember): ReactNode
102
- /** Where imprecise shape pins sit — a normalized (0–1) spot within the shape. Default top-right. */
103
- impreciseShapeAnchor?: { x: number; y: number }
104
- /** Region comment behaviour. Region is off by default — omit this for click-only point/shape
105
- * comments. Anything unset falls back to {@link DEFAULT_REGION_COMMENT_OPTIONS}. */
106
- regionOptions?: Partial<RegionCommentOptions>
107
- }
108
-
109
- const stop = (e: { stopPropagation(): void }) => e.stopPropagation()
110
-
111
- const initialOf = (name: string): string => (getFirstCharacter(name.trim()) || '?').toUpperCase()
112
- const CLUSTER_FADE_MS = 150
113
- /** Duration of the click-a-badge zoom-to-split animation. */
114
- const CLUSTER_EXPAND_ZOOM_MS = 450
115
-
116
- /** The leading element for the placement composer — the comment pin's shape, but a pencil
117
- * instead of an initial, marking an unsent draft. */
118
- const draftAvatar = (
119
- <CommentPin>
120
- <svg
121
- viewBox="0 0 24 24"
122
- width="15"
123
- height="15"
124
- fill="none"
125
- stroke="currentColor"
126
- strokeWidth="2"
127
- strokeLinecap="round"
128
- strokeLinejoin="round"
129
- aria-hidden="true"
130
- >
131
- <path d="M12 20h9" />
132
- <path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z" />
133
- </svg>
134
- </CommentPin>
135
- )
136
-
137
- function toCardProps(
138
- comment: TLComment,
139
- props: CanvasCommentsProps,
140
- components: CommentingComponents
141
- ): CommentCardProps {
142
- const Body = components.CommentBody
143
- // The `CommentBody` component slot overrides the built-in rich-text default (which resolves
144
- // mention ids to names).
145
- const body = Body ? (
146
- <Body comment={comment} />
147
- ) : (
148
- <CommentBody richText={comment.body} resolveName={props.resolveName} />
149
- )
150
- return {
151
- author: props.resolveName(comment.authorId) ?? UNKNOWN_AUTHOR,
152
- body,
153
- date: new Date(comment.createdAt).toISOString(),
154
- you: comment.authorId === props.currentUserId,
155
- edited: comment.editedAt != null,
156
- }
157
- }
158
-
159
- /** @public @react */
160
56
  export function CanvasComments(props: CanvasCommentsProps) {
161
- // Gate the whole layer on the license before doing any work. The inner component holds all the
162
- // other hooks, so mounting/unmounting it as the license resolves keeps hook order stable here.
57
+ // The inner component holds every other hook, so mounting it as the license resolves keeps hook
58
+ // order stable here.
163
59
  const commentingEnabled = useCommentingEnabled()
164
60
  if (!commentingEnabled) return null
165
61
  return <CanvasCommentsLayer {...props} />
166
62
  }
167
63
 
168
- function CanvasCommentsLayer(props: CanvasCommentsProps) {
64
+ function CanvasCommentsLayer(props: CommentingContext) {
169
65
  const editor = useEditor()
170
66
  const options = useCommentingOptions()
171
- const container = useContainer()
172
- // Merge the consumer's region options over the disabled defaults and publish them for this editor,
173
- // so the comment tool (which has no props) reads the same per-instance config.
174
- const regionOptions = useMemo(
175
- () => ({ ...DEFAULT_REGION_COMMENT_OPTIONS, ...props.regionOptions }),
176
- [props.regionOptions]
177
- )
178
- useEffect(() => setRegionCommentOptions(editor, regionOptions), [editor, regionOptions])
179
- const layerRef = useRef<HTMLDivElement>(null)
180
- // Over the pins and cluster badges, wheel and hover pass through to the canvas beneath (these
181
- // events bubble up from the pointer-interactive markers to this layer root).
182
- usePassThroughWheelEvents(layerRef)
183
- usePassThroughMouseOverEvents(layerRef)
184
- const deepLinkHandled = useRef(false)
185
- const threads = useCommentThreads(editor)
67
+ const allThreads = useCommentThreads(editor)
186
68
  const pending = usePendingComment()
187
- const openId = useValue('open thread id', () => openThreadId.get(editor), [editor])
188
- const impreciseShapeAnchor = props.impreciseShapeAnchor ?? options.impreciseShapeAnchor
189
- // Threads held out of clustering because their anchor moved while folded inside a badge
190
- // (drag, nudge, align, undo, a collaborator — detected by position, not gesture). They render
191
- // as live pins riding their anchor and rejoin clustering on the next zoom-out.
192
- const [heldThreadIds, setHeldThreadIds] = useState<ReadonlySet<string>>(EMPTY_SET)
193
- const adoptOnRebuild = useRef(false)
194
- const clusterLeaves = useValue(
195
- 'comment cluster leaves',
196
- () =>
197
- collectClusterLeaves(
198
- editor,
199
- threads.filter((thread) => !heldThreadIds.has(thread.id)),
200
- openThreadId.get(editor),
201
- impreciseShapeAnchor
202
- ),
203
- [editor, threads, impreciseShapeAnchor, heldThreadIds]
204
- )
205
- const clusterZoomBounds = useValue(
206
- 'comment cluster zoom bounds',
207
- () => getClusterZoomBounds(editor),
208
- [editor]
209
- )
210
- const latestModel = useMemo(() => {
211
- const table = computeClusterTable(clusterLeaves, clusterZoomBounds)
212
- const runtime = createClusterRuntime(table)
213
- runtime.seed(editor.getZoomLevel())
214
- return { runtime, table }
215
- }, [clusterLeaves, clusterZoomBounds, editor])
216
- // The core invariant: the only thing that re-flows clustering doc-wide is zoom. Every rebuild
217
- // (add / move / delete / open / pop-out) is computed immediately as `latestModel` — the MST
218
- // stays correct — but the on-screen partition is `renderedModel`, and it only ever changes via
219
- // (a) the cursor walking on zoom, (b) adoption of the pending rebuild on zoom-out, or
220
- // (c) LOCAL detach patches: a leaf that left the input (deleted, opened, popped out) is
221
- // detached from its own badge in place — count and centroid update for that badge alone,
222
- // and nothing else on the canvas moves.
223
- const [renderedModel, setRenderedModel] = useState(latestModel)
224
- let clusterModel = renderedModel
225
- // A page switch replaces the whole scene: hard-reset rather than detach the world.
226
- const pageId = useValue('comment cluster page', () => editor.getCurrentPageId(), [editor])
227
- const pageRef = useRef(pageId)
228
- if (pageRef.current !== pageId) {
229
- pageRef.current = pageId
230
- adoptOnRebuild.current = false
231
- latestModel.runtime.seed(editor.getZoomLevel())
232
- if (heldThreadIds.size > 0) setHeldThreadIds(EMPTY_SET)
233
- setRenderedModel(latestModel)
234
- clusterModel = latestModel
235
- }
236
- // adoptOnRebuild is set by the rejoin reaction below, outside React's render cycle, paired
237
- // with clearing heldThreadIds. Only trust it once that pairing is actually visible here
238
- // (heldThreadIds confirmed empty) — an unrelated re-render can land in the gap between the
239
- // ref being set and the state update it was paired with being applied.
240
- const rejoinPending = heldThreadIds.size === 0 && adoptOnRebuild.current
241
- if (renderedModel !== latestModel && rejoinPending) {
242
- adoptOnRebuild.current = false
243
- // Carryover seed: band events inherit the outgoing partition's merged/unmerged state, so
244
- // nothing changes state because of the swap alone. Idempotent, so safe during render.
245
- latestModel.runtime.seedFrom(editor.getZoomLevel(), renderedModel.runtime.getVisible())
246
- setRenderedModel(latestModel)
247
- clusterModel = latestModel
248
- } else if (heldThreadIds.size === 0 && renderedModel === latestModel) {
249
- // Nothing pending and nothing to adopt: clear any leftover force-adopt intent so it can't
250
- // survive to force-adopt a later, unrelated rebuild.
251
- adoptOnRebuild.current = false
252
- }
253
- // Pop-out detection: a leaf folded inside a badge can't follow its anchor (the badge position
254
- // is baked into the model), so when its live position drifts from the baked one, hold it out.
255
- // It renders as a live pin riding the anchor; the detach loop below shrinks its badge locally.
256
- const newlyMovedIds = findMovedClusteredLeafIds(clusterModel, latestModel)
257
- if (newlyMovedIds.length > 0) {
258
- const next = new Set(heldThreadIds)
259
- for (const id of newlyMovedIds) next.add(id)
260
- setHeldThreadIds(next)
261
- }
262
- // Local partition maintenance — the only non-zoom visual change, and it is local by
263
- // construction: any displayed leaf that has left the cluster input (deleted, thread opened,
264
- // popped out above) is detached from its badge in place. The corrected rebuild is already
265
- // sitting in latestModel awaiting the next zoom-out.
266
- {
267
- const latestLeafIds = new Set(latestModel.table.leaves.map((leaf) => leaf.id))
268
- for (const leaf of clusterModel.table.leaves) {
269
- if (!latestLeafIds.has(leaf.id)) {
270
- clusterModel.runtime.detachLeaf(leaf.id)
271
- }
272
- }
273
- }
274
- // Moved pins rejoin clustering on the next zoom-out motion: clear the set (so the rebuild
275
- // includes them again) and adopt that rebuild immediately instead of deferring it. Zooming in
276
- // never folds pins into clusters — merging is a zoom-out-only move, matching the runtime.
277
- useEffect(() => {
278
- if (heldThreadIds.size === 0) return
279
- let lastZoom = editor.getZoomLevel()
280
- return react('rejoin moved comment pins on zoom out', () => {
281
- const zoom = editor.getZoomLevel()
282
- const prevZoom = lastZoom
283
- lastZoom = zoom
284
- if (zoom >= prevZoom) return
285
- adoptOnRebuild.current = true
286
- setHeldThreadIds(EMPTY_SET)
287
- })
288
- }, [heldThreadIds, editor])
289
- // Adopt a pending rebuild only on zoom-out motion: folding deferred additions into clusters is
290
- // a merge, and merging only happens while zooming out. While zooming in, the stale table still
291
- // splits correctly on its own (split thresholds are direction-safe by the hysteresis invariant).
69
+ const canComment = useCanComment(props.currentUserId)
70
+ // Nothing renders a pending comment when composing is blocked and there's no fallback slot, and
71
+ // the dismiss handlers live inside PendingComposer — so clear the atom rather than strand it.
72
+ const canRenderComposer = canComment || options.components.ComposerFallback != null
73
+ const showPendingComposer = pending != null && canRenderComposer
292
74
  useEffect(() => {
293
- if (clusterModel === latestModel) return
294
- let lastZoom = editor.getZoomLevel()
295
- return react('adopt pending cluster model on zoom out', () => {
296
- const zoom = editor.getZoomLevel()
297
- const prevZoom = lastZoom
298
- lastZoom = zoom
299
- if (zoom >= prevZoom) return
300
- latestModel.runtime.seedFrom(zoom, clusterModel.runtime.getVisible())
301
- setRenderedModel(latestModel)
302
- })
303
- }, [clusterModel, latestModel, editor])
304
- // Threads in the current input that the displayed partition doesn't show anywhere (new
305
- // comments, reopened threads, undone deletions): render as plain pins until the next
306
- // zoom-out folds them in. Membership is judged against the *displayed* partition (with
307
- // detaches applied), not the rendered table, so a detached-then-restored leaf reappears.
308
- const partitionVersion = clusterModel.runtime.version
309
- const orphanThreads = useMemo(() => {
310
- if (clusterModel === latestModel) return []
311
- const displayed = new Set<string>()
312
- for (const node of clusterModel.runtime.getVisible().values()) {
313
- for (const member of node.members) displayed.add(member)
314
- }
315
- const latestIds = new Set(latestModel.table.leaves.map((leaf) => leaf.id))
316
- return threads.filter((thread) => latestIds.has(thread.id) && !displayed.has(thread.id))
317
- // The runtime mutates its partition in place; partitionVersion is its change stamp.
318
- // eslint-disable-next-line react-hooks/exhaustive-deps
319
- }, [clusterModel, latestModel, threads, partitionVersion])
320
- const heldThreads = useMemo(
321
- () => threads.filter((thread) => heldThreadIds.has(thread.id) && thread.id !== openId),
322
- [threads, heldThreadIds, openId]
323
- )
324
- // Subscribe to the runtime's partition version, not the raw zoom: onCamera runs on every zoom
325
- // tick (O(1) threshold checks) but the version only moves when the partition actually changes
326
- // — so this component only re-renders on cluster changes, not on every camera frame. The memo
327
- // below keys on a fresh inline read of the version rather than the subscribed value, because
328
- // render-time detaches (above) bump it after the subscription's computed already evaluated.
329
- useValue(
330
- 'comment cluster version',
331
- () => {
332
- clusterModel.runtime.onCamera(editor.getZoomLevel())
333
- return clusterModel.runtime.version
334
- },
335
- [clusterModel, editor]
75
+ if (pending && !showPendingComposer) pendingComment.set(editor, null)
76
+ }, [editor, pending, showPendingComposer])
77
+ const openId = useValue('open thread id', () => openThreadId.get(editor), [editor])
78
+ // Matches the sidebar's `showResolved` filter. The open thread stays in — resolving from its own
79
+ // popover shouldn't make the pin vanish under it.
80
+ const showResolved = useValue('show resolved', () => sidebarFilters.get(editor).showResolved, [
81
+ editor,
82
+ ])
83
+ const threads = useMemo(
84
+ () => allThreads.filter((t) => showResolved || t.resolved == null || t.id === openId),
85
+ [allThreads, showResolved, openId]
336
86
  )
337
- const visibleNodes = useMemo(() => {
338
- return Array.from(clusterModel.runtime.getVisible().values())
339
- // The runtime mutates its partition in place; partitionVersion is its change stamp.
340
- // eslint-disable-next-line react-hooks/exhaustive-deps
341
- }, [clusterModel, partitionVersion])
342
- const fadeNodes = useFadeVisibleNodes(visibleNodes, clusterModel)
87
+ useEffect(() => registerCommentAnchorLifecycle(editor), [editor])
88
+ const {
89
+ model: clusterModel,
90
+ zoomBounds: clusterZoomBounds,
91
+ fadeNodes,
92
+ orphanThreads,
93
+ heldThreads,
94
+ } = useClusterModel(editor, threads, openId)
343
95
  const threadsById = useMemo(
344
96
  () => new Map<string, TLCommentThread>(threads.map((thread) => [thread.id, thread])),
345
97
  [threads]
346
98
  )
99
+ // Pins with the *same* anchor point coincide at every zoom, so they render as one count-badge
100
+ // stack. Keyed on page-space anchors, so camera moves never recompute this. Holding the map's
101
+ // identity while the grouping is unchanged keeps a reply from re-rendering every pin — but the
102
+ // map has no positions in it, so anything needing a stack's *point* must read the anchors itself.
103
+ const pinStacksRef = useRef<Map<string, readonly string[]>>(new Map())
104
+ const pinStacks = useValue(
105
+ 'comment pin stacks',
106
+ () => {
107
+ const stacks = computePinStacks(editor, threads)
108
+ if (pinStacksEqual(pinStacksRef.current, stacks)) return pinStacksRef.current
109
+ pinStacksRef.current = stacks
110
+ return stacks
111
+ },
112
+ [editor, threads]
113
+ )
347
114
  const openThread = openId ? threadsById.get(openId) : null
348
115
  const hidden = useValue('comments hidden', () => commentsHidden.get(editor), [editor])
349
116
 
350
- // Reset the transient UI state (open thread, half-placed comment) when this unmounts.
351
117
  useEffect(() => {
352
118
  return () => {
353
119
  openThreadId.set(editor, null)
120
+ openStackId.set(editor, null)
354
121
  pendingComment.set(editor, null)
122
+ revealThreadRequest.set(editor, null)
355
123
  }
356
124
  }, [editor])
357
125
 
358
- // Open the thread named by a deep link (?comment=<thread or comment id>). If the thread is
359
- // currently inside a cluster, zoom to the first split that reveals it before opening.
126
+ // Clear a stale open-stack key: only the stack's own mounted handlers clear it, so collapsing to
127
+ // a single pin strands it — and `useMarkerPreview` reads any non-null value as "a stack is open"
128
+ // and suppresses every hover preview. Kept while any live stack still sits at that key. Reads the
129
+ // anchors rather than keying off `pinStacks`, whose identity survives a stack moving as a whole.
130
+ const openStackKeyIsStale = useValue(
131
+ 'open stack key stale',
132
+ () => {
133
+ const key = openStackId.get(editor)
134
+ if (!key) return false
135
+ return !isOpenStackKeyLive(editor, key, pinStacks, threadsById)
136
+ },
137
+ [editor, pinStacks, threadsById]
138
+ )
360
139
  useEffect(() => {
361
- if (deepLinkHandled.current) return
362
- const id = new URLSearchParams(window.location.search).get('comment')
363
- if (!id) {
364
- deepLinkHandled.current = true
365
- return
366
- }
367
-
368
- const record = getCommentRecord(editor, id)
369
- if (!record) return
140
+ if (openStackKeyIsStale) openStackId.set(editor, null)
141
+ }, [editor, openStackKeyIsStale])
370
142
 
371
- let thread: TLCommentThread | undefined
372
- if (record.typeName === 'comment') {
373
- thread = threadsById.get(record.threadId)
374
- } else {
375
- thread = record
376
- }
377
- if (!thread) return
143
+ // The requested thread, once it (and, for a comment id, its parent thread) has synced into the
144
+ // store; null while records are still arriving or when no request is pending.
145
+ const requestedRevealThread = useValue(
146
+ 'requested reveal thread',
147
+ () => {
148
+ const id = revealThreadRequest.get(editor)
149
+ if (!id) return null
150
+ const record = getCommentRecord(editor, id)
151
+ if (!record) return null
152
+ const thread =
153
+ record.typeName === 'comment' ? getCommentRecord(editor, record.threadId) : record
154
+ return thread?.typeName === 'comment-thread' ? thread : null
155
+ },
156
+ [editor]
157
+ )
378
158
 
379
- deepLinkHandled.current = true
380
- revealDeepLinkedThread(
381
- editor,
382
- thread,
383
- clusterModel.table,
384
- clusterZoomBounds,
385
- options,
386
- impreciseShapeAnchor
387
- )
388
- openThreadId.set(editor, thread.id)
389
- }, [clusterModel.table, clusterZoomBounds, editor, threadsById, impreciseShapeAnchor, options])
159
+ // Serve a pending reveal request, zooming to the first cluster split that reveals the pin if it's
160
+ // folded into a badge. Also unhides pins: the popover opens on the layer that hiding withholds.
161
+ useEffect(() => {
162
+ if (!requestedRevealThread) return
163
+ revealThreadRequest.set(editor, null)
164
+ commentsHidden.set(editor, false)
165
+ revealThreadPin(editor, requestedRevealThread, clusterModel.table, clusterZoomBounds, options)
166
+ openThreadId.set(editor, requestedRevealThread.id)
167
+ }, [requestedRevealThread, clusterModel.table, clusterZoomBounds, editor, options])
168
+
169
+ // Picking a thread out of a cluster's hover preview. `openThreadId` alone would work, but would
170
+ // cut straight there from the badge — zoom in first, the same move the badge's own click makes.
171
+ const revealClusteredThread = useCallback(
172
+ (thread: TLCommentThread) => {
173
+ revealThreadPin(
174
+ editor,
175
+ thread,
176
+ clusterModel.table,
177
+ clusterZoomBounds,
178
+ options,
179
+ CLUSTER_EXPAND_ZOOM_MS
180
+ )
181
+ openThreadId.set(editor, thread.id)
182
+ },
183
+ [clusterModel.table, clusterZoomBounds, editor, options]
184
+ )
390
185
 
391
- // Clicking a badge zooms to just past the zoom at which that cluster first unclusters,
392
- // centered on its centroid. The event that created a visible cluster is the event that splits
393
- // it, and (by the table's sort + monotone thresholds) it has the smallest zSplit of everything
394
- // applied inside it — so its zSplit is exactly the first split within those comments. The
395
- // animated zoom-in then drives the runtime cursor like any manual zoom, so the badge splits
396
- // (and can be drilled into further) with no extra bookkeeping.
397
- const zoomToClusterSplit = useCallback(
186
+ const expandCluster = useCallback(
398
187
  (node: ClusterNode) => {
399
- const event = clusterModel.table.events.find((e) => e.result.id === node.id)
400
- if (!event || !Number.isFinite(event.zSplit)) return
401
- const zoom = clamp(
402
- event.zSplit * options.clusterSplitZoomFactor,
403
- clusterZoomBounds.minZoom,
404
- clusterZoomBounds.maxZoom
405
- )
406
- centerOnPointAtZoom(editor, node.centroid, zoom, CLUSTER_EXPAND_ZOOM_MS)
188
+ zoomToClusterSplit(editor, clusterModel.table, clusterZoomBounds, node)
407
189
  },
408
- [clusterModel, clusterZoomBounds, editor, options]
190
+ [clusterModel.table, clusterZoomBounds, editor]
409
191
  )
410
192
 
411
- // Escape collapses the open thread. Capture-phase + stopPropagation so it runs ahead of the
412
- // editor (which would otherwise cancel the current tool or clear the selection). If a comment is
413
- // being edited, let its own Escape handler exit edit mode first, keeping the thread open.
193
+ // Escape collapses the open thread. Capture-phase so it runs ahead of the editor, which would
194
+ // otherwise cancel the tool or clear the selection.
414
195
  useEffect(() => {
415
196
  const onKeyDown = (e: KeyboardEvent) => {
416
197
  if (e.key !== 'Escape' || openThreadId.get(editor) === null) return
@@ -426,8 +207,8 @@ function CanvasCommentsLayer(props: CanvasCommentsProps) {
426
207
  return () => document.removeEventListener('keydown', onKeyDown, true)
427
208
  }, [editor])
428
209
 
429
- // Shift+C toggles comment-pin visibility on the canvas (matching Figma). Skipped while typing so
430
- // it never fires from inside a composer. Physical `KeyC` (layout-independent) with shift only.
210
+ // Shift+C toggles pin visibility. Physical `KeyC` so it's layout-independent, and skipped while
211
+ // typing so it never fires from inside a composer.
431
212
  useEffect(() => {
432
213
  const onKeyDown = (e: KeyboardEvent) => {
433
214
  if (e.code !== 'KeyC' || !e.shiftKey || e.metaKey || e.ctrlKey || e.altKey) return
@@ -440,1054 +221,123 @@ function CanvasCommentsLayer(props: CanvasCommentsProps) {
440
221
  return () => document.removeEventListener('keydown', onKeyDown, true)
441
222
  }, [editor])
442
223
 
443
- // Hidden: the whole canvas layer (pins, open popover, pending composer) is withheld. The signal
444
- // is read above so this component stays mounted and its shortcut/Escape effects keep running.
224
+ // The signal is read above so this stays mounted and its shortcut/Escape effects keep running.
445
225
  if (hidden) return null
446
226
 
447
- // Render into the container (above the panels' stacking context) so the pins and popovers
448
- // live in the UI layer rather than being clipped by the canvas layer.
449
- return createPortal(
450
- <div ref={layerRef} className="tlui-cmt-canvas-layer">
451
- {options.enableClustering ? (
452
- <>
453
- {fadeNodes.map(({ node, phase }) => {
454
- let content: ReactNode
455
- if (node.count === 1) {
456
- const thread = threadsById.get(node.id)
457
- if (!thread) return null
458
- content = (
459
- <ThreadPin
460
- editor={editor}
461
- thread={thread}
462
- {...props}
463
- regionOptions={regionOptions}
464
- />
465
- )
466
- } else {
467
- content = <ClusterBadge editor={editor} node={node} onExpand={zoomToClusterSplit} />
468
- }
469
- return (
470
- <div key={`cluster-fade:${node.id}`} className={clusterFadeClassName(phase)}>
471
- {content}
472
- </div>
473
- )
474
- })}
475
- {orphanThreads.map((thread) => (
476
- <ThreadPin
477
- key={thread.id}
478
- editor={editor}
479
- thread={thread}
480
- {...props}
481
- regionOptions={regionOptions}
482
- />
483
- ))}
484
- {heldThreads.map((thread) => (
485
- <ThreadPin
486
- key={thread.id}
487
- editor={editor}
488
- thread={thread}
489
- {...props}
490
- regionOptions={regionOptions}
491
- />
492
- ))}
493
- </>
494
- ) : (
495
- // Clustering off: every thread renders as its own live pin (each returns null when it's
496
- // not on the current page or its anchor is missing). The open thread is excluded here and
497
- // rendered once below, mirroring how the clustering path keeps it out of the cluster leaves —
498
- // otherwise it would mount a second, stacked pin.
499
- threads
500
- .filter((thread) => thread.id !== openId)
501
- .map((thread) => (
502
- <ThreadPin
503
- key={thread.id}
504
- editor={editor}
505
- thread={thread}
506
- {...props}
507
- regionOptions={regionOptions}
508
- />
509
- ))
510
- )}
511
- {openThread && (
512
- <ThreadPin
513
- key={`open:${openThread.id}`}
514
- editor={editor}
515
- thread={openThread}
516
- {...props}
517
- regionOptions={regionOptions}
518
- />
519
- )}
520
- <RegionDraftBox editor={editor} />
521
- {/* Keep the region visible while composing — the drag draft is gone by now, and no thread
522
- exists yet, so the pending anchor is what shows the area under the open composer. */}
523
- {pending?.anchor.type === 'region' && <RegionBox editor={editor} box={pending.anchor} />}
524
- {pending && props.currentUserId && (
525
- <PendingComposer editor={editor} pending={pending} {...props} />
526
- )}
527
- </div>,
528
- container
529
- )
530
- }
531
-
532
- const EMPTY_SET: ReadonlySet<string> = new Set()
533
- const MOVED_LEAF_EPSILON = 1e-6
534
- type ClusterFadePhase = 'entering' | 'present' | 'exiting'
535
-
536
- interface ClusterFadeNode {
537
- node: ClusterNode
538
- phase: ClusterFadePhase
539
- }
540
-
541
- function useFadeVisibleNodes(
542
- nodes: readonly ClusterNode[],
543
- resetKey: { runtime: ClusterRuntime; table: ClusterTable }
544
- ): ClusterFadeNode[] {
545
- const resetKeyRef = useRef(resetKey)
546
- const didReset = resetKeyRef.current !== resetKey
547
- if (didReset) {
548
- resetKeyRef.current = resetKey
549
- }
550
-
551
- const [fadeNodes, setFadeNodes] = useState<ClusterFadeNode[]>(() => toPresentFadeNodes(nodes))
552
- const renderedNodes = didReset ? toPresentFadeNodes(nodes) : fadeNodes
553
-
554
- useEffect(() => {
555
- setFadeNodes(toPresentFadeNodes(nodes))
556
- // Resets only on a new model (resetKey); node-list changes within the same model are
557
- // handled by the reconcile effect below, which fades entries in/out instead of snapping.
558
- // eslint-disable-next-line react-hooks/exhaustive-deps
559
- }, [resetKey])
560
-
561
- useEffect(() => {
562
- if (didReset) return
563
- setFadeNodes((previous) => reconcileFadeNodes(previous, nodes))
564
- }, [didReset, nodes])
565
-
566
- const hasEntering = renderedNodes.some((item) => item.phase === 'entering')
567
- useEffect(() => {
568
- if (!hasEntering) return
569
- const frame = requestClusterFadeFrame(() => {
570
- setFadeNodes((previous) =>
571
- previous.map((item) => (item.phase === 'entering' ? { ...item, phase: 'present' } : item))
572
- )
573
- })
574
- return () => cancelClusterFadeFrame(frame)
575
- }, [hasEntering, renderedNodes])
576
-
577
- const hasExiting = renderedNodes.some((item) => item.phase === 'exiting')
578
- useEffect(() => {
579
- if (!hasExiting) return
580
- const timeout = window.setTimeout(() => {
581
- setFadeNodes((previous) => previous.filter((item) => item.phase !== 'exiting'))
582
- }, CLUSTER_FADE_MS)
583
- return () => window.clearTimeout(timeout)
584
- }, [hasExiting, renderedNodes])
585
-
586
- return renderedNodes
587
- }
588
-
589
- function toPresentFadeNodes(nodes: readonly ClusterNode[]): ClusterFadeNode[] {
590
- return nodes.map((node) => ({ node, phase: 'present' }))
591
- }
592
-
593
- function reconcileFadeNodes(
594
- previous: readonly ClusterFadeNode[],
595
- nextNodes: readonly ClusterNode[]
596
- ): ClusterFadeNode[] {
597
- const previousById = new Map(previous.map((item) => [item.node.id, item]))
598
- const nextIds = new Set(nextNodes.map((node) => node.id))
599
- const next: ClusterFadeNode[] = []
600
-
601
- for (const node of nextNodes) {
602
- const previousItem = previousById.get(node.id)
603
- next.push({
604
- node,
605
- phase:
606
- previousItem && previousItem.phase !== 'exiting'
607
- ? previousItem.phase
608
- : previousItem
609
- ? 'present'
610
- : 'entering',
611
- })
612
- }
613
-
614
- for (const item of previous) {
615
- if (nextIds.has(item.node.id)) continue
616
- next.push(item.phase === 'exiting' ? item : { ...item, phase: 'exiting' })
617
- }
618
-
619
- return next
620
- }
621
-
622
- function requestClusterFadeFrame(callback: FrameRequestCallback): number {
623
- if (typeof requestAnimationFrame === 'function') return requestAnimationFrame(callback)
624
- return window.setTimeout(() => callback(0), 16)
625
- }
626
-
627
- function cancelClusterFadeFrame(frame: number) {
628
- if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frame)
629
- else window.clearTimeout(frame)
630
- }
631
-
632
- function clusterFadeClassName(phase: ClusterFadePhase): string {
633
- return `tlui-cmt-cluster-fade tlui-cmt-cluster-fade--${phase}`
634
- }
635
-
636
- /**
637
- * Leaves folded inside a badge whose live anchor no longer matches the position the rendered
638
- * model was built with. Visible (unclustered) leaf pins track their anchor live, so they can
639
- * stay deferred; a badge can't follow a member, so these must pop out of clustering.
640
- */
641
- function findMovedClusteredLeafIds(
642
- rendered: { runtime: ClusterRuntime; table: ClusterTable },
643
- latest: { table: ClusterTable }
644
- ): string[] {
645
- if (rendered.table === latest.table) return []
646
- const visible = rendered.runtime.getVisible()
647
- const latestById = new Map(latest.table.leaves.map((leaf) => [leaf.id, leaf]))
648
- const moved: string[] = []
649
- for (const leaf of rendered.table.leaves) {
650
- if (visible.has(leaf.id)) continue
651
- const current = latestById.get(leaf.id)
652
- if (!current) continue
653
- if (
654
- Math.abs(current.centroid.x - leaf.centroid.x) > MOVED_LEAF_EPSILON ||
655
- Math.abs(current.centroid.y - leaf.centroid.y) > MOVED_LEAF_EPSILON
656
- ) {
657
- moved.push(leaf.id)
658
- }
659
- }
660
- return moved
661
- }
662
-
663
- function getClusterZoomBounds(editor: Editor): { minZoom: number; maxZoom: number } {
664
- const cameraOptions = editor.getCameraOptions()
665
- const baseZoom = cameraOptions.constraints ? editor.getBaseZoom() : 1
666
- const zoomSteps = cameraOptions.zoomSteps
667
- return {
668
- minZoom: zoomSteps[0] * baseZoom,
669
- maxZoom: zoomSteps[zoomSteps.length - 1] * baseZoom,
670
- }
671
- }
672
-
673
- function revealDeepLinkedThread(
674
- editor: Editor,
675
- thread: TLCommentThread,
676
- table: ClusterTable,
677
- zoomBounds: { minZoom: number; maxZoom: number },
678
- options: CommentingOptions,
679
- impreciseShapeAnchor: { x: number; y: number }
680
- ) {
681
- if (thread.pageId !== editor.getCurrentPageId()) {
682
- editor.setCurrentPage(thread.pageId as any)
227
+ // The node's pin-stack group when every member shares one — a stack standing on its own, which
228
+ // renders as a cascading count-badge list rather than a zoom-to-split cluster badge. The group
229
+ // can include an open or orphan member the node's own leaves omit.
230
+ const stackGroupOf = (node: ClusterNode): readonly string[] | null => {
231
+ const group = pinStacks.get(node.members[0])
232
+ if (!group) return null
233
+ return node.members.every((id) => group.includes(id)) ? group : null
683
234
  }
684
235
 
685
- // Match where the rendered pin sits (resolved prop-or-option), so the camera centers on the pin.
686
- const point = anchorPagePoint(editor, thread.anchor, impreciseShapeAnchor)
687
- if (!point) return
688
-
689
- // With clustering off the pin always renders individually, so skip the zoom-to-split (its cluster
690
- // badge never exists) and just center on the pin.
236
+ // Which threads are on screen this render. A stack renders once, owned by its first on-screen
237
+ // member — members arrive by different paths, so ownership can't be decided per-path.
238
+ const renderedThreadIds = new Set<string>()
691
239
  if (options.enableClustering) {
692
- const parentEvent = findDirectParentEvent(table, thread.id)
693
- if (
694
- parentEvent &&
695
- Number.isFinite(parentEvent.zSplit) &&
696
- parentEvent.zSplit <= zoomBounds.maxZoom
697
- ) {
698
- const zoom = clamp(
699
- parentEvent.zSplit * options.clusterSplitZoomFactor,
700
- zoomBounds.minZoom,
701
- zoomBounds.maxZoom
702
- )
703
- centerOnPointAtZoom(editor, point, zoom)
704
- return
705
- }
706
- }
707
-
708
- editor.centerOnPoint(point, { animation: { duration: 200 } })
709
- }
710
-
711
- function findDirectParentEvent(table: ClusterTable, threadId: string): MergeEvent | undefined {
712
- return table.events.find((event) => event.children.some((child) => child.id === threadId))
713
- }
714
-
715
- function centerOnPointAtZoom(
716
- editor: Editor,
717
- point: { x: number; y: number },
718
- zoom: number,
719
- duration = 200
720
- ) {
721
- const viewport = editor.getViewportScreenBounds()
722
- editor.setCamera(
723
- {
724
- x: viewport.w / (2 * zoom) - point.x,
725
- y: viewport.h / (2 * zoom) - point.y,
726
- z: zoom,
727
- },
728
- { animation: { duration } }
729
- )
730
- }
731
-
732
- function clamp(value: number, min: number, max: number): number {
733
- return Math.max(min, Math.min(max, value))
734
- }
735
-
736
- // Memoized: cluster nodes and thread records are identity-stable while unchanged, so pins and
737
- // badges skip re-rendering when the parent re-renders for reasons that don't concern them
738
- // (leaf recomputes during shape drags, partition changes elsewhere). Camera tracking still
739
- // works — each component subscribes to its own viewport position via signals, not via props.
740
- const ClusterBadge = memo(function ClusterBadge({
741
- editor,
742
- node,
743
- onExpand,
744
- }: {
745
- editor: Editor
746
- node: ClusterNode
747
- onExpand(node: ClusterNode): void
748
- }) {
749
- const point = useValue(
750
- 'cluster badge point',
751
- () => {
752
- const pagePoint = editor.pageToViewport(node.centroid)
753
- if (!isInInflatedViewport(editor, pagePoint)) return null
754
- return pagePoint
755
- },
756
- [editor, node]
757
- )
758
-
759
- if (!point) return null
760
-
761
- return (
762
- <div
763
- className="tlui-cmt-canvas-cluster"
764
- style={{ left: point.x, top: point.y }}
765
- onPointerDown={stop}
766
- onClick={(e) => {
767
- e.stopPropagation()
768
- onExpand(node)
769
- }}
770
- >
771
- <CountBadge count={node.count} />
772
- </div>
773
- )
774
- })
775
-
776
- function isInInflatedViewport(editor: Editor, point: { x: number; y: number }): boolean {
777
- const viewport = editor.getViewportScreenBounds()
778
- const margin = getCommentingOptions(editor).clusterCullMargin
779
- return (
780
- point.x >= -margin &&
781
- point.y >= -margin &&
782
- point.x <= viewport.w + margin &&
783
- point.y <= viewport.h + margin
784
- )
785
- }
786
-
787
- /** The open thread's popover, portaled above the UI panels. Over it, wheel and hover events pass
788
- * through to the canvas (unless the popover is scrolling its own content), like tldraw's panels. */
789
- function ThreadPopover({
790
- container,
791
- style,
792
- children,
793
- }: {
794
- container: HTMLElement
795
- style: CSSProperties
796
- children: ReactNode
797
- }) {
798
- const ref = useRef<HTMLDivElement>(null)
799
- usePassThroughWheelEvents(ref)
800
- usePassThroughMouseOverEvents(ref)
801
- return createPortal(
802
- <div ref={ref} className="tlui-cmt-canvas-popover" style={style} onPointerDown={stop}>
803
- {children}
804
- </div>,
805
- container
806
- )
807
- }
808
-
809
- /** A dashed rectangle over a region anchor's bounds, in viewport space. Sits in the canvas layer as
810
- * a sibling of the pins. `pointer-events` stays off (canvas interaction passes through) unless
811
- * `movable`, in which case dragging the body translates the region — previews live, commits on drop. */
812
- function RegionBox({
813
- editor,
814
- box,
815
- movable,
816
- onPreview,
817
- onCommit,
818
- }: {
819
- editor: Editor
820
- box: BoxModel
821
- movable?: boolean
822
- onPreview?(bounds: BoxModel | null): void
823
- onCommit?(bounds: BoxModel): void
824
- }) {
825
- const rect = useValue(
826
- 'region rect',
827
- () => {
828
- // Position from the page→viewport top-left; screen size scales with zoom, page size doesn't.
829
- const topLeft = editor.pageToViewport({ x: box.x, y: box.y })
830
- const zoom = editor.getZoomLevel()
831
- return { left: topLeft.x, top: topLeft.y, width: box.w * zoom, height: box.h * zoom }
832
- },
833
- [editor, box.x, box.y, box.w, box.h]
834
- )
835
- // The grab point and the box at grab time, captured so the drag translates by a stable delta even
836
- // as the box prop reflows under the live preview.
837
- const grabRef = useRef<{ page: VecLike; box: BoxModel } | null>(null)
838
- const translated = (e: ReactPointerEvent<HTMLDivElement>): BoxModel => {
839
- const g = grabRef.current!
840
- const p = editor.screenToPage({ x: e.clientX, y: e.clientY })
841
- return { ...g.box, x: g.box.x + (p.x - g.page.x), y: g.box.y + (p.y - g.page.y) }
842
- }
843
- const startMove = (e: ReactPointerEvent<HTMLDivElement>) => {
844
- e.stopPropagation()
845
- grabRef.current = { page: editor.screenToPage({ x: e.clientX, y: e.clientY }), box }
846
- e.currentTarget.setPointerCapture(e.pointerId)
847
- }
848
- const onMove = (e: ReactPointerEvent<HTMLDivElement>) => {
849
- if (grabRef.current) onPreview?.(translated(e))
850
- }
851
- const endMove = (e: ReactPointerEvent<HTMLDivElement>) => {
852
- if (!grabRef.current) return
853
- const bounds = translated(e)
854
- grabRef.current = null
855
- if (e.currentTarget.hasPointerCapture(e.pointerId))
856
- e.currentTarget.releasePointerCapture(e.pointerId)
857
- onCommit?.(bounds)
858
- }
859
- return (
860
- <div
861
- className={
862
- movable
863
- ? 'tlui-cmt-canvas-region tlui-cmt-canvas-region--movable'
864
- : 'tlui-cmt-canvas-region'
865
- }
866
- style={rect}
867
- onPointerDown={movable ? startMove : undefined}
868
- onPointerMove={movable ? onMove : undefined}
869
- onPointerUp={movable ? endMove : undefined}
870
- />
871
- )
872
- }
873
-
874
- /** The live region being dragged out by the comment tool, or nothing when not dragging. */
875
- function RegionDraftBox({ editor }: { editor: Editor }) {
876
- const box = useValue('region draft', () => regionDraft.get(editor), [editor])
877
- if (!box) return null
878
- return <RegionBox editor={editor} box={box} />
879
- }
880
-
881
- // A resize handle's normalized 0–1 spot on the box, and its cursor. An axis at 0.5 (a side midpoint)
882
- // is *not* controlled by that handle: corners resize both axes, edges resize only their own.
883
- interface RegionHandle {
884
- x: number
885
- y: number
886
- cursor: string
887
- }
888
-
889
- // The four corners (both axes) and the four side midpoints (one axis each).
890
- const REGION_CORNERS: readonly RegionHandle[] = [
891
- { x: 0, y: 0, cursor: 'nwse-resize' },
892
- { x: 1, y: 0, cursor: 'nesw-resize' },
893
- { x: 0, y: 1, cursor: 'nesw-resize' },
894
- { x: 1, y: 1, cursor: 'nwse-resize' },
895
- ]
896
- const REGION_EDGES: readonly RegionHandle[] = [
897
- { x: 0.5, y: 0, cursor: 'ns-resize' },
898
- { x: 1, y: 0.5, cursor: 'ew-resize' },
899
- { x: 0.5, y: 1, cursor: 'ns-resize' },
900
- { x: 0, y: 0.5, cursor: 'ew-resize' },
901
- ]
902
-
903
- // Screen-space slack around a region's bounds within which its box and handles stay revealed, so
904
- // the handles (which sit on the edge) are comfortably reachable.
905
- const REGION_HANDLE_MARGIN_PX = 12
906
-
907
- /** Resize `box` by dragging `handle` to `cursor` (page coords). Each controlled axis spans from the
908
- * handle's fixed opposite edge to the cursor (normalized, so dragging past it flips); an axis the
909
- * handle doesn't control (a midpoint, at 0.5) keeps its original position and size. */
910
- function resizeRegion(box: BoxModel, handle: RegionHandle, cursor: VecLike): BoxModel {
911
- const controlsX = handle.x !== 0.5
912
- const controlsY = handle.y !== 0.5
913
- const fixedX = box.x + (1 - handle.x) * box.w
914
- const fixedY = box.y + (1 - handle.y) * box.h
915
- return {
916
- x: controlsX ? Math.min(fixedX, cursor.x) : box.x,
917
- y: controlsY ? Math.min(fixedY, cursor.y) : box.y,
918
- w: controlsX ? Math.abs(cursor.x - fixedX) : box.w,
919
- h: controlsY ? Math.abs(cursor.y - fixedY) : box.h,
920
- }
921
- }
922
-
923
- /** Draggable handles that resize a region — corners (both axes) or edges (one axis), per the resize
924
- * option. Previews live, commits on release. */
925
- function RegionResizeHandles({
926
- editor,
927
- box,
928
- handles,
929
- onPreview,
930
- onCommit,
931
- }: {
932
- editor: Editor
933
- box: BoxModel
934
- handles: readonly RegionHandle[]
935
- onPreview(bounds: BoxModel | null): void
936
- onCommit(bounds: BoxModel): void
937
- }) {
938
- // The box at pointer-down, captured so the box prop reflowing under the live preview doesn't move
939
- // the fixed edges mid-drag.
940
- const boxRef = useRef<BoxModel | null>(null)
941
- const points = useValue(
942
- 'region handle points',
943
- () =>
944
- handles.map((h) => {
945
- const p = editor.pageToViewport({ x: box.x + h.x * box.w, y: box.y + h.y * box.h })
946
- return { ...h, key: `${h.x}-${h.y}`, left: p.x, top: p.y }
947
- }),
948
- [editor, box.x, box.y, box.w, box.h, handles]
949
- )
950
- const startResize = (e: ReactPointerEvent<HTMLDivElement>) => {
951
- e.stopPropagation()
952
- boxRef.current = box
953
- e.currentTarget.setPointerCapture(e.pointerId)
954
- }
955
- const resizedTo = (h: RegionHandle, e: ReactPointerEvent<HTMLDivElement>): BoxModel =>
956
- resizeRegion(boxRef.current!, h, editor.screenToPage({ x: e.clientX, y: e.clientY }))
957
- const onResize = (h: RegionHandle) => (e: ReactPointerEvent<HTMLDivElement>) => {
958
- if (boxRef.current) onPreview(resizedTo(h, e))
959
- }
960
- const endResize = (h: RegionHandle) => (e: ReactPointerEvent<HTMLDivElement>) => {
961
- if (!boxRef.current) return
962
- const bounds = resizedTo(h, e)
963
- boxRef.current = null
964
- if (e.currentTarget.hasPointerCapture(e.pointerId))
965
- e.currentTarget.releasePointerCapture(e.pointerId)
966
- onCommit(bounds)
967
- }
968
- return (
969
- <>
970
- {points.map((h) => (
971
- <div
972
- key={h.key}
973
- className="tlui-cmt-canvas-region-handle"
974
- style={{ left: h.left, top: h.top, cursor: h.cursor }}
975
- onPointerDown={startResize}
976
- onPointerMove={onResize(h)}
977
- onPointerUp={endResize(h)}
978
- />
979
- ))}
980
- </>
981
- )
982
- }
983
-
984
- const ThreadPin = memo(function ThreadPin({
985
- editor,
986
- thread,
987
- regionOptions,
988
- ...props
989
- }: Omit<CanvasCommentsProps, 'regionOptions'> & {
990
- editor: Editor
991
- thread: TLCommentThread
992
- regionOptions: RegionCommentOptions
993
- }) {
994
- const {
995
- currentUserId,
996
- resolveName,
997
- onPostComment,
998
- isCommentUnread,
999
- onCommentRead,
1000
- getMentionSuggestions,
1001
- renderMentionSuggestion,
1002
- } = props
1003
- const options = useCommentingOptions()
1004
- const impreciseShapeAnchor = props.impreciseShapeAnchor ?? options.impreciseShapeAnchor
1005
- const container = useContainer()
1006
- const comments = useThreadComments(editor, thread.id)
1007
- const msg = useTranslation()
1008
- // Only one thread's popover is open at a time — shared across pins via the atom.
1009
- const open = useValue('thread open', () => openThreadId.get(editor) === thread.id, [
1010
- editor,
1011
- thread.id,
1012
- ])
1013
- const [reply, setReply] = useState<TLRichText>(EMPTY_COMMENT)
1014
- const [editingId, setEditingId] = useState<string | null>(null)
1015
- const [editText, setEditText] = useState<TLRichText>(EMPTY_COMMENT)
1016
- // While dragging the marker, its page point overrides the anchor's; committed on drop.
1017
- const [dragPagePoint, setDragPagePoint] = useState<{ x: number; y: number } | null>(null)
1018
- // The live bounds while a corner handle is resizing the region, else null.
1019
- const [resizeBounds, setResizeBounds] = useState<BoxModel | null>(null)
1020
- // Whether the pin marker is hovered — only consulted by the 'pin-hover' reveal mode.
1021
- const [pinHovered, setPinHovered] = useState(false)
1022
- // The 'pointer' reveal mode: is the pointer within the region's bounds (plus a grab margin)?
1023
- // Driven by pointer position, not DOM hover, so moving from anywhere in the region out to a corner
1024
- // handle never loses the affordance — the box stays `pointer-events: none`.
1025
- const pointerInRegion = useValue(
1026
- 'pointer in region',
1027
- () => {
1028
- if (thread.anchor.type !== 'region' || thread.pageId !== editor.getCurrentPageId())
1029
- return false
1030
- const m = REGION_HANDLE_MARGIN_PX / editor.getZoomLevel()
1031
- const p = editor.inputs.getCurrentPagePoint()
1032
- const a = thread.anchor
1033
- return p.x >= a.x - m && p.x <= a.x + a.w + m && p.y >= a.y - m && p.y <= a.y + a.h + m
1034
- },
1035
- [editor, thread.anchor, thread.pageId]
1036
- )
1037
- // A region's box and handles are revealed while open or mid-resize, plus — per the reveal mode —
1038
- // while the pointer is within the region ('pointer') or the pin is hovered ('pin-hover').
1039
- const revealed =
1040
- open ||
1041
- resizeBounds != null ||
1042
- (regionOptions.reveal === 'pointer' && pointerInRegion) ||
1043
- (regionOptions.reveal === 'pin-hover' && pinHovered)
1044
- // The resize handles: side midpoints ('edges'), or the corners other than the pin's ('corners').
1045
- const resizeHandles = useMemo(
1046
- () =>
1047
- regionOptions.resize === 'edges'
1048
- ? REGION_EDGES
1049
- : REGION_CORNERS.filter(
1050
- (c) => c.x !== regionOptions.pinCorner.x || c.y !== regionOptions.pinCorner.y
1051
- ),
1052
- [regionOptions.resize, regionOptions.pinCorner]
1053
- )
1054
- const dragRef = useRef<{ startX: number; startY: number; moved: boolean } | null>(null)
1055
- const markerRef = useRef<HTMLDivElement>(null)
1056
-
1057
- // Clicking outside the open popover (and off its own pin) closes the thread — mirrors the
1058
- // pending composer's dismiss. Capture phase + a class check rather than stopPropagation, since the
1059
- // popover portals elsewhere in the DOM. The pin marker is excluded so its own click-to-toggle
1060
- // handles it instead of this closing then the toggle reopening.
1061
- useEffect(() => {
1062
- if (!open) return
1063
- const onPointerDown = (e: PointerEvent) => {
1064
- const target = e.target as HTMLElement | null
1065
- if (!target) return
1066
- if (target.closest('.tlui-cmt-canvas-popover')) return
1067
- const marker = markerRef.current
1068
- if (marker && marker.contains(target)) return
1069
- // A press on a region's resize handle or movable body edits this thread — don't dismiss it.
1070
- if (target.closest('.tlui-cmt-canvas-region-handle, .tlui-cmt-canvas-region--movable')) return
1071
- // A click inside a menu/popover layered above us (the sidebar's filter or overflow
1072
- // dropdown, or the composer's mention picker — all portaled elsewhere) belongs to that
1073
- // layer; defer to its own dismissal instead of closing the thread out from under it.
1074
- if (
1075
- target.closest('.tlui-menu, [data-radix-popper-content-wrapper], .tlui-cmt-mention-popup')
1076
- )
1077
- return
1078
- openThreadId.set(editor, null)
1079
- }
1080
- document.addEventListener('pointerdown', onPointerDown, true)
1081
- return () => document.removeEventListener('pointerdown', onPointerDown, true)
1082
- }, [open, editor])
1083
-
1084
- const point = useValue(
1085
- 'pin point',
1086
- () => {
1087
- if (thread.pageId !== editor.getCurrentPageId()) return null
1088
- const pagePoint = anchorPagePoint(editor, thread.anchor, impreciseShapeAnchor)
1089
- return pagePoint ? editor.pageToViewport(pagePoint) : null
1090
- },
1091
- [editor, thread.anchor, thread.pageId, impreciseShapeAnchor]
1092
- )
1093
- const visible = point !== null
1094
-
1095
- // While the popover is open, every unread comment on display gets reported read — including
1096
- // replies that arrive while it stays open, since the effect re-runs as `comments` changes.
1097
- // The host's receipt write flips isCommentUnread to false, so re-runs find nothing to report.
1098
- useEffect(() => {
1099
- if (!open || !visible || !isCommentUnread || !onCommentRead) return
1100
- for (const comment of comments) {
1101
- if (isCommentUnread(comment.id)) {
1102
- onCommentRead(comment.id)
1103
- }
1104
- }
1105
- }, [open, visible, comments, isCommentUnread, onCommentRead])
1106
-
1107
- if (!point) return null
1108
-
1109
- const postReply = () => {
1110
- if (isCommentEmpty(reply) || !currentUserId) return
1111
- commitCommentMutation(editor, () => {
1112
- const comment = createComment({
1113
- threadId: thread.id,
1114
- pageId: thread.pageId,
1115
- authorId: currentUserId,
1116
- body: reply,
1117
- })
1118
- putCommentRecords(editor, [comment])
1119
- if (onPostComment) onPostComment(comment)
1120
- })
1121
- setReply(EMPTY_COMMENT)
1122
- }
1123
-
1124
- const toggleResolve = () => {
1125
- if (!currentUserId) return
1126
- commitCommentMutation(editor, () => {
1127
- putCommentRecords(editor, [
1128
- {
1129
- ...thread,
1130
- resolved: thread.resolved ? null : { at: Date.now(), by: currentUserId },
1131
- },
1132
- ])
1133
- })
1134
- }
1135
-
1136
- const deleteThread = () => {
1137
- openThreadId.set(editor, null)
1138
- commitCommentMutation(editor, () =>
1139
- removeCommentRecords(editor, [thread.id, ...comments.map((c) => c.id)])
1140
- )
1141
- }
1142
-
1143
- const startEdit = (comment: TLComment) => {
1144
- setEditingId(comment.id)
1145
- setEditText(comment.body)
1146
- }
1147
-
1148
- const saveEdit = () => {
1149
- const comment = comments.find((c) => c.id === editingId)
1150
- if (!comment || isCommentEmpty(editText)) return
1151
- commitCommentMutation(editor, () => {
1152
- putCommentRecords(editor, [{ ...comment, body: editText, editedAt: Date.now() }])
1153
- })
1154
- setEditingId(null)
1155
- }
1156
-
1157
- // Swap a comment for a pre-filled composer while it's being edited; otherwise show the card,
1158
- // with an edit affordance on your own comments.
1159
- const renderComment = (card: CommentCardProps, index: number): ReactNode => {
1160
- const comment = comments[index]
1161
- if (editingId === comment.id) {
1162
- return (
1163
- <div
1164
- className="tlui-cmt-editing"
1165
- onKeyDown={(e) => {
1166
- if (e.key === 'Escape') {
1167
- setEditingId(null)
1168
- e.stopPropagation()
1169
- }
1170
- }}
1171
- >
1172
- <CommentComposer
1173
- author={card.author}
1174
- placeholder={msg('comments.edit-placeholder')}
1175
- value={editText}
1176
- onChange={setEditText}
1177
- onSubmit={saveEdit}
1178
- sendLabel={msg('comments.save')}
1179
- disabled={isCommentEmpty(editText)}
1180
- getMentionSuggestions={getMentionSuggestions}
1181
- renderMentionSuggestion={renderMentionSuggestion}
1182
- autoFocus
1183
- />
1184
- </div>
1185
- )
240
+ for (const { node } of fadeNodes) {
241
+ if (node.count === 1) renderedThreadIds.add(node.id)
242
+ // A pure-stack node's members aren't count-1 leaves, so register them here for the owner
243
+ // logic to pick from.
244
+ else if (stackGroupOf(node)) for (const id of node.members) renderedThreadIds.add(id)
1186
245
  }
1187
- return (
1188
- <CommentCard
1189
- {...card}
1190
- actions={
1191
- comment.authorId === currentUserId ? (
1192
- <button
1193
- className="tlui-cmt-thread__action"
1194
- title={msg('comments.edit')}
1195
- onClick={() => startEdit(comment)}
1196
- >
1197
- <TldrawUiIcon icon="dots-horizontal" label={msg('comments.edit')} small />
1198
- </button>
1199
- ) : undefined
1200
- }
1201
- />
1202
- )
1203
- }
1204
-
1205
- const headerActions = (
1206
- <>
1207
- {currentUserId && (
1208
- <button
1209
- className="tlui-cmt-thread__action"
1210
- title={msg(thread.resolved ? 'comments.reopen' : 'comments.resolve')}
1211
- onClick={toggleResolve}
1212
- >
1213
- <TldrawUiIcon
1214
- icon="check"
1215
- label={msg(thread.resolved ? 'comments.reopen' : 'comments.resolve')}
1216
- small
1217
- />
1218
- </button>
1219
- )}
1220
- {currentUserId && (
1221
- <button
1222
- className="tlui-cmt-thread__action"
1223
- title={msg('comments.delete')}
1224
- onClick={deleteThread}
1225
- >
1226
- <TldrawUiIcon icon="trash" label={msg('comments.delete')} small />
1227
- </button>
1228
- )}
1229
- <button
1230
- className="tlui-cmt-thread__action"
1231
- title={msg('comments.dismiss')}
1232
- onClick={() => openThreadId.set(editor, null)}
1233
- >
1234
- <TldrawUiIcon icon="cross-2" label={msg('comments.dismiss')} small />
1235
- </button>
1236
- </>
1237
- )
1238
-
1239
- const PinContent = options.components.PinContent
1240
- // The `PinContent` component slot overrides the built-in author-initial default.
1241
- const pinContent = PinContent ? (
1242
- <PinContent thread={thread} comments={comments} />
1243
- ) : (
1244
- initialOf(resolveName(thread.createdBy) ?? UNKNOWN_AUTHOR)
1245
- )
1246
-
1247
- // Drag the marker to move the thread: its position is overridden locally while dragging, then
1248
- // re-anchored on drop. A point/shape thread re-anchors to whatever it's dropped on (a shape, else
1249
- // a point); a region thread translates, keeping its size. A pointer that barely moves is a click —
1250
- // toggle the popover.
1251
- // Which affordances move a region, per the option: 'pin' → pin only, 'body' → body only, 'both'.
1252
- const isRegion = thread.anchor.type === 'region'
1253
- const pinMovable = regionOptions.move !== 'body'
1254
- const bodyMovable = regionOptions.move !== 'pin'
1255
- const startDrag = (e: ReactPointerEvent<HTMLDivElement>) => {
1256
- e.stopPropagation()
1257
- dragRef.current = { startX: e.clientX, startY: e.clientY, moved: false }
1258
- e.currentTarget.setPointerCapture(e.pointerId)
1259
- }
1260
- const onDrag = (e: ReactPointerEvent<HTMLDivElement>) => {
1261
- const drag = dragRef.current
1262
- if (!drag) return
1263
- // A region that moves by its body ignores pin drags (the pin only toggles the thread).
1264
- if (isRegion && !pinMovable) return
1265
- if (!drag.moved && Math.hypot(e.clientX - drag.startX, e.clientY - drag.startY) < 4) return
1266
- drag.moved = true
1267
- setDragPagePoint(editor.screenToPage({ x: e.clientX, y: e.clientY }))
246
+ for (const thread of orphanThreads) renderedThreadIds.add(thread.id)
247
+ for (const thread of heldThreads) renderedThreadIds.add(thread.id)
248
+ } else {
249
+ for (const thread of threads) renderedThreadIds.add(thread.id)
1268
250
  }
1269
- const endDrag = (e: ReactPointerEvent<HTMLDivElement>) => {
1270
- const drag = dragRef.current
1271
- dragRef.current = null
1272
- if (e.currentTarget.hasPointerCapture(e.pointerId)) {
1273
- e.currentTarget.releasePointerCapture(e.pointerId)
251
+ if (openThread) renderedThreadIds.add(openThread.id)
252
+
253
+ // A coincident-stack member renders as the group's single count-badge stack (if it owns it)
254
+ // or not at all; everything else is an ordinary pin.
255
+ const renderThreadPin = (thread: TLCommentThread): ReactNode => {
256
+ const group = pinStacks.get(thread.id)
257
+ if (group) {
258
+ const owner = group.find((id) => renderedThreadIds.has(id))
259
+ if (owner !== thread.id) return null
260
+ const stackThreads = group
261
+ .map((id) => threadsById.get(id))
262
+ .filter((t): t is TLCommentThread => t !== undefined)
263
+ return <ThreadStackPin editor={editor} threads={stackThreads} {...props} />
1274
264
  }
1275
- if (!drag) return
1276
- if (!drag.moved) {
1277
- openThreadId.set(editor, openThreadId.get(editor) === thread.id ? null : thread.id)
1278
- return
1279
- }
1280
- const pagePoint = editor.screenToPage({ x: e.clientX, y: e.clientY })
1281
- setDragPagePoint(null)
1282
- let anchor: TLCommentThread['anchor']
1283
- if (thread.anchor.type === 'region') {
1284
- // Translate so the pin (the region's pin corner) lands at the drop; size unchanged.
1285
- anchor = {
1286
- ...thread.anchor,
1287
- x: pagePoint.x - regionOptions.pinCorner.x * thread.anchor.w,
1288
- y: pagePoint.y - regionOptions.pinCorner.y * thread.anchor.h,
1289
- }
1290
- } else {
1291
- const hit = editor.getShapeAtPoint(pagePoint, { hitInside: true })
1292
- anchor = hit
1293
- ? shapeAnchorAt(editor, hit.id, pagePoint, e.altKey)
1294
- : { type: 'point', x: pagePoint.x, y: pagePoint.y }
1295
- }
1296
- commitCommentMutation(editor, () => putCommentRecords(editor, [{ ...thread, anchor }]), 'drag')
1297
- }
1298
-
1299
- // The pin (and its popover) track the live edit: a resize moves it to the region's pin corner, a
1300
- // move to the drag point; otherwise it sits at the stored anchor's viewport point.
1301
- const livePinPage = resizeBounds
1302
- ? regionPinPoint(resizeBounds, regionOptions.pinCorner)
1303
- : dragPagePoint
1304
- const renderPoint = livePinPage ? editor.pageToViewport(livePinPage) : point
1305
-
1306
- // A region's live box bounds, by priority: a corner resize, else a pin-drag translation (the pin
1307
- // corner tracks the cursor), else the stored anchor. Undefined for non-region threads.
1308
- const regionAnchor = thread.anchor.type === 'region' ? thread.anchor : undefined
1309
- const movedRegion =
1310
- regionAnchor && dragPagePoint
1311
- ? {
1312
- ...regionAnchor,
1313
- x: dragPagePoint.x - regionOptions.pinCorner.x * regionAnchor.w,
1314
- y: dragPagePoint.y - regionOptions.pinCorner.y * regionAnchor.h,
1315
- }
1316
- : regionAnchor
1317
- const regionBoxBounds = resizeBounds ?? movedRegion
1318
- const commitResize = (bounds: BoxModel) => {
1319
- setResizeBounds(null)
1320
- editor.run(
1321
- () => putCommentRecords(editor, [{ ...thread, anchor: { type: 'region', ...bounds } }]),
1322
- {
1323
- history: 'ignore',
1324
- }
1325
- )
265
+ return <ThreadPin editor={editor} thread={thread} {...props} />
1326
266
  }
1327
267
 
268
+ // Portalled rather than rendered into this component's slot: pins sit below the collaborator
269
+ // cursors and popovers above the UI panels, and no single canvas layer spans both. The portal
270
+ // also fixes where the layer lands among the container's children, keeping it behind the UI's
271
+ // skip link in the tab order.
1328
272
  return (
1329
- <>
1330
- {regionBoxBounds && (dragPagePoint || revealed) && (
1331
- <RegionBox
1332
- editor={editor}
1333
- box={regionBoxBounds}
1334
- movable={bodyMovable && !dragPagePoint}
1335
- onPreview={setResizeBounds}
1336
- onCommit={commitResize}
1337
- />
1338
- )}
1339
- {regionBoxBounds && revealed && !dragPagePoint && regionOptions.resize !== 'none' && (
1340
- <RegionResizeHandles
1341
- editor={editor}
1342
- box={regionBoxBounds}
1343
- handles={resizeHandles}
1344
- onPreview={setResizeBounds}
1345
- onCommit={commitResize}
1346
- />
1347
- )}
1348
- <div
1349
- className={open ? 'tlui-cmt-canvas-pin tlui-cmt-canvas-pin--open' : 'tlui-cmt-canvas-pin'}
1350
- style={{ left: renderPoint.x, top: renderPoint.y }}
1351
- >
1352
- <div
1353
- ref={markerRef}
1354
- className="tlui-cmt-canvas-pin__marker"
1355
- onPointerDown={startDrag}
1356
- onPointerMove={onDrag}
1357
- onPointerUp={endDrag}
1358
- onPointerEnter={() => setPinHovered(true)}
1359
- onPointerLeave={() => setPinHovered(false)}
1360
- >
1361
- <CommentPin resolved={thread.resolved != null} open={open}>
1362
- {pinContent}
1363
- </CommentPin>
1364
- </div>
1365
- {/* The popover portals up to the menus layer (above the UI panels) so it isn't clipped;
1366
- the pin itself stays in the canvas-in-front layer, beneath the UI. */}
1367
- {open && (
1368
- <ThreadPopover
1369
- container={container}
1370
- style={{ left: renderPoint.x + 36, top: renderPoint.y - 28 }}
1371
- >
1372
- <CommentThread
1373
- header={msg('comments.thread-title')}
1374
- headerActions={headerActions}
1375
- renderComment={renderComment}
1376
- comments={comments.map((c) => toCardProps(c, props, options.components))}
1377
- resolvedBanner={
1378
- thread.resolved
1379
- ? msg('comments.resolved-by').replace(
1380
- '{name}',
1381
- resolveName(thread.resolved.by) ?? UNKNOWN_AUTHOR
1382
- )
1383
- : undefined
273
+ <EditorPortal>
274
+ {/* Wheel pass-through lives on each interactive element, not this root: the root spans the
275
+ whole canvas, so a pin past its bottom/right edge inflates scrollHeight and the wheel
276
+ hook's is-this-scrollable guard silently disables pass-through. */}
277
+ <div className="tlui-cmt-canvas-layer">
278
+ {options.enableClustering ? (
279
+ <>
280
+ {fadeNodes.map(({ node, phase }) => {
281
+ let content: ReactNode
282
+ const stackGroup = node.count > 1 ? stackGroupOf(node) : null
283
+ if (node.count === 1) {
284
+ const thread = threadsById.get(node.id)
285
+ if (!thread) return null
286
+ content = renderThreadPin(thread)
287
+ } else if (stackGroup) {
288
+ // Routed through the stack's owner so the open/orphan/held slots stay deduped:
289
+ // when the owner is one of them, that slot draws the stack and this draws nothing.
290
+ const owner = stackGroup.find((id) => renderedThreadIds.has(id))
291
+ content =
292
+ owner && node.members.includes(owner)
293
+ ? renderThreadPin(threadsById.get(owner)!)
294
+ : null
295
+ } else {
296
+ content = (
297
+ <ClusterBadge
298
+ editor={editor}
299
+ node={node}
300
+ onExpand={expandCluster}
301
+ onSelectThread={revealClusteredThread}
302
+ threadsById={threadsById}
303
+ currentUserId={props.currentUserId}
304
+ resolveAuthor={props.resolveAuthor}
305
+ />
306
+ )
1384
307
  }
1385
- composer={
1386
- currentUserId && !thread.resolved
1387
- ? {
1388
- author: resolveName(currentUserId) ?? UNKNOWN_AUTHOR,
1389
- placeholder: msg('comments.reply-placeholder'),
1390
- sendLabel: msg('comments.send'),
1391
- value: reply,
1392
- onChange: setReply,
1393
- onSubmit: postReply,
1394
- disabled: isCommentEmpty(reply),
1395
- getMentionSuggestions,
1396
- renderMentionSuggestion,
1397
- }
1398
- : undefined
1399
- }
1400
- />
1401
- </ThreadPopover>
308
+ return (
309
+ <div key={`cluster-fade:${node.id}`} className={clusterFadeClassName(phase)}>
310
+ {content}
311
+ </div>
312
+ )
313
+ })}
314
+ {orphanThreads.map((thread) => (
315
+ <Fragment key={thread.id}>{renderThreadPin(thread)}</Fragment>
316
+ ))}
317
+ {heldThreads.map((thread) => (
318
+ <Fragment key={thread.id}>{renderThreadPin(thread)}</Fragment>
319
+ ))}
320
+ </>
321
+ ) : (
322
+ // Clustering off: every thread renders its own pin. The open thread is excluded and
323
+ // rendered once below, or it would mount a second, stacked pin.
324
+ threads
325
+ .filter((thread) => thread.id !== openId)
326
+ .map((thread) => <Fragment key={thread.id}>{renderThreadPin(thread)}</Fragment>)
327
+ )}
328
+ {openThread && (
329
+ <Fragment key={`open:${openThread.id}`}>{renderThreadPin(openThread)}</Fragment>
330
+ )}
331
+ <RegionDraftBox editor={editor} />
332
+ {/* Keep the region visible while composing — the drag draft is gone by now, and no thread
333
+ exists yet, so the pending anchor is what shows the area under the open composer. */}
334
+ {pending?.anchor.type === 'region' && showPendingComposer && (
335
+ <RegionBox editor={editor} box={pending.anchor} />
336
+ )}
337
+ {pending && showPendingComposer && (
338
+ <PendingComposer editor={editor} pending={pending} {...props} />
1402
339
  )}
1403
340
  </div>
1404
- </>
1405
- )
1406
- })
1407
-
1408
- function PendingComposer({
1409
- editor,
1410
- pending,
1411
- currentUserId,
1412
- resolveName,
1413
- onPostComment,
1414
- getMentionSuggestions,
1415
- renderMentionSuggestion,
1416
- }: CanvasCommentsProps & { editor: Editor; pending: PendingComment }) {
1417
- const [text, setText] = useState<TLRichText>(EMPTY_COMMENT)
1418
- const ref = useRef<HTMLDivElement>(null)
1419
- const msg = useTranslation()
1420
- const container = useContainer()
1421
- // Over this floating panel, scroll and hover reach the canvas (except where it scrolls itself).
1422
- usePassThroughWheelEvents(ref)
1423
- usePassThroughMouseOverEvents(ref)
1424
-
1425
- const point = useValue('composer point', () => editor.pageToViewport(pending.point), [
1426
- editor,
1427
- pending.point,
1428
- ])
1429
-
1430
- // Dismiss on a click anywhere outside the composer (capture-phase, ahead of stopPropagation).
1431
- useEffect(() => {
1432
- const onPointerDown = (e: PointerEvent) => {
1433
- const el = ref.current
1434
- const target = e.target as HTMLElement | null
1435
- if (!el || !target) return
1436
- // A click in the composer, or in the mention picker it spawns (portaled elsewhere), is
1437
- // not "outside" — keep the draft open so the pick can insert.
1438
- if (el.contains(target) || target.closest('.tlui-cmt-mention-popup')) return
1439
- pendingComment.set(editor, null)
1440
- }
1441
- document.addEventListener('pointerdown', onPointerDown, true)
1442
- return () => document.removeEventListener('pointerdown', onPointerDown, true)
1443
- }, [editor])
1444
-
1445
- const submit = () => {
1446
- if (isCommentEmpty(text) || !currentUserId) return
1447
- commitCommentMutation(editor, () => {
1448
- const pageId = editor.getCurrentPageId()
1449
- const thread = createCommentThread({
1450
- pageId,
1451
- anchor: pending.anchor,
1452
- createdBy: currentUserId,
1453
- })
1454
- const comment = createComment({
1455
- threadId: thread.id,
1456
- pageId,
1457
- authorId: currentUserId,
1458
- body: text,
1459
- })
1460
- putCommentRecords(editor, [thread, comment])
1461
- if (onPostComment) onPostComment(comment)
1462
- })
1463
- setText(EMPTY_COMMENT)
1464
- pendingComment.set(editor, null)
1465
- }
1466
-
1467
- return createPortal(
1468
- <div
1469
- ref={ref}
1470
- className="tlui-cmt-canvas-composer"
1471
- style={{ left: point.x, top: point.y }}
1472
- onPointerDown={stop}
1473
- onKeyDown={(e) => {
1474
- if (e.key === 'Escape' && !isMentionPickerOpen()) pendingComment.set(editor, null)
1475
- }}
1476
- >
1477
- <CommentComposer
1478
- author={currentUserId ? (resolveName(currentUserId) ?? UNKNOWN_AUTHOR) : ''}
1479
- placeholder={msg('comments.add-placeholder')}
1480
- sendLabel={msg('comments.send')}
1481
- value={text}
1482
- onChange={setText}
1483
- onSubmit={submit}
1484
- disabled={isCommentEmpty(text)}
1485
- getMentionSuggestions={getMentionSuggestions}
1486
- renderMentionSuggestion={renderMentionSuggestion}
1487
- autoFocus
1488
- leading={draftAvatar}
1489
- />
1490
- </div>,
1491
- container
341
+ </EditorPortal>
1492
342
  )
1493
343
  }