@flikk/ui 1.0.0-beta.31 → 1.0.0-beta.32

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 (428) hide show
  1. package/CHANGELOG.md +295 -22
  2. package/dist/components/ai/AgentRequest/AgentRequest.animations.d.ts +25 -0
  3. package/dist/components/ai/AgentRequest/AgentRequest.animations.js +81 -0
  4. package/dist/components/ai/AgentRequest/AgentRequest.d.ts +3 -0
  5. package/dist/components/ai/AgentRequest/AgentRequest.js +435 -0
  6. package/dist/components/ai/AgentRequest/AgentRequest.theme.d.ts +2 -0
  7. package/dist/components/ai/AgentRequest/AgentRequest.theme.js +106 -0
  8. package/dist/components/ai/AgentRequest/AgentRequest.types.d.ts +241 -0
  9. package/dist/components/ai/AgentRequest/index.d.ts +3 -0
  10. package/dist/components/ai/CodeBlock/CodeBlock.theme.js +1 -1
  11. package/dist/components/ai/PromptInput/PromptInput.js +2 -2
  12. package/dist/components/ai/PromptInput/PromptInput.theme.js +2 -2
  13. package/dist/components/ai/PromptSuggestion/PromptSuggestion.theme.js +2 -2
  14. package/dist/components/ai/Reasoning/Reasoning.js +27 -3
  15. package/dist/components/ai/Reasoning/Reasoning.theme.d.ts +6 -0
  16. package/dist/components/ai/Reasoning/Reasoning.theme.js +36 -0
  17. package/dist/components/ai/Reasoning/Reasoning.types.d.ts +58 -5
  18. package/dist/components/ai/Reasoning/ReasoningTrace.d.ts +11 -0
  19. package/dist/components/ai/Reasoning/ReasoningTrace.js +84 -0
  20. package/dist/components/ai/Reasoning/index.d.ts +2 -1
  21. package/dist/components/ai/StreamingResponse/AnimatedText.d.ts +7 -0
  22. package/dist/components/ai/StreamingResponse/AnimatedText.js +8 -7
  23. package/dist/components/ai/StreamingResponse/MarkdownRenderer.d.ts +5 -0
  24. package/dist/components/ai/StreamingResponse/MarkdownRenderer.js +4 -4
  25. package/dist/components/ai/StreamingResponse/StreamingCursor.d.ts +2 -2
  26. package/dist/components/ai/StreamingResponse/StreamingCursor.js +10 -7
  27. package/dist/components/ai/StreamingResponse/StreamingResponse.animations.d.ts +10 -0
  28. package/dist/components/ai/StreamingResponse/StreamingResponse.animations.js +59 -33
  29. package/dist/components/ai/StreamingResponse/StreamingResponse.js +13 -7
  30. package/dist/components/ai/StreamingResponse/StreamingResponse.types.d.ts +33 -2
  31. package/dist/components/ai/StreamingResponse/StreamingSurface.d.ts +13 -0
  32. package/dist/components/ai/StreamingResponse/StreamingSurface.js +38 -0
  33. package/dist/components/ai/StreamingResponse/WordAnimationContext.d.ts +5 -0
  34. package/dist/components/ai/StreamingResponse/WordAnimationContext.js +5 -4
  35. package/dist/components/ai/StreamingResponse/index.d.ts +4 -2
  36. package/dist/components/ai/TokenCounter/TokenCounter.theme.js +1 -1
  37. package/dist/components/ai/index.d.ts +3 -2
  38. package/dist/components/ai/index.js +4 -0
  39. package/dist/components/canvas/BaseNode.js +1 -1
  40. package/dist/components/canvas/CanvasToolbar.js +0 -1
  41. package/dist/components/canvas/Edge.js +2 -2
  42. package/dist/components/canvas/NodeControls.js +0 -1
  43. package/dist/components/canvas/NodeRenderer.js +2 -2
  44. package/dist/components/charts/ActivityRings/ActivityRings.js +2 -2
  45. package/dist/components/charts/ActivityRings/ActivityRings.theme.js +1 -1
  46. package/dist/components/charts/AreaChart/AreaChart.js +3 -3
  47. package/dist/components/charts/AreaChart/AreaChart.theme.js +3 -3
  48. package/dist/components/charts/BarChart/BarChart.js +4 -4
  49. package/dist/components/charts/ComboChart/BarRenderer.js +2 -2
  50. package/dist/components/charts/ComboChart/BarRenderer.types.d.ts +1 -1
  51. package/dist/components/charts/ComboChart/ComboChartCanvas.js +1 -1
  52. package/dist/components/charts/ComboChart/LineRenderer.js +1 -1
  53. package/dist/components/charts/ComboChart/LineRenderer.types.d.ts +1 -1
  54. package/dist/components/charts/DonutChart/DonutChart.theme.js +4 -4
  55. package/dist/components/charts/DonutChart/MultiSegmentDonutChart.theme.js +1 -1
  56. package/dist/components/charts/Heatmap/Heatmap.js +49 -42
  57. package/dist/components/charts/Heatmap/Heatmap.theme.d.ts +6 -2
  58. package/dist/components/charts/Heatmap/Heatmap.theme.js +20 -8
  59. package/dist/components/charts/Heatmap/Heatmap.types.d.ts +49 -82
  60. package/dist/components/charts/Heatmap/HeatmapCell.js +30 -81
  61. package/dist/components/charts/Heatmap/HeatmapLegend.d.ts +7 -6
  62. package/dist/components/charts/Heatmap/HeatmapLegend.js +6 -6
  63. package/dist/components/charts/Heatmap/index.d.ts +1 -1
  64. package/dist/components/charts/Heatmap/utils/heatmapUtils.d.ts +7 -12
  65. package/dist/components/charts/Heatmap/utils/heatmapUtils.js +16 -61
  66. package/dist/components/charts/Heatmap/utils/heatmapUtils.test.d.ts +1 -0
  67. package/dist/components/charts/HorizontalBarChart/HorizontalBarChart.js +1 -1
  68. package/dist/components/charts/LineChart/LineChart.js +2 -2
  69. package/dist/components/charts/LollipopChart/LollipopChart.js +1 -1
  70. package/dist/components/charts/RadarChart/RadarChart.js +1 -1
  71. package/dist/components/charts/StackedBarChart/StackedBarChart.js +3 -3
  72. package/dist/components/charts/hooks/useChartAccessibility.js +9 -6
  73. package/dist/components/charts/index.d.ts +4 -8
  74. package/dist/components/charts/index.js +2 -4
  75. package/dist/components/charts/shared/ChartText/ChartText.theme.js +1 -1
  76. package/dist/components/charts/shared/index.d.ts +1 -1
  77. package/dist/components/charts/theme/chart.theme.js +3 -3
  78. package/dist/components/charts/utils/animation-utils.d.ts +12 -7
  79. package/dist/components/charts/utils/animation-utils.js +19 -19
  80. package/dist/components/core/Accordion/Accordion.theme.js +1 -1
  81. package/dist/components/core/Alert/Alert.animations.d.ts +11 -4
  82. package/dist/components/core/Alert/Alert.animations.js +11 -4
  83. package/dist/components/core/Alert/Alert.js +16 -2
  84. package/dist/components/core/Alert/Alert.theme.js +1 -1
  85. package/dist/components/core/Alert/Alert.types.d.ts +4 -2
  86. package/dist/components/core/AlertDialog/AlertDialog.js +2 -2
  87. package/dist/components/core/Avatar/Avatar.theme.js +1 -1
  88. package/dist/components/core/Badge/Badge.animations.d.ts +0 -5
  89. package/dist/components/core/Badge/Badge.animations.js +5 -84
  90. package/dist/components/core/Badge/Badge.d.ts +7 -4
  91. package/dist/components/core/Badge/Badge.js +27 -64
  92. package/dist/components/core/Badge/Badge.theme.js +8 -12
  93. package/dist/components/core/Badge/Badge.types.d.ts +18 -34
  94. package/dist/components/core/Breadcrumbs/Breadcrumbs.theme.js +4 -4
  95. package/dist/components/core/Button/Button.js +7 -43
  96. package/dist/components/core/Button/Button.theme.js +2 -2
  97. package/dist/components/core/Button/Button.types.d.ts +8 -12
  98. package/dist/components/core/Button/index.d.ts +0 -2
  99. package/dist/components/core/Calendar/Calendar.theme.js +1 -1
  100. package/dist/components/core/Calendar/CalendarMini/CalendarMini.theme.js +2 -2
  101. package/dist/components/core/Card/Card.js +7 -2
  102. package/dist/components/core/Card/Card.theme.js +29 -1
  103. package/dist/components/core/Card/Card.types.d.ts +20 -0
  104. package/dist/components/core/Card/CardBody.js +9 -1
  105. package/dist/components/core/Card/CardContext.d.ts +13 -0
  106. package/dist/components/core/Card/CardContext.js +14 -0
  107. package/dist/components/core/Card/CardHeader.js +4 -1
  108. package/dist/components/core/ContextMenu/ContextMenu.theme.js +4 -3
  109. package/dist/components/core/ContextMenu/ContextMenu.types.d.ts +8 -1
  110. package/dist/components/core/ContextMenu/ContextMenuSub.d.ts +11 -1
  111. package/dist/components/core/ContextMenu/ContextMenuSub.js +35 -22
  112. package/dist/components/core/ContextMenu/ContextMenuSubBody.js +14 -3
  113. package/dist/components/core/ContextMenu/ContextMenuSubTrigger.js +21 -8
  114. package/dist/components/core/DragDrop/DragDrop.theme.js +2 -2
  115. package/dist/components/core/Drawer/Drawer.theme.js +1 -1
  116. package/dist/components/core/Drawer/DrawerHeader.js +0 -1
  117. package/dist/components/core/Dropdown/DropdownMenu.js +22 -7
  118. package/dist/components/core/Link/Link.js +1 -1
  119. package/dist/components/core/Masonry/Masonry.theme.js +1 -1
  120. package/dist/components/core/MenuItem/MenuItem.js +2 -1
  121. package/dist/components/core/MenuItem/MenuItem.theme.js +13 -1
  122. package/dist/components/core/Message/Message.js +2 -0
  123. package/dist/components/core/Message/Message.theme.js +3 -3
  124. package/dist/components/core/Modal/Modal.animations.d.ts +1 -1
  125. package/dist/components/core/Modal/Modal.animations.js +50 -11
  126. package/dist/components/core/Modal/Modal.js +5 -1
  127. package/dist/components/core/Modal/Modal.theme.js +1 -1
  128. package/dist/components/core/Modal/ModalHeader.js +0 -1
  129. package/dist/components/core/ModalStack/ModalStackModal.js +3 -1
  130. package/dist/components/core/NavItem/NavItem.js +3 -2
  131. package/dist/components/core/NavItem/NavItem.theme.js +1 -1
  132. package/dist/components/core/OfflineIndicator/OfflineIndicator.theme.js +4 -2
  133. package/dist/components/core/PageHeading/PageHeading.theme.js +1 -1
  134. package/dist/components/core/Pagination/Pagination.theme.js +2 -2
  135. package/dist/components/core/Pill/Pill.js +2 -1
  136. package/dist/components/core/Pill/Pill.theme.js +4 -2
  137. package/dist/components/core/Popover/PopoverBody.js +16 -5
  138. package/dist/components/core/Progress/Progress.d.ts +0 -25
  139. package/dist/components/core/Progress/Progress.js +79 -11
  140. package/dist/components/core/Progress/Progress.theme.js +17 -0
  141. package/dist/components/core/Progress/Progress.types.d.ts +47 -1
  142. package/dist/components/core/Rating/Rating.theme.js +1 -1
  143. package/dist/components/core/Rating/Rating.types.d.ts +3 -2
  144. package/dist/components/core/ScrollArea/ScrollArea.js +1 -1
  145. package/dist/components/core/ScrollArea/ScrollArea.theme.js +1 -1
  146. package/dist/components/core/Segmented/Segmented.theme.js +3 -3
  147. package/dist/components/core/Segmented/SegmentedContext.js +1 -0
  148. package/dist/components/core/Sidebar/Sidebar.js +5 -2
  149. package/dist/components/core/Sidebar/Sidebar.theme.js +2 -2
  150. package/dist/components/core/Sidebar/SidebarContent.js +1 -1
  151. package/dist/components/core/Sidebar/SidebarHeader.js +1 -1
  152. package/dist/components/core/Sidebar/SidebarSearch.js +2 -2
  153. package/dist/components/core/Sidebar/SidebarToggle.js +1 -1
  154. package/dist/components/core/Sidebar/SidebarUserProfile.js +1 -1
  155. package/dist/components/core/Sortable/Sortable.theme.js +1 -1
  156. package/dist/components/core/Tabs/Tabs.theme.js +1 -1
  157. package/dist/components/core/Tag/Tag.theme.js +1 -1
  158. package/dist/components/core/Toast/ToastProvider.js +1 -1
  159. package/dist/components/core/Tree/Tree.theme.js +1 -1
  160. package/dist/components/core/index.d.ts +0 -2
  161. package/dist/components/core/index.js +0 -4
  162. package/dist/components/core/shared/ChartTooltip/ChartTooltip.animations.d.ts +4 -0
  163. package/dist/components/core/shared/ChartTooltip/ChartTooltip.animations.js +20 -0
  164. package/dist/components/{charts → core}/shared/ChartTooltip/ChartTooltip.js +1 -1
  165. package/dist/components/core/shared/Ripple.d.ts +16 -0
  166. package/dist/components/core/shared/Ripple.js +141 -0
  167. package/dist/components/data-display/GanttChart/GanttChart.theme.js +6 -6
  168. package/dist/components/data-display/GanttChart/GanttTaskBar.js +1 -1
  169. package/dist/components/data-display/GanttChart/GanttTimelineHeader.js +1 -1
  170. package/dist/components/data-display/GanttChart/GanttToolbar.js +0 -1
  171. package/dist/components/data-display/KPI/KPI.js +11 -20
  172. package/dist/components/data-display/KPI/KPI.theme.js +8 -4
  173. package/dist/components/data-display/Metric/Metric.theme.js +4 -4
  174. package/dist/components/data-display/Table/Table.theme.js +2 -2
  175. package/dist/components/data-display/Table/TableColumnManager.js +1 -2
  176. package/dist/components/data-display/Table/TableContext.js +1 -0
  177. package/dist/components/data-display/Table/TableFilter.js +9 -2
  178. package/dist/components/data-display/Table/TableSelectionHeader.js +1 -1
  179. package/dist/components/data-display/Timeline/Timeline.theme.js +1 -1
  180. package/dist/components/effects/CustomCursor/CustomCursor.d.ts +1 -1
  181. package/dist/components/effects/CustomCursor/CustomCursor.js +1 -1
  182. package/dist/components/effects/CustomCursor/CustomCursor.theme.js +4 -4
  183. package/dist/components/effects/Neumorphic/InsetCircleButton.js +1 -1
  184. package/dist/components/effects/Overlay/Overlay.js +7 -3
  185. package/dist/components/effects/index.d.ts +0 -32
  186. package/dist/components/effects/index.js +0 -16
  187. package/dist/components/effects/shared/ShaderCanvas/ShaderCanvas.d.ts +0 -2
  188. package/dist/components/effects/shared/ShaderCanvas/ShaderCanvas.js +1 -93
  189. package/dist/components/effects/shared/ShaderCanvas/ShaderCanvas.types.d.ts +0 -10
  190. package/dist/components/effects/shared/ShaderCanvas/index.d.ts +1 -1
  191. package/dist/components/effects/shared/index.d.ts +1 -3
  192. package/dist/components/effects/shared/shaderNoise.glsl.d.ts +1 -1
  193. package/dist/components/effects/shared/shaderNoise.glsl.js +2 -11
  194. package/dist/components/forms/Checkbox/Checkbox.theme.js +1 -1
  195. package/dist/components/forms/ColorPicker/ColorPickerHeader.js +1 -1
  196. package/dist/components/forms/ColorPicker/ColorPickerImage.js +1 -1
  197. package/dist/components/forms/Combobox/Combobox.js +2 -0
  198. package/dist/components/forms/DateRangePicker/DateRangePicker.theme.js +1 -1
  199. package/dist/components/forms/DateRangePicker/DateRangePickerContext.js +1 -0
  200. package/dist/components/forms/FileUpload/FileUpload.theme.js +2 -2
  201. package/dist/components/forms/FileUpload/FileUploadProgress.theme.js +1 -1
  202. package/dist/components/forms/InputAddress/InputAddress.types.d.ts +2 -2
  203. package/dist/components/forms/Radio/Radio.theme.js +1 -1
  204. package/dist/components/forms/RichTextEditor/RichTextEditor.d.ts +12 -16
  205. package/dist/components/forms/RichTextEditor/RichTextEditor.js +165 -1680
  206. package/dist/components/forms/RichTextEditor/RichTextEditor.theme.d.ts +12 -56
  207. package/dist/components/forms/RichTextEditor/RichTextEditor.theme.js +60 -118
  208. package/dist/components/forms/RichTextEditor/RichTextEditor.types.d.ts +62 -126
  209. package/dist/components/forms/RichTextEditor/RichTextLinkField.d.ts +18 -0
  210. package/dist/components/forms/RichTextEditor/RichTextLinkField.js +46 -0
  211. package/dist/components/forms/RichTextEditor/RichTextToolbar.d.ts +15 -0
  212. package/dist/components/forms/RichTextEditor/RichTextToolbar.js +93 -0
  213. package/dist/components/forms/RichTextEditor/editorCommands.d.ts +50 -0
  214. package/dist/components/forms/RichTextEditor/editorCommands.js +58 -0
  215. package/dist/components/forms/RichTextEditor/editorState.d.ts +19 -0
  216. package/dist/components/forms/RichTextEditor/editorState.js +103 -0
  217. package/dist/components/forms/RichTextEditor/index.d.ts +5 -3
  218. package/dist/components/forms/RichTextEditor/sanitizeHtml.d.ts +38 -0
  219. package/dist/components/forms/RichTextEditor/sanitizeHtml.js +179 -0
  220. package/dist/components/forms/RichTextEditor/sanitizeHtml.test.d.ts +1 -0
  221. package/dist/components/forms/Select/Select.js +4 -4
  222. package/dist/components/forms/Select/Select.types.d.ts +70 -7
  223. package/dist/components/forms/Select/useSelectState.d.ts +9 -3
  224. package/dist/components/forms/Select/useSelectState.js +4 -1
  225. package/dist/components/forms/SelectableCard/SelectableCard.js +2 -1
  226. package/dist/components/forms/SelectableCard/SelectableCard.theme.js +1 -1
  227. package/dist/components/forms/Switch/Switch.theme.js +2 -2
  228. package/dist/components/forms/TimePicker/TimePicker.theme.js +1 -1
  229. package/dist/components/forms/TimePicker/TimePickerTrigger.js +1 -1
  230. package/dist/components/forms/forms.theme.js +19 -5
  231. package/dist/components/forms/index.js +1 -0
  232. package/dist/components/generative/FormShell.d.ts +22 -0
  233. package/dist/components/generative/FormShell.js +102 -0
  234. package/dist/components/generative/GenerativeView.d.ts +52 -1
  235. package/dist/components/generative/GenerativeView.js +203 -11
  236. package/dist/components/generative/actions.d.ts +5 -0
  237. package/dist/components/generative/ai-sdk/index.d.ts +1 -0
  238. package/dist/components/generative/ai-sdk/index.js +1 -0
  239. package/dist/components/generative/ai-sdk/useGenerativeChat.d.ts +52 -0
  240. package/dist/components/generative/ai-sdk/useGenerativeChat.js +73 -0
  241. package/dist/components/generative/ai-sdk/useGenerativeChat.test.d.ts +1 -0
  242. package/dist/components/generative/fieldBinding.d.ts +31 -0
  243. package/dist/components/generative/fieldBinding.js +33 -0
  244. package/dist/components/generative/fieldBinding.test.d.ts +1 -0
  245. package/dist/components/generative/formScope.d.ts +71 -0
  246. package/dist/components/generative/formScope.js +135 -0
  247. package/dist/components/generative/index.d.ts +4 -0
  248. package/dist/components/generative/index.js +4 -0
  249. package/dist/components/generative/registry.d.ts +2 -0
  250. package/dist/components/generative/registry.js +10 -10
  251. package/dist/components/generative/schema.generated.js +178 -292
  252. package/dist/components/generative/toToolResult.d.ts +21 -0
  253. package/dist/components/generative/toToolResult.js +15 -0
  254. package/dist/components/generative/toToolResult.test.d.ts +1 -0
  255. package/dist/components/generative/validate.d.ts +10 -1
  256. package/dist/components/generative/validate.js +126 -11
  257. package/dist/components/layout/Grid/Grid.js +1 -0
  258. package/dist/components/layout/Section/Section.theme.js +1 -1
  259. package/dist/components/layout/Stack/Stack.js +1 -0
  260. package/dist/generative.schema.json +178 -292
  261. package/dist/index.js +1 -4
  262. package/dist/registry.json +2599 -2375
  263. package/dist/shadcn-compat.css +5 -5
  264. package/dist/styles/theme.test.d.ts +1 -0
  265. package/dist/styles.css +1 -1
  266. package/dist/test/render.d.ts +17 -0
  267. package/dist/themes/precision.css +232 -0
  268. package/dist/tools.json +179 -294
  269. package/dist/utils/index.d.ts +0 -1
  270. package/package.json +31 -1
  271. package/src/global.scss +21 -28
  272. package/src/styles/theme.css +124 -41
  273. package/src/styles/theme.test.ts +119 -0
  274. package/tailwind.preset.cjs +30 -20
  275. package/dist/components/charts/FunnelChart/FunnelChart.animations.d.ts +0 -35
  276. package/dist/components/charts/FunnelChart/FunnelChart.animations.js +0 -59
  277. package/dist/components/charts/FunnelChart/FunnelChart.d.ts +0 -8
  278. package/dist/components/charts/FunnelChart/FunnelChart.js +0 -410
  279. package/dist/components/charts/FunnelChart/FunnelChart.theme.d.ts +0 -2
  280. package/dist/components/charts/FunnelChart/FunnelChart.theme.js +0 -12
  281. package/dist/components/charts/FunnelChart/FunnelChart.types.d.ts +0 -105
  282. package/dist/components/charts/FunnelChart/index.d.ts +0 -4
  283. package/dist/components/charts/ScatterPlot/ScatterPlot.d.ts +0 -9
  284. package/dist/components/charts/ScatterPlot/ScatterPlot.js +0 -208
  285. package/dist/components/charts/ScatterPlot/ScatterPlot.theme.d.ts +0 -18
  286. package/dist/components/charts/ScatterPlot/ScatterPlot.theme.js +0 -42
  287. package/dist/components/charts/ScatterPlot/ScatterPlot.types.d.ts +0 -60
  288. package/dist/components/charts/ScatterPlot/ScatterPlot.types.js +0 -19
  289. package/dist/components/charts/ScatterPlot/index.d.ts +0 -3
  290. package/dist/components/core/Button/Button.ripple.d.ts +0 -71
  291. package/dist/components/core/Button/Button.ripple.js +0 -236
  292. package/dist/components/core/Calendar/CalendarEvent/CalendarEvent.d.ts +0 -4
  293. package/dist/components/core/Calendar/CalendarEvent/CalendarEvent.theme.d.ts +0 -12
  294. package/dist/components/core/Calendar/CalendarEvent/CalendarEvent.types.d.ts +0 -23
  295. package/dist/components/core/Calendar/CalendarEvent/index.d.ts +0 -2
  296. package/dist/components/core/CardStack/CardStack.animations.d.ts +0 -47
  297. package/dist/components/core/CardStack/CardStack.d.ts +0 -3
  298. package/dist/components/core/CardStack/CardStack.js +0 -187
  299. package/dist/components/core/CardStack/CardStack.theme.d.ts +0 -6
  300. package/dist/components/core/CardStack/CardStack.theme.js +0 -33
  301. package/dist/components/core/CardStack/CardStack.types.d.ts +0 -139
  302. package/dist/components/core/CardStack/index.d.ts +0 -7
  303. package/dist/components/core/Carousel/Carousel.d.ts +0 -3
  304. package/dist/components/core/Carousel/Carousel.js +0 -83
  305. package/dist/components/core/Carousel/Carousel.theme.d.ts +0 -10
  306. package/dist/components/core/Carousel/Carousel.theme.js +0 -20
  307. package/dist/components/core/Carousel/Carousel.types.d.ts +0 -113
  308. package/dist/components/core/Carousel/CarouselBody.d.ts +0 -4
  309. package/dist/components/core/Carousel/CarouselBody.js +0 -59
  310. package/dist/components/core/Carousel/CarouselContext.d.ts +0 -3
  311. package/dist/components/core/Carousel/CarouselContext.js +0 -13
  312. package/dist/components/core/Carousel/CarouselItem.d.ts +0 -4
  313. package/dist/components/core/Carousel/CarouselItem.js +0 -11
  314. package/dist/components/core/Carousel/CarouselNext.d.ts +0 -4
  315. package/dist/components/core/Carousel/CarouselNext.js +0 -16
  316. package/dist/components/core/Carousel/CarouselPrevious.d.ts +0 -4
  317. package/dist/components/core/Carousel/CarouselPrevious.js +0 -16
  318. package/dist/components/core/Carousel/index.d.ts +0 -3
  319. package/dist/components/effects/ColorPanels/ColorPanels.d.ts +0 -8
  320. package/dist/components/effects/ColorPanels/ColorPanels.js +0 -66
  321. package/dist/components/effects/ColorPanels/ColorPanels.shaders.d.ts +0 -12
  322. package/dist/components/effects/ColorPanels/ColorPanels.shaders.js +0 -218
  323. package/dist/components/effects/ColorPanels/ColorPanels.types.d.ts +0 -29
  324. package/dist/components/effects/ColorPanels/ColorPanels.types.js +0 -3
  325. package/dist/components/effects/ColorPanels/index.d.ts +0 -2
  326. package/dist/components/effects/FlutedGlass/FlutedGlass.d.ts +0 -9
  327. package/dist/components/effects/FlutedGlass/FlutedGlass.js +0 -80
  328. package/dist/components/effects/FlutedGlass/FlutedGlass.shaders.d.ts +0 -12
  329. package/dist/components/effects/FlutedGlass/FlutedGlass.shaders.js +0 -335
  330. package/dist/components/effects/FlutedGlass/FlutedGlass.types.d.ts +0 -61
  331. package/dist/components/effects/FlutedGlass/FlutedGlass.types.js +0 -16
  332. package/dist/components/effects/FlutedGlass/index.d.ts +0 -3
  333. package/dist/components/effects/GlassEffect/GlassEffect.d.ts +0 -15
  334. package/dist/components/effects/GlassEffect/GlassEffect.js +0 -38
  335. package/dist/components/effects/GlassEffect/GlassEffect.types.d.ts +0 -19
  336. package/dist/components/effects/GlassEffect/index.d.ts +0 -2
  337. package/dist/components/effects/GlassSurface/GlassSurface.d.ts +0 -8
  338. package/dist/components/effects/GlassSurface/GlassSurface.js +0 -250
  339. package/dist/components/effects/GlassSurface/GlassSurface.types.d.ts +0 -66
  340. package/dist/components/effects/GlassSurface/index.d.ts +0 -2
  341. package/dist/components/effects/GodRays/GodRays.d.ts +0 -8
  342. package/dist/components/effects/GodRays/GodRays.js +0 -68
  343. package/dist/components/effects/GodRays/GodRays.shaders.d.ts +0 -10
  344. package/dist/components/effects/GodRays/GodRays.shaders.js +0 -128
  345. package/dist/components/effects/GodRays/GodRays.types.d.ts +0 -25
  346. package/dist/components/effects/GodRays/GodRays.types.js +0 -3
  347. package/dist/components/effects/GodRays/index.d.ts +0 -2
  348. package/dist/components/effects/GridPattern/GridPattern.d.ts +0 -18
  349. package/dist/components/effects/GridPattern/GridPattern.js +0 -65
  350. package/dist/components/effects/GridPattern/GridPattern.types.d.ts +0 -47
  351. package/dist/components/effects/GridPattern/index.d.ts +0 -2
  352. package/dist/components/effects/HalftoneCmyk/HalftoneCmyk.d.ts +0 -10
  353. package/dist/components/effects/HalftoneCmyk/HalftoneCmyk.js +0 -78
  354. package/dist/components/effects/HalftoneCmyk/HalftoneCmyk.shaders.d.ts +0 -22
  355. package/dist/components/effects/HalftoneCmyk/HalftoneCmyk.shaders.js +0 -239
  356. package/dist/components/effects/HalftoneCmyk/HalftoneCmyk.types.d.ts +0 -52
  357. package/dist/components/effects/HalftoneCmyk/index.d.ts +0 -2
  358. package/dist/components/effects/HalftoneDots/HalftoneDots.d.ts +0 -9
  359. package/dist/components/effects/HalftoneDots/HalftoneDots.js +0 -68
  360. package/dist/components/effects/HalftoneDots/HalftoneDots.shaders.d.ts +0 -13
  361. package/dist/components/effects/HalftoneDots/HalftoneDots.shaders.js +0 -296
  362. package/dist/components/effects/HalftoneDots/HalftoneDots.types.d.ts +0 -43
  363. package/dist/components/effects/HalftoneDots/HalftoneDots.types.js +0 -12
  364. package/dist/components/effects/HalftoneDots/index.d.ts +0 -3
  365. package/dist/components/effects/ImageDithering/ImageDithering.d.ts +0 -9
  366. package/dist/components/effects/ImageDithering/ImageDithering.js +0 -68
  367. package/dist/components/effects/ImageDithering/ImageDithering.shaders.d.ts +0 -12
  368. package/dist/components/effects/ImageDithering/ImageDithering.shaders.js +0 -117
  369. package/dist/components/effects/ImageDithering/ImageDithering.types.d.ts +0 -30
  370. package/dist/components/effects/ImageDithering/ImageDithering.types.js +0 -8
  371. package/dist/components/effects/ImageDithering/index.d.ts +0 -3
  372. package/dist/components/effects/MagneticElement/MagneticElement.d.ts +0 -30
  373. package/dist/components/effects/MagneticElement/MagneticElement.js +0 -111
  374. package/dist/components/effects/MagneticElement/MagneticElement.types.d.ts +0 -44
  375. package/dist/components/effects/MagneticElement/index.d.ts +0 -2
  376. package/dist/components/effects/Metaballs/Metaballs.d.ts +0 -8
  377. package/dist/components/effects/Metaballs/Metaballs.js +0 -59
  378. package/dist/components/effects/Metaballs/Metaballs.shaders.d.ts +0 -10
  379. package/dist/components/effects/Metaballs/Metaballs.shaders.js +0 -102
  380. package/dist/components/effects/Metaballs/Metaballs.types.d.ts +0 -16
  381. package/dist/components/effects/Metaballs/Metaballs.types.js +0 -3
  382. package/dist/components/effects/Metaballs/index.d.ts +0 -2
  383. package/dist/components/effects/PaperTexture/PaperTexture.d.ts +0 -9
  384. package/dist/components/effects/PaperTexture/PaperTexture.js +0 -61
  385. package/dist/components/effects/PaperTexture/PaperTexture.shaders.d.ts +0 -22
  386. package/dist/components/effects/PaperTexture/PaperTexture.shaders.js +0 -145
  387. package/dist/components/effects/PaperTexture/PaperTexture.types.d.ts +0 -19
  388. package/dist/components/effects/PaperTexture/index.d.ts +0 -2
  389. package/dist/components/effects/PulsingBorder/PulsingBorder.d.ts +0 -27
  390. package/dist/components/effects/PulsingBorder/PulsingBorder.js +0 -174
  391. package/dist/components/effects/PulsingBorder/PulsingBorder.shaders.d.ts +0 -14
  392. package/dist/components/effects/PulsingBorder/PulsingBorder.shaders.js +0 -258
  393. package/dist/components/effects/PulsingBorder/PulsingBorder.types.d.ts +0 -75
  394. package/dist/components/effects/PulsingBorder/PulsingBorder.types.js +0 -3
  395. package/dist/components/effects/PulsingBorder/index.d.ts +0 -2
  396. package/dist/components/effects/SmokeRing/SmokeRing.d.ts +0 -8
  397. package/dist/components/effects/SmokeRing/SmokeRing.js +0 -62
  398. package/dist/components/effects/SmokeRing/SmokeRing.shaders.d.ts +0 -14
  399. package/dist/components/effects/SmokeRing/SmokeRing.shaders.js +0 -130
  400. package/dist/components/effects/SmokeRing/SmokeRing.types.d.ts +0 -22
  401. package/dist/components/effects/SmokeRing/SmokeRing.types.js +0 -3
  402. package/dist/components/effects/SmokeRing/index.d.ts +0 -2
  403. package/dist/components/effects/StaticGradientMesh/StaticGradientMesh.d.ts +0 -9
  404. package/dist/components/effects/StaticGradientMesh/StaticGradientMesh.js +0 -59
  405. package/dist/components/effects/StaticGradientMesh/StaticGradientMesh.shaders.d.ts +0 -14
  406. package/dist/components/effects/StaticGradientMesh/StaticGradientMesh.shaders.js +0 -129
  407. package/dist/components/effects/StaticGradientMesh/StaticGradientMesh.types.d.ts +0 -23
  408. package/dist/components/effects/StaticGradientMesh/StaticGradientMesh.types.js +0 -3
  409. package/dist/components/effects/StaticGradientMesh/index.d.ts +0 -2
  410. package/dist/components/effects/Water/Water.d.ts +0 -9
  411. package/dist/components/effects/Water/Water.js +0 -65
  412. package/dist/components/effects/Water/Water.shaders.d.ts +0 -11
  413. package/dist/components/effects/Water/Water.shaders.js +0 -123
  414. package/dist/components/effects/Water/Water.types.d.ts +0 -25
  415. package/dist/components/effects/Water/index.d.ts +0 -2
  416. package/dist/components/effects/shared/bayerMatrices.glsl.d.ts +0 -10
  417. package/dist/components/effects/shared/bayerMatrices.glsl.js +0 -44
  418. package/dist/components/effects/shared/imageUV.glsl.d.ts +0 -12
  419. package/dist/components/effects/shared/imageUV.glsl.js +0 -26
  420. package/dist/components/forms/RichTextEditor/RichTextEditor.animations.d.ts +0 -7
  421. package/dist/components/forms/RichTextEditor/RichTextEditor.animations.js +0 -32
  422. package/dist/utils/calendarUtils.d.ts +0 -60
  423. /package/dist/components/{charts → core}/shared/ChartTooltip/ChartTooltip.d.ts +0 -0
  424. /package/dist/components/{charts → core}/shared/ChartTooltip/ChartTooltip.theme.d.ts +0 -0
  425. /package/dist/components/{charts → core}/shared/ChartTooltip/ChartTooltip.theme.js +0 -0
  426. /package/dist/components/{charts → core}/shared/ChartTooltip/ChartTooltip.types.d.ts +0 -0
  427. /package/dist/components/{charts → core}/shared/ChartTooltip/ChartTooltipContent.d.ts +0 -0
  428. /package/dist/components/{charts → core}/shared/ChartTooltip/index.d.ts +0 -0
@@ -1,1715 +1,200 @@
1
1
  "use client";
2
2
  import { jsxs, jsx } from 'react/jsx-runtime';
3
- import React__default, { useState, useCallback, useRef, useMemo, useEffect } from 'react';
4
- import { createPortal } from 'react-dom';
5
- import { useReducedMotion, AnimatePresence, motion } from 'motion/react';
3
+ import React__default, { useRef, useId, useState, useCallback, useEffect } from 'react';
6
4
  import { FormLabel } from '../FormLabel/FormLabel.js';
7
- import { MONO_COLORS, TAILWIND_COLOR_FAMILIES, getTailwindShadeTokens, richTextEditorTheme, resolveTailwindColor } from './RichTextEditor.theme.js';
8
- import { floatingToolbarVariants } from './RichTextEditor.animations.js';
9
5
  import { cn } from '../../../utils/cn.js';
10
- import { Button } from '../../core/Button/Button.js';
11
- import { ScrollArea } from '../../core/ScrollArea/ScrollArea.js';
12
- import '../../core/ScrollArea/smooth/SmoothScrollEngine.js';
13
- import { ArrowUUpRight, ArrowUUpLeft, TextAlignRight, List, TextAlignLeft, PaintBrush, ArrowsLeftRight, ArrowsDownUp, TextB, TextUnderline, TextItalic } from '@phosphor-icons/react';
14
- import { useSelectPortal } from '../../../hooks/useSelectPortal.js';
15
- import { createDropdownAnimations } from '../Select/Select.animations.js';
16
- import { useIsClient } from '../../../hooks/useIsClient.js';
17
- import { useSurfaceElevation, SurfaceProvider, surfaceClasses } from '../../../theme/SurfaceContext.js';
6
+ import { richTextEditorTheme } from './RichTextEditor.theme.js';
7
+ import { DEFAULT_TOOLBAR_TOOLS, RichTextToolbar } from './RichTextToolbar.js';
8
+ import { RichTextLinkField } from './RichTextLinkField.js';
9
+ import { sanitizeHtml } from './sanitizeHtml.js';
10
+ import { EMPTY_FORMATTING_STATE, readFormattingState } from './editorState.js';
11
+ import { redo, undo, clearFormatting, toggleCodeBlock, toggleBlockquote, toggleOrderedList, toggleBulletList, toggleStrikethrough, toggleUnderline, toggleItalic, toggleBold, setBlockStyle, insertSanitizedHtml, insertText, createLink, removeLink } from './editorCommands.js';
18
12
 
19
- const FONT_SIZE_OPTIONS = [
20
- { key: "xs", label: "XS", value: "0.75rem", px: 12, className: "text-xs" },
21
- { key: "sm", label: "SM", value: "0.875rem", px: 14, className: "text-sm" },
22
- { key: "md", label: "MD", value: "1rem", px: 16, className: "text-base" },
23
- { key: "lg", label: "LG", value: "1.125rem", px: 18, className: "text-lg" },
24
- { key: "xl", label: "XL", value: "1.25rem", px: 20, className: "text-xl" },
25
- { key: "2xl", label: "2XL", value: "1.5rem", px: 24, className: "text-2xl" },
26
- { key: "3xl", label: "3XL", value: "1.875rem", px: 30, className: "text-3xl" },
27
- { key: "4xl", label: "4XL", value: "2.25rem", px: 36, className: "text-4xl" },
28
- { key: "5xl", label: "5XL", value: "3rem", px: 48, className: "text-5xl" },
29
- { key: "6xl", label: "6XL", value: "3.75rem", px: 60, className: "text-6xl" },
30
- { key: "7xl", label: "7XL", value: "4.5rem", px: 72, className: "text-7xl" },
31
- { key: "8xl", label: "8XL", value: "6rem", px: 96, className: "text-8xl" },
32
- { key: "9xl", label: "9XL", value: "8rem", px: 128, className: "text-9xl" },
33
- ];
34
- /** All font-size class names — used to scrub stale classes when swapping. */
35
- const FONT_SIZE_CLASSES = FONT_SIZE_OPTIONS.map((o) => o.className);
36
- const getFontSizeOption = (key) => { var _a; return (_a = FONT_SIZE_OPTIONS.find((option) => option.key === key)) !== null && _a !== void 0 ? _a : FONT_SIZE_OPTIONS[2]; };
37
- const getClosestFontSizeKey = (px) => {
38
- let closest = "md";
39
- let minDiff = Number.POSITIVE_INFINITY;
40
- FONT_SIZE_OPTIONS.forEach((option) => {
41
- const diff = Math.abs(option.px - px);
42
- if (diff < minDiff) {
43
- minDiff = diff;
44
- closest = option.key;
45
- }
46
- });
47
- return closest;
48
- };
49
- /**
50
- * Curated default list of font families shipped with the editor.
51
- * The `Default` entry clears the inline font-family. The rest are popular
52
- * Google Fonts chosen for broad weight coverage. Each stack ends in a sensible
53
- * fallback so text stays readable while the font is loading.
54
- */
55
- const DEFAULT_FONT_FAMILY_OPTIONS = [
56
- { key: "default", label: "Default", stack: "" },
57
- { key: "inter", label: "Inter", family: "Inter", stack: "'Inter', system-ui, sans-serif" },
58
- { key: "roboto", label: "Roboto", family: "Roboto", stack: "'Roboto', system-ui, sans-serif" },
59
- { key: "manrope", label: "Manrope", family: "Manrope", stack: "'Manrope', system-ui, sans-serif" },
60
- { key: "poppins", label: "Poppins", family: "Poppins", stack: "'Poppins', system-ui, sans-serif" },
61
- { key: "lora", label: "Lora", family: "Lora", stack: "'Lora', Georgia, serif" },
62
- { key: "playfair", label: "Playfair Display", family: "Playfair Display", stack: "'Playfair Display', Georgia, serif" },
63
- { key: "merriweather", label: "Merriweather", family: "Merriweather", stack: "'Merriweather', Georgia, serif" },
64
- { key: "jetbrains", label: "JetBrains Mono", family: "JetBrains Mono", stack: "'JetBrains Mono', Menlo, monospace" },
65
- ];
66
- // Bumped when migrating from raw hex values to Tailwind shade tokens
67
- // (e.g. "rose-500"). Old hex entries from prior versions are ignored — the
68
- // picker now applies color via `text-{token}` classes, not via execCommand.
69
- const RECENT_COLORS_KEY = "flikkui-rte-recent-colors-v2";
70
- const RECENT_COLORS_LIMIT = 10;
71
- const DEFAULT_FONT_WEIGHT_REQUEST = [100, 200, 300, 400, 500, 600, 700, 800, 900];
72
- const loadedGoogleFonts = new Set();
73
13
  /**
74
- * Lazily injects a Google Fonts `<link rel="stylesheet">` for the given family.
75
- * Idempotent: each family is requested at most once per page lifetime.
76
- * SSR-safe (no-ops when `document` is undefined).
14
+ * RichTextEditor a semantic authoring surface over `contentEditable`.
77
15
  *
78
- * @example
79
- * import { loadGoogleFont } from "@flikk/ui";
80
- * loadGoogleFont("Inter");
81
- */
82
- const loadGoogleFont = (family, weights = DEFAULT_FONT_WEIGHT_REQUEST) => {
83
- if (typeof document === "undefined")
84
- return;
85
- if (!family)
86
- return;
87
- const cacheKey = `${family}:${weights.join(",")}`;
88
- if (loadedGoogleFonts.has(cacheKey))
89
- return;
90
- loadedGoogleFonts.add(cacheKey);
91
- const familyParam = family.replace(/\s+/g, "+");
92
- const weightsParam = weights.length > 0 ? `:wght@${weights.join(";")}` : "";
93
- const href = `https://fonts.googleapis.com/css2?family=${familyParam}${weightsParam}&display=swap`;
94
- const link = document.createElement("link");
95
- link.rel = "stylesheet";
96
- link.href = href;
97
- link.setAttribute("data-flikkui-font", family);
98
- document.head.appendChild(link);
99
- };
100
- const FONT_WEIGHT_OPTIONS = [
101
- { key: "thin", label: "Thin", value: "100", weight: 100, className: "font-thin" },
102
- { key: "extralight", label: "Extra Light", value: "200", weight: 200, className: "font-extralight" },
103
- { key: "light", label: "Light", value: "300", weight: 300, className: "font-light" },
104
- { key: "normal", label: "Regular", value: "400", weight: 400, className: "font-normal" },
105
- { key: "medium", label: "Medium", value: "500", weight: 500, className: "font-medium" },
106
- { key: "semibold", label: "Semibold", value: "600", weight: 600, className: "font-semibold" },
107
- { key: "bold", label: "Bold", value: "700", weight: 700, className: "font-bold" },
108
- { key: "extrabold", label: "Extra Bold", value: "800", weight: 800, className: "font-extrabold" },
109
- { key: "black", label: "Black", value: "900", weight: 900, className: "font-black" },
110
- ];
111
- const FONT_WEIGHT_CLASSES = FONT_WEIGHT_OPTIONS.map((o) => o.className);
112
- const getFontWeightOption = (key) => { var _a; return (_a = FONT_WEIGHT_OPTIONS.find((option) => option.key === key)) !== null && _a !== void 0 ? _a : FONT_WEIGHT_OPTIONS[3]; };
113
- const getClosestFontWeightKey = (weight) => {
114
- let closest = "normal";
115
- let minDiff = Number.POSITIVE_INFINITY;
116
- FONT_WEIGHT_OPTIONS.forEach((option) => {
117
- const diff = Math.abs(option.weight - weight);
118
- if (diff < minDiff) {
119
- minDiff = diff;
120
- closest = option.key;
121
- }
122
- });
123
- return closest;
124
- };
125
- const LINE_HEIGHT_OPTIONS = [
126
- { key: "tight", label: "Tight", value: "1.25", className: "leading-tight" },
127
- { key: "snug", label: "Snug", value: "1.375", className: "leading-snug" },
128
- { key: "normal", label: "Normal", value: "1.5", className: "leading-normal" },
129
- { key: "relaxed", label: "Relaxed", value: "1.625", className: "leading-relaxed" },
130
- { key: "loose", label: "Loose", value: "2", className: "leading-loose" },
131
- ];
132
- const LINE_HEIGHT_CLASSES = LINE_HEIGHT_OPTIONS.map((o) => o.className);
133
- const getLineHeightOption = (key) => { var _a; return (_a = LINE_HEIGHT_OPTIONS.find((option) => option.key === key)) !== null && _a !== void 0 ? _a : LINE_HEIGHT_OPTIONS[2]; };
134
- const LETTER_SPACING_OPTIONS = [
135
- { key: "tighter", label: "Tighter", value: "-0.05em", em: -0.05, className: "tracking-tighter" },
136
- { key: "tight", label: "Tight", value: "-0.025em", em: -0.025, className: "tracking-tight" },
137
- { key: "normal", label: "Normal", value: "0em", em: 0, className: "tracking-normal" },
138
- { key: "wide", label: "Wide", value: "0.025em", em: 0.025, className: "tracking-wide" },
139
- { key: "wider", label: "Wider", value: "0.05em", em: 0.05, className: "tracking-wider" },
140
- { key: "widest", label: "Widest", value: "0.1em", em: 0.1, className: "tracking-widest" },
141
- ];
142
- const LETTER_SPACING_CLASSES = LETTER_SPACING_OPTIONS.map((o) => o.className);
143
- /**
144
- * Every text-color class the picker can apply: `text-white`, `text-black`,
145
- * and `text-{family}-{shade}` for each Tailwind family/shade. Used both to
146
- * apply the new color and to scrub stale color classes off ancestor wrappers.
147
- * Derived once at module load — list size is static.
16
+ * Produces portable HTML (`<h2>`, `<strong>`, `<ul>`, `<a href>`) with no
17
+ * framework classes, so stored content renders anywhere. Formatting is applied
18
+ * through `editorCommands.ts` (the only `execCommand` caller) and read back
19
+ * through `editorState.ts`.
20
+ *
21
+ * 🔴 Every write path is sanitized: the `value` prop, paste, drop, and the string
22
+ * handed to `onChange` — the last regardless of whether `onChange` was passed, so
23
+ * an uncontrolled editor is not a hole.
24
+ *
25
+ * 🔴 Per §9, `className`, `ref` and `...rest` target the contentEditable surface.
148
26
  */
149
- const TEXT_COLOR_CLASSES = [
150
- ...MONO_COLORS.map((c) => `text-${c.token}`),
151
- ...TAILWIND_COLOR_FAMILIES.flatMap((family) => getTailwindShadeTokens(family).map((token) => `text-${token}`)),
152
- ];
153
- /** Returns the active text-color token (e.g. `"rose-500"`) walking up from the
154
- * given element, or `""` if no `text-{token}` class is found before the editor
155
- * boundary. */
156
- const matchTextColorClass = (el, editor) => {
157
- let n = el;
158
- while (n && n !== editor) {
159
- for (let i = 0; i < n.classList.length; i++) {
160
- const cls = n.classList.item(i);
161
- if (cls && TEXT_COLOR_CLASSES.includes(cls))
162
- return cls.slice("text-".length);
163
- }
164
- n = n.parentElement;
165
- }
166
- return "";
167
- };
168
- const getLetterSpacingOption = (key) => { var _a; return (_a = LETTER_SPACING_OPTIONS.find((option) => option.key === key)) !== null && _a !== void 0 ? _a : LETTER_SPACING_OPTIONS[2]; };
169
- const DEFAULT_FORMATTING_STATE = {
170
- bold: false,
171
- italic: false,
172
- underline: false,
173
- textAlign: "left",
174
- fontSize: "md",
175
- fontWeight: "normal",
176
- fontFamily: "default",
177
- lineHeight: "normal",
178
- letterSpacing: "normal",
179
- // Token like "rose-500" / "white" / "black"; "" means inherit (no class
180
- // applied). The picker now applies color via `text-{token}` classes
181
- // rather than execCommand("foreColor"), so the state holds tokens.
182
- textColor: "",
183
- };
184
- const DEFAULT_TOOLBAR = {
185
- show: true,
186
- position: "top",
187
- tools: [
188
- "fontWeight",
189
- "italic",
190
- "underline",
191
- "separator",
192
- "fontFamily",
193
- "fontSize",
194
- "lineHeight",
195
- "letterSpacing",
196
- "textColor",
197
- "separator",
198
- "alignLeft",
199
- "alignCenter",
200
- "alignRight",
201
- "separator",
202
- "undo",
203
- "redo",
204
- ],
205
- };
206
- const RichTextEditor = React__default.forwardRef(({ size = "md", state = "default", className = "", label, labelClassName = "", helperText, errorMessage, helperTextClassName = "", value = "", onChange, placeholder = "Start typing...", id, required, minHeight = 120, maxHeight, toolbar: toolbarProp = DEFAULT_TOOLBAR, theme = {}, fontFamilies = DEFAULT_FONT_FAMILY_OPTIONS, loadFontsOnDemand = true, sanitize, elevation, lift, ...props }, ref) => {
207
- // Relative elevation: the floating toolbar (bubble menu) and the toolbar
208
- // dropdowns lift above their host surface (overlay base = 5) so an editor
209
- // inside a Popover/Modal still reads its floating chrome as a higher plane.
210
- const surfaceLevel = useSurfaceElevation({ baseRung: 5, offset: 2, elevation, lift });
211
- const [isFocused, setIsFocused] = useState(false);
212
- const [showToolbar, setShowToolbar] = useState(false);
213
- const [toolbarPosition, setToolbarPosition] = useState({ top: 0, left: 0 });
214
- const [formattingState, setFormattingState] = useState(DEFAULT_FORMATTING_STATE);
215
- const [showFontSizePicker, setShowFontSizePicker] = useState(false);
216
- const [showFontWeightPicker, setShowFontWeightPicker] = useState(false);
217
- const [showFontFamilyPicker, setShowFontFamilyPicker] = useState(false);
218
- const [showLineHeightPicker, setShowLineHeightPicker] = useState(false);
219
- const [showLetterSpacingPicker, setShowLetterSpacingPicker] = useState(false);
220
- const [showColorPicker, setShowColorPicker] = useState(false);
221
- // Recently used text colors — persisted to localStorage so they survive reloads.
222
- const [recentColors, setRecentColors] = useState(() => {
223
- if (typeof window === "undefined")
224
- return [];
225
- try {
226
- const stored = window.localStorage.getItem(RECENT_COLORS_KEY);
227
- if (!stored)
228
- return [];
229
- const parsed = JSON.parse(stored);
230
- return Array.isArray(parsed)
231
- ? parsed.filter((v) => typeof v === "string").slice(0, RECENT_COLORS_LIMIT)
232
- : [];
233
- }
234
- catch (_a) {
235
- return [];
236
- }
237
- });
238
- const addRecentColor = useCallback((token) => {
239
- if (!token)
240
- return;
241
- setRecentColors((prev) => {
242
- const next = [token, ...prev.filter((c) => c !== token)].slice(0, RECENT_COLORS_LIMIT);
243
- if (typeof window !== "undefined") {
244
- try {
245
- window.localStorage.setItem(RECENT_COLORS_KEY, JSON.stringify(next));
246
- }
247
- catch (_a) {
248
- // localStorage unavailable (private mode, quota exceeded, etc.) — ignore.
249
- }
250
- }
251
- return next;
252
- });
253
- }, []);
254
- const shouldReduceMotion = useReducedMotion();
255
- const isClient = useIsClient();
256
- // Built-in basic sanitizer: strips <script> tags and on* event handlers
257
- const sanitizeHtml = useCallback((html) => {
258
- if (sanitize)
259
- return sanitize(html);
260
- // Basic sanitization — strips script tags and inline event handlers
261
- return html
262
- .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
263
- .replace(/\bon\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '');
264
- }, [sanitize]);
27
+ const RichTextEditor = React__default.forwardRef(({ size = "md", state = "default", label, helperText, errorMessage, value, onChange, placeholder, className, wrapperClassName, containerClassName, toolbarClassName, labelClassName, helperTextClassName, required = false, minHeight = 160, maxHeight, toolbar, theme: themeOverrides, sanitize, ...rest }, ref) => {
28
+ var _a;
29
+ const theme = { ...richTextEditorTheme, ...themeOverrides };
265
30
  const editorRef = useRef(null);
266
- const toolbarRef = useRef(null);
267
- const fontSizeTriggerRef = useRef(null);
268
- const fontWeightTriggerRef = useRef(null);
269
- const fontFamilyTriggerRef = useRef(null);
270
- const lineHeightTriggerRef = useRef(null);
271
- const letterSpacingTriggerRef = useRef(null);
272
- const colorTriggerRef = useRef(null);
273
- // Single linear history covering ALL mutations: typing, execCommand
274
- // (bold/italic/foreColor/justify/…), and direct-DOM style ops. Typing is
275
- // coalesced into one undo entry per ~500 ms run, so users get coarse-grained
276
- // word-level undo instead of per-keystroke. Discrete style ops always start
277
- // a fresh entry by passing kind='op'.
278
- const historyRef = useRef({ undo: [], redo: [], lastPushKind: null, lastPushAt: 0 });
279
- const HISTORY_LIMIT = 100;
280
- const TYPING_COALESCE_MS = 500;
281
- const pushHistory = useCallback((kind = "op") => {
282
- if (!editorRef.current)
283
- return;
284
- const now = Date.now();
285
- const stack = historyRef.current;
286
- // Coalesce successive typing events into a single undo entry while the
287
- // user is mid-word. Skip when the previous push was also typing AND it
288
- // happened recently — the existing entry already represents this group.
289
- if (kind === "typing" &&
290
- stack.lastPushKind === "typing" &&
291
- now - stack.lastPushAt < TYPING_COALESCE_MS) {
292
- stack.lastPushAt = now;
293
- // Any new mutation still invalidates the redo stack.
294
- stack.redo = [];
295
- return;
296
- }
297
- stack.undo.push(editorRef.current.innerHTML);
298
- stack.redo = [];
299
- stack.lastPushKind = kind;
300
- stack.lastPushAt = now;
301
- if (stack.undo.length > HISTORY_LIMIT)
302
- stack.undo.shift();
303
- }, []);
304
- const generatedId = React__default.useId();
305
- const editorId = id || generatedId;
306
- const themeStyles = useMemo(() => {
307
- var _a, _b;
308
- return ({
309
- ...richTextEditorTheme,
310
- ...theme,
311
- sizes: {
312
- ...richTextEditorTheme.sizes,
313
- ...((_a = theme === null || theme === void 0 ? void 0 : theme.sizes) !== null && _a !== void 0 ? _a : {}),
314
- },
315
- states: {
316
- ...richTextEditorTheme.states,
317
- ...((_b = theme === null || theme === void 0 ? void 0 : theme.states) !== null && _b !== void 0 ? _b : {}),
318
- },
319
- });
320
- }, [theme]);
321
- const toolbarConfig = useMemo(() => {
322
- var _a, _b, _c;
323
- const base = {
324
- show: (_a = DEFAULT_TOOLBAR.show) !== null && _a !== void 0 ? _a : true,
325
- position: (_b = DEFAULT_TOOLBAR.position) !== null && _b !== void 0 ? _b : "top",
326
- tools: [...((_c = DEFAULT_TOOLBAR.tools) !== null && _c !== void 0 ? _c : [])],
327
- className: DEFAULT_TOOLBAR.className,
328
- };
329
- if (toolbarProp) {
330
- if (typeof toolbarProp.show === "boolean") {
331
- base.show = toolbarProp.show;
332
- }
333
- if (toolbarProp.position) {
334
- base.position = toolbarProp.position;
335
- }
336
- if (toolbarProp.tools) {
337
- base.tools = [...toolbarProp.tools];
338
- }
339
- if (typeof toolbarProp.className === "string") {
340
- base.className = toolbarProp.className;
341
- }
342
- }
343
- return base;
344
- }, [toolbarProp]);
345
- const { position: fontSizePortalPosition, cssVariables: fontSizePortalCssVars, contentRef: fontSizePortalContentRef, isReady: fontSizePortalReady, isFlipped: fontSizeIsFlipped, } = useSelectPortal({
346
- triggerRef: fontSizeTriggerRef,
347
- isOpen: showFontSizePicker,
348
- placement: "bottom-start",
349
- offset: 6,
350
- autoWidth: true,
351
- });
352
- const { position: fontWeightPortalPosition, cssVariables: fontWeightPortalCssVars, contentRef: fontWeightPortalContentRef, isReady: fontWeightPortalReady, isFlipped: fontWeightIsFlipped, } = useSelectPortal({
353
- triggerRef: fontWeightTriggerRef,
354
- isOpen: showFontWeightPicker,
355
- placement: "bottom-start",
356
- offset: 6,
357
- autoWidth: true,
358
- });
359
- const { position: fontFamilyPortalPosition, cssVariables: fontFamilyPortalCssVars, contentRef: fontFamilyPortalContentRef, isReady: fontFamilyPortalReady, isFlipped: fontFamilyIsFlipped, } = useSelectPortal({
360
- triggerRef: fontFamilyTriggerRef,
361
- isOpen: showFontFamilyPicker,
362
- placement: "bottom-start",
363
- offset: 6,
364
- autoWidth: true,
365
- });
366
- const { position: lineHeightPortalPosition, cssVariables: lineHeightPortalCssVars, contentRef: lineHeightPortalContentRef, isReady: lineHeightPortalReady, isFlipped: lineHeightIsFlipped, } = useSelectPortal({
367
- triggerRef: lineHeightTriggerRef,
368
- isOpen: showLineHeightPicker,
369
- placement: "bottom-start",
370
- offset: 6,
371
- autoWidth: true,
372
- });
373
- const { position: letterSpacingPortalPosition, cssVariables: letterSpacingPortalCssVars, contentRef: letterSpacingPortalContentRef, isReady: letterSpacingPortalReady, isFlipped: letterSpacingIsFlipped, } = useSelectPortal({
374
- triggerRef: letterSpacingTriggerRef,
375
- isOpen: showLetterSpacingPicker,
376
- placement: "bottom-start",
377
- offset: 6,
378
- autoWidth: true,
379
- });
380
- const { position: colorPortalPosition, cssVariables: colorPortalCssVars, contentRef: colorPortalContentRef, isReady: colorPortalReady, isFlipped: colorIsFlipped, } = useSelectPortal({
381
- triggerRef: colorTriggerRef,
382
- isOpen: showColorPicker,
383
- placement: "bottom-start",
384
- offset: 6,
385
- autoWidth: true,
386
- });
31
+ const generatedId = useId();
32
+ const describedById = `${generatedId}-description`;
387
33
  const isDisabled = state === "disabled";
388
34
  const isInvalid = state === "invalid";
389
- // errorMessage takes precedence over helperText while invalid; helperText
390
- // behavior is unchanged otherwise.
391
- const displayedMessage = isInvalid && errorMessage ? errorMessage : helperText;
392
- const messageId = `${editorId}-message`;
393
- const getDataState = () => {
394
- if (isDisabled)
395
- return "disabled";
396
- if (isInvalid)
397
- return "invalid";
398
- if (isFocused)
399
- return "focus";
400
- return "default";
401
- };
402
- const focusEditor = useCallback(() => {
403
- if (editorRef.current && document.activeElement !== editorRef.current) {
404
- editorRef.current.focus();
405
- }
406
- }, []);
407
- const closeAllPickers = useCallback(() => {
408
- setShowFontSizePicker(false);
409
- setShowFontWeightPicker(false);
410
- setShowFontFamilyPicker(false);
411
- setShowLineHeightPicker(false);
412
- setShowLetterSpacingPicker(false);
413
- setShowColorPicker(false);
414
- }, []);
415
- const togglePicker = useCallback((which) => {
416
- setShowFontSizePicker((prev) => (which === "fontSize" ? !prev : false));
417
- setShowFontWeightPicker((prev) => (which === "fontWeight" ? !prev : false));
418
- setShowFontFamilyPicker((prev) => (which === "fontFamily" ? !prev : false));
419
- setShowLineHeightPicker((prev) => (which === "lineHeight" ? !prev : false));
420
- setShowLetterSpacingPicker((prev) => (which === "letterSpacing" ? !prev : false));
421
- setShowColorPicker((prev) => (which === "color" ? !prev : false));
422
- }, []);
423
- const getCurrentFontSize = useCallback(() => {
424
- if (!editorRef.current)
425
- return DEFAULT_FORMATTING_STATE.fontSize;
426
- const selection = window.getSelection();
427
- let node = null;
428
- if (selection && selection.rangeCount > 0) {
429
- node = selection.getRangeAt(0).startContainer;
430
- if (node && node.nodeType === Node.TEXT_NODE)
431
- node = node.parentElement;
432
- }
433
- // Walk up looking for a `text-*` class (the size classes also bundle a
434
- // matching line-height — that's why class-based size is reliable).
435
- while (node && node !== editorRef.current) {
436
- if (node instanceof HTMLElement) {
437
- const match = FONT_SIZE_OPTIONS.find((o) => node && node.classList.contains(o.className));
438
- if (match)
439
- return match.key;
440
- }
441
- node = node ? node.parentNode : null;
442
- }
443
- // No explicit class found — fall back to the editor's computed font-size
444
- // mapped to the closest preset. Handles initial/no-selection state.
445
- const editorComputed = window.getComputedStyle(editorRef.current);
446
- const editorSize = parseFloat(editorComputed.fontSize || "");
447
- return Number.isFinite(editorSize)
448
- ? getClosestFontSizeKey(editorSize)
449
- : DEFAULT_FORMATTING_STATE.fontSize;
450
- }, []);
451
- const getCurrentFontFamily = useCallback(() => {
452
- if (!editorRef.current)
453
- return "default";
454
- const selection = window.getSelection();
455
- let element = null;
456
- if (selection && selection.rangeCount > 0) {
457
- let node = selection.getRangeAt(0).startContainer;
458
- if (node && node.nodeType === Node.TEXT_NODE)
459
- node = node.parentElement;
460
- if (node instanceof HTMLElement)
461
- element = node;
462
- }
463
- while (element && editorRef.current.contains(element)) {
464
- const inline = element.style.fontFamily;
465
- if (inline) {
466
- // Match against the first family in the inline stack
467
- const firstFamily = inline.split(",")[0].trim().replace(/^['"]|['"]$/g, "");
468
- const match = fontFamilies.find((opt) => {
469
- if (!opt.family)
470
- return false;
471
- return opt.family.toLowerCase() === firstFamily.toLowerCase();
472
- });
473
- if (match)
474
- return match.key;
475
- }
476
- element = element.parentElement;
477
- }
478
- return "default";
479
- }, [fontFamilies]);
480
- const getCurrentFontWeight = useCallback(() => {
35
+ const [formatting, setFormatting] = useState(EMPTY_FORMATTING_STATE);
36
+ const [isLinkFieldOpen, setLinkFieldOpen] = useState(false);
37
+ const [isEmpty, setIsEmpty] = useState(true);
38
+ // The Range as of the last selection inside the editor. The block <Select>
39
+ // takes focus when opened, which collapses the selection — restoring this
40
+ // before a command is what lets focusable toolbar widgets (which cannot use
41
+ // the preventDefault trick) still act on the user's text.
42
+ const savedRangeRef = useRef(null);
43
+ const sanitizeFn = useCallback((html) => (sanitize ? sanitize(html) : sanitizeHtml(html)), [sanitize]);
44
+ const saveSelection = useCallback(() => {
481
45
  var _a;
482
- if (!editorRef.current)
483
- return DEFAULT_FORMATTING_STATE.fontWeight;
484
- const selection = window.getSelection();
485
- let node = null;
486
- if (selection && selection.rangeCount > 0) {
487
- node = selection.getRangeAt(0).startContainer;
488
- if (node && node.nodeType === Node.TEXT_NODE)
489
- node = node.parentElement;
490
- }
491
- while (node && node !== editorRef.current) {
492
- if (node instanceof HTMLElement) {
493
- const match = FONT_WEIGHT_OPTIONS.find((o) => node && node.classList.contains(o.className));
494
- if (match)
495
- return match.key;
496
- }
497
- node = node ? node.parentNode : null;
498
- }
499
- // Fallback: read computed font-weight (covers <strong>/<b> tags from
500
- // the Bold toggle which produce semantic markup, not classes).
501
- const target = (_a = (selection && selection.rangeCount > 0
502
- ? (selection.getRangeAt(0).startContainer instanceof HTMLElement
503
- ? selection.getRangeAt(0).startContainer
504
- : selection.getRangeAt(0).startContainer.parentElement)
505
- : null)) !== null && _a !== void 0 ? _a : editorRef.current;
506
- const computed = window.getComputedStyle(target);
507
- const weight = parseInt(computed.fontWeight, 10);
508
- return Number.isFinite(weight)
509
- ? getClosestFontWeightKey(weight)
510
- : DEFAULT_FORMATTING_STATE.fontWeight;
511
- }, []);
512
- const getCurrentLineHeight = useCallback(() => {
513
- if (!editorRef.current)
514
- return DEFAULT_FORMATTING_STATE.lineHeight;
515
- const selection = window.getSelection();
516
- let element = null;
517
- if (selection && selection.rangeCount > 0) {
518
- let node = selection.getRangeAt(0).startContainer;
519
- if (node && node.nodeType === Node.TEXT_NODE)
520
- node = node.parentElement;
521
- if (node instanceof HTMLElement)
522
- element = node;
523
- }
524
- while (element && editorRef.current.contains(element)) {
525
- const match = LINE_HEIGHT_OPTIONS.find((o) => element && element.classList.contains(o.className));
526
- if (match)
527
- return match.key;
528
- element = element.parentElement;
529
- }
530
- return DEFAULT_FORMATTING_STATE.lineHeight;
531
- }, []);
532
- const getCurrentLetterSpacing = useCallback(() => {
533
- if (!editorRef.current)
534
- return DEFAULT_FORMATTING_STATE.letterSpacing;
535
- const selection = window.getSelection();
536
- let element = null;
537
- if (selection && selection.rangeCount > 0) {
538
- let node = selection.getRangeAt(0).startContainer;
539
- if (node && node.nodeType === Node.TEXT_NODE)
540
- node = node.parentElement;
541
- if (node instanceof HTMLElement)
542
- element = node;
543
- }
544
- while (element && editorRef.current.contains(element)) {
545
- const match = LETTER_SPACING_OPTIONS.find((o) => element && element.classList.contains(o.className));
546
- if (match)
547
- return match.key;
548
- element = element.parentElement;
549
- }
550
- return DEFAULT_FORMATTING_STATE.letterSpacing;
551
- }, []);
552
- const updateFormattingState = useCallback(() => {
553
- if (!editorRef.current || isDisabled) {
554
- setFormattingState(DEFAULT_FORMATTING_STATE);
555
- return;
556
- }
557
- let bold = false;
558
- let italic = false;
559
- let underline = false;
560
- let textAlign = "left";
561
- let fontSize = DEFAULT_FORMATTING_STATE.fontSize;
562
- let fontWeight = DEFAULT_FORMATTING_STATE.fontWeight;
563
- let fontFamily = DEFAULT_FORMATTING_STATE.fontFamily;
564
- let lineHeight = DEFAULT_FORMATTING_STATE.lineHeight;
565
- let letterSpacing = DEFAULT_FORMATTING_STATE.letterSpacing;
566
- let textColor = DEFAULT_FORMATTING_STATE.textColor;
567
- // Bold is class-driven — the toolbar Bold button and Weight=Bold
568
- // dropdown share `font-bold`, so we walk class ancestors and only fall
569
- // back to computed font-weight when no class is found (covers legacy
570
- // <strong>/<b> tags from pasted content).
571
- try {
572
- const sel = window.getSelection();
573
- let startEl = null;
574
- if (sel && sel.rangeCount > 0) {
575
- let node = sel.getRangeAt(0).startContainer;
576
- if (node && node.nodeType === Node.TEXT_NODE)
577
- node = node.parentElement;
578
- if (node instanceof HTMLElement)
579
- startEl = node;
580
- }
581
- const boldClasses = ["font-bold", "font-extrabold", "font-black"];
582
- const notBoldClasses = ["font-thin", "font-extralight", "font-light", "font-normal", "font-medium", "font-semibold"];
583
- let n = startEl;
584
- let boldClassFound = null;
585
- while (n && n !== editorRef.current) {
586
- if (boldClasses.some((c) => n.classList.contains(c))) {
587
- boldClassFound = true;
588
- break;
589
- }
590
- if (notBoldClasses.some((c) => n.classList.contains(c))) {
591
- boldClassFound = false;
592
- break;
593
- }
594
- n = n.parentElement;
595
- }
596
- bold = boldClassFound !== null
597
- ? boldClassFound
598
- : startEl
599
- ? parseInt(window.getComputedStyle(startEl).fontWeight, 10) >= 600
600
- : false;
601
- }
602
- catch (error) {
603
- if (process.env.NODE_ENV !== 'production') {
604
- console.warn("Failed to determine bold state", error);
605
- }
606
- }
607
- // Italic and underline route through execCommand and produce semantic
608
- // <em>/<u> tags, so queryCommandState is the canonical read.
609
- try {
610
- italic = document.queryCommandState("italic");
611
- }
612
- catch (_a) { }
613
- try {
614
- underline = document.queryCommandState("underline");
615
- }
616
- catch (_b) { }
617
- try {
618
- if (document.queryCommandState("justifyCenter")) {
619
- textAlign = "center";
620
- }
621
- else if (document.queryCommandState("justifyRight")) {
622
- textAlign = "right";
623
- }
624
- else if (document.queryCommandState("justifyFull")) {
625
- textAlign = "justify";
626
- }
627
- else {
628
- textAlign = "left";
629
- }
630
- }
631
- catch (error) {
632
- if (process.env.NODE_ENV !== 'production') {
633
- console.warn("queryCommandState alignment failed", error);
634
- }
635
- }
636
- try {
637
- fontSize = getCurrentFontSize();
638
- }
639
- catch (error) {
640
- if (process.env.NODE_ENV !== 'production') {
641
- console.warn("Failed to determine font size", error);
642
- }
643
- }
644
- try {
645
- fontWeight = getCurrentFontWeight();
646
- }
647
- catch (error) {
648
- if (process.env.NODE_ENV !== 'production') {
649
- console.warn("Failed to determine font weight", error);
650
- }
651
- }
652
- try {
653
- fontFamily = getCurrentFontFamily();
654
- }
655
- catch (error) {
656
- if (process.env.NODE_ENV !== 'production') {
657
- console.warn("Failed to determine font family", error);
658
- }
659
- }
660
- try {
661
- lineHeight = getCurrentLineHeight();
662
- }
663
- catch (error) {
664
- if (process.env.NODE_ENV !== 'production') {
665
- console.warn("Failed to determine line height", error);
666
- }
667
- }
668
- try {
669
- letterSpacing = getCurrentLetterSpacing();
670
- }
671
- catch (error) {
672
- if (process.env.NODE_ENV !== 'production') {
673
- console.warn("Failed to determine letter spacing", error);
674
- }
675
- }
676
- try {
677
- // Walk up from the selection's start container to find the nearest
678
- // ancestor carrying a `text-{token}` class; that token (e.g.
679
- // "rose-500", "white") is the active color. queryCommandValue is no
680
- // longer used because color is applied via class swaps, not foreColor.
681
- const sel = window.getSelection();
682
- let startEl = null;
683
- if (sel && sel.rangeCount > 0) {
684
- let node = sel.getRangeAt(0).startContainer;
685
- if (node && node.nodeType === Node.TEXT_NODE)
686
- node = node.parentElement;
687
- if (node instanceof HTMLElement)
688
- startEl = node;
689
- }
690
- textColor = matchTextColorClass(startEl, editorRef.current);
691
- }
692
- catch (error) {
693
- if (process.env.NODE_ENV !== 'production') {
694
- console.warn("Failed to determine text color", error);
695
- }
696
- }
697
- setFormattingState({
698
- bold,
699
- italic,
700
- underline,
701
- textAlign,
702
- fontSize,
703
- fontWeight,
704
- fontFamily,
705
- lineHeight,
706
- letterSpacing,
707
- textColor,
708
- });
709
- }, [
710
- getCurrentFontSize,
711
- getCurrentFontWeight,
712
- getCurrentFontFamily,
713
- getCurrentLineHeight,
714
- getCurrentLetterSpacing,
715
- isDisabled,
716
- ]);
717
- const handleContentChange = useCallback(() => {
718
- if (!editorRef.current || !onChange)
719
- return;
720
- const raw = editorRef.current.innerHTML;
721
- const clean = sanitizeHtml(raw);
722
- // If sanitizer stripped something (e.g. pasted <script> or on*= handlers),
723
- // reconcile the DOM so what's rendered matches what we emit.
724
- if (clean !== raw) {
725
- editorRef.current.innerHTML = clean;
726
- }
727
- onChange(clean);
728
- }, [onChange, sanitizeHtml]);
729
- const execEditorCommand = useCallback((command, value) => {
730
- if (isDisabled || !editorRef.current)
731
- return;
732
- focusEditor();
733
- // Snapshot before mutating so bold/italic/foreColor/justify/… land on
734
- // the same undo stack as direct-DOM style ops and typing.
735
- pushHistory("op");
736
- try {
737
- document.execCommand(command, false, value);
738
- }
739
- catch (error) {
740
- if (process.env.NODE_ENV !== 'production') {
741
- console.warn(`execCommand ${command} failed`, error);
742
- }
743
- }
744
- requestAnimationFrame(() => {
745
- updateFormattingState();
746
- handleContentChange();
747
- });
748
- }, [focusEditor, handleContentChange, isDisabled, pushHistory, updateFormattingState]);
749
- const handleUndo = useCallback((event) => {
750
- event === null || event === void 0 ? void 0 : event.preventDefault();
751
- event === null || event === void 0 ? void 0 : event.stopPropagation();
752
- const stack = historyRef.current;
753
- if (stack.undo.length === 0 || !editorRef.current)
754
- return;
755
- const previous = stack.undo.pop();
756
- stack.redo.push(editorRef.current.innerHTML);
757
- // Reset the typing-coalesce window so the next keystroke after an
758
- // undo always starts a fresh entry.
759
- stack.lastPushKind = null;
760
- editorRef.current.innerHTML = sanitizeHtml(previous);
761
- requestAnimationFrame(() => {
762
- updateFormattingState();
763
- handleContentChange();
764
- });
765
- }, [handleContentChange, sanitizeHtml, updateFormattingState]);
766
- const handleRedo = useCallback((event) => {
767
- event === null || event === void 0 ? void 0 : event.preventDefault();
768
- event === null || event === void 0 ? void 0 : event.stopPropagation();
769
- const stack = historyRef.current;
770
- if (stack.redo.length === 0 || !editorRef.current)
771
- return;
772
- const next = stack.redo.pop();
773
- stack.undo.push(editorRef.current.innerHTML);
774
- stack.lastPushKind = null;
775
- editorRef.current.innerHTML = sanitizeHtml(next);
776
- requestAnimationFrame(() => {
777
- updateFormattingState();
778
- handleContentChange();
779
- });
780
- }, [handleContentChange, sanitizeHtml, updateFormattingState]);
781
- const applyStyleToSelection = useCallback((apply) => {
782
- var _a, _b, _c;
783
- if (!editorRef.current)
784
- return;
785
46
  const selection = window.getSelection();
786
47
  if (!selection || selection.rangeCount === 0)
787
48
  return;
788
49
  const range = selection.getRangeAt(0);
789
- if (selection.isCollapsed) {
790
- let node = selection.anchorNode;
791
- if (node && node.nodeType === Node.TEXT_NODE)
792
- node = node.parentElement;
793
- while (node && node !== editorRef.current) {
794
- if (node instanceof HTMLElement) {
795
- apply(node);
796
- break;
797
- }
798
- node = node.parentElement;
799
- }
800
- return;
801
- }
802
- // Non-collapsed: try to wrap just the selected range in a styled span so
803
- // only the selected text changes. surroundContents works when the range
804
- // doesn't cross element boundaries (the common case for inline selections).
805
- const span = document.createElement("span");
806
- apply(span);
807
- try {
808
- range.surroundContents(span);
809
- selection.removeAllRanges();
810
- const restored = document.createRange();
811
- restored.selectNodeContents(span);
812
- selection.addRange(restored);
813
- return;
814
- }
815
- catch (_d) {
816
- // Range crosses element boundaries — fall through to per-parent walker.
817
- }
818
- // Cross-element fallback: split each intersecting text node at the
819
- // range boundaries so only the selected characters end up wrapped.
820
- // Collect first — splitText() mutates the tree and breaks live walking.
821
- const startContainer = range.startContainer;
822
- const startOffset = range.startOffset;
823
- const endContainer = range.endContainer;
824
- const endOffset = range.endOffset;
825
- const textNodes = [];
826
- const walker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_TEXT, {
827
- acceptNode: (n) => range.intersectsNode(n) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT,
828
- });
829
- let current;
830
- while ((current = walker.nextNode()))
831
- textNodes.push(current);
832
- const editor = editorRef.current;
833
- let firstWrap = null;
834
- let lastWrap = null;
835
- for (const textNode of textNodes) {
836
- if (!editor.contains(textNode))
837
- continue;
838
- // Trim leading portion when range starts inside this text node
839
- let target = textNode;
840
- if (textNode === startContainer && startOffset > 0) {
841
- target = textNode.splitText(startOffset);
842
- }
843
- // Trim trailing portion when range ends inside this text node
844
- if (textNode === endContainer) {
845
- const endInTarget = textNode === startContainer ? endOffset - startOffset : endOffset;
846
- if (endInTarget < target.length) {
847
- target.splitText(endInTarget);
848
- }
849
- }
850
- // Wrap the precise text fragment in a styled span
851
- const wrap = document.createElement("span");
852
- apply(wrap);
853
- (_a = target.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(wrap, target);
854
- wrap.appendChild(target);
855
- if (!firstWrap)
856
- firstWrap = wrap;
857
- lastWrap = wrap;
858
- }
859
- // Restore the visible selection across the wrapped fragments so the
860
- // user doesn't have to re-highlight before chaining another action.
861
- if (firstWrap && lastWrap) {
862
- selection.removeAllRanges();
863
- const restored = document.createRange();
864
- restored.setStartBefore((_b = firstWrap.firstChild) !== null && _b !== void 0 ? _b : firstWrap);
865
- restored.setEndAfter((_c = lastWrap.lastChild) !== null && _c !== void 0 ? _c : lastWrap);
866
- selection.addRange(restored);
50
+ if ((_a = editorRef.current) === null || _a === void 0 ? void 0 : _a.contains(range.commonAncestorContainer)) {
51
+ savedRangeRef.current = range.cloneRange();
867
52
  }
868
53
  }, []);
869
- /**
870
- * Strip a redundant class from any element whose every non-whitespace text
871
- * descendant already sits under a closer descendant carrying a class from
872
- * the same group. The outer declaration is dead weight at that point —
873
- * leaving it in place causes nested wrappers to win on properties whose
874
- * line box height (e.g. `text-7xl`'s `line-height: 1`) is computed from the
875
- * outer's own font-size, regardless of what the inner element declares.
876
- * After stripping, span/font wrappers that are now attribute-less are
877
- * unwrapped so we don't accumulate empty markup over time.
878
- */
879
- const flattenClassGroup = useCallback((classes) => {
880
- if (!editorRef.current || classes.length === 0)
881
- return;
54
+ const restoreSelection = useCallback(() => {
882
55
  const editor = editorRef.current;
883
- const selector = classes.map((c) => `.${c}`).join(",");
884
- const candidates = Array.from(editor.querySelectorAll(selector));
885
- for (const ancestor of candidates) {
886
- const ancestorClass = classes.find((c) => ancestor.classList.contains(c));
887
- if (!ancestorClass)
888
- continue;
889
- const walker = document.createTreeWalker(ancestor, NodeFilter.SHOW_TEXT);
890
- let everyTextHasCloser = true;
891
- let sawAnyText = false;
892
- let textNode;
893
- while ((textNode = walker.nextNode())) {
894
- const data = textNode.data;
895
- if (!data || !data.trim())
896
- continue;
897
- sawAnyText = true;
898
- let p = textNode.parentElement;
899
- let foundCloser = false;
900
- while (p && p !== ancestor) {
901
- if (classes.some((c) => p.classList.contains(c))) {
902
- foundCloser = true;
903
- break;
904
- }
905
- p = p.parentElement;
906
- }
907
- if (!foundCloser) {
908
- everyTextHasCloser = false;
909
- break;
910
- }
911
- }
912
- if (!sawAnyText || !everyTextHasCloser)
913
- continue;
914
- ancestor.classList.remove(ancestorClass);
915
- if (ancestor.classList.length === 0)
916
- ancestor.removeAttribute("class");
917
- const tag = ancestor.tagName.toLowerCase();
918
- if ((tag === "span" || tag === "font") &&
919
- ancestor.attributes.length === 0 &&
920
- ancestor.parentNode) {
921
- const parent = ancestor.parentNode;
922
- while (ancestor.firstChild)
923
- parent.insertBefore(ancestor.firstChild, ancestor);
924
- parent.removeChild(ancestor);
925
- }
926
- }
927
- }, []);
928
- /**
929
- * Generic class-swap helper. Wraps the selected text in a span carrying
930
- * `nextClass` (also stripping any sibling class from the same group on
931
- * that wrap, so we never end up with `text-sm text-7xl`), then runs a
932
- * flatten pass over the editor to collapse newly-redundant outer wrappers.
933
- */
934
- const applyClassSwap = useCallback((group, nextClass) => {
935
- applyStyleToSelection((el) => {
936
- for (const cls of group) {
937
- if (cls !== nextClass)
938
- el.classList.remove(cls);
939
- }
940
- el.classList.add(nextClass);
941
- });
942
- flattenClassGroup(group);
943
- }, [applyStyleToSelection, flattenClassGroup]);
944
- const handleBold = useCallback((event) => {
945
- event === null || event === void 0 ? void 0 : event.preventDefault();
946
- event === null || event === void 0 ? void 0 : event.stopPropagation();
947
- if (isDisabled || !editorRef.current)
948
- return;
949
- focusEditor();
950
- const selection = window.getSelection();
951
- if (!selection || selection.rangeCount === 0)
952
- return;
953
- pushHistory();
954
- // Bold lives in the font-weight class group: ON → font-bold,
955
- // OFF → font-normal. The toolbar Bold button and the Weight=Bold
956
- // dropdown entry share the same underlying class, so they stay in
957
- // sync automatically — toggling one lights up the other.
958
- const next = formattingState.bold ? "font-normal" : "font-bold";
959
- applyClassSwap(FONT_WEIGHT_CLASSES, next);
960
- requestAnimationFrame(() => {
961
- updateFormattingState();
962
- handleContentChange();
963
- });
964
- }, [
965
- applyClassSwap,
966
- focusEditor,
967
- formattingState.bold,
968
- handleContentChange,
969
- isDisabled,
970
- pushHistory,
971
- updateFormattingState,
972
- ]);
973
- // Italic and underline route through execCommand because it produces
974
- // semantic <em>/<u> tags, handles toggle-on/off (including unwrap) without
975
- // a hand-rolled negation-class scheme, and the editor's CSS already
976
- // styles those tags via descendant selectors. execEditorCommand
977
- // pre-snapshots history so undo/redo ordering is preserved.
978
- const handleItalic = useCallback((event) => {
979
- event === null || event === void 0 ? void 0 : event.preventDefault();
980
- event === null || event === void 0 ? void 0 : event.stopPropagation();
981
- execEditorCommand("italic");
982
- }, [execEditorCommand]);
983
- const handleUnderline = useCallback((event) => {
984
- event === null || event === void 0 ? void 0 : event.preventDefault();
985
- event === null || event === void 0 ? void 0 : event.stopPropagation();
986
- execEditorCommand("underline");
987
- }, [execEditorCommand]);
988
- const handleFontSize = useCallback((sizeKey) => {
989
- if (isDisabled || !editorRef.current)
56
+ if (!editor)
990
57
  return;
991
- focusEditor();
992
- const option = getFontSizeOption(sizeKey);
993
- const selection = window.getSelection();
994
- if (!selection || selection.rangeCount === 0) {
995
- closeAllPickers();
996
- return;
997
- }
998
- pushHistory();
999
- // Tailwind's `text-*` utilities bundle font-size + a matching
1000
- // line-height in one rule, so swapping the size class swaps both —
1001
- // no separate flattening pass needed for the line-height.
1002
- applyClassSwap(FONT_SIZE_CLASSES, option.className);
1003
- requestAnimationFrame(() => {
1004
- updateFormattingState();
1005
- handleContentChange();
1006
- });
1007
- closeAllPickers();
1008
- }, [
1009
- applyClassSwap,
1010
- closeAllPickers,
1011
- focusEditor,
1012
- handleContentChange,
1013
- isDisabled,
1014
- pushHistory,
1015
- updateFormattingState,
1016
- ]);
1017
- const applyToBlockAncestors = useCallback((apply) => {
1018
- if (!editorRef.current)
58
+ editor.focus();
59
+ const range = savedRangeRef.current;
60
+ if (!range)
1019
61
  return;
1020
62
  const selection = window.getSelection();
1021
- if (!selection || selection.rangeCount === 0)
1022
- return;
1023
- const editor = editorRef.current;
1024
- // Normalize: ensure no text node or inline element is a *direct*
1025
- // child of the editor. Otherwise `findBlock` would fall back to the
1026
- // editor itself, and any class set on it would live on the live DOM
1027
- // but never serialize through `editor.innerHTML` — line-height
1028
- // changes would silently disappear from saved HTML. Wrap each
1029
- // contiguous run of inline-or-text top-level children in a fresh
1030
- // `<div>`. Idempotent: blocks that are already block-level are left
1031
- // alone, so calling this on every block-level mutation is cheap.
1032
- const isInlineChild = (node) => {
1033
- if (node.nodeType === Node.TEXT_NODE)
1034
- return true;
1035
- if (node instanceof HTMLElement) {
1036
- const d = window.getComputedStyle(node).display;
1037
- return d === "inline" || d === "inline-block";
1038
- }
1039
- return false;
1040
- };
1041
- const groups = [];
1042
- let currentGroup = null;
1043
- for (const child of Array.from(editor.childNodes)) {
1044
- if (isInlineChild(child)) {
1045
- if (!currentGroup) {
1046
- currentGroup = [];
1047
- groups.push(currentGroup);
1048
- }
1049
- currentGroup.push(child);
1050
- }
1051
- else {
1052
- currentGroup = null;
1053
- }
1054
- }
1055
- for (const group of groups) {
1056
- if (group.length === 0)
1057
- continue;
1058
- const wrap = document.createElement("div");
1059
- editor.insertBefore(wrap, group[0]);
1060
- for (const node of group)
1061
- wrap.appendChild(node);
1062
- }
1063
- // Re-read range after potential mutations — Range objects survive
1064
- // moves but offsets into reparented text nodes stay valid, so
1065
- // `selection.getRangeAt(0)` still points at the same characters.
1066
- const range = selection.getRangeAt(0);
1067
- const findBlock = (node) => {
1068
- let n = node;
1069
- if (n && n.nodeType === Node.TEXT_NODE)
1070
- n = n.parentElement;
1071
- while (n && n !== editor && editor.contains(n)) {
1072
- if (n instanceof HTMLElement) {
1073
- const d = window.getComputedStyle(n).display;
1074
- if (d === "block" || d === "list-item" || d === "table-cell" || d === "flex" || d === "grid") {
1075
- return n;
1076
- }
1077
- }
1078
- n = n.parentElement;
1079
- }
1080
- // After normalization above, an inline node always has a non-editor
1081
- // block ancestor; this branch is now only reached for malformed
1082
- // cases. Returning null is safer than returning the editor (which
1083
- // wouldn't serialize anyway).
1084
- return null;
1085
- };
1086
- const blocks = new Set();
1087
- if (selection.isCollapsed) {
1088
- const block = findBlock(range.startContainer);
1089
- if (block)
1090
- blocks.add(block);
1091
- }
1092
- else if (range.commonAncestorContainer.nodeType === Node.TEXT_NODE) {
1093
- const block = findBlock(range.commonAncestorContainer);
1094
- if (block)
1095
- blocks.add(block);
1096
- }
1097
- else {
1098
- const walker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_TEXT, {
1099
- acceptNode: (n) => range.intersectsNode(n) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT,
1100
- });
1101
- let current;
1102
- while ((current = walker.nextNode())) {
1103
- const block = findBlock(current);
1104
- if (block)
1105
- blocks.add(block);
1106
- }
1107
- }
1108
- blocks.forEach((b) => apply(b));
63
+ selection === null || selection === void 0 ? void 0 : selection.removeAllRanges();
64
+ selection === null || selection === void 0 ? void 0 : selection.addRange(range);
1109
65
  }, []);
1110
- const handleFontFamily = useCallback((key) => {
1111
- if (isDisabled || !editorRef.current)
1112
- return;
1113
- focusEditor();
1114
- const option = fontFamilies.find((opt) => opt.key === key);
1115
- if (!option)
1116
- return;
1117
- if (loadFontsOnDemand && option.family) {
1118
- loadGoogleFont(option.family, option.weights);
1119
- }
1120
- pushHistory();
1121
- applyStyleToSelection((el) => {
1122
- el.style.fontFamily = option.stack;
1123
- });
1124
- requestAnimationFrame(() => {
1125
- updateFormattingState();
1126
- handleContentChange();
1127
- });
1128
- closeAllPickers();
1129
- }, [
1130
- applyStyleToSelection,
1131
- closeAllPickers,
1132
- focusEditor,
1133
- fontFamilies,
1134
- handleContentChange,
1135
- isDisabled,
1136
- loadFontsOnDemand,
1137
- pushHistory,
1138
- updateFormattingState,
1139
- ]);
1140
- const handleFontWeight = useCallback((key) => {
1141
- if (isDisabled || !editorRef.current)
1142
- return;
1143
- focusEditor();
1144
- const option = getFontWeightOption(key);
1145
- pushHistory();
1146
- applyClassSwap(FONT_WEIGHT_CLASSES, option.className);
1147
- requestAnimationFrame(() => {
1148
- updateFormattingState();
1149
- handleContentChange();
1150
- });
1151
- closeAllPickers();
1152
- }, [
1153
- applyClassSwap,
1154
- closeAllPickers,
1155
- focusEditor,
1156
- handleContentChange,
1157
- isDisabled,
1158
- pushHistory,
1159
- updateFormattingState,
1160
- ]);
1161
- const handleLineHeight = useCallback((key) => {
1162
- if (isDisabled || !editorRef.current)
1163
- return;
1164
- focusEditor();
1165
- const option = getLineHeightOption(key);
1166
- pushHistory();
1167
- // Line height is paragraph-level, so swap the `leading-*` class on the
1168
- // block ancestors that contain the selection rather than wrapping in a
1169
- // span. Each block carries at most one `leading-*` class — clear any
1170
- // existing one first, then add the new one.
1171
- applyToBlockAncestors((el) => {
1172
- for (const cls of LINE_HEIGHT_CLASSES) {
1173
- if (cls !== option.className)
1174
- el.classList.remove(cls);
1175
- }
1176
- el.classList.add(option.className);
1177
- });
1178
- requestAnimationFrame(() => {
1179
- updateFormattingState();
1180
- handleContentChange();
1181
- });
1182
- closeAllPickers();
1183
- }, [
1184
- applyToBlockAncestors,
1185
- closeAllPickers,
1186
- focusEditor,
1187
- handleContentChange,
1188
- isDisabled,
1189
- pushHistory,
1190
- updateFormattingState,
1191
- ]);
1192
- const handleLetterSpacing = useCallback((key) => {
1193
- if (isDisabled || !editorRef.current)
1194
- return;
1195
- focusEditor();
1196
- const option = getLetterSpacingOption(key);
1197
- pushHistory();
1198
- applyClassSwap(LETTER_SPACING_CLASSES, option.className);
1199
- requestAnimationFrame(() => {
1200
- updateFormattingState();
1201
- handleContentChange();
1202
- });
1203
- closeAllPickers();
1204
- }, [
1205
- applyClassSwap,
1206
- closeAllPickers,
1207
- focusEditor,
1208
- handleContentChange,
1209
- isDisabled,
1210
- pushHistory,
1211
- updateFormattingState,
1212
- ]);
1213
- const handleTextColor = useCallback((token) => {
1214
- if (isDisabled || !editorRef.current || !token)
1215
- return;
1216
- focusEditor();
1217
- const selection = window.getSelection();
1218
- if (!selection || selection.rangeCount === 0) {
1219
- closeAllPickers();
1220
- return;
1221
- }
1222
- pushHistory();
1223
- applyClassSwap(TEXT_COLOR_CLASSES, `text-${token}`);
1224
- addRecentColor(token);
1225
- requestAnimationFrame(() => {
1226
- updateFormattingState();
1227
- handleContentChange();
1228
- });
1229
- closeAllPickers();
1230
- }, [
1231
- addRecentColor,
1232
- applyClassSwap,
1233
- closeAllPickers,
1234
- focusEditor,
1235
- handleContentChange,
1236
- isDisabled,
1237
- pushHistory,
1238
- updateFormattingState,
1239
- ]);
1240
- const handleMouseDown = useCallback((event) => {
1241
- event.preventDefault();
1242
- focusEditor();
1243
- }, [focusEditor]);
1244
- const fontSizeAnimations = useMemo(() => createDropdownAnimations(fontSizeIsFlipped), [fontSizeIsFlipped]);
1245
- const fontWeightAnimations = useMemo(() => createDropdownAnimations(fontWeightIsFlipped), [fontWeightIsFlipped]);
1246
- const fontFamilyAnimations = useMemo(() => createDropdownAnimations(fontFamilyIsFlipped), [fontFamilyIsFlipped]);
1247
- const lineHeightAnimations = useMemo(() => createDropdownAnimations(lineHeightIsFlipped), [lineHeightIsFlipped]);
1248
- const letterSpacingAnimations = useMemo(() => createDropdownAnimations(letterSpacingIsFlipped), [letterSpacingIsFlipped]);
1249
- const colorAnimations = useMemo(() => createDropdownAnimations(colorIsFlipped), [colorIsFlipped]);
1250
- const handleAlign = useCallback((alignment) => {
1251
- const commandMap = {
1252
- left: "justifyLeft",
1253
- center: "justifyCenter",
1254
- right: "justifyRight",
1255
- };
1256
- execEditorCommand(commandMap[alignment]);
1257
- }, [execEditorCommand]);
1258
- const handleSelection = useCallback(() => {
66
+ const syncFormatting = useCallback(() => {
67
+ setFormatting(readFormattingState(editorRef.current, window.getSelection()));
68
+ }, []);
69
+ /**
70
+ * Emit the current DOM as sanitized HTML.
71
+ *
72
+ * Note what this does NOT do: write the sanitized string back into the
73
+ * editor. Doing that mid-typing discards every live Range and moves the
74
+ * caret — the previous implementation's most user-visible bug. Foreign
75
+ * markup can only arrive via paste/drop/`value`, each sanitized at its own
76
+ * boundary, so the DOM is already clean by the time we read it.
77
+ */
78
+ const emitChange = useCallback(() => {
1259
79
  var _a;
1260
- if (!editorRef.current || isDisabled)
1261
- return;
1262
- updateFormattingState();
1263
- if (toolbarConfig.position !== "floating")
1264
- return;
1265
- const selection = window.getSelection();
1266
- if (!selection || selection.rangeCount === 0) {
1267
- setShowToolbar(false);
1268
- return;
1269
- }
1270
- const range = selection.getRangeAt(0);
1271
- if (!editorRef.current.contains(range.commonAncestorContainer) || selection.isCollapsed) {
1272
- setShowToolbar(false);
1273
- return;
1274
- }
1275
- const rect = range.getBoundingClientRect();
1276
- const editorRect = editorRef.current.getBoundingClientRect();
1277
- if (rect.width === 0 && rect.height === 0) {
1278
- setShowToolbar(false);
80
+ const editor = editorRef.current;
81
+ if (!editor)
1279
82
  return;
1280
- }
1281
- // Measure the actual toolbar width the floating toolbar grows with
1282
- // the active control set (font family, font size, ) and a static
1283
- // 200 px constant clipped it off-canvas at the editor's right edge.
1284
- // offsetWidth is 0 while the toolbar is unmounted via AnimatePresence;
1285
- // fall back to a realistic default for the very first frame.
1286
- const toolbarWidth = ((_a = toolbarRef.current) === null || _a === void 0 ? void 0 : _a.offsetWidth) || 320;
1287
- const left = Math.max(10, Math.min(rect.left - editorRect.left + rect.width / 2 - toolbarWidth / 2, editorRect.width - toolbarWidth - 10));
1288
- setToolbarPosition({ top: rect.top - editorRect.top - 50, left });
1289
- setShowToolbar(true);
1290
- }, [isDisabled, toolbarConfig.position, updateFormattingState]);
83
+ setIsEmpty(((_a = editor.textContent) !== null && _a !== void 0 ? _a : "").trim().length === 0);
84
+ onChange === null || onChange === void 0 ? void 0 : onChange(sanitizeFn(editor.innerHTML));
85
+ }, [onChange, sanitizeFn]);
86
+ // Sync the controlled value in. Guarded on inequality so typing does not
87
+ // re-enter and reset the caret.
1291
88
  useEffect(() => {
1292
- if (!editorRef.current)
1293
- return;
89
+ var _a;
1294
90
  const editor = editorRef.current;
1295
- const handleInput = () => {
1296
- handleContentChange();
1297
- updateFormattingState();
1298
- };
1299
- // beforeinput fires synchronously *before* the DOM mutation, so
1300
- // editorRef.current.innerHTML is still the pre-keystroke snapshot —
1301
- // exactly what undo needs. Coalescing in pushHistory groups successive
1302
- // keystrokes into one undo entry per ~500 ms run.
1303
- const handleBeforeInput = () => {
1304
- pushHistory("typing");
1305
- };
1306
- // Intercept native undo/redo shortcuts so the browser's contentEditable
1307
- // stack doesn't drift out of sync with our linear history. Without this
1308
- // the browser would still honor Cmd/Ctrl+Z on its own internal stack.
1309
- const handleKeyDown = (event) => {
1310
- const mod = event.metaKey || event.ctrlKey;
1311
- if (!mod)
1312
- return;
1313
- const key = event.key.toLowerCase();
1314
- if (key === "z") {
1315
- event.preventDefault();
1316
- if (event.shiftKey)
1317
- handleRedo(event);
1318
- else
1319
- handleUndo(event);
1320
- }
1321
- else if (key === "y" && !event.shiftKey) {
1322
- event.preventDefault();
1323
- handleRedo(event);
1324
- }
1325
- };
1326
- editor.addEventListener("input", handleInput);
1327
- editor.addEventListener("beforeinput", handleBeforeInput);
1328
- editor.addEventListener("keydown", handleKeyDown);
1329
- return () => {
1330
- editor.removeEventListener("input", handleInput);
1331
- editor.removeEventListener("beforeinput", handleBeforeInput);
1332
- editor.removeEventListener("keydown", handleKeyDown);
1333
- };
1334
- }, [handleContentChange, handleRedo, handleUndo, pushHistory, updateFormattingState]);
91
+ if (!editor || value === undefined)
92
+ return;
93
+ const clean = sanitizeFn(value);
94
+ if (clean !== editor.innerHTML) {
95
+ editor.innerHTML = clean;
96
+ }
97
+ setIsEmpty(((_a = editor.textContent) !== null && _a !== void 0 ? _a : "").trim().length === 0);
98
+ }, [value, sanitizeFn]);
99
+ // Keep the toolbar's pressed states truthful as the caret moves.
1335
100
  useEffect(() => {
1336
- const handleSelectionChange = () => {
1337
- if (!editorRef.current)
1338
- return;
101
+ const handler = () => {
1339
102
  const selection = window.getSelection();
1340
- if (!selection || selection.rangeCount === 0) {
1341
- setShowToolbar(false);
1342
- updateFormattingState();
103
+ const editor = editorRef.current;
104
+ if (!selection || !editor || !selection.anchorNode)
1343
105
  return;
106
+ if (editor.contains(selection.anchorNode)) {
107
+ saveSelection();
108
+ syncFormatting();
1344
109
  }
1345
- const range = selection.getRangeAt(0);
1346
- if (!editorRef.current.contains(range.commonAncestorContainer)) {
1347
- setShowToolbar(false);
1348
- return;
1349
- }
1350
- handleSelection();
1351
110
  };
1352
- document.addEventListener("selectionchange", handleSelectionChange);
1353
- return () => document.removeEventListener("selectionchange", handleSelectionChange);
1354
- }, [handleSelection, updateFormattingState]);
1355
- useEffect(() => {
1356
- const handleClickOutside = (event) => {
1357
- var _a, _b, _c, _d, _e, _f, _g, _h;
1358
- const target = event.target;
1359
- const isInEditor = (_a = editorRef.current) === null || _a === void 0 ? void 0 : _a.contains(target);
1360
- const isInToolbar = (_b = toolbarRef.current) === null || _b === void 0 ? void 0 : _b.contains(target);
1361
- const isInFontSizeDropdown = (_c = fontSizePortalContentRef.current) === null || _c === void 0 ? void 0 : _c.contains(target);
1362
- const isInFontWeightDropdown = (_d = fontWeightPortalContentRef.current) === null || _d === void 0 ? void 0 : _d.contains(target);
1363
- const isInFontFamilyDropdown = (_e = fontFamilyPortalContentRef.current) === null || _e === void 0 ? void 0 : _e.contains(target);
1364
- const isInLineHeightDropdown = (_f = lineHeightPortalContentRef.current) === null || _f === void 0 ? void 0 : _f.contains(target);
1365
- const isInLetterSpacingDropdown = (_g = letterSpacingPortalContentRef.current) === null || _g === void 0 ? void 0 : _g.contains(target);
1366
- const isInColorDropdown = (_h = colorPortalContentRef.current) === null || _h === void 0 ? void 0 : _h.contains(target);
1367
- const isInAnyDropdown = isInFontSizeDropdown ||
1368
- isInFontWeightDropdown ||
1369
- isInFontFamilyDropdown ||
1370
- isInLineHeightDropdown ||
1371
- isInLetterSpacingDropdown ||
1372
- isInColorDropdown;
1373
- if (!isInEditor && !isInToolbar && !isInAnyDropdown) {
1374
- if (toolbarConfig.position === "floating") {
1375
- setShowToolbar(false);
1376
- }
1377
- closeAllPickers();
1378
- }
1379
- else if (isInToolbar || isInAnyDropdown) {
1380
- const targetEl = target;
1381
- const isFontSizeRelated = isInFontSizeDropdown || Boolean(targetEl === null || targetEl === void 0 ? void 0 : targetEl.closest('[data-tool="fontSize"]'));
1382
- const isFontWeightRelated = isInFontWeightDropdown || Boolean(targetEl === null || targetEl === void 0 ? void 0 : targetEl.closest('[data-tool="fontWeight"]'));
1383
- const isFontFamilyRelated = isInFontFamilyDropdown || Boolean(targetEl === null || targetEl === void 0 ? void 0 : targetEl.closest('[data-tool="fontFamily"]'));
1384
- const isLineHeightRelated = isInLineHeightDropdown || Boolean(targetEl === null || targetEl === void 0 ? void 0 : targetEl.closest('[data-tool="lineHeight"]'));
1385
- const isLetterSpacingRelated = isInLetterSpacingDropdown ||
1386
- Boolean(targetEl === null || targetEl === void 0 ? void 0 : targetEl.closest('[data-tool="letterSpacing"]'));
1387
- const isColorRelated = isInColorDropdown || Boolean(targetEl === null || targetEl === void 0 ? void 0 : targetEl.closest('[data-tool="textColor"]'));
1388
- if (!isFontSizeRelated)
1389
- setShowFontSizePicker(false);
1390
- if (!isFontWeightRelated)
1391
- setShowFontWeightPicker(false);
1392
- if (!isFontFamilyRelated)
1393
- setShowFontFamilyPicker(false);
1394
- if (!isLineHeightRelated)
1395
- setShowLineHeightPicker(false);
1396
- if (!isLetterSpacingRelated)
1397
- setShowLetterSpacingPicker(false);
1398
- if (!isColorRelated)
1399
- setShowColorPicker(false);
1400
- }
1401
- else if (isInEditor) {
1402
- closeAllPickers();
1403
- }
1404
- };
1405
- document.addEventListener("mousedown", handleClickOutside);
1406
- return () => document.removeEventListener("mousedown", handleClickOutside);
1407
- }, [closeAllPickers, toolbarConfig.position]);
1408
- useEffect(() => {
1409
- if (editorRef.current && value !== editorRef.current.innerHTML) {
1410
- editorRef.current.innerHTML = sanitizeHtml(value);
1411
- // External `value` change — flush undo history. Snapshots taken
1412
- // from the previous document point at HTML that no longer matches
1413
- // anything reachable via the new value, so leaving them in place
1414
- // would let Undo restore content from a prior session/document.
1415
- historyRef.current.undo = [];
1416
- historyRef.current.redo = [];
1417
- historyRef.current.lastPushKind = null;
1418
- historyRef.current.lastPushAt = 0;
1419
- updateFormattingState();
1420
- }
1421
- }, [updateFormattingState, value, sanitizeHtml]);
1422
- const renderToolbarTool = (tool, toolKey) => {
1423
- var _a;
1424
- const isActive = tool === "bold"
1425
- ? formattingState.bold
1426
- : tool === "italic"
1427
- ? formattingState.italic
1428
- : tool === "underline"
1429
- ? formattingState.underline
1430
- : tool === "fontSize"
1431
- ? formattingState.fontSize !== DEFAULT_FORMATTING_STATE.fontSize
1432
- : tool === "fontWeight"
1433
- ? formattingState.fontWeight !== DEFAULT_FORMATTING_STATE.fontWeight
1434
- : tool === "fontFamily"
1435
- ? formattingState.fontFamily !== DEFAULT_FORMATTING_STATE.fontFamily
1436
- : tool === "lineHeight"
1437
- ? formattingState.lineHeight !== DEFAULT_FORMATTING_STATE.lineHeight
1438
- : tool === "letterSpacing"
1439
- ? formattingState.letterSpacing !== DEFAULT_FORMATTING_STATE.letterSpacing
1440
- : tool === "alignLeft"
1441
- ? formattingState.textAlign === "left"
1442
- : tool === "alignCenter"
1443
- ? formattingState.textAlign === "center"
1444
- : tool === "alignRight"
1445
- ? formattingState.textAlign === "right"
1446
- : false;
1447
- switch (tool) {
1448
- case "bold":
1449
- return (jsx(Button, { size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), "data-state": isActive ? "active" : "inactive", onMouseDown: handleMouseDown, onClick: handleBold, disabled: isDisabled, "aria-label": "Bold", "aria-pressed": isActive ? "true" : "false", children: jsx(TextB, { className: "size-4" }) }, toolKey));
1450
- case "italic":
1451
- return (jsx(Button, { size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), "data-state": isActive ? "active" : "inactive", onMouseDown: handleMouseDown, onClick: handleItalic, disabled: isDisabled, "aria-label": "Italic", "aria-pressed": isActive ? "true" : "false", children: jsx(TextItalic, { className: "size-4" }) }, toolKey));
1452
- case "underline":
1453
- return (jsx(Button, { size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), "data-state": isActive ? "active" : "inactive", onMouseDown: handleMouseDown, onClick: handleUnderline, disabled: isDisabled, "aria-label": "Underline", "aria-pressed": isActive ? "true" : "false", children: jsx(TextUnderline, { className: "size-4" }) }, toolKey));
1454
- case "fontFamily": {
1455
- // The `fontFamily` tool is opt-in via toolbar config, but
1456
- // `fontFamilies` is also a public prop — if a consumer passes an
1457
- // empty array the dropdown has nothing to show and the trigger
1458
- // can't compute a current option to display. Skip rendering the
1459
- // tool entirely in that case rather than crashing on undefined.
1460
- if (fontFamilies.length === 0) {
1461
- if (process.env.NODE_ENV !== "production") {
1462
- console.warn("[RichTextEditor]: `fontFamily` toolbar tool was requested but `fontFamilies` is empty — the tool will not render. Either remove `fontFamily` from toolbar.tools or supply at least one option.");
1463
- }
1464
- return null;
1465
- }
1466
- const currentOption = (_a = fontFamilies.find((opt) => opt.key === formattingState.fontFamily)) !== null && _a !== void 0 ? _a : fontFamilies[0];
1467
- const portalStyle = {
1468
- position: "fixed",
1469
- top: fontFamilyPortalPosition.top,
1470
- left: fontFamilyPortalPosition.left,
1471
- zIndex: 1000,
1472
- ...fontFamilyPortalCssVars,
1473
- };
1474
- const renderedDropdown = isClient
1475
- ? createPortal(jsx(AnimatePresence, { mode: "wait", children: showFontFamilyPicker && (jsx(motion.div, { ref: (el) => {
1476
- fontFamilyPortalContentRef.current = el;
1477
- }, "data-flikkui-portal": "", role: "listbox", className: cn(surfaceClasses(surfaceLevel, { translucent: true, shadow: false }), themeStyles.dropdownStyle), style: portalStyle, variants: shouldReduceMotion ? undefined : fontFamilyAnimations, initial: "initial", animate: fontFamilyPortalReady ? "visible" : "initial", exit: "exit", children: jsx(SurfaceProvider, { level: surfaceLevel, children: fontFamilies.map((option) => {
1478
- const selected = option.key === formattingState.fontFamily;
1479
- return (jsx("button", { className: themeStyles.dropdownItemStyle, "data-active": selected ? "true" : "false", onMouseDown: (event) => {
1480
- event.preventDefault();
1481
- focusEditor();
1482
- }, onClick: (event) => {
1483
- event.preventDefault();
1484
- event.stopPropagation();
1485
- handleFontFamily(option.key);
1486
- }, role: "option", "aria-selected": selected, children: jsxs("span", { className: "flex items-center justify-between gap-3", children: [jsx("span", { className: "text-sm", style: { fontFamily: option.stack || undefined }, children: option.label }), option.family && (jsx("span", { className: "text-xs text-[var(--color-text-muted)]", children: "Google" }))] }) }, option.key));
1487
- }) }) })) }), document.body)
1488
- : null;
1489
- return (jsxs("div", { className: "relative", "data-tool": "fontFamily", children: [jsx(Button, { ref: fontFamilyTriggerRef, size: "sm", color: "mono", variant: "soft", className: cn(themeStyles.toolbarButtonStyle, "!justify-start !w-auto px-2 min-w-[4rem] gap-1"), "data-state": isActive ? "active" : "inactive", onMouseDown: handleMouseDown, onClick: (event) => {
1490
- event.preventDefault();
1491
- event.stopPropagation();
1492
- focusEditor();
1493
- togglePicker("fontFamily");
1494
- }, disabled: isDisabled, "aria-label": `Font family (${currentOption.label})`, "aria-expanded": showFontFamilyPicker, "aria-haspopup": "listbox", children: jsx("span", { className: "text-sm font-medium truncate text-left max-w-[5.5rem] block", style: { fontFamily: currentOption.stack || undefined }, children: currentOption.label }) }), renderedDropdown] }, toolKey));
1495
- }
1496
- case "fontWeight": {
1497
- const currentOption = getFontWeightOption(formattingState.fontWeight);
1498
- const portalStyle = {
1499
- position: "fixed",
1500
- top: fontWeightPortalPosition.top,
1501
- left: fontWeightPortalPosition.left,
1502
- zIndex: 1000,
1503
- ...fontWeightPortalCssVars,
1504
- };
1505
- const renderedDropdown = isClient
1506
- ? createPortal(jsx(AnimatePresence, { mode: "wait", children: showFontWeightPicker && (jsx(motion.div, { ref: (el) => {
1507
- fontWeightPortalContentRef.current = el;
1508
- }, "data-flikkui-portal": "", role: "listbox", className: cn(surfaceClasses(surfaceLevel, { translucent: true, shadow: false }), themeStyles.dropdownStyle), style: portalStyle, variants: shouldReduceMotion ? undefined : fontWeightAnimations, initial: "initial", animate: fontWeightPortalReady ? "visible" : "initial", exit: "exit", children: jsx(SurfaceProvider, { level: surfaceLevel, children: FONT_WEIGHT_OPTIONS.map((option) => {
1509
- const selected = option.key === formattingState.fontWeight;
1510
- return (jsx("button", { className: themeStyles.dropdownItemStyle, "data-active": selected ? "true" : "false", onMouseDown: (event) => {
1511
- event.preventDefault();
1512
- focusEditor();
1513
- }, onClick: (event) => {
1514
- event.preventDefault();
1515
- event.stopPropagation();
1516
- handleFontWeight(option.key);
1517
- }, role: "option", "aria-selected": selected, children: jsxs("span", { className: "flex items-center justify-between gap-3", children: [jsx("span", { className: "text-sm", style: { fontWeight: option.value }, children: option.label }), jsx("span", { className: "text-sm text-[var(--color-text-muted)]", children: option.value })] }) }, option.key));
1518
- }) }) })) }), document.body)
1519
- : null;
1520
- return (jsxs("div", { className: "relative", "data-tool": "fontWeight", children: [jsx(Button, { ref: fontWeightTriggerRef, size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), "data-state": isActive ? "active" : "inactive", onMouseDown: handleMouseDown, onClick: (event) => {
1521
- event.preventDefault();
1522
- event.stopPropagation();
1523
- focusEditor();
1524
- togglePicker("fontWeight");
1525
- }, disabled: isDisabled, "aria-label": `Font weight (${currentOption.label})`, "aria-expanded": showFontWeightPicker, "aria-haspopup": "listbox", children: jsx(TextB, { className: "w-4 h-4" }) }), renderedDropdown] }, toolKey));
1526
- }
1527
- case "fontSize": {
1528
- const currentOption = getFontSizeOption(formattingState.fontSize);
1529
- const portalStyle = {
1530
- position: "fixed",
1531
- top: fontSizePortalPosition.top,
1532
- left: fontSizePortalPosition.left,
1533
- zIndex: 1000,
1534
- ...fontSizePortalCssVars,
1535
- };
1536
- const renderedDropdown = isClient
1537
- ? createPortal(jsx(AnimatePresence, { mode: "wait", children: showFontSizePicker && (jsx(motion.div, { ref: (el) => {
1538
- fontSizePortalContentRef.current = el;
1539
- }, "data-flikkui-portal": "", role: "listbox", className: cn(surfaceClasses(surfaceLevel, { translucent: true, shadow: false }), themeStyles.dropdownStyle), style: portalStyle, variants: shouldReduceMotion ? undefined : fontSizeAnimations, initial: "initial", animate: fontSizePortalReady ? "visible" : "initial", exit: "exit", children: jsx(SurfaceProvider, { level: surfaceLevel, children: FONT_SIZE_OPTIONS.map((option) => {
1540
- const selected = option.key === formattingState.fontSize;
1541
- return (jsx("button", { className: themeStyles.dropdownItemStyle, "data-active": selected ? "true" : "false", onMouseDown: (event) => {
1542
- event.preventDefault();
1543
- focusEditor();
1544
- }, onClick: (event) => {
1545
- event.preventDefault();
1546
- event.stopPropagation();
1547
- handleFontSize(option.key);
1548
- }, role: "option", "aria-selected": selected, children: jsxs("span", { className: "flex items-center justify-between gap-3", children: [jsx("span", { className: "uppercase text-sm font-medium", children: option.label }), jsxs("span", { className: "text-sm text-[var(--color-text-muted)]", children: [option.px, "px"] })] }) }, option.key));
1549
- }) }) })) }), document.body)
1550
- : null;
1551
- return (jsxs("div", { className: "relative", "data-tool": "fontSize", children: [jsx(Button, { ref: fontSizeTriggerRef, size: "sm", color: "mono", variant: "soft", className: cn(themeStyles.toolbarButtonStyle, "px-2 min-w-[3rem] gap-1"), "data-state": isActive ? "active" : "inactive", onMouseDown: handleMouseDown, onClick: (event) => {
1552
- event.preventDefault();
1553
- event.stopPropagation();
1554
- focusEditor();
1555
- togglePicker("fontSize");
1556
- }, disabled: isDisabled, "aria-label": "Font size", "aria-expanded": showFontSizePicker, "aria-haspopup": "listbox", children: jsx("span", { className: "text-sm font-medium tracking-wide uppercase", children: currentOption.label }) }), renderedDropdown] }, toolKey));
1557
- }
1558
- case "lineHeight": {
1559
- const currentOption = getLineHeightOption(formattingState.lineHeight);
1560
- const portalStyle = {
1561
- position: "fixed",
1562
- top: lineHeightPortalPosition.top,
1563
- left: lineHeightPortalPosition.left,
1564
- zIndex: 1000,
1565
- ...lineHeightPortalCssVars,
1566
- };
1567
- const renderedDropdown = isClient
1568
- ? createPortal(jsx(AnimatePresence, { mode: "wait", children: showLineHeightPicker && (jsx(motion.div, { ref: (el) => {
1569
- lineHeightPortalContentRef.current = el;
1570
- }, "data-flikkui-portal": "", role: "listbox", className: cn(surfaceClasses(surfaceLevel, { translucent: true, shadow: false }), themeStyles.dropdownStyle), style: portalStyle, variants: shouldReduceMotion ? undefined : lineHeightAnimations, initial: "initial", animate: lineHeightPortalReady ? "visible" : "initial", exit: "exit", children: jsx(SurfaceProvider, { level: surfaceLevel, children: LINE_HEIGHT_OPTIONS.map((option) => {
1571
- const selected = option.key === formattingState.lineHeight;
1572
- return (jsx("button", { className: themeStyles.dropdownItemStyle, "data-active": selected ? "true" : "false", onMouseDown: (event) => {
1573
- event.preventDefault();
1574
- focusEditor();
1575
- }, onClick: (event) => {
1576
- event.preventDefault();
1577
- event.stopPropagation();
1578
- handleLineHeight(option.key);
1579
- }, role: "option", "aria-selected": selected, children: jsxs("span", { className: "flex items-center justify-between gap-3", children: [jsx("span", { className: "text-sm font-medium", children: option.label }), jsx("span", { className: "text-sm text-[var(--color-text-muted)]", children: option.value })] }) }, option.key));
1580
- }) }) })) }), document.body)
1581
- : null;
1582
- return (jsxs("div", { className: "relative", "data-tool": "lineHeight", children: [jsx(Button, { ref: lineHeightTriggerRef, size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), "data-state": isActive ? "active" : "inactive", onMouseDown: handleMouseDown, onClick: (event) => {
1583
- event.preventDefault();
1584
- event.stopPropagation();
1585
- focusEditor();
1586
- togglePicker("lineHeight");
1587
- }, disabled: isDisabled, "aria-label": `Line height (${currentOption.label})`, "aria-expanded": showLineHeightPicker, "aria-haspopup": "listbox", children: jsx(ArrowsDownUp, { className: "w-4 h-4" }) }), renderedDropdown] }, toolKey));
1588
- }
1589
- case "letterSpacing": {
1590
- const currentOption = getLetterSpacingOption(formattingState.letterSpacing);
1591
- const portalStyle = {
1592
- position: "fixed",
1593
- top: letterSpacingPortalPosition.top,
1594
- left: letterSpacingPortalPosition.left,
1595
- zIndex: 1000,
1596
- ...letterSpacingPortalCssVars,
1597
- };
1598
- const renderedDropdown = isClient
1599
- ? createPortal(jsx(AnimatePresence, { mode: "wait", children: showLetterSpacingPicker && (jsx(motion.div, { ref: (el) => {
1600
- letterSpacingPortalContentRef.current = el;
1601
- }, "data-flikkui-portal": "", role: "listbox", className: cn(surfaceClasses(surfaceLevel, { translucent: true, shadow: false }), themeStyles.dropdownStyle), style: portalStyle, variants: shouldReduceMotion ? undefined : letterSpacingAnimations, initial: "initial", animate: letterSpacingPortalReady ? "visible" : "initial", exit: "exit", children: jsx(SurfaceProvider, { level: surfaceLevel, children: LETTER_SPACING_OPTIONS.map((option) => {
1602
- const selected = option.key === formattingState.letterSpacing;
1603
- return (jsx("button", { className: themeStyles.dropdownItemStyle, "data-active": selected ? "true" : "false", onMouseDown: (event) => {
1604
- event.preventDefault();
1605
- focusEditor();
1606
- }, onClick: (event) => {
1607
- event.preventDefault();
1608
- event.stopPropagation();
1609
- handleLetterSpacing(option.key);
1610
- }, role: "option", "aria-selected": selected, children: jsxs("span", { className: "flex items-center justify-between gap-3", children: [jsx("span", { className: "text-sm font-medium", children: option.label }), jsx("span", { className: "text-sm text-[var(--color-text-muted)]", children: option.value })] }) }, option.key));
1611
- }) }) })) }), document.body)
1612
- : null;
1613
- return (jsxs("div", { className: "relative", "data-tool": "letterSpacing", children: [jsx(Button, { ref: letterSpacingTriggerRef, size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), "data-state": isActive ? "active" : "inactive", onMouseDown: handleMouseDown, onClick: (event) => {
1614
- event.preventDefault();
1615
- event.stopPropagation();
1616
- focusEditor();
1617
- togglePicker("letterSpacing");
1618
- }, disabled: isDisabled, "aria-label": `Letter spacing (${currentOption.label})`, "aria-expanded": showLetterSpacingPicker, "aria-haspopup": "listbox", children: jsx(ArrowsLeftRight, { className: "w-4 h-4" }) }), renderedDropdown] }, toolKey));
1619
- }
1620
- case "textColor": {
1621
- const portalStyle = {
1622
- position: "fixed",
1623
- top: colorPortalPosition.top,
1624
- left: colorPortalPosition.left,
1625
- zIndex: 1000,
1626
- ...colorPortalCssVars,
1627
- };
1628
- const currentToken = formattingState.textColor;
1629
- // `bgValue` paints the swatch (resolved hex/oklch); `token` is the
1630
- // Tailwind shade fragment (`rose-500`, `white`, …) used to build
1631
- // the `text-{token}` class applied to the editor content.
1632
- const renderSwatch = (bgValue, token, label) => {
1633
- const isActiveSwatch = token === currentToken;
1634
- return (jsx("button", { className: themeStyles.colorSwatchStyle, style: { backgroundColor: bgValue }, "data-active": isActiveSwatch ? "true" : "false", onMouseDown: (event) => {
1635
- event.preventDefault();
1636
- focusEditor();
1637
- }, onClick: (event) => {
1638
- event.preventDefault();
1639
- event.stopPropagation();
1640
- handleTextColor(token);
1641
- }, "aria-label": `Set text color to ${label}` }, `swatch-${label}`));
1642
- };
1643
- const renderedColorDropdown = isClient
1644
- ? createPortal(jsx(AnimatePresence, { mode: "wait", children: showColorPicker && (jsx(motion.div, { ref: (el) => {
1645
- colorPortalContentRef.current = el;
1646
- }, "data-flikkui-portal": "", className: cn(surfaceClasses(surfaceLevel, { translucent: true, shadow: false }), themeStyles.dropdownStyle, "!max-h-none !overflow-visible"), style: portalStyle, variants: shouldReduceMotion ? undefined : colorAnimations, initial: "initial", animate: colorPortalReady ? "visible" : "initial", exit: "exit", children: jsx(SurfaceProvider, { level: surfaceLevel, children: jsx(ScrollArea, { type: "none", className: "max-h-[20rem]", children: jsxs("div", { className: themeStyles.colorPickerStyle, children: [recentColors.length > 0 && (jsxs("div", { className: "flex flex-col gap-1 pb-2 mb-1 border-b border-[var(--color-border)]", children: [jsx("span", { className: "text-[11px] font-medium uppercase tracking-wide text-[var(--color-text-muted)]", children: "Recent" }), jsx("div", { className: "flex gap-0.5", children: recentColors.map((token) => renderSwatch(resolveTailwindColor(token), token, `recent ${token}`)) })] })), jsxs("div", { className: "flex flex-col gap-1", children: [jsx("span", { className: "text-[11px] font-medium uppercase tracking-wide text-[var(--color-text-muted)]", children: "Mono" }), jsx("div", { className: "flex gap-0.5", children: MONO_COLORS.map((color) => renderSwatch(color.value, color.token, color.name)) }), jsx("span", { className: "mt-2 text-[11px] font-medium uppercase tracking-wide text-[var(--color-text-muted)]", children: "Spectrum" }), TAILWIND_COLOR_FAMILIES.map((family) => (jsx("div", { className: "flex gap-0.5", children: getTailwindShadeTokens(family).map((token) => renderSwatch(resolveTailwindColor(token), token, token)) }, family)))] })] }) }) }) })) }), document.body)
1647
- : null;
1648
- return (jsxs("div", { className: "relative", "data-tool": "textColor", children: [jsx(Button, { ref: colorTriggerRef, size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), onMouseDown: handleMouseDown, onClick: (event) => {
1649
- event.preventDefault();
1650
- event.stopPropagation();
1651
- focusEditor();
1652
- togglePicker("color");
1653
- }, disabled: isDisabled, "aria-label": "Text Color", "aria-expanded": showColorPicker, children: jsx(PaintBrush, { className: "w-4 h-4" }) }), renderedColorDropdown] }, toolKey));
1654
- }
1655
- case "alignLeft":
1656
- return (jsx(Button, { size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), "data-state": isActive ? "active" : "inactive", onMouseDown: handleMouseDown, onClick: (event) => {
1657
- event.preventDefault();
1658
- event.stopPropagation();
1659
- handleAlign("left");
1660
- }, disabled: isDisabled, "aria-label": "Align Left", "aria-pressed": isActive ? "true" : "false", children: jsx(TextAlignLeft, { className: "w-4 h-4" }) }, toolKey));
1661
- case "alignCenter":
1662
- return (jsx(Button, { size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), "data-state": isActive ? "active" : "inactive", onMouseDown: handleMouseDown, onClick: (event) => {
1663
- event.preventDefault();
1664
- event.stopPropagation();
1665
- handleAlign("center");
1666
- }, disabled: isDisabled, "aria-label": "Align Center", "aria-pressed": isActive ? "true" : "false", children: jsx(List, { className: "w-4 h-4" }) }, toolKey));
1667
- case "alignRight":
1668
- return (jsx(Button, { size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), "data-state": isActive ? "active" : "inactive", onMouseDown: handleMouseDown, onClick: (event) => {
1669
- event.preventDefault();
1670
- event.stopPropagation();
1671
- handleAlign("right");
1672
- }, disabled: isDisabled, "aria-label": "Align Right", "aria-pressed": isActive ? "true" : "false", children: jsx(TextAlignRight, { className: "w-4 h-4" }) }, toolKey));
1673
- case "undo":
1674
- return (jsx(Button, { size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), onMouseDown: handleMouseDown, onClick: handleUndo, disabled: isDisabled, "aria-label": "Undo", children: jsx(ArrowUUpLeft, { className: "w-4 h-4" }) }, toolKey));
1675
- case "redo":
1676
- return (jsx(Button, { size: "sm", color: "mono", variant: "soft", iconOnly: true, className: cn(themeStyles.toolbarButtonStyle), onMouseDown: handleMouseDown, onClick: handleRedo, disabled: isDisabled, "aria-label": "Redo", children: jsx(ArrowUUpRight, { className: "w-4 h-4" }) }, toolKey));
1677
- case "separator":
1678
- return jsx("div", { className: themeStyles.separatorStyle }, toolKey);
1679
- default:
1680
- return null;
1681
- }
1682
- };
1683
- const renderToolbar = () => {
1684
- if (!toolbarConfig.show || !toolbarConfig.tools)
1685
- return null;
1686
- const tools = toolbarConfig.tools.map((tool, index) => renderToolbarTool(tool, `${tool}-${index}`));
1687
- if (toolbarConfig.position === "floating") {
1688
- return (jsx(AnimatePresence, { mode: "wait", children: showToolbar && (jsx(motion.div, { ref: toolbarRef, variants: shouldReduceMotion ? undefined : floatingToolbarVariants, initial: "initial", animate: "animate", exit: "exit", className: cn(surfaceClasses(surfaceLevel, { translucent: true }), themeStyles.floatingToolbarStyle, toolbarConfig.className), style: { position: "absolute", top: toolbarPosition.top, left: toolbarPosition.left, zIndex: 50 }, children: jsx(SurfaceProvider, { level: surfaceLevel, children: tools }) }, "floating-toolbar")) }));
1689
- }
1690
- return (jsx("div", { ref: toolbarRef, className: cn(themeStyles.toolbarStyle, toolbarConfig.className), children: tools }));
1691
- };
1692
- return (jsxs("div", { className: cn(themeStyles.wrapperStyle, className), ...props, children: [label && (typeof label === 'string' ? (jsx("div", { className: "mb-1", children: jsx(FormLabel, { htmlFor: editorId, className: labelClassName, state: state, required: required, children: label }) })) : (label)), jsxs("div", { className: "relative", children: [jsxs("div", { className: cn(themeStyles.containerStyle, themeStyles.states[state], themeStyles.sizes[size]), "data-state": getDataState(), children: [toolbarConfig.position === "top" && renderToolbar(), jsx("div", { ref: (el) => {
1693
- if (el) {
1694
- editorRef.current = el;
1695
- if (typeof ref === "function") {
1696
- ref(el);
1697
- }
1698
- else if (ref) {
1699
- ref.current = el;
1700
- }
1701
- }
1702
- }, id: editorId, contentEditable: !isDisabled, className: cn(themeStyles.editorStyle), "data-state": getDataState(), style: { minHeight: `${minHeight}px`, maxHeight: maxHeight ? `${maxHeight}px` : undefined }, "data-placeholder": placeholder, onFocus: () => {
1703
- setIsFocused(true);
1704
- updateFormattingState();
1705
- }, onBlur: () => {
1706
- setIsFocused(false);
1707
- if (toolbarConfig.position === "floating") {
1708
- setShowToolbar(false);
1709
- }
1710
- closeAllPickers();
1711
- }, "aria-invalid": isInvalid, "aria-required": required, "aria-describedby": displayedMessage ? messageId : undefined, role: "textbox", "aria-multiline": "true", "aria-label": typeof label === 'string' ? label : "Rich text editor", suppressContentEditableWarning: true })] }), toolbarConfig.position === "floating" && renderToolbar()] }), displayedMessage && (typeof displayedMessage === 'string' ? (jsx("div", { id: messageId, role: isInvalid ? "alert" : undefined, className: cn(themeStyles.helperText, helperTextClassName), children: displayedMessage })) : (displayedMessage))] }));
111
+ document.addEventListener("selectionchange", handler);
112
+ return () => document.removeEventListener("selectionchange", handler);
113
+ }, [saveSelection, syncFormatting]);
114
+ const runCommand = useCallback((fn) => {
115
+ if (isDisabled)
116
+ return;
117
+ restoreSelection();
118
+ fn();
119
+ syncFormatting();
120
+ emitChange();
121
+ }, [isDisabled, restoreSelection, syncFormatting, emitChange]);
122
+ const handleToolCommand = useCallback((tool) => {
123
+ if (tool === "link") {
124
+ saveSelection();
125
+ setLinkFieldOpen((open) => !open);
126
+ return;
127
+ }
128
+ runCommand(() => {
129
+ switch (tool) {
130
+ case "bold": return toggleBold();
131
+ case "italic": return toggleItalic();
132
+ case "underline": return toggleUnderline();
133
+ case "strikethrough": return toggleStrikethrough();
134
+ case "bulletList": return toggleBulletList();
135
+ case "orderedList": return toggleOrderedList();
136
+ case "blockquote": return toggleBlockquote(formatting.blockquote);
137
+ case "code": return toggleCodeBlock(formatting.code);
138
+ case "clearFormat": return clearFormatting();
139
+ case "undo": return undo();
140
+ case "redo": return redo();
141
+ default: return undefined;
142
+ }
143
+ });
144
+ }, [runCommand, saveSelection, formatting.blockquote, formatting.code]);
145
+ const handleBlockChange = useCallback((block) => runCommand(() => setBlockStyle(block)), [runCommand]);
146
+ /**
147
+ * Paste and drop are the two ways foreign markup reaches the document. Both
148
+ * are intercepted, sanitized, and re-inserted — the browser's default
149
+ * handler never runs, so nothing unsanitized touches the DOM.
150
+ */
151
+ const insertForeignHtml = useCallback((html, text) => {
152
+ const clean = sanitizeFn(html);
153
+ if (clean)
154
+ insertSanitizedHtml(clean);
155
+ else if (text)
156
+ insertText(text);
157
+ syncFormatting();
158
+ emitChange();
159
+ }, [sanitizeFn, syncFormatting, emitChange]);
160
+ const handlePaste = useCallback((event) => {
161
+ if (isDisabled)
162
+ return;
163
+ event.preventDefault();
164
+ insertForeignHtml(event.clipboardData.getData("text/html"), event.clipboardData.getData("text/plain"));
165
+ }, [isDisabled, insertForeignHtml]);
166
+ const handleDrop = useCallback((event) => {
167
+ if (isDisabled)
168
+ return;
169
+ event.preventDefault();
170
+ insertForeignHtml(event.dataTransfer.getData("text/html"), event.dataTransfer.getData("text/plain"));
171
+ }, [isDisabled, insertForeignHtml]);
172
+ const applyLink = useCallback((href) => {
173
+ setLinkFieldOpen(false);
174
+ runCommand(() => createLink(href));
175
+ }, [runCommand]);
176
+ const removeLink$1 = useCallback(() => {
177
+ setLinkFieldOpen(false);
178
+ runCommand(() => removeLink());
179
+ }, [runCommand]);
180
+ const cancelLink = useCallback(() => {
181
+ setLinkFieldOpen(false);
182
+ restoreSelection();
183
+ }, [restoreSelection]);
184
+ const setRefs = useCallback((node) => {
185
+ editorRef.current = node;
186
+ if (typeof ref === "function")
187
+ ref(node);
188
+ else if (ref)
189
+ ref.current = node;
190
+ }, [ref]);
191
+ const showToolbar = (toolbar === null || toolbar === void 0 ? void 0 : toolbar.show) !== false;
192
+ const tools = (_a = toolbar === null || toolbar === void 0 ? void 0 : toolbar.tools) !== null && _a !== void 0 ? _a : DEFAULT_TOOLBAR_TOOLS;
193
+ const message = isInvalid && errorMessage ? errorMessage : helperText;
194
+ const hasMessage = Boolean(message);
195
+ const restAriaLabel = rest["aria-label"];
196
+ return (jsxs("div", { className: cn(theme.wrapperStyle, wrapperClassName), children: [label && (jsx(FormLabel, { htmlFor: generatedId, state: state, required: required, className: labelClassName, children: label })), jsxs("div", { className: cn(theme.containerStyle, theme.containerStates[state], containerClassName), children: [showToolbar && (jsx(RichTextToolbar, { tools: tools, formatting: formatting, disabled: isDisabled, size: size, className: cn(toolbar === null || toolbar === void 0 ? void 0 : toolbar.className, toolbarClassName), onCommand: handleToolCommand, onBlockChange: handleBlockChange })), isLinkFieldOpen && !isDisabled && (jsx(RichTextLinkField, { initialHref: formatting.link, onApply: applyLink, onRemove: removeLink$1, onCancel: cancelLink })), jsx("div", { ...rest, id: generatedId, ref: setRefs, role: "textbox", "aria-multiline": "true", "aria-label": typeof label === "string" ? label : restAriaLabel !== null && restAriaLabel !== void 0 ? restAriaLabel : "Rich text editor", "aria-required": required || undefined, "aria-invalid": isInvalid || undefined, "aria-describedby": hasMessage ? describedById : undefined, "aria-disabled": isDisabled || undefined, contentEditable: !isDisabled, suppressContentEditableWarning: true, "data-placeholder": placeholder, "data-empty": isEmpty || undefined, tabIndex: isDisabled ? -1 : 0, style: { minHeight, maxHeight }, className: cn(theme.editorStyle, theme.editorSizes[size], isEmpty && placeholder && theme.placeholderStyle, className), onInput: emitChange, onPaste: handlePaste, onDrop: handleDrop, onKeyUp: syncFormatting, onMouseUp: syncFormatting, onBlur: saveSelection })] }), hasMessage && (jsx("div", { id: describedById, className: cn(isInvalid && errorMessage ? theme.errorTextStyle : theme.helperTextStyle, helperTextClassName), children: message }))] }));
1712
197
  });
1713
198
  RichTextEditor.displayName = "RichTextEditor";
1714
199
 
1715
- export { DEFAULT_FONT_FAMILY_OPTIONS, RichTextEditor, loadGoogleFont };
200
+ export { RichTextEditor };