@eocrm/design-system 0.0.0-stage → 0.6.17

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 (897) hide show
  1. package/AI-PRIMER.md +341 -0
  2. package/README.md +262 -2
  3. package/docs/components/Accordion.md +114 -0
  4. package/docs/components/AgentAvatar.md +58 -0
  5. package/docs/components/Alert.md +81 -0
  6. package/docs/components/AppLayout.md +70 -0
  7. package/docs/components/Avatar.md +49 -0
  8. package/docs/components/AvatarGroup.md +47 -0
  9. package/docs/components/Badge.md +60 -0
  10. package/docs/components/Banner.md +89 -0
  11. package/docs/components/BrandIcon.md +32 -0
  12. package/docs/components/Breadcrumb.md +72 -0
  13. package/docs/components/Button.md +107 -0
  14. package/docs/components/ButtonGroup.md +78 -0
  15. package/docs/components/Calendar.md +158 -0
  16. package/docs/components/Card.md +165 -0
  17. package/docs/components/CatalogPicker.md +83 -0
  18. package/docs/components/Chart.md +114 -0
  19. package/docs/components/ChatBubble.md +55 -0
  20. package/docs/components/ChatLauncher.md +97 -0
  21. package/docs/components/Checkbox.md +55 -0
  22. package/docs/components/CircularProgress.md +53 -0
  23. package/docs/components/Cluster.md +96 -0
  24. package/docs/components/Code.md +35 -0
  25. package/docs/components/CodeBlock.md +67 -0
  26. package/docs/components/ColorPicker.md +115 -0
  27. package/docs/components/ConfirmationPopover.md +70 -0
  28. package/docs/components/Constrain.md +39 -0
  29. package/docs/components/CurrencySelect.md +57 -0
  30. package/docs/components/CursorPagination.md +43 -0
  31. package/docs/components/DashboardCanvas.md +79 -0
  32. package/docs/components/DashboardWidget.md +131 -0
  33. package/docs/components/DataTable.md +88 -0
  34. package/docs/components/DatePicker.md +68 -0
  35. package/docs/components/DateRangePicker.md +71 -0
  36. package/docs/components/DateStrip.md +56 -0
  37. package/docs/components/DefinitionList.md +82 -0
  38. package/docs/components/Divider.md +57 -0
  39. package/docs/components/Dot.md +26 -0
  40. package/docs/components/Drawer.md +94 -0
  41. package/docs/components/DropdownMenu.md +299 -0
  42. package/docs/components/EmojiPicker.md +84 -0
  43. package/docs/components/EmptyState.md +55 -0
  44. package/docs/components/EntityChip.md +102 -0
  45. package/docs/components/ErrorState.md +72 -0
  46. package/docs/components/Field.md +91 -0
  47. package/docs/components/FileUpload.md +109 -0
  48. package/docs/components/FilterChip.md +88 -0
  49. package/docs/components/FlowCanvas.md +108 -0
  50. package/docs/components/FormRow.md +31 -0
  51. package/docs/components/FormSection.md +37 -0
  52. package/docs/components/Grid.md +103 -0
  53. package/docs/components/Highlight.md +75 -0
  54. package/docs/components/HighlightedText.md +50 -0
  55. package/docs/components/IconPicker.md +134 -0
  56. package/docs/components/IconTile.md +30 -0
  57. package/docs/components/Image.md +84 -0
  58. package/docs/components/ImageCrop.md +163 -0
  59. package/docs/components/Indent.md +31 -0
  60. package/docs/components/InlineDatePicker.md +58 -0
  61. package/docs/components/InlineDateRangePicker.md +57 -0
  62. package/docs/components/Input.md +54 -0
  63. package/docs/components/Kanban.md +122 -0
  64. package/docs/components/Kbd.md +41 -0
  65. package/docs/components/Lightbox.md +105 -0
  66. package/docs/components/Link.md +65 -0
  67. package/docs/components/LinkCard.md +41 -0
  68. package/docs/components/LiquidEditor.md +84 -0
  69. package/docs/components/List.md +68 -0
  70. package/docs/components/LiveRegion.md +29 -0
  71. package/docs/components/LocaleProvider.md +25 -0
  72. package/docs/components/Logo.md +41 -0
  73. package/docs/components/Masonry.md +48 -0
  74. package/docs/components/MediaTile.md +95 -0
  75. package/docs/components/Modal.md +107 -0
  76. package/docs/components/MoneyInput.md +62 -0
  77. package/docs/components/OptionsPicker.md +123 -0
  78. package/docs/components/OtpInput.md +65 -0
  79. package/docs/components/Page.md +35 -0
  80. package/docs/components/PageHeader.md +133 -0
  81. package/docs/components/Pagination.md +44 -0
  82. package/docs/components/Palette.md +32 -0
  83. package/docs/components/PasswordInput.md +45 -0
  84. package/docs/components/PasswordStrengthMeter.md +27 -0
  85. package/docs/components/PersonDisplay.md +153 -0
  86. package/docs/components/PhoneInput.md +54 -0
  87. package/docs/components/PillMenu.md +91 -0
  88. package/docs/components/Popover.md +127 -0
  89. package/docs/components/Progress.md +56 -0
  90. package/docs/components/QrCode.md +34 -0
  91. package/docs/components/Radio.md +37 -0
  92. package/docs/components/RadioGroup.md +56 -0
  93. package/docs/components/Rail.md +191 -0
  94. package/docs/components/RelativeDateInput.md +114 -0
  95. package/docs/components/RichText.md +44 -0
  96. package/docs/components/RichTextEditor.md +112 -0
  97. package/docs/components/Screen.md +37 -0
  98. package/docs/components/ScrollArea.md +39 -0
  99. package/docs/components/Select.md +131 -0
  100. package/docs/components/SettingRow.md +98 -0
  101. package/docs/components/Skeleton.md +68 -0
  102. package/docs/components/Slider.md +92 -0
  103. package/docs/components/SlotGrid.md +55 -0
  104. package/docs/components/SocialButton.md +31 -0
  105. package/docs/components/Sortable.md +127 -0
  106. package/docs/components/SortableGroup.md +52 -0
  107. package/docs/components/Sparkline.md +51 -0
  108. package/docs/components/Split.md +76 -0
  109. package/docs/components/Stack.md +59 -0
  110. package/docs/components/StagePath.md +66 -0
  111. package/docs/components/StatGroup.md +61 -0
  112. package/docs/components/StatTile.md +58 -0
  113. package/docs/components/Sticky.md +69 -0
  114. package/docs/components/Switch.md +89 -0
  115. package/docs/components/Table.md +184 -0
  116. package/docs/components/TableOfContents.md +76 -0
  117. package/docs/components/Tabs.md +94 -0
  118. package/docs/components/Text.md +63 -0
  119. package/docs/components/Textarea.md +59 -0
  120. package/docs/components/Thread.md +52 -0
  121. package/docs/components/TimeField.md +70 -0
  122. package/docs/components/Timeline.md +57 -0
  123. package/docs/components/Title.md +54 -0
  124. package/docs/components/ToastViewport.md +61 -0
  125. package/docs/components/Tooltip.md +63 -0
  126. package/docs/components/TopBar.md +214 -0
  127. package/docs/components/Tour.md +85 -0
  128. package/docs/components/TreeView.md +113 -0
  129. package/docs/components/VisuallyHidden.md +43 -0
  130. package/docs/components/WidgetPreview.md +54 -0
  131. package/docs/components/useBelowBreakpoint.md +11 -0
  132. package/docs/components/useMonth.md +18 -0
  133. package/docs/setup.md +51 -0
  134. package/docs/theming.md +95 -0
  135. package/docs/tokens.md +123 -0
  136. package/docs/transient-state.md +56 -0
  137. package/package.json +82 -4
  138. package/src/_meta/manifest.ts +293 -0
  139. package/src/app/AppProvider.tsx +78 -0
  140. package/src/app/index.ts +3 -0
  141. package/src/app/themeTokens.ts +95 -0
  142. package/src/calendar/dateMath.ts +114 -0
  143. package/src/calendar/formatters.ts +75 -0
  144. package/src/calendar/index.ts +39 -0
  145. package/src/calendar/types.ts +36 -0
  146. package/src/calendar/useAgenda.ts +70 -0
  147. package/src/calendar/useDay.ts +51 -0
  148. package/src/calendar/useMonth.ts +82 -0
  149. package/src/calendar/useWeek.ts +62 -0
  150. package/src/calendar/weekInfo.ts +83 -0
  151. package/src/components/Accordion/Accordion.module.scss +304 -0
  152. package/src/components/Accordion/Accordion.tokens.scss +64 -0
  153. package/src/components/Accordion/Accordion.tsx +272 -0
  154. package/src/components/Accordion/AccordionContent.tsx +36 -0
  155. package/src/components/Accordion/AccordionItem.tsx +66 -0
  156. package/src/components/Accordion/AccordionTrigger.tsx +121 -0
  157. package/src/components/Accordion/context.ts +47 -0
  158. package/src/components/Accordion/index.ts +14 -0
  159. package/src/components/Alert/Alert.module.scss +92 -0
  160. package/src/components/Alert/Alert.tokens.scss +60 -0
  161. package/src/components/Alert/Alert.tsx +136 -0
  162. package/src/components/Alert/index.ts +2 -0
  163. package/src/components/AppLayout/AppLayout.module.scss +130 -0
  164. package/src/components/AppLayout/AppLayout.tokens.scss +27 -0
  165. package/src/components/AppLayout/AppLayout.tsx +211 -0
  166. package/src/components/AppLayout/index.ts +2 -0
  167. package/src/components/Avatar/AgentAvatar.module.scss +117 -0
  168. package/src/components/Avatar/AgentAvatar.tsx +122 -0
  169. package/src/components/Avatar/Avatar.module.scss +181 -0
  170. package/src/components/Avatar/Avatar.tokens.scss +107 -0
  171. package/src/components/Avatar/Avatar.tsx +210 -0
  172. package/src/components/Avatar/AvatarGroup.module.scss +128 -0
  173. package/src/components/Avatar/AvatarGroup.tsx +119 -0
  174. package/src/components/Avatar/AvatarGroupContext.tsx +20 -0
  175. package/src/components/Avatar/index.ts +6 -0
  176. package/src/components/Badge/Badge.module.scss +124 -0
  177. package/src/components/Badge/Badge.tokens.scss +74 -0
  178. package/src/components/Badge/Badge.tsx +164 -0
  179. package/src/components/Badge/index.ts +2 -0
  180. package/src/components/Banner/Banner.module.scss +73 -0
  181. package/src/components/Banner/Banner.tokens.scss +51 -0
  182. package/src/components/Banner/Banner.tsx +138 -0
  183. package/src/components/Banner/index.ts +2 -0
  184. package/src/components/BrandIcon/BrandIcon.module.scss +5 -0
  185. package/src/components/BrandIcon/BrandIcon.tsx +99 -0
  186. package/src/components/BrandIcon/index.ts +2 -0
  187. package/src/components/Breadcrumb/Breadcrumb.module.scss +32 -0
  188. package/src/components/Breadcrumb/Breadcrumb.tokens.scss +9 -0
  189. package/src/components/Breadcrumb/Breadcrumb.tsx +146 -0
  190. package/src/components/Breadcrumb/index.ts +2 -0
  191. package/src/components/Button/Button.module.scss +167 -0
  192. package/src/components/Button/Button.tokens.scss +90 -0
  193. package/src/components/Button/Button.tsx +205 -0
  194. package/src/components/Button/index.ts +2 -0
  195. package/src/components/ButtonGroup/ButtonGroup.module.scss +134 -0
  196. package/src/components/ButtonGroup/ButtonGroup.tokens.scss +42 -0
  197. package/src/components/ButtonGroup/ButtonGroup.tsx +278 -0
  198. package/src/components/ButtonGroup/ButtonGroupItem.tsx +74 -0
  199. package/src/components/ButtonGroup/context.ts +45 -0
  200. package/src/components/ButtonGroup/index.ts +2 -0
  201. package/src/components/Calendar/AgendaView.module.scss +231 -0
  202. package/src/components/Calendar/AgendaView.tsx +214 -0
  203. package/src/components/Calendar/AllDayBand.module.scss +18 -0
  204. package/src/components/Calendar/AllDayBand.tsx +75 -0
  205. package/src/components/Calendar/Calendar.module.scss +23 -0
  206. package/src/components/Calendar/Calendar.tokens.scss +262 -0
  207. package/src/components/Calendar/Calendar.tsx +370 -0
  208. package/src/components/Calendar/DayCell.module.scss +30 -0
  209. package/src/components/Calendar/DayCell.tsx +50 -0
  210. package/src/components/Calendar/DayView.module.scss +10 -0
  211. package/src/components/Calendar/DayView.tsx +163 -0
  212. package/src/components/Calendar/EventChip.module.scss +171 -0
  213. package/src/components/Calendar/EventChip.tsx +115 -0
  214. package/src/components/Calendar/HourGrid.module.scss +123 -0
  215. package/src/components/Calendar/HourGrid.tsx +381 -0
  216. package/src/components/Calendar/MonthView.module.scss +99 -0
  217. package/src/components/Calendar/MonthView.tsx +296 -0
  218. package/src/components/Calendar/TimedEvent.module.scss +205 -0
  219. package/src/components/Calendar/TimedEvent.tsx +247 -0
  220. package/src/components/Calendar/ViewSwitcher.module.scss +3 -0
  221. package/src/components/Calendar/ViewSwitcher.tsx +47 -0
  222. package/src/components/Calendar/WeekView.module.scss +10 -0
  223. package/src/components/Calendar/WeekView.tsx +137 -0
  224. package/src/components/Calendar/eventColor.ts +60 -0
  225. package/src/components/Calendar/index.ts +18 -0
  226. package/src/components/Calendar/types.ts +451 -0
  227. package/src/components/Calendar/useEventDrag.ts +783 -0
  228. package/src/components/Calendar/utils.ts +622 -0
  229. package/src/components/Card/Card.module.scss +264 -0
  230. package/src/components/Card/Card.tokens.scss +55 -0
  231. package/src/components/Card/Card.tsx +170 -0
  232. package/src/components/Card/CardBody.tsx +45 -0
  233. package/src/components/Card/CardHeader.tsx +113 -0
  234. package/src/components/Card/CardList.tsx +24 -0
  235. package/src/components/Card/CardListRow.tsx +24 -0
  236. package/src/components/Card/index.ts +7 -0
  237. package/src/components/CatalogPicker/CatalogPicker.module.scss +193 -0
  238. package/src/components/CatalogPicker/CatalogPicker.tokens.scss +26 -0
  239. package/src/components/CatalogPicker/CatalogPicker.tsx +339 -0
  240. package/src/components/CatalogPicker/index.ts +2 -0
  241. package/src/components/Chart/Chart.module.scss +287 -0
  242. package/src/components/Chart/Chart.tokens.scss +63 -0
  243. package/src/components/Chart/Chart.tsx +607 -0
  244. package/src/components/Chart/ChartLegend.tsx +99 -0
  245. package/src/components/Chart/ChartTable.tsx +62 -0
  246. package/src/components/Chart/ChartTooltip.tsx +91 -0
  247. package/src/components/Chart/chartModel.ts +689 -0
  248. package/src/components/Chart/index.ts +2 -0
  249. package/src/components/ChatBubble/ChatBubble.module.scss +93 -0
  250. package/src/components/ChatBubble/ChatBubble.tokens.scss +17 -0
  251. package/src/components/ChatBubble/ChatBubble.tsx +61 -0
  252. package/src/components/ChatBubble/ChatBubbleList.tsx +27 -0
  253. package/src/components/ChatBubble/index.ts +3 -0
  254. package/src/components/ChatLauncher/ChatLauncher.module.scss +68 -0
  255. package/src/components/ChatLauncher/ChatLauncher.tokens.scss +27 -0
  256. package/src/components/ChatLauncher/ChatLauncher.tsx +202 -0
  257. package/src/components/ChatLauncher/index.ts +2 -0
  258. package/src/components/ChatLauncher/isAtBottom.ts +12 -0
  259. package/src/components/Checkbox/Checkbox.module.scss +147 -0
  260. package/src/components/Checkbox/Checkbox.tokens.scss +44 -0
  261. package/src/components/Checkbox/Checkbox.tsx +188 -0
  262. package/src/components/Checkbox/index.ts +2 -0
  263. package/src/components/CircularProgress/CircularProgress.module.scss +133 -0
  264. package/src/components/CircularProgress/CircularProgress.tokens.scss +40 -0
  265. package/src/components/CircularProgress/CircularProgress.tsx +139 -0
  266. package/src/components/CircularProgress/index.ts +7 -0
  267. package/src/components/Cluster/Cluster.module.scss +145 -0
  268. package/src/components/Cluster/Cluster.tokens.scss +11 -0
  269. package/src/components/Cluster/Cluster.tsx +215 -0
  270. package/src/components/Cluster/index.ts +2 -0
  271. package/src/components/Code/Code.module.scss +28 -0
  272. package/src/components/Code/Code.tokens.scss +15 -0
  273. package/src/components/Code/Code.tsx +44 -0
  274. package/src/components/Code/index.ts +2 -0
  275. package/src/components/CodeBlock/CodeBlock.module.scss +146 -0
  276. package/src/components/CodeBlock/CodeBlock.tokens.scss +27 -0
  277. package/src/components/CodeBlock/CodeBlock.tsx +274 -0
  278. package/src/components/CodeBlock/highlight.ts +179 -0
  279. package/src/components/CodeBlock/index.ts +8 -0
  280. package/src/components/CodeBlock/sampleSync.ts +42 -0
  281. package/src/components/ColorPicker/ColorPicker.module.scss +286 -0
  282. package/src/components/ColorPicker/ColorPicker.tokens.scss +60 -0
  283. package/src/components/ColorPicker/ColorPicker.tsx +367 -0
  284. package/src/components/ColorPicker/ColorPickerPanel.tsx +265 -0
  285. package/src/components/ColorPicker/SVSquare.tsx +189 -0
  286. package/src/components/ColorPicker/colorMath.ts +141 -0
  287. package/src/components/ColorPicker/index.ts +6 -0
  288. package/src/components/ConfirmationPopover/ConfirmationPopover.module.scss +39 -0
  289. package/src/components/ConfirmationPopover/ConfirmationPopover.tokens.scss +13 -0
  290. package/src/components/ConfirmationPopover/ConfirmationPopover.tsx +395 -0
  291. package/src/components/ConfirmationPopover/index.ts +2 -0
  292. package/src/components/Constrain/Constrain.module.scss +99 -0
  293. package/src/components/Constrain/Constrain.tsx +79 -0
  294. package/src/components/Constrain/index.ts +2 -0
  295. package/src/components/CurrencySelect/CurrencySelect.module.scss +7 -0
  296. package/src/components/CurrencySelect/CurrencySelect.tsx +167 -0
  297. package/src/components/CurrencySelect/index.ts +3 -0
  298. package/src/components/CursorPagination/CursorPagination.module.scss +69 -0
  299. package/src/components/CursorPagination/CursorPagination.tokens.scss +32 -0
  300. package/src/components/CursorPagination/CursorPagination.tsx +121 -0
  301. package/src/components/CursorPagination/index.ts +2 -0
  302. package/src/components/DashboardCanvas/DashboardCanvas.module.scss +360 -0
  303. package/src/components/DashboardCanvas/DashboardCanvas.tokens.scss +48 -0
  304. package/src/components/DashboardCanvas/DashboardCanvas.tsx +1270 -0
  305. package/src/components/DashboardCanvas/DashboardCanvasItem.tsx +140 -0
  306. package/src/components/DashboardCanvas/DashboardCanvasSection.tsx +174 -0
  307. package/src/components/DashboardCanvas/engine.ts +363 -0
  308. package/src/components/DashboardCanvas/index.ts +9 -0
  309. package/src/components/DashboardWidget/DashboardWidget.module.scss +100 -0
  310. package/src/components/DashboardWidget/DashboardWidget.tokens.scss +16 -0
  311. package/src/components/DashboardWidget/DashboardWidget.tsx +188 -0
  312. package/src/components/DashboardWidget/index.ts +7 -0
  313. package/src/components/DataTable/BodyRow.tsx +197 -0
  314. package/src/components/DataTable/ColumnVisibilityTrigger.module.scss +7 -0
  315. package/src/components/DataTable/ColumnVisibilityTrigger.tsx +105 -0
  316. package/src/components/DataTable/DataTable.module.scss +511 -0
  317. package/src/components/DataTable/DataTable.tokens.scss +80 -0
  318. package/src/components/DataTable/DataTable.tsx +734 -0
  319. package/src/components/DataTable/HeaderCell.module.scss +215 -0
  320. package/src/components/DataTable/HeaderCell.tsx +440 -0
  321. package/src/components/DataTable/columnShift.ts +117 -0
  322. package/src/components/DataTable/index.ts +23 -0
  323. package/src/components/DataTable/pinStyle.ts +47 -0
  324. package/src/components/DataTable/reorderColumns.ts +66 -0
  325. package/src/components/DataTable/types.ts +289 -0
  326. package/src/components/DataTable/useColumnDragShift.ts +216 -0
  327. package/src/components/DataTable/useDataTable.ts +372 -0
  328. package/src/components/DataTable/useResizeHandle.ts +97 -0
  329. package/src/components/DatePicker/DatePicker.module.scss +180 -0
  330. package/src/components/DatePicker/DatePicker.tokens.scss +152 -0
  331. package/src/components/DatePicker/DatePicker.tsx +664 -0
  332. package/src/components/DatePicker/DatePickerGrid.module.scss +172 -0
  333. package/src/components/DatePicker/DatePickerGrid.tsx +341 -0
  334. package/src/components/DatePicker/InlineDatePicker.module.scss +32 -0
  335. package/src/components/DatePicker/InlineDatePicker.tsx +201 -0
  336. package/src/components/DatePicker/index.ts +4 -0
  337. package/src/components/DatePicker/utils.ts +364 -0
  338. package/src/components/DateRangePicker/DateRangePicker.module.scss +237 -0
  339. package/src/components/DateRangePicker/DateRangePicker.tokens.scss +78 -0
  340. package/src/components/DateRangePicker/DateRangePicker.tsx +720 -0
  341. package/src/components/DateRangePicker/InlineDateRangePicker.module.scss +94 -0
  342. package/src/components/DateRangePicker/InlineDateRangePicker.tsx +376 -0
  343. package/src/components/DateRangePicker/index.ts +5 -0
  344. package/src/components/DateRangePicker/utils.ts +151 -0
  345. package/src/components/DateStrip/DateStrip.module.scss +78 -0
  346. package/src/components/DateStrip/DateStrip.tokens.scss +23 -0
  347. package/src/components/DateStrip/DateStrip.tsx +205 -0
  348. package/src/components/DateStrip/index.ts +2 -0
  349. package/src/components/DefinitionList/DefinitionList.module.scss +102 -0
  350. package/src/components/DefinitionList/DefinitionList.tokens.scss +29 -0
  351. package/src/components/DefinitionList/DefinitionList.tsx +198 -0
  352. package/src/components/DefinitionList/index.ts +9 -0
  353. package/src/components/Divider/Divider.module.scss +144 -0
  354. package/src/components/Divider/Divider.tokens.scss +21 -0
  355. package/src/components/Divider/Divider.tsx +103 -0
  356. package/src/components/Divider/index.ts +2 -0
  357. package/src/components/Dot/Dot.module.scss +40 -0
  358. package/src/components/Dot/Dot.tokens.scss +4 -0
  359. package/src/components/Dot/Dot.tsx +45 -0
  360. package/src/components/Dot/index.ts +2 -0
  361. package/src/components/Drawer/Body.tsx +23 -0
  362. package/src/components/Drawer/Close.tsx +35 -0
  363. package/src/components/Drawer/Content.tsx +93 -0
  364. package/src/components/Drawer/Drawer.module.scss +232 -0
  365. package/src/components/Drawer/Drawer.tokens.scss +38 -0
  366. package/src/components/Drawer/Drawer.tsx +23 -0
  367. package/src/components/Drawer/DrawerRoot.tsx +190 -0
  368. package/src/components/Drawer/Footer.tsx +24 -0
  369. package/src/components/Drawer/Header.tsx +64 -0
  370. package/src/components/Drawer/Overlay.tsx +82 -0
  371. package/src/components/Drawer/context.ts +44 -0
  372. package/src/components/Drawer/index.ts +12 -0
  373. package/src/components/Drawer/useDragToClose.ts +149 -0
  374. package/src/components/DropdownMenu/CheckboxItem.tsx +144 -0
  375. package/src/components/DropdownMenu/Content.tsx +419 -0
  376. package/src/components/DropdownMenu/DropdownMenu.module.scss +280 -0
  377. package/src/components/DropdownMenu/DropdownMenu.tokens.scss +88 -0
  378. package/src/components/DropdownMenu/DropdownMenu.tsx +43 -0
  379. package/src/components/DropdownMenu/Group.tsx +76 -0
  380. package/src/components/DropdownMenu/Item.tsx +148 -0
  381. package/src/components/DropdownMenu/ItemIndicator.tsx +30 -0
  382. package/src/components/DropdownMenu/Radio.tsx +178 -0
  383. package/src/components/DropdownMenu/Root.tsx +100 -0
  384. package/src/components/DropdownMenu/Sub.tsx +332 -0
  385. package/src/components/DropdownMenu/Trigger.tsx +76 -0
  386. package/src/components/DropdownMenu/context.ts +65 -0
  387. package/src/components/DropdownMenu/index.ts +20 -0
  388. package/src/components/EmojiPicker/EmojiPicker.module.scss +84 -0
  389. package/src/components/EmojiPicker/EmojiPicker.tokens.scss +24 -0
  390. package/src/components/EmojiPicker/EmojiPicker.tsx +341 -0
  391. package/src/components/EmojiPicker/emojiData.ts +245 -0
  392. package/src/components/EmojiPicker/index.ts +3 -0
  393. package/src/components/EmptyState/EmptyState.module.scss +102 -0
  394. package/src/components/EmptyState/EmptyState.tokens.scss +28 -0
  395. package/src/components/EmptyState/EmptyState.tsx +112 -0
  396. package/src/components/EmptyState/index.ts +7 -0
  397. package/src/components/EntityChip/EntityChip.module.scss +275 -0
  398. package/src/components/EntityChip/EntityChip.tokens.scss +66 -0
  399. package/src/components/EntityChip/EntityChip.tsx +649 -0
  400. package/src/components/EntityChip/index.ts +10 -0
  401. package/src/components/ErrorState/ErrorState.module.scss +105 -0
  402. package/src/components/ErrorState/ErrorState.tokens.scss +32 -0
  403. package/src/components/ErrorState/ErrorState.tsx +125 -0
  404. package/src/components/ErrorState/index.ts +8 -0
  405. package/src/components/Field/Field.module.scss +46 -0
  406. package/src/components/Field/Field.tsx +185 -0
  407. package/src/components/Field/index.ts +2 -0
  408. package/src/components/FileUpload/FileUpload.module.scss +187 -0
  409. package/src/components/FileUpload/FileUpload.tokens.scss +81 -0
  410. package/src/components/FileUpload/FileUpload.tsx +569 -0
  411. package/src/components/FileUpload/formatBytes.ts +34 -0
  412. package/src/components/FileUpload/iconForFile.ts +40 -0
  413. package/src/components/FileUpload/index.ts +2 -0
  414. package/src/components/FilterChip/FilterChip.module.scss +61 -0
  415. package/src/components/FilterChip/FilterChip.tokens.scss +25 -0
  416. package/src/components/FilterChip/FilterChip.tsx +208 -0
  417. package/src/components/FilterChip/index.ts +5 -0
  418. package/src/components/FlowCanvas/FlowCanvas.module.scss +329 -0
  419. package/src/components/FlowCanvas/FlowCanvas.tokens.scss +45 -0
  420. package/src/components/FlowCanvas/FlowCanvas.tsx +1867 -0
  421. package/src/components/FlowCanvas/FlowControls.tsx +46 -0
  422. package/src/components/FlowCanvas/FlowEdge.tsx +58 -0
  423. package/src/components/FlowCanvas/FlowNode.tsx +76 -0
  424. package/src/components/FlowCanvas/edgePath.ts +85 -0
  425. package/src/components/FlowCanvas/index.ts +4 -0
  426. package/src/components/FlowCanvas/layout.ts +148 -0
  427. package/src/components/FlowCanvas/spatialNav.ts +76 -0
  428. package/src/components/FlowCanvas/types.ts +59 -0
  429. package/src/components/FlowCanvas/useViewport.ts +122 -0
  430. package/src/components/FormRow/FormRow.module.scss +2 -0
  431. package/src/components/FormRow/FormRow.tsx +37 -0
  432. package/src/components/FormRow/index.ts +2 -0
  433. package/src/components/FormSection/FormSection.module.scss +24 -0
  434. package/src/components/FormSection/FormSection.tsx +46 -0
  435. package/src/components/FormSection/index.ts +2 -0
  436. package/src/components/Grid/Grid.module.scss +162 -0
  437. package/src/components/Grid/Grid.tokens.scss +13 -0
  438. package/src/components/Grid/Grid.tsx +226 -0
  439. package/src/components/Grid/GridItem.tsx +77 -0
  440. package/src/components/Grid/index.ts +11 -0
  441. package/src/components/Highlight/Highlight.module.scss +43 -0
  442. package/src/components/Highlight/Highlight.tokens.scss +35 -0
  443. package/src/components/Highlight/Highlight.tsx +164 -0
  444. package/src/components/Highlight/HighlightOverlay.tsx +100 -0
  445. package/src/components/Highlight/index.ts +2 -0
  446. package/src/components/HighlightedText/HighlightedText.module.scss +11 -0
  447. package/src/components/HighlightedText/HighlightedText.tokens.scss +9 -0
  448. package/src/components/HighlightedText/HighlightedText.tsx +50 -0
  449. package/src/components/HighlightedText/highlightRanges.ts +44 -0
  450. package/src/components/HighlightedText/index.ts +2 -0
  451. package/src/components/IconPicker/IconPicker.module.scss +175 -0
  452. package/src/components/IconPicker/IconPicker.tokens.scss +40 -0
  453. package/src/components/IconPicker/IconPicker.tsx +629 -0
  454. package/src/components/IconPicker/index.ts +9 -0
  455. package/src/components/IconTile/IconTile.module.scss +57 -0
  456. package/src/components/IconTile/IconTile.tokens.scss +16 -0
  457. package/src/components/IconTile/IconTile.tsx +91 -0
  458. package/src/components/IconTile/index.ts +2 -0
  459. package/src/components/Image/Image.module.scss +266 -0
  460. package/src/components/Image/Image.tokens.scss +55 -0
  461. package/src/components/Image/Image.tsx +342 -0
  462. package/src/components/Image/index.ts +2 -0
  463. package/src/components/ImageCrop/ImageCrop.module.scss +274 -0
  464. package/src/components/ImageCrop/ImageCrop.tokens.scss +33 -0
  465. package/src/components/ImageCrop/ImageCrop.tsx +542 -0
  466. package/src/components/ImageCrop/cropGeometry.ts +120 -0
  467. package/src/components/ImageCrop/extractCropBlob.ts +140 -0
  468. package/src/components/ImageCrop/index.ts +11 -0
  469. package/src/components/ImageCrop/useCropPreview.ts +161 -0
  470. package/src/components/Indent/Indent.module.scss +33 -0
  471. package/src/components/Indent/Indent.tokens.scss +10 -0
  472. package/src/components/Indent/Indent.tsx +46 -0
  473. package/src/components/Indent/index.ts +2 -0
  474. package/src/components/Input/Input.module.scss +99 -0
  475. package/src/components/Input/Input.tokens.scss +54 -0
  476. package/src/components/Input/Input.tsx +105 -0
  477. package/src/components/Input/Suggestions.tsx +260 -0
  478. package/src/components/Input/index.ts +2 -0
  479. package/src/components/Kanban/Kanban.module.scss +39 -0
  480. package/src/components/Kanban/Kanban.tokens.scss +15 -0
  481. package/src/components/Kanban/Kanban.tsx +951 -0
  482. package/src/components/Kanban/index.ts +7 -0
  483. package/src/components/Kbd/Kbd.module.scss +47 -0
  484. package/src/components/Kbd/Kbd.tokens.scss +26 -0
  485. package/src/components/Kbd/Kbd.tsx +73 -0
  486. package/src/components/Kbd/index.ts +2 -0
  487. package/src/components/Lightbox/Lightbox.module.scss +283 -0
  488. package/src/components/Lightbox/Lightbox.tokens.scss +36 -0
  489. package/src/components/Lightbox/Lightbox.tsx +506 -0
  490. package/src/components/Lightbox/index.ts +2 -0
  491. package/src/components/Link/Link.module.scss +78 -0
  492. package/src/components/Link/Link.tokens.scss +28 -0
  493. package/src/components/Link/Link.tsx +114 -0
  494. package/src/components/Link/index.ts +2 -0
  495. package/src/components/LinkCard/LinkCard.module.scss +92 -0
  496. package/src/components/LinkCard/LinkCard.tokens.scss +9 -0
  497. package/src/components/LinkCard/LinkCard.tsx +72 -0
  498. package/src/components/LinkCard/index.ts +2 -0
  499. package/src/components/LiquidEditor/AutocompleteMenu.tsx +133 -0
  500. package/src/components/LiquidEditor/HighlightLayer.tsx +53 -0
  501. package/src/components/LiquidEditor/InsertVariableMenu.tsx +81 -0
  502. package/src/components/LiquidEditor/LiquidEditor.module.scss +339 -0
  503. package/src/components/LiquidEditor/LiquidEditor.tokens.scss +81 -0
  504. package/src/components/LiquidEditor/LiquidEditor.tsx +412 -0
  505. package/src/components/LiquidEditor/PreviewPane.tsx +29 -0
  506. package/src/components/LiquidEditor/caretCoordinates.ts +97 -0
  507. package/src/components/LiquidEditor/index.ts +7 -0
  508. package/src/components/LiquidEditor/liquidFilters.ts +23 -0
  509. package/src/components/LiquidEditor/liquidTokenizer.ts +235 -0
  510. package/src/components/LiquidEditor/types.ts +101 -0
  511. package/src/components/LiquidEditor/useLiquidAutocomplete.ts +178 -0
  512. package/src/components/List/List.module.scss +105 -0
  513. package/src/components/List/List.tokens.scss +42 -0
  514. package/src/components/List/List.tsx +124 -0
  515. package/src/components/List/index.ts +9 -0
  516. package/src/components/LiveRegion/LiveRegion.module.scss +3 -0
  517. package/src/components/LiveRegion/LiveRegion.tsx +116 -0
  518. package/src/components/LiveRegion/index.ts +2 -0
  519. package/src/components/Logo/Logo.module.scss +139 -0
  520. package/src/components/Logo/Logo.tokens.scss +14 -0
  521. package/src/components/Logo/Logo.tsx +126 -0
  522. package/src/components/Logo/index.ts +2 -0
  523. package/src/components/Masonry/Masonry.module.scss +42 -0
  524. package/src/components/Masonry/Masonry.tokens.scss +8 -0
  525. package/src/components/Masonry/Masonry.tsx +136 -0
  526. package/src/components/Masonry/index.ts +2 -0
  527. package/src/components/Masonry/masonryUtils.ts +42 -0
  528. package/src/components/MediaTile/MediaTile.module.scss +183 -0
  529. package/src/components/MediaTile/MediaTile.tokens.scss +60 -0
  530. package/src/components/MediaTile/MediaTile.tsx +208 -0
  531. package/src/components/MediaTile/index.ts +8 -0
  532. package/src/components/Modal/Body.tsx +27 -0
  533. package/src/components/Modal/Close.tsx +45 -0
  534. package/src/components/Modal/Content.tsx +98 -0
  535. package/src/components/Modal/Footer.tsx +28 -0
  536. package/src/components/Modal/Header.tsx +51 -0
  537. package/src/components/Modal/Modal.module.scss +262 -0
  538. package/src/components/Modal/Modal.tokens.scss +50 -0
  539. package/src/components/Modal/Modal.tsx +23 -0
  540. package/src/components/Modal/ModalRoot.tsx +299 -0
  541. package/src/components/Modal/Overlay.tsx +101 -0
  542. package/src/components/Modal/context.ts +60 -0
  543. package/src/components/Modal/index.ts +11 -0
  544. package/src/components/MoneyInput/MoneyInput.module.scss +57 -0
  545. package/src/components/MoneyInput/MoneyInput.tsx +433 -0
  546. package/src/components/MoneyInput/index.ts +2 -0
  547. package/src/components/OptionsPicker/OptionsPicker.module.scss +216 -0
  548. package/src/components/OptionsPicker/OptionsPicker.tokens.scss +68 -0
  549. package/src/components/OptionsPicker/OptionsPicker.tsx +936 -0
  550. package/src/components/OptionsPicker/index.ts +9 -0
  551. package/src/components/OtpInput/OtpInput.module.scss +69 -0
  552. package/src/components/OtpInput/OtpInput.tokens.scss +45 -0
  553. package/src/components/OtpInput/OtpInput.tsx +368 -0
  554. package/src/components/OtpInput/index.ts +2 -0
  555. package/src/components/Page/Page.module.scss +30 -0
  556. package/src/components/Page/Page.tokens.scss +11 -0
  557. package/src/components/Page/Page.tsx +53 -0
  558. package/src/components/Page/index.ts +2 -0
  559. package/src/components/PageHeader/PageHeader.module.scss +197 -0
  560. package/src/components/PageHeader/PageHeader.tokens.scss +41 -0
  561. package/src/components/PageHeader/PageHeader.tsx +310 -0
  562. package/src/components/PageHeader/index.ts +20 -0
  563. package/src/components/Pagination/Pagination.module.scss +117 -0
  564. package/src/components/Pagination/Pagination.tokens.scss +54 -0
  565. package/src/components/Pagination/Pagination.tsx +165 -0
  566. package/src/components/Pagination/index.ts +4 -0
  567. package/src/components/Pagination/paginationRange.ts +72 -0
  568. package/src/components/PasswordInput/PasswordInput.module.scss +120 -0
  569. package/src/components/PasswordInput/PasswordInput.tokens.scss +44 -0
  570. package/src/components/PasswordInput/PasswordInput.tsx +210 -0
  571. package/src/components/PasswordInput/index.ts +2 -0
  572. package/src/components/PasswordStrengthMeter/PasswordStrengthMeter.module.scss +80 -0
  573. package/src/components/PasswordStrengthMeter/PasswordStrengthMeter.tokens.scss +40 -0
  574. package/src/components/PasswordStrengthMeter/PasswordStrengthMeter.tsx +96 -0
  575. package/src/components/PasswordStrengthMeter/index.ts +2 -0
  576. package/src/components/PersonDisplay/PersonDisplay.module.scss +180 -0
  577. package/src/components/PersonDisplay/PersonDisplay.tokens.scss +35 -0
  578. package/src/components/PersonDisplay/PersonDisplay.tsx +420 -0
  579. package/src/components/PersonDisplay/index.ts +10 -0
  580. package/src/components/PhoneInput/PhoneInput.module.scss +23 -0
  581. package/src/components/PhoneInput/PhoneInput.tsx +271 -0
  582. package/src/components/PhoneInput/index.ts +4 -0
  583. package/src/components/PhoneInput/phone.ts +128 -0
  584. package/src/components/PillMenu/PillMenu.module.scss +117 -0
  585. package/src/components/PillMenu/PillMenu.tokens.scss +22 -0
  586. package/src/components/PillMenu/PillMenu.tsx +324 -0
  587. package/src/components/PillMenu/index.ts +2 -0
  588. package/src/components/Popover/Anchor.tsx +37 -0
  589. package/src/components/Popover/Close.tsx +45 -0
  590. package/src/components/Popover/Content.tsx +213 -0
  591. package/src/components/Popover/Heading.tsx +33 -0
  592. package/src/components/Popover/Popover.module.scss +177 -0
  593. package/src/components/Popover/Popover.tokens.scss +22 -0
  594. package/src/components/Popover/Popover.tsx +23 -0
  595. package/src/components/Popover/PopoverRoot.tsx +75 -0
  596. package/src/components/Popover/Trigger.tsx +86 -0
  597. package/src/components/Popover/context.ts +22 -0
  598. package/src/components/Popover/index.ts +7 -0
  599. package/src/components/Progress/Progress.module.scss +110 -0
  600. package/src/components/Progress/Progress.tokens.scss +44 -0
  601. package/src/components/Progress/Progress.tsx +129 -0
  602. package/src/components/Progress/index.ts +2 -0
  603. package/src/components/QrCode/QrCode.module.scss +97 -0
  604. package/src/components/QrCode/QrCode.tokens.scss +17 -0
  605. package/src/components/QrCode/QrCode.tsx +233 -0
  606. package/src/components/QrCode/index.ts +2 -0
  607. package/src/components/QrCode/qr.ts +161 -0
  608. package/src/components/Radio/Radio.module.scss +175 -0
  609. package/src/components/Radio/Radio.tokens.scss +59 -0
  610. package/src/components/Radio/Radio.tsx +127 -0
  611. package/src/components/Radio/RadioGroup.module.scss +42 -0
  612. package/src/components/Radio/RadioGroup.tsx +120 -0
  613. package/src/components/Radio/RadioGroupContext.tsx +30 -0
  614. package/src/components/Radio/index.ts +4 -0
  615. package/src/components/Rail/Rail.module.scss +510 -0
  616. package/src/components/Rail/Rail.tokens.scss +92 -0
  617. package/src/components/Rail/Rail.tsx +287 -0
  618. package/src/components/Rail/RailCollapseToggle.tsx +57 -0
  619. package/src/components/Rail/RailFooter.tsx +17 -0
  620. package/src/components/Rail/RailGroup.tsx +728 -0
  621. package/src/components/Rail/RailGroupContext.ts +9 -0
  622. package/src/components/Rail/RailHeader.tsx +23 -0
  623. package/src/components/Rail/RailItem.tsx +119 -0
  624. package/src/components/Rail/RailSection.tsx +39 -0
  625. package/src/components/Rail/RailSpacer.tsx +19 -0
  626. package/src/components/Rail/index.ts +9 -0
  627. package/src/components/RelativeDateInput/RelativeDateInput.module.scss +15 -0
  628. package/src/components/RelativeDateInput/RelativeDateInput.tokens.scss +6 -0
  629. package/src/components/RelativeDateInput/RelativeDateInput.tsx +474 -0
  630. package/src/components/RelativeDateInput/index.ts +10 -0
  631. package/src/components/RelativeDateInput/relativeDate.ts +127 -0
  632. package/src/components/RichText/RichText.module.scss +5 -0
  633. package/src/components/RichText/RichText.tsx +70 -0
  634. package/src/components/RichText/RichTextAttachment.module.scss +82 -0
  635. package/src/components/RichText/RichTextAttachment.tsx +122 -0
  636. package/src/components/RichText/_prose.scss +79 -0
  637. package/src/components/RichText/attachmentIcon.tsx +24 -0
  638. package/src/components/RichText/engine/attachment.ts +154 -0
  639. package/src/components/RichText/engine/autolink.ts +64 -0
  640. package/src/components/RichText/engine/blockUnit.ts +174 -0
  641. package/src/components/RichText/engine/colorMarks.ts +85 -0
  642. package/src/components/RichText/engine/escape.ts +11 -0
  643. package/src/components/RichText/engine/fromHtml.ts +353 -0
  644. package/src/components/RichText/engine/fromMarkdown.ts +20 -0
  645. package/src/components/RichText/engine/inlines.ts +82 -0
  646. package/src/components/RichText/engine/listDepths.ts +32 -0
  647. package/src/components/RichText/engine/marks.ts +80 -0
  648. package/src/components/RichText/engine/mdToHtml.ts +178 -0
  649. package/src/components/RichText/engine/model.ts +157 -0
  650. package/src/components/RichText/engine/position.ts +118 -0
  651. package/src/components/RichText/engine/renderDoc.tsx +395 -0
  652. package/src/components/RichText/engine/renderLink.ts +15 -0
  653. package/src/components/RichText/engine/renderMention.ts +16 -0
  654. package/src/components/RichText/engine/safeHref.ts +22 -0
  655. package/src/components/RichText/engine/toHtml.ts +154 -0
  656. package/src/components/RichText/engine/toMarkdown.ts +97 -0
  657. package/src/components/RichText/engine/transforms.ts +434 -0
  658. package/src/components/RichText/imageMaxHeightStyle.ts +10 -0
  659. package/src/components/RichText/index.ts +31 -0
  660. package/src/components/RichTextEditor/RichTextAttachmentConfig.tsx +264 -0
  661. package/src/components/RichTextEditor/RichTextBlockControls.tsx +365 -0
  662. package/src/components/RichTextEditor/RichTextBlockMenu.tsx +162 -0
  663. package/src/components/RichTextEditor/RichTextColorMenu.tsx +115 -0
  664. package/src/components/RichTextEditor/RichTextEditor.module.scss +298 -0
  665. package/src/components/RichTextEditor/RichTextEditor.tsx +1910 -0
  666. package/src/components/RichTextEditor/RichTextImageResizer.tsx +131 -0
  667. package/src/components/RichTextEditor/RichTextLinkEditor.tsx +151 -0
  668. package/src/components/RichTextEditor/RichTextMentionMenu.tsx +99 -0
  669. package/src/components/RichTextEditor/RichTextToolbar.tsx +379 -0
  670. package/src/components/RichTextEditor/autolinkInput.ts +65 -0
  671. package/src/components/RichTextEditor/blockDrop.ts +9 -0
  672. package/src/components/RichTextEditor/blockReflow.ts +62 -0
  673. package/src/components/RichTextEditor/commands.ts +300 -0
  674. package/src/components/RichTextEditor/history.ts +93 -0
  675. package/src/components/RichTextEditor/icons.tsx +152 -0
  676. package/src/components/RichTextEditor/imageSize.ts +70 -0
  677. package/src/components/RichTextEditor/index.ts +5 -0
  678. package/src/components/RichTextEditor/input.ts +209 -0
  679. package/src/components/RichTextEditor/inputRules.ts +71 -0
  680. package/src/components/RichTextEditor/links.ts +103 -0
  681. package/src/components/RichTextEditor/mentionContext.ts +37 -0
  682. package/src/components/RichTextEditor/mentions.ts +28 -0
  683. package/src/components/RichTextEditor/preventSelectionLoss.ts +15 -0
  684. package/src/components/RichTextEditor/selection.ts +415 -0
  685. package/src/components/RichTextEditor/shortcuts.ts +44 -0
  686. package/src/components/RichTextEditor/useAnchoredFloating.ts +50 -0
  687. package/src/components/RichTextEditor/useAttachmentConfig.ts +134 -0
  688. package/src/components/RichTextEditor/useDismissOnOutsidePointerDown.ts +26 -0
  689. package/src/components/RichTextEditor/useLinkEditor.ts +107 -0
  690. package/src/components/RichTextEditor/useMention.ts +226 -0
  691. package/src/components/RichTextEditor/useOverlayRect.ts +73 -0
  692. package/src/components/RichTextEditor/useUpload.ts +246 -0
  693. package/src/components/Screen/Screen.module.scss +46 -0
  694. package/src/components/Screen/Screen.tokens.scss +20 -0
  695. package/src/components/Screen/Screen.tsx +97 -0
  696. package/src/components/Screen/index.ts +2 -0
  697. package/src/components/ScrollArea/ScrollArea.module.scss +39 -0
  698. package/src/components/ScrollArea/ScrollArea.tokens.scss +15 -0
  699. package/src/components/ScrollArea/ScrollArea.tsx +154 -0
  700. package/src/components/ScrollArea/index.ts +2 -0
  701. package/src/components/Select/Chip.tsx +45 -0
  702. package/src/components/Select/Empty.tsx +39 -0
  703. package/src/components/Select/Error.tsx +51 -0
  704. package/src/components/Select/HiddenInputs.tsx +44 -0
  705. package/src/components/Select/Listbox.tsx +557 -0
  706. package/src/components/Select/Loading.tsx +30 -0
  707. package/src/components/Select/Select.module.scss +512 -0
  708. package/src/components/Select/Select.tokens.scss +140 -0
  709. package/src/components/Select/Select.tsx +685 -0
  710. package/src/components/Select/Trigger.tsx +952 -0
  711. package/src/components/Select/context.ts +101 -0
  712. package/src/components/Select/emptyStateText.ts +19 -0
  713. package/src/components/Select/index.ts +9 -0
  714. package/src/components/Select/useSelectState.ts +157 -0
  715. package/src/components/Select/utils-types.ts +7 -0
  716. package/src/components/Select/utils.ts +122 -0
  717. package/src/components/SettingRow/SettingRow.module.scss +166 -0
  718. package/src/components/SettingRow/SettingRow.tokens.scss +37 -0
  719. package/src/components/SettingRow/SettingRow.tsx +242 -0
  720. package/src/components/SettingRow/index.ts +7 -0
  721. package/src/components/Skeleton/Skeleton.module.scss +55 -0
  722. package/src/components/Skeleton/Skeleton.tokens.scss +17 -0
  723. package/src/components/Skeleton/Skeleton.tsx +131 -0
  724. package/src/components/Skeleton/index.ts +4 -0
  725. package/src/components/Skeleton/useSkeletonVisibility.ts +95 -0
  726. package/src/components/Slider/Slider.module.scss +293 -0
  727. package/src/components/Slider/Slider.tokens.scss +98 -0
  728. package/src/components/Slider/Slider.tsx +624 -0
  729. package/src/components/Slider/index.ts +9 -0
  730. package/src/components/SlotGrid/SlotGrid.module.scss +61 -0
  731. package/src/components/SlotGrid/SlotGrid.tokens.scss +21 -0
  732. package/src/components/SlotGrid/SlotGrid.tsx +111 -0
  733. package/src/components/SlotGrid/index.ts +2 -0
  734. package/src/components/SocialButton/SocialButton.module.scss +4 -0
  735. package/src/components/SocialButton/SocialButton.tsx +40 -0
  736. package/src/components/SocialButton/index.ts +2 -0
  737. package/src/components/Sortable/Sortable.module.scss +177 -0
  738. package/src/components/Sortable/Sortable.tokens.scss +27 -0
  739. package/src/components/Sortable/Sortable.tsx +572 -0
  740. package/src/components/Sortable/containerAwareCollision.ts +125 -0
  741. package/src/components/Sortable/index.ts +13 -0
  742. package/src/components/SortableGroup/SortableGroup.module.scss +23 -0
  743. package/src/components/SortableGroup/SortableGroup.tsx +315 -0
  744. package/src/components/SortableGroup/index.ts +4 -0
  745. package/src/components/SortableGroup/moveSortableItem.ts +39 -0
  746. package/src/components/Sparkline/Sparkline.module.scss +28 -0
  747. package/src/components/Sparkline/Sparkline.tokens.scss +7 -0
  748. package/src/components/Sparkline/Sparkline.tsx +133 -0
  749. package/src/components/Sparkline/index.ts +2 -0
  750. package/src/components/Sparkline/sparklineModel.ts +119 -0
  751. package/src/components/Split/Split.module.scss +158 -0
  752. package/src/components/Split/Split.tokens.scss +10 -0
  753. package/src/components/Split/Split.tsx +231 -0
  754. package/src/components/Split/index.ts +2 -0
  755. package/src/components/Stack/Stack.module.scss +67 -0
  756. package/src/components/Stack/Stack.tokens.scss +11 -0
  757. package/src/components/Stack/Stack.tsx +100 -0
  758. package/src/components/Stack/index.ts +2 -0
  759. package/src/components/StagePath/StagePath.module.scss +255 -0
  760. package/src/components/StagePath/StagePath.tokens.scss +43 -0
  761. package/src/components/StagePath/StagePath.tsx +176 -0
  762. package/src/components/StagePath/index.ts +2 -0
  763. package/src/components/StatGroup/StatGroup.module.scss +6 -0
  764. package/src/components/StatGroup/StatGroup.tsx +70 -0
  765. package/src/components/StatGroup/StatGroupContext.ts +10 -0
  766. package/src/components/StatGroup/StatTile.module.scss +99 -0
  767. package/src/components/StatGroup/StatTile.tokens.scss +35 -0
  768. package/src/components/StatGroup/StatTile.tsx +143 -0
  769. package/src/components/StatGroup/index.ts +4 -0
  770. package/src/components/Sticky/Sticky.module.scss +98 -0
  771. package/src/components/Sticky/Sticky.tokens.scss +17 -0
  772. package/src/components/Sticky/Sticky.tsx +103 -0
  773. package/src/components/Sticky/index.ts +2 -0
  774. package/src/components/Switch/Switch.module.scss +182 -0
  775. package/src/components/Switch/Switch.tokens.scss +59 -0
  776. package/src/components/Switch/Switch.tsx +214 -0
  777. package/src/components/Switch/index.ts +2 -0
  778. package/src/components/Table/Table.module.scss +308 -0
  779. package/src/components/Table/Table.tokens.scss +79 -0
  780. package/src/components/Table/Table.tsx +381 -0
  781. package/src/components/Table/index.ts +15 -0
  782. package/src/components/TableOfContents/TableOfContents.module.scss +83 -0
  783. package/src/components/TableOfContents/TableOfContents.tokens.scss +26 -0
  784. package/src/components/TableOfContents/TableOfContents.tsx +192 -0
  785. package/src/components/TableOfContents/activeSection.ts +18 -0
  786. package/src/components/TableOfContents/index.ts +2 -0
  787. package/src/components/Tabs/Tabs.module.scss +359 -0
  788. package/src/components/Tabs/Tabs.tokens.scss +50 -0
  789. package/src/components/Tabs/Tabs.tsx +538 -0
  790. package/src/components/Tabs/index.ts +2 -0
  791. package/src/components/Text/Text.module.scss +115 -0
  792. package/src/components/Text/Text.tokens.scss +55 -0
  793. package/src/components/Text/Text.tsx +197 -0
  794. package/src/components/Text/index.ts +2 -0
  795. package/src/components/Textarea/Textarea.module.scss +94 -0
  796. package/src/components/Textarea/Textarea.tokens.scss +48 -0
  797. package/src/components/Textarea/Textarea.tsx +246 -0
  798. package/src/components/Textarea/index.ts +2 -0
  799. package/src/components/Thread/Thread.module.scss +161 -0
  800. package/src/components/Thread/Thread.tokens.scss +32 -0
  801. package/src/components/Thread/Thread.tsx +176 -0
  802. package/src/components/Thread/index.ts +2 -0
  803. package/src/components/TimeField/TimeField.module.scss +232 -0
  804. package/src/components/TimeField/TimeField.tsx +793 -0
  805. package/src/components/TimeField/index.ts +2 -0
  806. package/src/components/Timeline/Timeline.module.scss +58 -0
  807. package/src/components/Timeline/Timeline.tokens.scss +13 -0
  808. package/src/components/Timeline/Timeline.tsx +53 -0
  809. package/src/components/Timeline/index.ts +2 -0
  810. package/src/components/Title/Title.module.scss +84 -0
  811. package/src/components/Title/Title.tokens.scss +37 -0
  812. package/src/components/Title/Title.tsx +150 -0
  813. package/src/components/Title/index.ts +2 -0
  814. package/src/components/Toast/Toast.module.scss +299 -0
  815. package/src/components/Toast/Toast.tokens.scss +65 -0
  816. package/src/components/Toast/Toast.tsx +122 -0
  817. package/src/components/Toast/ToastViewport.tsx +166 -0
  818. package/src/components/Toast/api.ts +175 -0
  819. package/src/components/Toast/index.ts +5 -0
  820. package/src/components/Toast/store.ts +133 -0
  821. package/src/components/Toast/useToastTimer.ts +94 -0
  822. package/src/components/Tooltip/Tooltip.module.scss +99 -0
  823. package/src/components/Tooltip/Tooltip.tokens.scss +23 -0
  824. package/src/components/Tooltip/Tooltip.tsx +341 -0
  825. package/src/components/Tooltip/index.ts +2 -0
  826. package/src/components/TopBar/TopBar.module.scss +235 -0
  827. package/src/components/TopBar/TopBar.tokens.scss +79 -0
  828. package/src/components/TopBar/TopBar.tsx +87 -0
  829. package/src/components/TopBar/TopBarEnd.tsx +20 -0
  830. package/src/components/TopBar/TopBarIconButton.tsx +86 -0
  831. package/src/components/TopBar/TopBarSearch.tsx +319 -0
  832. package/src/components/TopBar/TopBarSearchPanel.tsx +268 -0
  833. package/src/components/TopBar/TopBarStart.tsx +20 -0
  834. package/src/components/TopBar/index.ts +11 -0
  835. package/src/components/Tour/Spotlight.tsx +121 -0
  836. package/src/components/Tour/Tour.module.scss +210 -0
  837. package/src/components/Tour/Tour.tokens.scss +58 -0
  838. package/src/components/Tour/Tour.tsx +617 -0
  839. package/src/components/Tour/index.ts +2 -0
  840. package/src/components/Tour/useTourTarget.ts +115 -0
  841. package/src/components/TreeView/TreeView.module.scss +268 -0
  842. package/src/components/TreeView/TreeView.tokens.scss +36 -0
  843. package/src/components/TreeView/TreeView.tsx +536 -0
  844. package/src/components/TreeView/index.ts +3 -0
  845. package/src/components/TreeView/treeModel.ts +224 -0
  846. package/src/components/VisuallyHidden/VisuallyHidden.module.scss +7 -0
  847. package/src/components/VisuallyHidden/VisuallyHidden.tsx +29 -0
  848. package/src/components/VisuallyHidden/index.ts +2 -0
  849. package/src/components/WidgetPreview/WidgetPreview.module.scss +11 -0
  850. package/src/components/WidgetPreview/WidgetPreview.tokens.scss +26 -0
  851. package/src/components/WidgetPreview/WidgetPreview.tsx +36 -0
  852. package/src/components/WidgetPreview/WidgetShape.module.scss +140 -0
  853. package/src/components/WidgetPreview/WidgetShape.tsx +159 -0
  854. package/src/components/WidgetPreview/index.ts +2 -0
  855. package/src/components/_internal/Trend.tsx +27 -0
  856. package/src/components/_internal/choiceTile.scss +74 -0
  857. package/src/components/_internal/collapse.scss +10 -0
  858. package/src/components/_internal/collapse.ts +58 -0
  859. package/src/components/_internal/currency.ts +257 -0
  860. package/src/components/_internal/dragAnnouncements.ts +200 -0
  861. package/src/components/_internal/fieldWiring.ts +225 -0
  862. package/src/components/_internal/gridSpan.ts +54 -0
  863. package/src/components/_internal/isoDay.ts +35 -0
  864. package/src/components/_internal/letterKey.ts +26 -0
  865. package/src/components/_internal/overlay/focusRestore.ts +21 -0
  866. package/src/components/_internal/overlay/index.ts +12 -0
  867. package/src/components/_internal/overlay/tourHold.ts +23 -0
  868. package/src/components/_internal/overlay/useFocusTrap.ts +120 -0
  869. package/src/components/_internal/overlay/useInOverlay.ts +81 -0
  870. package/src/components/_internal/overlay/useOverlayStack.ts +232 -0
  871. package/src/components/_internal/overlay/useScrollLock.ts +112 -0
  872. package/src/components/_internal/refs.ts +48 -0
  873. package/src/components/_internal/statusColor.ts +26 -0
  874. package/src/components/_internal/timeUtils.ts +23 -0
  875. package/src/components/_internal/useAsyncOptions.ts +145 -0
  876. package/src/components/_internal/useClippedTooltip.ts +50 -0
  877. package/src/components/_internal/useControllableState.ts +50 -0
  878. package/src/components.manifest.json +1141 -0
  879. package/src/hooks/useBelowBreakpoint.ts +58 -0
  880. package/src/i18n/I18nProvider.tsx +52 -0
  881. package/src/i18n/LocaleProvider.tsx +17 -0
  882. package/src/i18n/en.ts +648 -0
  883. package/src/i18n/format.ts +71 -0
  884. package/src/i18n/index.ts +13 -0
  885. package/src/i18n/messages.ts +1275 -0
  886. package/src/i18n/ru.ts +677 -0
  887. package/src/i18n/useLocale.ts +19 -0
  888. package/src/i18n/useTranslation.ts +58 -0
  889. package/src/index.ts +913 -0
  890. package/src/palette/index.ts +2 -0
  891. package/src/palette/palette.ts +108 -0
  892. package/src/styles/dark.scss +4 -0
  893. package/src/styles/global.scss +7 -0
  894. package/src/styles/mixins.scss +143 -0
  895. package/src/styles/reset.scss +78 -0
  896. package/src/styles/tokens.scss +18 -0
  897. package/src/styles/typography.scss +44 -0
@@ -0,0 +1,1910 @@
1
+ import {
2
+ forwardRef,
3
+ useCallback,
4
+ useEffect,
5
+ useLayoutEffect,
6
+ useMemo,
7
+ useRef,
8
+ useState,
9
+ type HTMLAttributes,
10
+ } from 'react';
11
+ import { flushSync } from 'react-dom';
12
+ import clsx from 'clsx';
13
+ import type { RichDoc, Range, Mark, MarkType, Point } from '../RichText/engine/model';
14
+ import { nextId } from '../RichText/engine/model';
15
+ import { renderDoc } from '../RichText/engine/renderDoc';
16
+ import type { RenderLink } from '../RichText/engine/renderLink';
17
+ import type { RenderMention } from '../RichText/engine/renderMention';
18
+ import {
19
+ blockLength,
20
+ isCollapsed,
21
+ wholeBlockRange,
22
+ marksForTypedText,
23
+ } from '../RichText/engine/position';
24
+ import { linkAt, setLink } from './links';
25
+ import { applyTypeAutolink, atomicLinkDeleteRange } from './autolinkInput';
26
+ import { RichTextLinkEditor } from './RichTextLinkEditor';
27
+ import { useLinkEditor } from './useLinkEditor';
28
+ import {
29
+ insertText,
30
+ insertFragment,
31
+ insertMention,
32
+ deleteRange,
33
+ setColorMark,
34
+ } from '../RichText/engine/transforms';
35
+ import { linkifyRuns, findUrl } from '../RichText/engine/autolink';
36
+ import { useMention } from './useMention';
37
+ import { RichTextMentionMenu } from './RichTextMentionMenu';
38
+ import type { MentionItem, MentionsConfig } from './mentions';
39
+ import { fromHtml } from '../RichText/engine/fromHtml';
40
+ import { hasMark, withMark, withoutMark } from '../RichText/engine/marks';
41
+ import { useTranslation } from '../../i18n';
42
+ import { readSelection, writeSelection, rangeRect, voidCaretSide, blockOwnText } from './selection';
43
+ import { applyInput, voidDelete } from './input';
44
+ import { matchBlockRule, applyBlockRule } from './inputRules';
45
+ import { runsText } from '../RichText/engine/inlines';
46
+ import { isLetterKey } from '../_internal/letterKey';
47
+ import { shortcutMark } from './shortcuts';
48
+ import {
49
+ activeMarks as deriveActiveMarks,
50
+ activeColors as deriveActiveColors,
51
+ currentBlock as deriveCurrentBlock,
52
+ runToggleMark,
53
+ runSetBlock,
54
+ runToggleList,
55
+ runIndent,
56
+ applyExactMarks,
57
+ } from './commands';
58
+ import { RichTextToolbar, type BlockChoice } from './RichTextToolbar';
59
+ import {
60
+ moveBlockUnit,
61
+ moveBlockUnitToIndex,
62
+ duplicateBlockUnit,
63
+ removeBlockUnit,
64
+ insertEmptyBlockBelow,
65
+ } from '../RichText/engine/blockUnit';
66
+ import { RichTextBlockControls } from './RichTextBlockControls';
67
+ import { RichTextAttachmentConfig } from './RichTextAttachmentConfig';
68
+ import { useAttachmentConfig } from './useAttachmentConfig';
69
+ import { RichTextImageResizer } from './RichTextImageResizer';
70
+ import { LiveRegion } from '../LiveRegion';
71
+ import { capWidthToHeight } from './imageSize';
72
+ import { imageMaxHeightStyle } from '../RichText/imageMaxHeightStyle';
73
+ import { attachmentIsImage, isAttachmentSettled } from '../RichText/engine/attachment';
74
+ import { safeHref } from '../RichText/engine/safeHref';
75
+ import type { BlockAction } from './RichTextBlockMenu';
76
+ import { useUpload, type UploadConfig } from './useUpload';
77
+ import {
78
+ reset as historyReset,
79
+ record as historyRecord,
80
+ undo as historyUndo,
81
+ redo as historyRedo,
82
+ canUndo as historyCanUndo,
83
+ canRedo as historyCanRedo,
84
+ } from './history';
85
+ import type { History, EditKind } from './history';
86
+ import styles from './RichTextEditor.module.scss';
87
+
88
+ // Stable sentinel ReactNode passed as `renderLink`'s `defaultNode` when probing
89
+ // whether a link is "resolved" (the consumer returns a custom chip) vs. declined
90
+ // (returns the fallback). A custom return is `!== FALLBACK_SENTINEL` by identity;
91
+ // declining returns the exact sentinel back. A frozen one-off element keeps a
92
+ // stable reference across calls.
93
+ const FALLBACK_SENTINEL: React.ReactNode = Object.freeze(<span key="rt-fallback-sentinel" />);
94
+
95
+ export interface RichTextEditorProps extends Omit<
96
+ HTMLAttributes<HTMLDivElement>,
97
+ 'onChange' | 'children'
98
+ > {
99
+ /** Controlled document. Render the doc returned by `onChange` back into `value` as-is, right away — a cloned/normalized copy reads as an outside replacement and resets undo history; one stored only after a later edit (debounced, or a deferred render the next keystroke beats) is treated as rejected. Defer expensive consumers (preview, save), not `value`. */
100
+ value: RichDoc;
101
+ /** `aria-invalid` on the textbox. Field / SettingRow inject it (#568). @default false */
102
+ invalid?: boolean;
103
+ /** `aria-required` on the textbox. Field / SettingRow inject it (#568). @default false */
104
+ required?: boolean;
105
+ /** Fires with the new document after every edit. */
106
+ onChange: (doc: RichDoc) => void;
107
+ /** Non-editable: renders the content read-only (prefer `<RichText>` for pure display). */
108
+ readOnly?: boolean;
109
+ /** Shown when the document is empty. */
110
+ placeholder?: string;
111
+ /** Focus the editor on mount. */
112
+ autoFocus?: boolean;
113
+ /**
114
+ * Render the built-in formatting toolbar above the editor — Undo/Redo buttons,
115
+ * mark toggle buttons (bold/italic/underline/strike), a block-type dropdown
116
+ * (paragraph/headings/quote/code), and bullet/numbered list toggles. The
117
+ * toolbar dispatches through the same commit path the keyboard uses and
118
+ * reflects the active marks + current block of the live selection. Default
119
+ * `false` (keyboard-only). When `readOnly`, the toolbar renders disabled.
120
+ *
121
+ * `'auto'` shows the toolbar only when the editor is **focused or non-empty**,
122
+ * and keeps it shown while the editor's own overlays (the link editor / mention
123
+ * menu) are open — so opening the link editor on a focused-but-empty composer
124
+ * doesn't collapse the bar. The editable is NOT remounted as the bar appears or
125
+ * hides (the bar toggles in a stable shell), so there's no focus/selection loss.
126
+ * Use it for a compact, focus-gated composer (e.g. a comment box) instead of
127
+ * hand-rolling the show-on-focus logic and working around overlay focus theft.
128
+ */
129
+ toolbar?: boolean | 'auto';
130
+ /**
131
+ * Enable `@`-mention autocomplete. Supply `onQuery` to resolve candidates for
132
+ * the text typed after the trigger (default `@`); the editor renders a floating
133
+ * combobox and inserts a styled mention chip carrying the chosen item's `id`.
134
+ * Omit to disable mentions. See {@link MentionsConfig}.
135
+ */
136
+ mentions?: MentionsConfig;
137
+ /**
138
+ * Turn typed and pasted URLs into links automatically. While typing, a URL is
139
+ * linked when you type a space after it; on paste, plain-text URLs are linked
140
+ * (a single bare URL pasted over a selection links the selection). Default
141
+ * `true`. Set `false` to disable both the type rule and paste autolinking (the
142
+ * ⌘/Ctrl+K link tool still works). The href is sanitized — only safe schemes
143
+ * (http/https/`www.`) become links.
144
+ */
145
+ autolink?: boolean;
146
+ /**
147
+ * Substitute how a link renders. Called per link with `{ href, text }` and the
148
+ * default `<a>`; return your own node (e.g. a task/member chip) or the
149
+ * `defaultNode` to keep the standard anchor. A custom node renders as a
150
+ * non-editable **atomic chip** — the caret steps over it and a single Backspace/
151
+ * Delete removes the whole link.
152
+ *
153
+ * @remarks Render-time only — the model is unchanged, so `toHtml`/`toMarkdown`
154
+ * still serialize a plain link. Keep it cheap (it runs on every render): don't
155
+ * do heavy synchronous work or block on the network inside `renderLink`; return
156
+ * a component that fetches/caches the lookup itself (falling back to
157
+ * `defaultNode` while loading). Because the chip is atomic and not editable
158
+ * text, only links your `renderLink` actually replaces become chips — links you
159
+ * return `defaultNode` for stay plain, editable anchors.
160
+ */
161
+ renderLink?: RenderLink;
162
+ /**
163
+ * Substitute how an `@`-mention renders. Called per mention with `{ id, label }`
164
+ * and the default mention span; return your own node (e.g. an interactive member
165
+ * chip / popover trigger) or the `defaultNode` to keep the standard
166
+ * non-interactive span. A custom node renders as a non-editable **atomic chip** —
167
+ * the caret steps over it as a single unit. Composes with `renderLink` (both
168
+ * usable together).
169
+ *
170
+ * @remarks Render-time only — the model is unchanged, so `toHtml`/`toMarkdown`
171
+ * still serialize the mention mark. Keep it cheap (it runs on every render):
172
+ * don't do heavy synchronous work or block on the network inside `renderMention`;
173
+ * return a component that fetches/caches the lookup itself (falling back to
174
+ * `defaultNode` while loading).
175
+ */
176
+ renderMention?: RenderMention;
177
+ /**
178
+ * Maximum DISPLAYED height of image attachments, in px. Default: the
179
+ * `--size-rich-text-image-max-height` token (480px). A taller image shrinks
180
+ * (width follows, aspect preserved); the resize handle and width slider stop
181
+ * where the image hits the cap. Render-time only — stored `width`/`height` are
182
+ * unchanged. Pass the same value to the read-only `<RichText>` so both agree.
183
+ */
184
+ imageMaxHeight?: number;
185
+ /**
186
+ * Show Notion-style per-block controls: a left gutter that appears on the
187
+ * hovered/focused block with an insert button (`+`, adds an empty paragraph
188
+ * below) and a drag handle (`⠿`) that opens a block menu (Turn into ▸,
189
+ * Duplicate, Move up/down, Delete). Reordering is subtree-aware for nested
190
+ * lists. Keyboard: Shift+F10 / the ContextMenu key opens the focused block's
191
+ * menu; ⌘/Ctrl+⇧↑ / ⌘/Ctrl+⇧↓ move the block; ⌘/Ctrl+D duplicates. Default
192
+ * `false`. Ignored when `readOnly`. Independent of `toolbar`.
193
+ */
194
+ blockControls?: boolean;
195
+ /**
196
+ * Enable file upload: a toolbar button (when `toolbar`) and clipboard-file paste.
197
+ * `onUpload(file)` resolves with where the file landed; images render inline as a
198
+ * preview, other files as a download chip. Reject `onUpload` to show a retry/remove
199
+ * error; reject with `new UploadError(message)` to also show that (user-facing,
200
+ * localized) reason on the block — any other rejection shows only "Upload
201
+ * failed". `onUploadingChange` fires while any upload is in flight — wire it to your
202
+ * submit button's disabled state. Validation (size/type) belongs in `onUpload`
203
+ * (`accept` is only a native-picker hint and is bypassed by paste). Omit to
204
+ * disable. Ignored when `readOnly`.
205
+ * When `blockControls` is also on, a ready image attachment can be configured
206
+ * (alt text, alignment, replace, open/download) via the block menu's
207
+ * "Configure" item. The width slider appears only for an image that renders as
208
+ * a preview (a safe, fetchable src — an embed); an uploaded image whose
209
+ * object-URL src renders as a download chip isn't resizable here. Alignment +
210
+ * width round-trip through HTML but not Markdown.
211
+ */
212
+ upload?: UploadConfig;
213
+ }
214
+
215
+ function isEmptyDoc(doc: RichDoc): boolean {
216
+ return doc.blocks.length === 1 && blockLength(doc.blocks[0]) === 0;
217
+ }
218
+
219
+ /** Toggle `mark` within a `Mark[]` (used to fold a shortcut into pending marks). */
220
+ function toggleInList(marks: Mark[], mark: Mark): Mark[] {
221
+ return hasMark(marks, mark.type) ? withoutMark(marks, mark.type) : withMark(marks, mark);
222
+ }
223
+
224
+ /**
225
+ * Insert `text` at `point` carrying exactly `marks` (staged pending marks). The
226
+ * span comes from the insert's resulting caret, not `point`: beside a void block
227
+ * the text lands in a NEW paragraph after it.
228
+ */
229
+ function insertWithMarks(
230
+ doc: RichDoc,
231
+ point: Point,
232
+ text: string,
233
+ marks: Mark[],
234
+ ): { doc: RichDoc; selection: Range } {
235
+ const inserted = insertText(doc, point, text);
236
+ const end = inserted.selection.focus;
237
+ const span: Range = {
238
+ anchor: { blockId: end.blockId, offset: end.offset - text.length },
239
+ focus: end,
240
+ };
241
+ return { doc: applyExactMarks(inserted.doc, span, marks), selection: inserted.selection };
242
+ }
243
+
244
+ /**
245
+ * Controlled rich-text editor: a contentEditable surface over the in-house engine with marks, lists, links, mentions, uploads and undo/redo.
246
+ * @see docs/components/RichTextEditor.md
247
+ */
248
+ export const RichTextEditor = forwardRef<HTMLDivElement, RichTextEditorProps>(
249
+ function RichTextEditor(
250
+ {
251
+ value,
252
+ onChange,
253
+ readOnly = false,
254
+ placeholder,
255
+ autoFocus,
256
+ toolbar = false,
257
+ blockControls = false,
258
+ mentions,
259
+ autolink = true,
260
+ renderLink,
261
+ renderMention,
262
+ imageMaxHeight,
263
+ upload,
264
+ invalid = false,
265
+ required = false,
266
+ className,
267
+ style,
268
+ ...rest
269
+ },
270
+ ref,
271
+ ) {
272
+ const t = useTranslation();
273
+ const rootRef = useRef<HTMLDivElement | null>(null);
274
+ const isComposingRef = useRef(false);
275
+ // Selection to restore after the next model-driven re-render.
276
+ // `afterVoid`: a void block whose DOM caret goes AFTER its figure (voidDelete's
277
+ // caretAfterVoid — a spot the model's single void point can't name). Bundled
278
+ // with the selection so every path that places a caret replaces both at once:
279
+ // a stale marker can never fire with someone else's selection. A block id, so
280
+ // it survives a parent that copies the doc in onChange.
281
+ const pendingSelectionRef = useRef<{ range: Range; afterVoid: string | null } | null>(null);
282
+ // Which committed docs had their caret after a void — keyed by the exact doc
283
+ // object history keeps, so undo/redo restore the same side.
284
+ const caretAfterVoidDocs = useRef(new WeakMap<RichDoc, string>());
285
+ // Latest props for the native beforeinput listener (avoids stale closures).
286
+ const latest = useRef({
287
+ value,
288
+ onChange,
289
+ readOnly,
290
+ autolink,
291
+ renderLink,
292
+ upload,
293
+ });
294
+ latest.current = {
295
+ value,
296
+ onChange,
297
+ readOnly,
298
+ autolink,
299
+ renderLink,
300
+ upload,
301
+ };
302
+ // The synchronous "live" doc — the doc the parent has taken, possibly ahead of
303
+ // the last render's `value`, so several async upload settles chain off each
304
+ // other's result instead of all reading a stale `value` (which would make the
305
+ // last settle clobber the earlier ones). Never an edit the parent hasn't taken
306
+ // yet (see unconfirmedRef). Re-synced to `value` each render so external
307
+ // replacements flow in.
308
+ const liveDocRef = useRef(value);
309
+ liveDocRef.current = value;
310
+
311
+ // Stable getters for the synchronously-latest doc/flags — passed to the
312
+ // feature hooks so their handlers read current values without re-subscribing
313
+ // or depending on `latest`'s shape (keeps the handlers' identity stable).
314
+ const getValue = useCallback(() => latest.current.value, []);
315
+ const getLiveDoc = useCallback(() => liveDocRef.current, []);
316
+ const getReadOnly = useCallback(() => latest.current.readOnly, []);
317
+
318
+ // Focus state — only consulted by `toolbar="auto"` to gate the bar's visibility.
319
+ // Focus moving to an editor overlay (the link editor / mention menu, portaled to
320
+ // <body>) fires a blur, so `focused` flips false there; the `showToolbar`
321
+ // formula keeps the bar up via the overlay-open term instead.
322
+ const [focused, setFocused] = useState(false);
323
+ // True while any toolbar popover is open — it blurs the editable by opening,
324
+ // which would otherwise unmount the bar and the popover with it.
325
+ const [toolbarOverlayOpen, setToolbarOverlayOpen] = useState(false);
326
+ const autoToolbar = toolbar === 'auto';
327
+
328
+ // Toolbar state: the live selection (tracked via `selectionchange`) and any
329
+ // marks staged at a collapsed caret to apply to the next typed character.
330
+ const [selection, setSelection] = useState<Range | null>(null);
331
+ const [pendingMarks, setPendingMarks] = useState<Mark[] | null>(null);
332
+ // Mirror pending marks into a ref so the native beforeinput listener reads
333
+ // the current value without re-subscribing.
334
+ const pendingMarksRef = useRef<Mark[] | null>(null);
335
+ pendingMarksRef.current = pendingMarks;
336
+ // The collapsed caret where pending marks were staged. Used to clear them
337
+ // when the caret moves to a different spot (vs. typing at the same point).
338
+ const pendingAtRef = useRef<Point | null>(null);
339
+ // The most recent NON-null editor selection. Survives focus moving into a toolbar
340
+ // popover (e.g. the emoji/search box), where the live selection reads null. Used by
341
+ // popover-driven inserts so they target where the caret actually was.
342
+ const lastSelectionRef = useRef<Range | null>(null);
343
+
344
+ const setRefs = useCallback(
345
+ (node: HTMLDivElement | null) => {
346
+ rootRef.current = node;
347
+ if (typeof ref === 'function') ref(node);
348
+ else if (ref) ref.current = node;
349
+ },
350
+ [ref],
351
+ );
352
+
353
+ const controlsOn = blockControls && !readOnly;
354
+ // Whether the stable `.shell` wrapper is rendered (a toolbar mode is active or
355
+ // block controls need the anchor). The image resize handle anchors into the
356
+ // shell, so its hover tracking + element are gated on this. Declared up here
357
+ // (vs. near the shell render) so the image-hover effect below can depend on it.
358
+ const usesShell = toolbar === true || autoToolbar || controlsOn;
359
+ // The same gate the mention menu uses — drives both `useMention`'s `enabled`
360
+ // and the consolidated selectionchange listener's mention fan-out below.
361
+ const mentionsEnabled = !!mentions && !readOnly;
362
+ const shellRef = useRef<HTMLDivElement | null>(null);
363
+ // Active block = hover wins, else the caret block (keyboard / after the mouse
364
+ // leaves). Split so clearing hover on editor-leave never wipes the caret target.
365
+ const [hoverBlockId, setHoverBlockId] = useState<string | null>(null);
366
+ const [caretBlockId, setCaretBlockId] = useState<string | null>(null);
367
+ const activeBlockId = hoverBlockId ?? caretBlockId;
368
+ const [blockMenuOpen, setBlockMenuOpen] = useState(false);
369
+ // Mirror the open state into a ref so the hover listener can read it without
370
+ // re-subscribing: while the menu is open, hovering another block must NOT move
371
+ // the active block (the menu's actions are bound to it — moving it would make
372
+ // a click act on the wrong block).
373
+ const blockMenuOpenRef = useRef(false);
374
+ blockMenuOpenRef.current = blockMenuOpen;
375
+ // Set by RichTextBlockControls' onDraggingChange. While a block drag is in
376
+ // progress the active block must not change (it IS the block being dragged), so
377
+ // the hover handlers below read this ref and bail — mirroring blockMenuOpenRef.
378
+ const draggingRef = useRef(false);
379
+ // Stable setter for draggingRef — passed to the image resizer so its memoized
380
+ // shell doesn't re-render every keystroke on a fresh inline lambda. Used by the
381
+ // resizer's OWN drag: it sets draggingRef only (NOT blockDragging), so a resize
382
+ // never hides the handle mid-drag.
383
+ const setDragging = useCallback((d: boolean) => {
384
+ draggingRef.current = d;
385
+ }, []);
386
+ // The previewable image currently under the pointer → the resize-handle target.
387
+ // Tracked independently of blockControls/upload/active-block so the handle shows
388
+ // for ANY previewable image on hover (see the image-hover effect below).
389
+ const [hoveredImageId, setHoveredImageId] = useState<string | null>(null);
390
+ // True while a blockControls reorder drag is in flight. Hides the image resize
391
+ // handle (it can't follow the block's in-place reflow); it reappears at the drop.
392
+ const [blockDragging, setBlockDragging] = useState(false);
393
+ // Block-drag report (passed to RichTextBlockControls): set draggingRef so the
394
+ // hover/caret tracking bails AND set blockDragging so the image handle hides.
395
+ // Separate from setDragging (which the resizer's own drag uses) on purpose.
396
+ const onBlockDraggingChange = useCallback((d: boolean) => {
397
+ draggingRef.current = d;
398
+ setBlockDragging(d);
399
+ }, []);
400
+
401
+ // Resolve the [data-block-id] of the block element containing a DOM node.
402
+ const blockIdFromNode = useCallback((node: Node | null): string | null => {
403
+ let el: HTMLElement | null =
404
+ node instanceof HTMLElement ? node : (node?.parentElement ?? null);
405
+ while (el && el !== rootRef.current) {
406
+ if (el.hasAttribute('data-block-id')) return el.getAttribute('data-block-id');
407
+ el = el.parentElement;
408
+ }
409
+ return null; // reached the root (or ran out of ancestors) — no block
410
+ }, []);
411
+
412
+ // Resolve the [data-block-id] of the previewable-image FIGURE containing a DOM
413
+ // node, or null. A previewable image renders `<figure data-block-id><img></figure>`;
414
+ // a non-preview file chip renders `<figure data-block-id><a></figure>` — so a
415
+ // figure that contains an <img> = a previewable image. DOM-based (no `value`
416
+ // dep), so it stays stable; the editor re-validates the id against the model.
417
+ const imageFigureIdAt = useCallback((node: Node | null): string | null => {
418
+ let el: HTMLElement | null =
419
+ node instanceof HTMLElement ? node : (node?.parentElement ?? null);
420
+ while (el && el !== rootRef.current) {
421
+ if (
422
+ el.tagName === 'FIGURE' &&
423
+ el.hasAttribute('data-block-id') &&
424
+ el.querySelector('img')
425
+ ) {
426
+ return el.getAttribute('data-block-id');
427
+ }
428
+ el = el.parentElement;
429
+ }
430
+ return null;
431
+ }, []);
432
+
433
+ // The block whose vertical band contains viewport-y `clientY`, or null. Used to
434
+ // resolve a hover over the gutter/padding column (where there is no block element
435
+ // under the pointer) to the row beside it. Block elements are in document order =
436
+ // top-to-bottom, so we can stop once a block starts below the pointer; among the
437
+ // blocks that contain the pointer the LAST in document order is the deepest (a
438
+ // nested list item comes after — and sits inside — its parent), matching how a
439
+ // direct hover resolves to the innermost block. Reads a layout rect per block up
440
+ // to the pointer's row — an accepted cost: the caller only invokes this for the
441
+ // narrow no-block-under-pointer case (the gutter/padding column), never the hot
442
+ // text-hover path, so there's no need to cache rects or rAF-throttle.
443
+ const blockAtPointerY = useCallback((root: HTMLElement, clientY: number): string | null => {
444
+ let found: string | null = null;
445
+ for (const el of root.querySelectorAll<HTMLElement>('[data-block-id]')) {
446
+ const box = el.getBoundingClientRect();
447
+ if (box.top > clientY) break;
448
+ if (clientY <= box.bottom) found = el.getAttribute('data-block-id');
449
+ }
450
+ return found;
451
+ }, []);
452
+
453
+ const historyRef = useRef<History>(historyReset({ doc: value, selection: null }));
454
+ // Timestamp of the last ⌘Z/⌘⇧Z/⌘Y keydown — lets the beforeinput net skip the
455
+ // historyUndo/historyRedo event that a keydown ALSO emits (already handled),
456
+ // while still honoring a menu/trackpad undo that emits no keydown.
457
+ const historyKeyAtRef = useRef(0);
458
+ const [canUndo, setCanUndo] = useState(false);
459
+ const [canRedo, setCanRedo] = useState(false);
460
+ const syncHistoryFlags = useCallback(() => {
461
+ setCanUndo(historyCanUndo(historyRef.current));
462
+ setCanRedo(historyCanRedo(historyRef.current));
463
+ }, []);
464
+
465
+ // The last doc handed to onChange that `value` hasn't become yet, with the
466
+ // history to restore if it never does. flushSync renders a synchronously-
467
+ // accepting parent before onChange returns, so most edits never land here;
468
+ // one that does was either REJECTED or is still on its way (a parent storing
469
+ // it in startTransition / useDeferredValue — tolerated for a single edit,
470
+ // discouraged; see the docs). Resolved by whichever comes
471
+ // first: that doc arriving as `value` (accepted late — keep everything), a
472
+ // different `value` arriving (rejected — the layout effect drops its pending
473
+ // caret), or the next edit / undo / settle (reconcile() rolls its history
474
+ // entry back). Meanwhile the live doc stays the SHOWN one, so async upload
475
+ // settles never build on an edit the parent may have refused.
476
+ const unconfirmedRef = useRef<{ doc: RichDoc; prevHistory: History } | null>(null);
477
+
478
+ // Every commit path calls this FIRST — before writing pendingSelectionRef —
479
+ // since a rollback also drops the refused edit's pending caret.
480
+ const reconcile = useCallback(() => {
481
+ const u = unconfirmedRef.current;
482
+ unconfirmedRef.current = null;
483
+ if (u && latest.current.value !== u.doc) {
484
+ historyRef.current = u.prevHistory;
485
+ syncHistoryFlags();
486
+ // Its caret too — a caller that returns early (an empty undo/redo) would
487
+ // otherwise leave it for some unrelated re-render to write.
488
+ pendingSelectionRef.current = null;
489
+ }
490
+ }, [syncHistoryFlags]);
491
+
492
+ const emit = useCallback((doc: RichDoc, prevHistory: History) => {
493
+ const before = latest.current.value;
494
+ liveDocRef.current = doc;
495
+ try {
496
+ flushSync(() => latest.current.onChange(doc));
497
+ } finally {
498
+ // `finally`: an onChange that throws counts as not (yet) accepted too.
499
+ if (latest.current.value === before) {
500
+ unconfirmedRef.current = { doc, prevHistory };
501
+ liveDocRef.current = before;
502
+ }
503
+ }
504
+ }, []);
505
+
506
+ const commit = useCallback(
507
+ (
508
+ result: { doc: RichDoc; selection: Range },
509
+ kind: EditKind = 'other',
510
+ options?: {
511
+ /**
512
+ * Keep the DOM selection as-is — do NOT writeSelection on the re-render.
513
+ * Used by edits applied from a floating UI that owns focus (e.g. the ⠿
514
+ * block-color submenu): writing `result.selection` would both yank focus
515
+ * out of the open menu and visibly select the whole block. `result.selection`
516
+ * is still recorded in history so undo lands somewhere sensible.
517
+ */
518
+ keepSelection?: boolean;
519
+ /** Place the DOM caret AFTER this void block's figure on the re-render. */
520
+ caretAfterVoid?: string;
521
+ },
522
+ ) => {
523
+ // No-op transforms (e.g. Backspace at the very start of the document)
524
+ // return the SAME doc reference — skip so we don't fire onChange or leave a
525
+ // stale pending selection that React would never consume (no re-render).
526
+ if (result.doc === latest.current.value) return;
527
+ if (options?.caretAfterVoid)
528
+ caretAfterVoidDocs.current.set(result.doc, options.caretAfterVoid);
529
+ reconcile();
530
+ const prevHistory = historyRef.current;
531
+ historyRef.current = historyRecord(
532
+ historyRef.current,
533
+ { doc: result.doc, selection: result.selection },
534
+ kind,
535
+ Date.now(),
536
+ );
537
+ syncHistoryFlags();
538
+ // Every commit path writes pendingSelectionRef (null = "place no caret on
539
+ // this render"), so a pending selection left by a commit the parent
540
+ // rejected can never fire on a later, unrelated render.
541
+ pendingSelectionRef.current = options?.keepSelection
542
+ ? null
543
+ : { range: result.selection, afterVoid: options?.caretAfterVoid ?? null };
544
+ emit(result.doc, prevHistory);
545
+ },
546
+ [syncHistoryFlags, emit, reconcile],
547
+ );
548
+
549
+ // Live-resize commit path for attachment width drags (used by
550
+ // useAttachmentConfig's onConfigWidth and the image resizer). Records ONE
551
+ // coalescing 'resize' history entry per drag (whole drag = one undo step),
552
+ // clears the pending selection so no caret is placed (the slider/handle keeps
553
+ // focus mid-drag — a writeSelection into the editable would yank it), and chains off
554
+ // `liveDocRef` so rapid moves before a re-render stack on each other. The
555
+ // no-op guard skips an unchanged doc (same width). This stays in the editor
556
+ // so the history coupling is isolated from the hook.
557
+ const commitResizeLive = useCallback(
558
+ (doc: RichDoc) => {
559
+ if (doc === liveDocRef.current) return;
560
+ reconcile();
561
+ pendingSelectionRef.current = null; // the slider/handle keeps focus
562
+ const prevHistory = historyRef.current;
563
+ historyRef.current = historyRecord(
564
+ historyRef.current,
565
+ { doc, selection: historyRef.current.present.selection },
566
+ 'resize',
567
+ Date.now(),
568
+ );
569
+ syncHistoryFlags();
570
+ emit(doc, prevHistory);
571
+ },
572
+ [syncHistoryFlags, emit, reconcile],
573
+ );
574
+
575
+ // Like commit, but records NO history entry — used for async upload settles so
576
+ // Undo never steps through an upload resolving. Preserves the caret across the
577
+ // model-driven re-render by re-pinning the current selection (or placing none
578
+ // when the selection is outside the editor), and keeps the
579
+ // history's `present` snapshot in sync with the new doc (without pushing a
580
+ // past/future entry) so the layout effect's `value !== present.doc` external-
581
+ // replacement heuristic doesn't mistake a settle for a doc swap and reset undo.
582
+ const commitSilent = useCallback(
583
+ (doc: RichDoc) => {
584
+ if (doc === latest.current.value) return;
585
+ reconcile();
586
+ const root = rootRef.current;
587
+ const sel = root ? readSelection(root) : null;
588
+ pendingSelectionRef.current = sel ? { range: sel, afterVoid: null } : null;
589
+ const prevHistory = historyRef.current;
590
+ historyRef.current = {
591
+ ...historyRef.current,
592
+ present: { doc, selection: sel ?? historyRef.current.present.selection },
593
+ };
594
+ emit(doc, prevHistory);
595
+ },
596
+ [emit, reconcile],
597
+ );
598
+
599
+ const uploadOn = !!upload && !readOnly;
600
+ // A failure usually lands while the user keeps typing elsewhere in the doc,
601
+ // so the block's visible text alone is never heard: announce it (Hard rule 10).
602
+ const [uploadFailure, setUploadFailure] = useState<{ name: string; reason?: string } | null>(
603
+ null,
604
+ );
605
+ const uploader = useUpload({
606
+ config: upload ?? { onUpload: async () => ({ url: '' }) },
607
+ getValue: () => liveDocRef.current,
608
+ applyInsert: (doc) => {
609
+ const root = rootRef.current;
610
+ const sel = (root ? readSelection(root) : null) ?? {
611
+ anchor: { blockId: liveDocRef.current.blocks[0].id, offset: 0 },
612
+ focus: { blockId: liveDocRef.current.blocks[0].id, offset: 0 },
613
+ };
614
+ commit({ doc, selection: sel }, 'other');
615
+ },
616
+ applySettle: commitSilent,
617
+ getCaret: () =>
618
+ (rootRef.current ? readSelection(rootRef.current)?.anchor : undefined) ?? {
619
+ blockId: liveDocRef.current.blocks[0].id,
620
+ offset: 0,
621
+ },
622
+ // Cap a freshly-uploaded image's initial width to the editor content width
623
+ // (mirrors the resizer's maxWidth measurement). `0` when unmounted → no cap.
624
+ getContentWidth: () => rootRef.current?.getBoundingClientRect().width ?? 0,
625
+ onFailureChange: setUploadFailure,
626
+ });
627
+ // The paste/click handlers close over a stale `uploader`; mirror it in a ref so
628
+ // we read the current one without re-subscribing the native paste listener.
629
+ const uploaderRef = useRef(uploader);
630
+ uploaderRef.current = uploader;
631
+ // The toolbar's Add-file button clicks this; the input is rendered by the shell.
632
+ const uploadInputRef = useRef<HTMLInputElement>(null);
633
+
634
+ // Drop any caret-staged pending mark — the doc + caret are about to change,
635
+ // so a mark staged at the old caret must not bleed into the next typed text.
636
+ const clearPendingMarks = useCallback(() => {
637
+ setPendingMarks(null);
638
+ pendingMarksRef.current = null; // ahead of the re-render, for same-tick events
639
+ pendingAtRef.current = null;
640
+ }, []);
641
+
642
+ // Consume the staged pending marks if they were staged at `point`; marks staged
643
+ // anywhere else are dropped. The selectionchange cleanup runs only with a
644
+ // toolbar, so a keyboard-only editor relies on this to keep a ⌘B staged
645
+ // elsewhere from leaking into text typed here.
646
+ const takePendingAt = useCallback(
647
+ (point: Point): Mark[] | null => {
648
+ const pend = pendingMarksRef.current;
649
+ const at = pendingAtRef.current;
650
+ if (!pend) return null;
651
+ clearPendingMarks();
652
+ return at && at.blockId === point.blockId && at.offset === point.offset ? pend : null;
653
+ },
654
+ [clearPendingMarks],
655
+ );
656
+
657
+ // A voidDelete result that only moves the caret returns the SAME doc, which
658
+ // commit() skips as a no-op — apply its selection directly instead.
659
+ const applyVoidDelete = useCallback(
660
+ (result: ReturnType<typeof voidDelete>) => {
661
+ if (!result) return;
662
+ if (result.doc === latest.current.value) {
663
+ if (rootRef.current) writeSelection(rootRef.current, result.selection);
664
+ return;
665
+ }
666
+ commit(result, 'delete', {
667
+ caretAfterVoid: result.caretAfterVoid ? result.selection.anchor.blockId : undefined,
668
+ });
669
+ },
670
+ [commit],
671
+ );
672
+
673
+ const onUndo = useCallback(() => {
674
+ reconcile();
675
+ const h = historyRef.current;
676
+ if (!historyCanUndo(h)) return;
677
+ const next = historyUndo(h);
678
+ historyRef.current = next;
679
+ syncHistoryFlags();
680
+ clearPendingMarks();
681
+ pendingSelectionRef.current = next.present.selection && {
682
+ range: next.present.selection,
683
+ afterVoid: caretAfterVoidDocs.current.get(next.present.doc) ?? null,
684
+ };
685
+ emit(next.present.doc, h);
686
+ }, [syncHistoryFlags, clearPendingMarks, emit, reconcile]);
687
+
688
+ const onRedo = useCallback(() => {
689
+ reconcile();
690
+ const h = historyRef.current;
691
+ if (!historyCanRedo(h)) return;
692
+ const next = historyRedo(h);
693
+ historyRef.current = next;
694
+ syncHistoryFlags();
695
+ clearPendingMarks();
696
+ pendingSelectionRef.current = next.present.selection && {
697
+ range: next.present.selection,
698
+ afterVoid: caretAfterVoidDocs.current.get(next.present.doc) ?? null,
699
+ };
700
+ emit(next.present.doc, h);
701
+ }, [syncHistoryFlags, clearPendingMarks, emit, reconcile]);
702
+
703
+ const insertMentionItem = useCallback(
704
+ (
705
+ blockId: string,
706
+ range: { from: number; to: number },
707
+ trigger: string,
708
+ item: MentionItem,
709
+ ) => {
710
+ commit(insertMention(latest.current.value, blockId, range, trigger, item), 'other');
711
+ clearPendingMarks();
712
+ },
713
+ [commit, clearPendingMarks],
714
+ );
715
+
716
+ const mention = useMention({
717
+ enabled: mentionsEnabled,
718
+ rootRef,
719
+ doc: value,
720
+ trigger: mentions?.trigger ?? '@',
721
+ onQuery: mentions?.onQuery,
722
+ onInsert: insertMentionItem,
723
+ });
724
+ const recomputeMention = mention.recompute;
725
+
726
+ // Shared by the keyboard shortcut and the toolbar: with a collapsed caret,
727
+ // stage a pending mark for the next typed text (remembering where); with a
728
+ // selection, toggle the mark over it now.
729
+ const stageOrToggleMark = useCallback(
730
+ (range: Range, mark: Mark) => {
731
+ if (isCollapsed(range)) {
732
+ pendingAtRef.current = range.anchor;
733
+ setPendingMarks((prev) =>
734
+ toggleInList(prev ?? marksForTypedText(latest.current.value, range.anchor), mark),
735
+ );
736
+ } else {
737
+ commit(runToggleMark(latest.current.value, range, mark));
738
+ }
739
+ },
740
+ [commit],
741
+ );
742
+
743
+ // Color sibling of stageOrToggleMark: with a collapsed caret, stage the color
744
+ // as a pending mark for the next typed text (replacing any pending color of the
745
+ // same type, or clearing it when `key` is null); with a selection, set it now.
746
+ const stageOrSetColor = useCallback(
747
+ (range: Range, type: 'textColor' | 'bgColor', key: string | null) => {
748
+ if (isCollapsed(range)) {
749
+ pendingAtRef.current = range.anchor;
750
+ setPendingMarks((prev) => {
751
+ const base = (prev ?? marksForTypedText(latest.current.value, range.anchor)).filter(
752
+ (m) => m.type !== type,
753
+ );
754
+ return key ? [...base, { type, color: key }] : base;
755
+ });
756
+ } else {
757
+ // setColorMark returns a bare RichDoc (a color change never moves the
758
+ // caret), so wrap it for commit and keep the existing selection.
759
+ commit({ doc: setColorMark(latest.current.value, range, type, key), selection: range });
760
+ }
761
+ },
762
+ [commit],
763
+ );
764
+
765
+ // Toolbar color dispatch — read the live selection (falling back to the most
766
+ // recent one, which survives the Popover stealing focus) and route through the
767
+ // shared color path, then restore focus so typing continues after the pick.
768
+ const onSetColor = useCallback(
769
+ (type: 'textColor' | 'bgColor', key: string | null) => {
770
+ const root = rootRef.current;
771
+ const range = (root ? readSelection(root) : null) ?? lastSelectionRef.current;
772
+ if (range) {
773
+ stageOrSetColor(range, type, key);
774
+ root?.focus();
775
+ }
776
+ },
777
+ [stageOrSetColor],
778
+ );
779
+
780
+ // Link editor: open-state + apply/remove/cancel handlers (see useLinkEditor).
781
+ // The toolbar's `linkActive` derivation and the `<RichTextLinkEditor>` render
782
+ // stay in this file — they need the live selection / render scope.
783
+ const { linkEditor, openLinkEditor, onLinkApply, onLinkRemove, onLinkCancel } = useLinkEditor({
784
+ rootRef,
785
+ commit,
786
+ getValue,
787
+ getReadOnly,
788
+ });
789
+
790
+ // Restore the caret/selection after a model-driven re-render.
791
+ // The `value` the layout effect last saw — it also re-runs on mentions/readOnly
792
+ // changes, which must not be mistaken for a new value arriving.
793
+ const seenValueRef = useRef(value);
794
+ useLayoutEffect(() => {
795
+ const valueChanged = value !== seenValueRef.current;
796
+ seenValueRef.current = value;
797
+ // External value replacement (parent sets a wholly different doc) — reset
798
+ // history so Undo can't travel back into the old document's timeline. Only
799
+ // when `value` actually changed: during a pending (unconfirmed) edit,
800
+ // present.doc runs ahead of an unchanged value.
801
+ if (valueChanged && value !== historyRef.current.present.doc) {
802
+ historyRef.current = historyReset({ doc: value, selection: null });
803
+ syncHistoryFlags();
804
+ // A programmatic value swap fires no user `selectionchange`, so the
805
+ // consolidated listener below never re-runs the mention menu for it.
806
+ // Recompute here so an external swap updates/closes the menu. Internal
807
+ // commits keep `present.doc === value`, so they DON'T reach this branch —
808
+ // no per-keystroke double-recompute is reintroduced.
809
+ if (mentionsEnabled) {
810
+ const r = rootRef.current;
811
+ recomputeMention(r ? readSelection(r) : null);
812
+ }
813
+ }
814
+ const root = rootRef.current;
815
+ // A pending edit's doc arriving late = accepted (keep its caret); any OTHER
816
+ // value arriving first = it was rejected, so its caret must not fire here.
817
+ const unconfirmed = unconfirmedRef.current;
818
+ if (unconfirmed && valueChanged) {
819
+ if (value !== unconfirmed.doc) pendingSelectionRef.current = null;
820
+ unconfirmedRef.current = null;
821
+ }
822
+ const pending = pendingSelectionRef.current;
823
+ // Not while an edit is still awaiting acceptance: its caret belongs to a doc
824
+ // the DOM doesn't show yet (written once that value arrives, or dropped).
825
+ if (root && pending && !unconfirmedRef.current) {
826
+ writeSelection(root, pending.range);
827
+ pendingSelectionRef.current = null;
828
+ // Only with the selection it was bundled with (a commit / undo / redo) —
829
+ // never on an unrelated re-run such as a readOnly toggle.
830
+ const afterVoid = pending.afterVoid;
831
+ const fig = afterVoid
832
+ ? root.querySelector(`[data-block-id="${CSS.escape(afterVoid)}"]`)
833
+ : null;
834
+ if (fig) {
835
+ // At the END of the figure's content — where Chrome's own Ctrl+End puts
836
+ // it. A root-level caret after a trailing contentEditable=false figure
837
+ // has no visible position: Chrome snaps it to the start of the editor.
838
+ const r = fig.ownerDocument.createRange();
839
+ r.setStart(fig, fig.childNodes.length);
840
+ r.collapse(true);
841
+ const sel = fig.ownerDocument.getSelection();
842
+ sel?.removeAllRanges();
843
+ sel?.addRange(r);
844
+ }
845
+ }
846
+ }, [value, syncHistoryFlags, mentionsEnabled, recomputeMention]);
847
+
848
+ // Native beforeinput (React's onBeforeInput is NOT the modern beforeinput —
849
+ // it's a legacy textInput polyfill that carries no `inputType`).
850
+ useEffect(() => {
851
+ const root = rootRef.current;
852
+ if (!root) return;
853
+ const onBeforeInput = (e: InputEvent) => {
854
+ const { value: doc, readOnly: ro, autolink: autolinkOn, renderLink: rl } = latest.current;
855
+ if (ro || isComposingRef.current) return;
856
+ // Undo/redo via beforeinput. Always preventDefault so the browser's native
857
+ // contentEditable undo never mutates the DOM under the controlled model.
858
+ // A ⌘Z/⌘⇧Z/⌘Y keydown ALSO emits a paired historyUndo/historyRedo here —
859
+ // the keydown handler already ran onUndo/onRedo, so skip that one (within a
860
+ // short window of the keydown). A menu/trackpad undo emits no keydown, so it
861
+ // falls through and is honored here.
862
+ if (e.inputType === 'historyUndo' || e.inputType === 'historyRedo') {
863
+ e.preventDefault();
864
+ if (Date.now() - historyKeyAtRef.current < 100) return;
865
+ if (e.inputType === 'historyUndo') onUndo();
866
+ else onRedo();
867
+ return;
868
+ }
869
+ const range = readSelection(root);
870
+ if (!range) {
871
+ // Unmappable selection: never cede an editing input to the browser —
872
+ // an un-prevented default insert/delete mutates the contentEditable
873
+ // DOM outside the model (permanent DOM/model divergence, #321). A
874
+ // dropped keystroke is recoverable; a future resolver bug surfaces
875
+ // as dropped keystrokes instead of DOM corruption — acceptable.
876
+ if (e.inputType.startsWith('insert') || e.inputType.startsWith('delete'))
877
+ e.preventDefault();
878
+ return;
879
+ }
880
+ // Markdown block input rules: a marker + space at the start of a paragraph
881
+ // converts the block (e.g. "# " → heading, "- " → bullet). The space is
882
+ // consumed; one commit → one undo step (⌘Z reverts the conversion).
883
+ if (e.inputType === 'insertText' && e.data === ' ' && isCollapsed(range)) {
884
+ const block = doc.blocks.find((b) => b.id === range.anchor.blockId);
885
+ if (block) {
886
+ const before = runsText(block.inlines).slice(0, range.anchor.offset);
887
+ const match = matchBlockRule(block.type, before, ' ');
888
+ if (match) {
889
+ e.preventDefault();
890
+ clearPendingMarks();
891
+ commit(applyBlockRule(doc, block.id, match), 'other');
892
+ return;
893
+ }
894
+ }
895
+ }
896
+ // Autolink on type: typing a space after a URL links the URL AND inserts the
897
+ // space — both in one commit (one undo step). `applyTypeAutolink` inserts the
898
+ // boundary first (so it stays OUTSIDE the link) and links only the URL. Skips
899
+ // when the caret is already inside a link.
900
+ if (
901
+ autolinkOn !== false &&
902
+ e.inputType === 'insertText' &&
903
+ e.data === ' ' &&
904
+ isCollapsed(range)
905
+ ) {
906
+ const linked = applyTypeAutolink(doc, range.anchor, e.data);
907
+ if (linked) {
908
+ e.preventDefault();
909
+ clearPendingMarks();
910
+ commit(linked, 'type');
911
+ return;
912
+ }
913
+ }
914
+ // Atomic delete: a Backspace just after (or Delete just before) a link that
915
+ // `renderLink` resolves to a custom chip removes the whole link in one step.
916
+ // `isResolved` probes `renderLink` with a stable fallback sentinel: a custom
917
+ // return (chip) is `!== FALLBACK_SENTINEL`; declining returns the sentinel.
918
+ if (
919
+ rl &&
920
+ (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteContentForward') &&
921
+ isCollapsed(range)
922
+ ) {
923
+ const dir = e.inputType === 'deleteContentBackward' ? 'backward' : 'forward';
924
+ const isResolved = (href: string) =>
925
+ rl({ href, text: href }, FALLBACK_SENTINEL) !== FALLBACK_SENTINEL;
926
+ const delRange = atomicLinkDeleteRange(doc, range.anchor, dir, isResolved);
927
+ if (delRange) {
928
+ e.preventDefault();
929
+ clearPendingMarks();
930
+ commit(deleteRange(doc, delRange), 'delete');
931
+ return;
932
+ }
933
+ }
934
+ // Delete/Backspace beside a void: the model has one position per void, so
935
+ // the DOM side decides (see voidDelete) — never delete it from the wrong side.
936
+ if (/^delete.*(Backward|Forward)$/.test(e.inputType) && isCollapsed(range)) {
937
+ const vside = voidCaretSide(root, range.anchor.blockId);
938
+ if (vside) {
939
+ e.preventDefault();
940
+ const dir = /Backward$/.test(e.inputType) ? 'backward' : 'forward';
941
+ applyVoidDelete(voidDelete(doc, range.anchor.blockId, vside.side, dir));
942
+ return;
943
+ }
944
+ }
945
+ // Pending marks: a mark toggled at a collapsed caret applies to the next
946
+ // text typed at that same caret (takePendingAt drops it anywhere else).
947
+ const pend = takePendingAt(range.anchor);
948
+ if (pend && e.inputType === 'insertText' && isCollapsed(range) && e.data) {
949
+ e.preventDefault();
950
+ commit(insertWithMarks(doc, range.anchor, e.data, pend), 'type');
951
+ return;
952
+ }
953
+ const data = e.data ?? e.dataTransfer?.getData('text/plain') ?? null;
954
+ const result = applyInput(doc, range, e.inputType, data);
955
+ if (result === null) {
956
+ // Unsupported (incl. format* from ⌘B) — stop the browser editing, no
957
+ // model change. Marks are handled in onKeyDown to avoid a double-toggle.
958
+ if (e.inputType.startsWith('format')) e.preventDefault();
959
+ return;
960
+ }
961
+ e.preventDefault();
962
+ const kind: EditKind =
963
+ e.inputType === 'insertText' ||
964
+ e.inputType === 'insertCompositionText' ||
965
+ e.inputType === 'insertReplacementText'
966
+ ? 'type'
967
+ : e.inputType.startsWith('delete')
968
+ ? 'delete'
969
+ : 'other';
970
+ commit(result, kind);
971
+ };
972
+ root.addEventListener('beforeinput', onBeforeInput);
973
+ return () => root.removeEventListener('beforeinput', onBeforeInput);
974
+ }, [commit, onUndo, onRedo, takePendingAt, clearPendingMarks, applyVoidDelete]);
975
+
976
+ // Rich paste: when the clipboard carries HTML, parse it into the model and
977
+ // splice it at the selection. No usable HTML → if autolink is on and the
978
+ // plain text carries a URL, linkify it; otherwise don't preventDefault, so the
979
+ // native beforeinput path inserts text/plain (unchanged behavior).
980
+ useEffect(() => {
981
+ const root = rootRef.current;
982
+ if (!root) return;
983
+ const onPaste = (e: ClipboardEvent) => {
984
+ if (latest.current.readOnly) return;
985
+ // File paste (images/files from the clipboard) → upload. Takes priority
986
+ // over HTML/URL paste. Gated on `upload` being configured.
987
+ if (latest.current.upload && !latest.current.readOnly) {
988
+ const files = Array.from(e.clipboardData?.files ?? []);
989
+ if (files.length > 0) {
990
+ e.preventDefault();
991
+ uploaderRef.current.uploadFiles(files);
992
+ return;
993
+ }
994
+ }
995
+ const html = e.clipboardData?.getData('text/html');
996
+ if (html && html.trim()) {
997
+ const range = readSelection(root);
998
+ if (!range) return;
999
+ const fragment = fromHtml(html);
1000
+ if (isEmptyDoc(fragment)) return;
1001
+ e.preventDefault();
1002
+ commit(insertFragment(latest.current.value, range, fragment));
1003
+ return;
1004
+ }
1005
+ // No usable HTML — autolink plain-text URLs.
1006
+ if (latest.current.autolink === false) return;
1007
+ const plain = e.clipboardData?.getData('text/plain');
1008
+ if (!plain || !plain.trim()) return;
1009
+ const runs = linkifyRuns(plain);
1010
+ const hasLink = runs.some((r) => r.marks.some((m) => m.type === 'link'));
1011
+ if (!hasLink) return; // no URL → let the native path insert the text
1012
+ const range = readSelection(root);
1013
+ if (!range) return;
1014
+ const trimmed = plain.trim();
1015
+ const whole = findUrl(trimmed);
1016
+ // A single bare URL pasted over a selection → link the selection in place.
1017
+ if (!isCollapsed(range) && whole && whole.start === 0 && whole.end === trimmed.length) {
1018
+ e.preventDefault();
1019
+ commit(setLink(latest.current.value, range, trimmed));
1020
+ return;
1021
+ }
1022
+ // Otherwise splice a one-paragraph fragment of linkified runs.
1023
+ const fragment: RichDoc = {
1024
+ blocks: [{ id: nextId(), type: 'paragraph', inlines: runs }],
1025
+ };
1026
+ e.preventDefault();
1027
+ commit(insertFragment(latest.current.value, range, fragment));
1028
+ };
1029
+ root.addEventListener('paste', onPaste);
1030
+ return () => root.removeEventListener('paste', onPaste);
1031
+ }, [commit]);
1032
+
1033
+ useEffect(() => {
1034
+ if (autoFocus) rootRef.current?.focus();
1035
+ }, [autoFocus]);
1036
+
1037
+ // ONE selectionchange subscription shared by the toolbar, block-controls caret
1038
+ // tracking, and the mention menu. A caret move (incl. every keystroke, which
1039
+ // moves the caret) reads the model selection ONCE here and fans it out, instead
1040
+ // of three independent listeners each re-walking the DOM via their own
1041
+ // readSelection. Only subscribed when at least one consumer needs it.
1042
+ useEffect(() => {
1043
+ const toolbarOn = toolbar && !readOnly;
1044
+ if (!toolbarOn && !controlsOn && !mentionsEnabled) return;
1045
+ const onSelChange = () => {
1046
+ const root = rootRef.current;
1047
+ const sel = root ? readSelection(root) : null;
1048
+ if (toolbarOn) {
1049
+ setSelection(sel);
1050
+ if (sel != null) lastSelectionRef.current = sel;
1051
+ // Abandon pending marks if the caret left its staged point (the user
1052
+ // moved the caret or made a selection instead of typing there).
1053
+ const pend = pendingMarksRef.current;
1054
+ const stagedAt = pendingAtRef.current;
1055
+ const sameSpot =
1056
+ sel != null &&
1057
+ isCollapsed(sel) &&
1058
+ stagedAt != null &&
1059
+ sel.anchor.blockId === stagedAt.blockId &&
1060
+ sel.anchor.offset === stagedAt.offset;
1061
+ if (pend && !sameSpot) {
1062
+ clearPendingMarks();
1063
+ }
1064
+ }
1065
+ if (controlsOn) {
1066
+ // Caret → active block (keyboard users get a gutter target too). Reads the
1067
+ // NATIVE selection's anchorNode directly (not the model `sel` above): a
1068
+ // root-level caret beside a void block resolves to no data-block-id here,
1069
+ // leaving the active block unchanged — the original behavior, preserved.
1070
+ const domSel = root?.ownerDocument.getSelection();
1071
+ if (domSel && root && domSel.anchorNode && root.contains(domSel.anchorNode)) {
1072
+ const id = blockIdFromNode(domSel.anchorNode);
1073
+ if (id) setCaretBlockId(id);
1074
+ }
1075
+ }
1076
+ if (mentionsEnabled) recomputeMention(sel);
1077
+ };
1078
+ document.addEventListener('selectionchange', onSelChange);
1079
+ return () => document.removeEventListener('selectionchange', onSelChange);
1080
+ }, [
1081
+ toolbar,
1082
+ readOnly,
1083
+ controlsOn,
1084
+ mentionsEnabled,
1085
+ blockIdFromNode,
1086
+ recomputeMention,
1087
+ clearPendingMarks,
1088
+ ]);
1089
+
1090
+ // Initial mention computation: on mount, when mentions toggle on, or when the
1091
+ // trigger changes. The selectionchange listener above covers caret moves AND
1092
+ // typing (a typed char commits → writeSelection re-sets the DOM selection →
1093
+ // selectionchange fires), so this deliberately omits `value` from its deps —
1094
+ // depending on it would recompute a second time per keystroke, the very
1095
+ // redundancy this consolidation removes.
1096
+ useEffect(() => {
1097
+ if (!mentionsEnabled) return;
1098
+ const root = rootRef.current;
1099
+ recomputeMention(root ? readSelection(root) : null);
1100
+ }, [mentionsEnabled, mentions?.trigger, recomputeMention]);
1101
+
1102
+ // Hover tracking (mouse). Listens on the SHELL (which wraps both the editable and
1103
+ // the gutter) so reaching from a block onto its controls keeps them alive:
1104
+ // `mouseover` over the gutter finds no `data-block-id` on the walk up (the gutter
1105
+ // isn't inside the editable), so blockIdFromNode returns null and hoverBlockId is
1106
+ // left unchanged — keeping the controls alive as you reach for them. `mouseleave`
1107
+ // on the shell fires only when the pointer truly leaves the editor → clear hover.
1108
+ useEffect(() => {
1109
+ if (!controlsOn) return;
1110
+ const shell = shellRef.current;
1111
+ if (!shell) return;
1112
+ const onOver = (e: MouseEvent) => {
1113
+ // Don't let hover steal the active block while the menu is open (its actions
1114
+ // are bound to the active block) or while a drag is in progress.
1115
+ if (blockMenuOpenRef.current || draggingRef.current) return;
1116
+ const id = blockIdFromNode(e.target as Node);
1117
+ if (id) setHoverBlockId(id);
1118
+ };
1119
+ // The gutter (+ / ⠿) and the reserved left column are NOT inside the editable,
1120
+ // so `mouseover` there resolves to no block id and would leave the controls
1121
+ // stranded on whichever row was last hovered. Track the pointer's height while
1122
+ // it's over that controls column and activate the row at that height — so
1123
+ // hovering the controls area reveals/follows the adjacent row's controls.
1124
+ // Scoped to the no-block case so block-targeted hovers stay on the cheap
1125
+ // `mouseover` path; `mousemove` (not `mouseover`) is needed because sliding
1126
+ // within the column fires no new `mouseover`.
1127
+ // blockAtPointerY is an O(blocks) getBoundingClientRect scan, so resolve the
1128
+ // gutter-column hover at most once per animation frame: capture the latest move
1129
+ // on every event, but coalesce the actual resolution into a single rAF.
1130
+ let moveRaf = 0;
1131
+ let lastMove: { clientY: number; target: EventTarget | null } | null = null;
1132
+ const onMove = (e: MouseEvent) => {
1133
+ if (blockMenuOpenRef.current || draggingRef.current) return;
1134
+ // capture the latest move; resolve at most once per frame
1135
+ lastMove = { clientY: e.clientY, target: e.target };
1136
+ if (moveRaf) return;
1137
+ moveRaf = requestAnimationFrame(() => {
1138
+ moveRaf = 0;
1139
+ const m = lastMove;
1140
+ if (!m) return;
1141
+ const root = rootRef.current;
1142
+ if (!root) return;
1143
+ // Only the editable's OWN area (its reserved left column / padding). The gutter
1144
+ // overlay is a sibling of the editable, not a descendant, so this skips it —
1145
+ // its buttons stay alive via onOver's leave-unchanged path, and we never fight
1146
+ // the controls the pointer is aiming for.
1147
+ if (!root.contains(m.target as Node)) return;
1148
+ if (blockIdFromNode(m.target as Node)) return; // a real block hover — onOver has it
1149
+ const id = blockAtPointerY(root, m.clientY);
1150
+ if (id) setHoverBlockId(id);
1151
+ });
1152
+ };
1153
+ const onLeave = () => {
1154
+ // Keep the active block while the menu is open or a drag is mid-flight.
1155
+ if (blockMenuOpenRef.current || draggingRef.current) return;
1156
+ setHoverBlockId(null);
1157
+ };
1158
+ shell.addEventListener('mouseover', onOver);
1159
+ shell.addEventListener('mousemove', onMove);
1160
+ shell.addEventListener('mouseleave', onLeave);
1161
+ return () => {
1162
+ shell.removeEventListener('mouseover', onOver);
1163
+ shell.removeEventListener('mousemove', onMove);
1164
+ shell.removeEventListener('mouseleave', onLeave);
1165
+ if (moveRaf) cancelAnimationFrame(moveRaf);
1166
+ };
1167
+ }, [controlsOn, blockIdFromNode, blockAtPointerY]);
1168
+
1169
+ // Image-hover tracking (mouse) → drives the resize handle. Independent of the
1170
+ // blockControls hover/caret tracking above so the handle shows for ANY
1171
+ // previewable image, even in a toolbar-only composer (no blockControls/upload).
1172
+ // Gated on `usesShell` because the handle anchors into the shell — without a
1173
+ // shell there's nowhere to position it. Listens on the SHELL so reaching from
1174
+ // the image onto the handle (a shell child, outside the editable) keeps it alive.
1175
+ useEffect(() => {
1176
+ if (readOnly || !usesShell) return;
1177
+ const shell = shellRef.current;
1178
+ if (!shell) return;
1179
+ const onOver = (e: MouseEvent) => {
1180
+ if (draggingRef.current) return; // don't retarget mid-drag (block OR resize)
1181
+ const t = e.target as HTMLElement;
1182
+ const id = imageFigureIdAt(t);
1183
+ if (id) {
1184
+ setHoveredImageId(id);
1185
+ return;
1186
+ }
1187
+ // Over the handle itself → keep it alive (it sits at the image's corner,
1188
+ // just outside the figure, so it wouldn't match imageFigureIdAt).
1189
+ if (t.closest?.('[data-rte-resize-handle]')) return;
1190
+ setHoveredImageId(null); // over text/other content → clear
1191
+ };
1192
+ const onLeave = () => {
1193
+ if (!draggingRef.current) setHoveredImageId(null);
1194
+ };
1195
+ shell.addEventListener('mouseover', onOver);
1196
+ shell.addEventListener('mouseleave', onLeave);
1197
+ return () => {
1198
+ shell.removeEventListener('mouseover', onOver);
1199
+ shell.removeEventListener('mouseleave', onLeave);
1200
+ };
1201
+ }, [readOnly, usesShell, imageFigureIdAt]);
1202
+
1203
+ const onKeyDown = useCallback(
1204
+ (e: React.KeyboardEvent<HTMLDivElement>) => {
1205
+ if (readOnly) return;
1206
+ const root = rootRef.current;
1207
+ if (!root) return;
1208
+ // Undo/redo don't need a live selection — check them BEFORE the
1209
+ // readSelection guard so ⌘Z still works if the caret was lost. stopPropagation
1210
+ // keeps the shortcut from triggering a host app's undo. preventDefault
1211
+ // suppresses the browser's native contentEditable undo. We stamp the time so
1212
+ // the paired historyUndo/historyRedo beforeinput (emitted by this same
1213
+ // keydown) is skipped there rather than double-applied.
1214
+ const mod = e.metaKey || e.ctrlKey;
1215
+ if (mod && isLetterKey(e, 'z') && !e.shiftKey) {
1216
+ e.preventDefault();
1217
+ e.stopPropagation();
1218
+ historyKeyAtRef.current = Date.now();
1219
+ onUndo();
1220
+ return;
1221
+ }
1222
+ if (mod && (isLetterKey(e, 'y') || (isLetterKey(e, 'z') && e.shiftKey))) {
1223
+ e.preventDefault();
1224
+ e.stopPropagation();
1225
+ historyKeyAtRef.current = Date.now();
1226
+ onRedo();
1227
+ return;
1228
+ }
1229
+ const range = readSelection(root);
1230
+ if (!range) return;
1231
+ if (controlsOn) {
1232
+ const caretBlock = range.anchor.blockId;
1233
+ if (mod && e.shiftKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {
1234
+ e.preventDefault();
1235
+ e.stopPropagation();
1236
+ commit(moveBlockUnit(value, caretBlock, e.key === 'ArrowUp' ? -1 : 1), 'other');
1237
+ return;
1238
+ }
1239
+ if (mod && !e.shiftKey && isLetterKey(e, 'd')) {
1240
+ e.preventDefault();
1241
+ e.stopPropagation();
1242
+ commit(duplicateBlockUnit(value, caretBlock), 'other');
1243
+ return;
1244
+ }
1245
+ if ((e.shiftKey && e.key === 'F10') || e.key === 'ContextMenu') {
1246
+ e.preventDefault();
1247
+ // Clear hover so the menu binds to the caret block, not a stale hovered one.
1248
+ setHoverBlockId(null);
1249
+ setCaretBlockId(caretBlock);
1250
+ setBlockMenuOpen(true);
1251
+ return;
1252
+ }
1253
+ }
1254
+ // Caret INSIDE a void block's contentEditable=false figure (e.g. after a
1255
+ // doc-final image): browsers fire NO beforeinput there, only keydown, so
1256
+ // route the editing keys ourselves. Only for keys aimed at the editable —
1257
+ // an attachment's own Retry/Remove buttons keep theirs.
1258
+ const vcaret =
1259
+ e.target === root && isCollapsed(range) && !e.nativeEvent.isComposing
1260
+ ? voidCaretSide(root, range.anchor.blockId)
1261
+ : null;
1262
+ if (vcaret?.inside) {
1263
+ // A single character, not a shortcut. Ctrl+Alt is AltGr on Windows
1264
+ // (e.g. "@" on a German layout), so that still counts as typing.
1265
+ const printable = [...e.key].length === 1 && !e.metaKey && (!e.ctrlKey || e.altKey);
1266
+ if (printable) {
1267
+ e.preventDefault();
1268
+ const pend = takePendingAt(range.anchor);
1269
+ commit(
1270
+ pend
1271
+ ? insertWithMarks(value, range.anchor, e.key, pend)
1272
+ : insertText(value, range.anchor, e.key),
1273
+ 'type',
1274
+ );
1275
+ return;
1276
+ }
1277
+ if (!mod && e.key === 'Enter') {
1278
+ e.preventDefault();
1279
+ commit(applyInput(value, range, 'insertParagraph', null)!, 'other');
1280
+ return;
1281
+ }
1282
+ if (!mod && (e.key === 'Backspace' || e.key === 'Delete')) {
1283
+ e.preventDefault();
1284
+ const dir = e.key === 'Backspace' ? 'backward' : 'forward';
1285
+ applyVoidDelete(voidDelete(value, range.anchor.blockId, vcaret.side, dir));
1286
+ return;
1287
+ }
1288
+ }
1289
+ // Mention menu navigation takes priority over editor keys when open.
1290
+ if (mention.open && mention.items.length > 0) {
1291
+ if (e.key === 'ArrowDown') {
1292
+ e.preventDefault();
1293
+ mention.move(1);
1294
+ return;
1295
+ }
1296
+ if (e.key === 'ArrowUp') {
1297
+ e.preventDefault();
1298
+ mention.move(-1);
1299
+ return;
1300
+ }
1301
+ if (e.key === 'Enter' || e.key === 'Tab') {
1302
+ e.preventDefault();
1303
+ mention.commitActive();
1304
+ return;
1305
+ }
1306
+ }
1307
+ if (mention.open && e.key === 'Escape') {
1308
+ e.preventDefault();
1309
+ e.stopPropagation();
1310
+ mention.close();
1311
+ return;
1312
+ }
1313
+ // ⌘/Ctrl+K opens the link editor (create or edit a link). Stop
1314
+ // propagation so the shortcut doesn't ALSO trigger a host app's global
1315
+ // ⌘K (command palette / search) while the editor is focused.
1316
+ if ((e.metaKey || e.ctrlKey) && !e.shiftKey && isLetterKey(e, 'k')) {
1317
+ e.preventDefault();
1318
+ e.stopPropagation();
1319
+ openLinkEditor();
1320
+ return;
1321
+ }
1322
+
1323
+ const blockType = deriveCurrentBlock(value, range)?.type;
1324
+ const inList = blockType === 'bullet_item' || blockType === 'ordered_item';
1325
+
1326
+ // Tab / Shift+Tab indent/outdent — only inside a list, so Tab still
1327
+ // moves focus out of the editor everywhere else (keyboard a11y).
1328
+ if (e.key === 'Tab' && inList) {
1329
+ e.preventDefault();
1330
+ commit(runIndent(value, range, e.shiftKey ? 'out' : 'in'));
1331
+ return;
1332
+ }
1333
+
1334
+ // Enter in an EMPTY list item exits the list (→ paragraph).
1335
+ if (e.key === 'Enter' && inList && isCollapsed(range)) {
1336
+ const idx = value.blocks.findIndex((b) => b.id === range.anchor.blockId);
1337
+ if (idx !== -1 && blockLength(value.blocks[idx]) === 0) {
1338
+ e.preventDefault();
1339
+ commit(runSetBlock(value, range, { type: 'paragraph' }));
1340
+ return;
1341
+ }
1342
+ }
1343
+
1344
+ // Mark shortcut: with a collapsed caret, stage a pending mark for the
1345
+ // next typed text instead of a no-op toggle; with a selection, toggle it.
1346
+ const mark = shortcutMark(e);
1347
+ if (mark) {
1348
+ e.preventDefault();
1349
+ stageOrToggleMark(range, mark);
1350
+ return;
1351
+ }
1352
+ },
1353
+ [
1354
+ value,
1355
+ readOnly,
1356
+ commit,
1357
+ stageOrToggleMark,
1358
+ openLinkEditor,
1359
+ onUndo,
1360
+ onRedo,
1361
+ mention,
1362
+ controlsOn,
1363
+ takePendingAt,
1364
+ applyVoidDelete,
1365
+ ],
1366
+ );
1367
+
1368
+ // Snapshot at compositionstart — the last moment the DOM and the model agree:
1369
+ // the selection, and the anchor block's own DOM text (in model offsets).
1370
+ const compositionRef = useRef<{ range: Range; before: string } | null>(null);
1371
+ const onCompositionStart = useCallback(() => {
1372
+ isComposingRef.current = true;
1373
+ const root = rootRef.current;
1374
+ const range = root ? readSelection(root) : null;
1375
+ const before = range && root ? blockOwnText(root, range.anchor.blockId) : null;
1376
+ compositionRef.current = range && before != null ? { range, before } : null;
1377
+ }, []);
1378
+
1379
+ const onCompositionEnd = useCallback(
1380
+ (e: React.CompositionEvent<HTMLDivElement>) => {
1381
+ isComposingRef.current = false;
1382
+ const snap = compositionRef.current;
1383
+ compositionRef.current = null;
1384
+ const root = rootRef.current;
1385
+ if (readOnly || !root || !snap) return;
1386
+ const { range, before } = snap;
1387
+ // A selection across blocks: the browser merged them in the DOM, so a text
1388
+ // diff of one block can't see it — replace the captured range instead.
1389
+ if (range.anchor.blockId !== range.focus.blockId) {
1390
+ const result = applyInput(value, range, 'insertText', e.data);
1391
+ if (result) commit(result, 'type');
1392
+ return;
1393
+ }
1394
+ // The browser composed into the DOM ahead of the model. Diff the block's
1395
+ // own text before vs after (common prefix + suffix) to find exactly what
1396
+ // changed — no caret math, so an IME that recomposes an existing word
1397
+ // (Android Gboard), leaves the caret mid-word, or commits unchanged is
1398
+ // handled. The re-render then snaps the DOM back to the model.
1399
+ const blockId = range.anchor.blockId;
1400
+ const after = blockOwnText(root, blockId);
1401
+ if (after == null || after === before) return;
1402
+ // Cap the prefix at the composition start: in a repeated run ("ab" + "b")
1403
+ // the change can't begin after the caret it started from.
1404
+ const startCap = Math.min(range.anchor.offset, range.focus.offset);
1405
+ let pre = 0;
1406
+ while (pre < startCap && pre < after.length && before[pre] === after[pre]) pre += 1;
1407
+ // ...and the suffix at the end of the snapshot selection (it was replaced).
1408
+ const endCap = before.length - Math.max(range.anchor.offset, range.focus.offset);
1409
+ let suf = 0;
1410
+ while (
1411
+ suf < Math.min(endCap, before.length - pre) &&
1412
+ suf < after.length - pre &&
1413
+ before[before.length - 1 - suf] === after[after.length - 1 - suf]
1414
+ )
1415
+ suf += 1;
1416
+ const replaced: Range = {
1417
+ anchor: { blockId, offset: pre },
1418
+ focus: { blockId, offset: before.length - suf },
1419
+ };
1420
+ const inserted = after.slice(pre, after.length - suf);
1421
+ const result = inserted
1422
+ ? applyInput(value, replaced, 'insertText', inserted)
1423
+ : applyInput(value, replaced, 'deleteContentBackward', null);
1424
+ if (result) commit(result, 'type');
1425
+ },
1426
+ [value, readOnly, commit],
1427
+ );
1428
+
1429
+ // Active marks + current block derived from the live selection for the toolbar.
1430
+ const toolbarMarks = useMemo<MarkType[]>(
1431
+ () => (selection ? deriveActiveMarks(value, selection, pendingMarks) : []),
1432
+ [value, selection, pendingMarks],
1433
+ );
1434
+ const toolbarColors = useMemo(
1435
+ () => (selection ? deriveActiveColors(value, selection, pendingMarks) : {}),
1436
+ [value, selection, pendingMarks],
1437
+ );
1438
+ const toolbarBlock = useMemo<BlockChoice | null>(
1439
+ () => (selection ? deriveCurrentBlock(value, selection) : null),
1440
+ [value, selection],
1441
+ );
1442
+ const toolbarLinkActive = useMemo<boolean>(
1443
+ () => (selection ? linkAt(value, selection.focus) != null : false),
1444
+ [value, selection],
1445
+ );
1446
+
1447
+ // Toolbar dispatch — read the live selection (falling back to tracked state)
1448
+ // and route through the same commit path the keyboard uses. A mark at a
1449
+ // collapsed caret stages a pending mark, mirroring the keyboard shortcut.
1450
+ const onInsertEmoji = useCallback(
1451
+ (emoji: string) => {
1452
+ const root = rootRef.current;
1453
+ const range = (root ? readSelection(root) : null) ?? lastSelectionRef.current;
1454
+ if (!range) return;
1455
+ const result = applyInput(latest.current.value, range, 'insertText', emoji);
1456
+ if (result) {
1457
+ commit(result);
1458
+ root?.focus(); // keep the editor focused so typing continues after the pick
1459
+ }
1460
+ },
1461
+ [commit],
1462
+ );
1463
+
1464
+ const onToolbarMark = useCallback(
1465
+ (type: MarkType) => {
1466
+ // Value-carrying marks aren't plain toggles: link needs an href, mention an
1467
+ // id+label, textColor/bgColor a palette key — this toolbar path fires none.
1468
+ if (type === 'link' || type === 'mention' || type === 'textColor' || type === 'bgColor')
1469
+ return;
1470
+ const root = rootRef.current;
1471
+ // lastSelectionRef = last non-null selection; survives a toolbar popover taking focus
1472
+ const range = (root ? readSelection(root) : null) ?? lastSelectionRef.current;
1473
+ if (range) stageOrToggleMark(range, { type });
1474
+ },
1475
+ [stageOrToggleMark],
1476
+ );
1477
+ const onToolbarSetBlock = useCallback(
1478
+ (choice: BlockChoice) => {
1479
+ const root = rootRef.current;
1480
+ const range = (root ? readSelection(root) : null) ?? lastSelectionRef.current;
1481
+ if (range) commit(runSetBlock(latest.current.value, range, choice));
1482
+ },
1483
+ [commit],
1484
+ );
1485
+ const onToolbarToggleList = useCallback(
1486
+ (listType: 'bullet_item' | 'ordered_item') => {
1487
+ const root = rootRef.current;
1488
+ const range = (root ? readSelection(root) : null) ?? lastSelectionRef.current;
1489
+ if (range) commit(runToggleList(latest.current.value, range, listType));
1490
+ },
1491
+ [commit],
1492
+ );
1493
+
1494
+ const onPickFiles = useCallback(() => uploadInputRef.current?.click(), []);
1495
+
1496
+ const onBlockInsertBelow = useCallback(
1497
+ (id: string) => commit(insertEmptyBlockBelow(latest.current.value, id), 'other'),
1498
+ [commit],
1499
+ );
1500
+ const onBlockAction = useCallback(
1501
+ (id: string, action: BlockAction) => {
1502
+ const v = latest.current.value;
1503
+ switch (action) {
1504
+ case 'duplicate':
1505
+ commit(duplicateBlockUnit(v, id), 'other');
1506
+ break;
1507
+ case 'moveUp':
1508
+ commit(moveBlockUnit(v, id, -1), 'other');
1509
+ break;
1510
+ case 'moveDown':
1511
+ commit(moveBlockUnit(v, id, 1), 'other');
1512
+ break;
1513
+ case 'delete':
1514
+ commit(removeBlockUnit(v, id), 'other');
1515
+ break;
1516
+ default: {
1517
+ // Exhaustiveness: a new BlockAction must be handled above.
1518
+ const _never: never = action;
1519
+ return _never;
1520
+ }
1521
+ }
1522
+ setBlockMenuOpen(false);
1523
+ },
1524
+ [commit],
1525
+ );
1526
+ const onBlockTurnInto = useCallback(
1527
+ (id: string, choice: BlockChoice) => {
1528
+ const v = latest.current.value;
1529
+ const range = { anchor: { blockId: id, offset: 0 }, focus: { blockId: id, offset: 0 } };
1530
+ // "Turn into X" is an idempotent SET (not a toggle) on the single anchor
1531
+ // block — choosing the block's current type is a no-op, never a revert.
1532
+ // List types carry depth 0; runSetBlock routes both through setBlockType.
1533
+ const patch =
1534
+ choice.type === 'bullet_item' || choice.type === 'ordered_item'
1535
+ ? { type: choice.type, depth: 0 }
1536
+ : choice;
1537
+ commit(runSetBlock(v, range, patch), 'other');
1538
+ setBlockMenuOpen(false);
1539
+ },
1540
+ [commit],
1541
+ );
1542
+ const onBlockReorder = useCallback(
1543
+ (id: string, targetIndex: number) =>
1544
+ commit(moveBlockUnitToIndex(latest.current.value, id, targetIndex), 'other'),
1545
+ [commit],
1546
+ );
1547
+ // Whole-block color from the ⠿ menu's Color submenu. Colors the block's full
1548
+ // range via the shared setColorMark path, but commits with `keepSelection` so it
1549
+ // does NOT writeSelection: the block menu owns focus and stays open, and the block
1550
+ // isn't left visibly fully-selected after the pick.
1551
+ const onBlockColor = useCallback(
1552
+ (id: string, type: 'textColor' | 'bgColor', key: string | null) => {
1553
+ const r = wholeBlockRange(latest.current.value, id);
1554
+ if (r)
1555
+ commit({ doc: setColorMark(latest.current.value, r, type, key), selection: r }, 'other', {
1556
+ keepSelection: true,
1557
+ });
1558
+ },
1559
+ [commit],
1560
+ );
1561
+
1562
+ // Attachment config popover: open-state + alt/align/width/reset/replace
1563
+ // handlers (see useAttachmentConfig). The live-resize history coupling stays
1564
+ // in this file via `commitResizeLive`; the popover JSX (which derives the
1565
+ // configured block + anchor from render scope) is rendered below.
1566
+ const {
1567
+ configBlockId,
1568
+ onConfigOpen,
1569
+ onConfigClose,
1570
+ onConfigAlt,
1571
+ onConfigAlign,
1572
+ onConfigWidth,
1573
+ onConfigWidthReset,
1574
+ onConfigReplace,
1575
+ } = useAttachmentConfig({
1576
+ rootRef,
1577
+ commit,
1578
+ commitResizeLive,
1579
+ getValue,
1580
+ getLiveDoc,
1581
+ uploaderRef,
1582
+ });
1583
+ // Stable resize handler for the image resizer — keeps the memoized resizer from
1584
+ // re-rendering every keystroke on a fresh inline lambda. Targets the hovered
1585
+ // image; guards hoveredImageId so a late move after the hover clears is a no-op.
1586
+ const onImageResize = useCallback(
1587
+ (w: number) => {
1588
+ if (hoveredImageId) onConfigWidth(hoveredImageId, w);
1589
+ },
1590
+ [onConfigWidth, hoveredImageId],
1591
+ );
1592
+
1593
+ // Delegate clicks on the error-state attachment Retry/Remove buttons (they
1594
+ // carry data-attachment-action + data-block-id). On the editable so it works
1595
+ // in every return branch, including the toolbar-less bare-fragment path.
1596
+ const onEditableClick = useCallback((e: React.MouseEvent) => {
1597
+ if (latest.current.readOnly) return; // never mutate a read-only doc
1598
+ const el = (e.target as HTMLElement).closest?.('[data-attachment-action]');
1599
+ if (!el) return;
1600
+ const id = el.getAttribute('data-block-id');
1601
+ const action = el.getAttribute('data-attachment-action');
1602
+ if (!id) return;
1603
+ if (action === 'retry') uploaderRef.current.retry(id);
1604
+ else if (action === 'remove') uploaderRef.current.remove(id);
1605
+ }, []);
1606
+
1607
+ // The rendered doc tree is a pure fn of (value, renderLink, renderMention) — it
1608
+ // does NOT depend on selection/hover/focus. Memoize so the whole element tree is
1609
+ // not rebuilt on selection/hover/focus re-renders that leave the doc unchanged.
1610
+ const content = useMemo(
1611
+ () => renderDoc(value, { editable: true, renderLink, renderMention }),
1612
+ [value, renderLink, renderMention],
1613
+ );
1614
+ // Signature of block order. `value.blocks` is a new array on every edit, so this
1615
+ // recomputes per keystroke (a cheap join) — but the STRING is unchanged while
1616
+ // typing within a block, so the gutter (blockOrderKey) and the image resizer's
1617
+ // layoutKey keep their memoized shells stable.
1618
+ const blockOrderKey = useMemo(() => value.blocks.map((b) => b.id).join('|'), [value.blocks]);
1619
+
1620
+ const editable = (
1621
+ <div
1622
+ // {...rest} FIRST so the component's own role/aria/contentEditable/handlers
1623
+ // below win — the textbox contract must be preserved (Rule 7, Pattern B).
1624
+ // A consumer aria-label still flows in via the spread AND is read above to
1625
+ // decide whether to fall back to the i18n default.
1626
+ {...rest}
1627
+ ref={setRefs}
1628
+ style={imageMaxHeightStyle(imageMaxHeight, style)}
1629
+ className={clsx(
1630
+ styles.root,
1631
+ readOnly && styles.readOnly,
1632
+ controlsOn && styles.withGutter,
1633
+ className,
1634
+ )}
1635
+ contentEditable={!readOnly}
1636
+ suppressContentEditableWarning
1637
+ role="textbox"
1638
+ aria-multiline="true"
1639
+ aria-readonly={readOnly || undefined}
1640
+ aria-invalid={invalid || undefined}
1641
+ aria-required={required || undefined}
1642
+ // Mentions makes the textbox an editable combobox. role stays "textbox"
1643
+ // (ARIA combobox is single-line only; this editor is multiline), with
1644
+ // aria-autocomplete + aria-controls + aria-activedescendant describing the
1645
+ // popup. Gated so a readOnly or mention-less editor advertises no popup.
1646
+ aria-haspopup={mentions && !readOnly ? 'listbox' : undefined}
1647
+ aria-autocomplete={mentions && !readOnly ? 'list' : undefined}
1648
+ aria-expanded={mentions && !readOnly ? mention.open : undefined}
1649
+ aria-controls={mention.open ? mention.listboxId : undefined}
1650
+ aria-activedescendant={mention.open ? mention.activeOptionId : undefined}
1651
+ aria-label={
1652
+ rest['aria-label'] ||
1653
+ (rest['aria-labelledby'] ? undefined : t('richTextEditor.editorLabel'))
1654
+ }
1655
+ data-empty={isEmptyDoc(value) ? '' : undefined}
1656
+ data-placeholder={placeholder}
1657
+ spellCheck
1658
+ onKeyDown={onKeyDown}
1659
+ onClick={onEditableClick}
1660
+ onCompositionStart={onCompositionStart}
1661
+ onCompositionEnd={onCompositionEnd}
1662
+ // Only tracked for `toolbar="auto"` (gates the bar's visibility); omitted
1663
+ // otherwise so other modes never re-render on focus changes.
1664
+ onFocus={autoToolbar ? () => setFocused(true) : undefined}
1665
+ onBlur={autoToolbar ? () => setFocused(false) : undefined}
1666
+ >
1667
+ {content}
1668
+ </div>
1669
+ );
1670
+
1671
+ const linkBubble =
1672
+ linkEditor && !readOnly ? (
1673
+ <RichTextLinkEditor
1674
+ key={linkEditor.key}
1675
+ href={linkEditor.href}
1676
+ editing={linkEditor.editing}
1677
+ anchorRect={linkEditor.anchorRect}
1678
+ // Re-derive the anchor from the captured model range on each reposition so
1679
+ // the bubble tracks the line on scroll (the editor's live selection is
1680
+ // gone once the URL input takes focus, so re-measure the range, not it).
1681
+ getAnchorRect={() =>
1682
+ rootRef.current ? rangeRect(rootRef.current, linkEditor.range) : null
1683
+ }
1684
+ onApply={onLinkApply}
1685
+ onRemove={onLinkRemove}
1686
+ onCancel={onLinkCancel}
1687
+ />
1688
+ ) : null;
1689
+
1690
+ const mentionMenu =
1691
+ mention.open && !readOnly && mention.anchorRect ? (
1692
+ <RichTextMentionMenu
1693
+ items={mention.items}
1694
+ activeIndex={mention.activeIndex}
1695
+ anchorRect={mention.anchorRect}
1696
+ getAnchorRect={mention.getAnchorRect}
1697
+ listboxId={mention.listboxId}
1698
+ getOptionId={mention.getOptionId}
1699
+ label={t('richTextEditor.mentionsLabel')}
1700
+ emptyLabel={t('richTextEditor.mentionsEmpty')}
1701
+ onSelect={mention.selectIndex}
1702
+ onHover={mention.setActiveIndex}
1703
+ />
1704
+ ) : null;
1705
+
1706
+ const activeBlock = activeBlockId
1707
+ ? value.blocks.find((b) => b.id === activeBlockId)
1708
+ : undefined;
1709
+ const activeBlockType = activeBlock?.type;
1710
+ const canConfigure =
1711
+ uploadOn && activeBlock?.type === 'attachment' && isAttachmentSettled(activeBlock);
1712
+ const configBlock = configBlockId
1713
+ ? value.blocks.find((b) => b.id === configBlockId)
1714
+ : undefined;
1715
+ const blockControlsEl = controlsOn ? (
1716
+ <RichTextBlockControls
1717
+ rootRef={shellRef}
1718
+ activeBlockId={activeBlockId}
1719
+ blockOrderKey={blockOrderKey}
1720
+ activeBlockType={activeBlockType}
1721
+ menuOpen={blockMenuOpen}
1722
+ onMenuOpenChange={setBlockMenuOpen}
1723
+ onInsertBelow={onBlockInsertBelow}
1724
+ onAction={onBlockAction}
1725
+ onTurnInto={onBlockTurnInto}
1726
+ onReorder={onBlockReorder}
1727
+ onConfigure={canConfigure ? onConfigOpen : undefined}
1728
+ onColor={onBlockColor}
1729
+ onDraggingChange={onBlockDraggingChange}
1730
+ />
1731
+ ) : null;
1732
+
1733
+ // A bottom-right resize handle on the HOVERED previewable image — shown for any
1734
+ // previewable image (a safe, fetchable src that renders as <img>) on hover, as
1735
+ // long as the editor is editable and has a shell to anchor the handle in
1736
+ // (`usesShell`). Independent of blockControls/upload/active-block: a pasted image
1737
+ // in a toolbar-only composer gets a handle too. The keyboard-accessible Width
1738
+ // slider remains the a11y path where blockControls+upload are configured (the
1739
+ // Configure popover). The layoutKey carries the image's width so the handle
1740
+ // re-measures as it resizes; `hidden` hides it during a block reorder (it can't
1741
+ // track the in-place reflow), reappearing at the drop.
1742
+ const resizableImage = hoveredImageId
1743
+ ? value.blocks.find(
1744
+ (b) =>
1745
+ b.id === hoveredImageId &&
1746
+ b.type === 'attachment' &&
1747
+ // Settled = ready OR no status (a persisted/imported block drops its
1748
+ // transient status); mirrors the renderer's "ready-or-absent" displayable
1749
+ // rule so the handle can't drift from what's shown. See #263.
1750
+ isAttachmentSettled(b) &&
1751
+ attachmentIsImage(b) &&
1752
+ !!safeHref(b.src ?? ''),
1753
+ )
1754
+ : undefined;
1755
+ // Widest an image may be resized to: the content width, further limited so
1756
+ // its height stays within the display cap (#644) — the handle/slider stop
1757
+ // where the rendered image stops growing.
1758
+ const imageWidthMax = (id: string) => {
1759
+ const contentWidth = rootRef.current?.getBoundingClientRect().width ?? 600;
1760
+ const img = rootRef.current?.querySelector<HTMLImageElement>(
1761
+ `[data-block-id="${CSS.escape(id)}"] img`,
1762
+ );
1763
+ return img
1764
+ ? capWidthToHeight(
1765
+ contentWidth,
1766
+ img.naturalWidth,
1767
+ img.naturalHeight,
1768
+ parseFloat(getComputedStyle(img).maxHeight),
1769
+ )
1770
+ : contentWidth;
1771
+ };
1772
+ const imageResizerEl =
1773
+ !readOnly && usesShell && resizableImage ? (
1774
+ <RichTextImageResizer
1775
+ rootRef={shellRef}
1776
+ blockId={hoveredImageId!}
1777
+ layoutKey={`${blockOrderKey}:${resizableImage.width ?? ''}`}
1778
+ maxWidth={imageWidthMax(hoveredImageId!)}
1779
+ onResize={onImageResize}
1780
+ onDraggingChange={setDragging}
1781
+ hidden={blockDragging}
1782
+ />
1783
+ ) : null;
1784
+
1785
+ const configEl =
1786
+ configBlock &&
1787
+ configBlock.type === 'attachment' &&
1788
+ isAttachmentSettled(configBlock) &&
1789
+ uploadOn
1790
+ ? (() => {
1791
+ const figEl = rootRef.current?.querySelector<HTMLElement>(
1792
+ `[data-block-id="${CSS.escape(configBlock.id)}"]`,
1793
+ );
1794
+ const r = figEl?.getBoundingClientRect();
1795
+ if (!r) return null;
1796
+ return (
1797
+ <RichTextAttachmentConfig
1798
+ key={configBlock.id}
1799
+ block={configBlock}
1800
+ anchorRect={{ top: r.top, left: r.left, width: r.width, height: r.height }}
1801
+ getAnchorRect={() => {
1802
+ // Re-query the figure live so the popover tracks it on scroll.
1803
+ const el = rootRef.current?.querySelector<HTMLElement>(
1804
+ `[data-block-id="${CSS.escape(configBlock.id)}"]`,
1805
+ );
1806
+ if (!el) return null;
1807
+ const b = el.getBoundingClientRect();
1808
+ return { top: b.top, left: b.left, width: b.width, height: b.height };
1809
+ }}
1810
+ maxWidth={imageWidthMax(configBlock.id)}
1811
+ accept={latest.current.upload?.accept}
1812
+ onAltChange={(alt) => onConfigAlt(configBlock.id, alt)}
1813
+ onAlignChange={(align) => onConfigAlign(configBlock.id, align)}
1814
+ onWidthChange={(w) => onConfigWidth(configBlock.id, w)}
1815
+ onWidthReset={() => onConfigWidthReset(configBlock.id)}
1816
+ onReplace={(file) => onConfigReplace(configBlock.id, file)}
1817
+ onClose={onConfigClose}
1818
+ />
1819
+ );
1820
+ })()
1821
+ : null;
1822
+
1823
+ // Toolbar visibility. `true` → always; `'auto'` → focused, non-empty, or while
1824
+ // one of the editor's own overlays is open (so opening the link editor on a
1825
+ // focused-but-empty composer keeps the bar up rather than collapsing it). The
1826
+ // overlay term is what survives the blur caused by the overlay stealing focus.
1827
+ const overlayOpen = linkEditor != null || mention.open || toolbarOverlayOpen;
1828
+ const showToolbar =
1829
+ toolbar === true || (autoToolbar && (focused || !isEmptyDoc(value) || overlayOpen));
1830
+ // `usesShell` (the stable `.shell` gate) is declared near the top so the
1831
+ // image-hover effect can depend on it; it's reused here for the shell render.
1832
+
1833
+ const toolbarBar = showToolbar ? (
1834
+ <RichTextToolbar
1835
+ activeMarks={toolbarMarks}
1836
+ colors={toolbarColors}
1837
+ onSetColor={onSetColor}
1838
+ block={toolbarBlock}
1839
+ disabled={readOnly}
1840
+ onToggleMark={onToolbarMark}
1841
+ onSetBlock={onToolbarSetBlock}
1842
+ onToggleList={onToolbarToggleList}
1843
+ linkActive={toolbarLinkActive}
1844
+ onOpenLink={openLinkEditor}
1845
+ canUndo={canUndo}
1846
+ canRedo={canRedo}
1847
+ onUndo={onUndo}
1848
+ onRedo={onRedo}
1849
+ onPickFiles={uploadOn ? onPickFiles : undefined}
1850
+ onOverlayOpenChange={autoToolbar ? setToolbarOverlayOpen : undefined}
1851
+ onInsertEmoji={onInsertEmoji}
1852
+ />
1853
+ ) : null;
1854
+
1855
+ // The upload picker's input lives HERE, in the always-rendered shell, not in
1856
+ // the toolbar: a native file dialog blurs the editable, and under
1857
+ // `toolbar="auto"` on an empty doc that unmounts the bar — detaching the input
1858
+ // mid-pick, so its `change` never reaches React and the file is silently lost.
1859
+ const uploadInput = uploadOn ? (
1860
+ <input
1861
+ ref={uploadInputRef}
1862
+ type="file"
1863
+ multiple
1864
+ accept={upload?.accept}
1865
+ style={{ display: 'none' }}
1866
+ onChange={(e) => {
1867
+ const files = Array.from(e.target.files ?? []);
1868
+ if (files.length) uploaderRef.current.uploadFiles(files);
1869
+ e.target.value = ''; // allow re-picking the same file
1870
+ }}
1871
+ />
1872
+ ) : null;
1873
+
1874
+ // Always mounted while uploads are on, so only its text changes. Outside the
1875
+ // editable: inside the textbox it would join the document's content.
1876
+ const uploadStatus = uploadOn ? (
1877
+ <LiveRegion>
1878
+ {uploadFailure
1879
+ ? [`${t('richTextEditor.uploadFailed')}: ${uploadFailure.name}`, uploadFailure.reason]
1880
+ .filter(Boolean)
1881
+ .join('. ')
1882
+ : ''}
1883
+ </LiveRegion>
1884
+ ) : null;
1885
+
1886
+ if (!usesShell) {
1887
+ return (
1888
+ <>
1889
+ {uploadStatus}
1890
+ {editable}
1891
+ {linkBubble}
1892
+ {mentionMenu}
1893
+ </>
1894
+ );
1895
+ }
1896
+ return (
1897
+ <div className={styles.shell} ref={shellRef}>
1898
+ {toolbarBar}
1899
+ {uploadInput}
1900
+ {uploadStatus}
1901
+ {editable}
1902
+ {linkBubble}
1903
+ {mentionMenu}
1904
+ {blockControlsEl}
1905
+ {imageResizerEl}
1906
+ {configEl}
1907
+ </div>
1908
+ );
1909
+ },
1910
+ );