@react-md/core 6.4.0 → 6.5.1

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 (431) hide show
  1. package/dist/_a11y.scss +3 -1
  2. package/dist/_box-shadows.scss +20 -12
  3. package/dist/_core.scss +1 -1
  4. package/dist/_utils.scss +26 -11
  5. package/dist/app-bar/_app-bar.scss +3 -3
  6. package/dist/autocomplete/AutocompleteChip.js +2 -2
  7. package/dist/autocomplete/AutocompleteChip.js.map +1 -1
  8. package/dist/autocomplete/AutocompleteListboxChildren.js +1 -1
  9. package/dist/autocomplete/AutocompleteListboxChildren.js.map +1 -1
  10. package/dist/autocomplete/_autocomplete.scss +20 -16
  11. package/dist/autocomplete/useAutocomplete.js +4 -4
  12. package/dist/autocomplete/useAutocomplete.js.map +1 -1
  13. package/dist/autocomplete/utils.js +3 -3
  14. package/dist/autocomplete/utils.js.map +1 -1
  15. package/dist/avatar/_avatar.scss +2 -1
  16. package/dist/box/styles.js +2 -2
  17. package/dist/box/styles.js.map +1 -1
  18. package/dist/button/AsyncButton.js +1 -1
  19. package/dist/button/AsyncButton.js.map +1 -1
  20. package/dist/button/_button.scss +9 -5
  21. package/dist/card/_card.scss +6 -6
  22. package/dist/chip/Chip.js +1 -1
  23. package/dist/chip/Chip.js.map +1 -1
  24. package/dist/chip/_chip.scss +6 -6
  25. package/dist/cssUtils.d.ts +11 -6
  26. package/dist/cssUtils.js.map +1 -1
  27. package/dist/datetime/useTimeField.js +1 -1
  28. package/dist/datetime/useTimeField.js.map +1 -1
  29. package/dist/delegateEvent.js +9 -9
  30. package/dist/delegateEvent.js.map +1 -1
  31. package/dist/dialog/_dialog.scss +6 -6
  32. package/dist/divider/_divider.scss +6 -2
  33. package/dist/draggable/useDraggable.js +4 -4
  34. package/dist/draggable/useDraggable.js.map +1 -1
  35. package/dist/draggable/utils.js +1 -1
  36. package/dist/draggable/utils.js.map +1 -1
  37. package/dist/expansion-panel/ExpansionPanel.js +1 -1
  38. package/dist/expansion-panel/ExpansionPanel.js.map +1 -1
  39. package/dist/expansion-panel/useExpansionPanels.js +1 -1
  40. package/dist/expansion-panel/useExpansionPanels.js.map +1 -1
  41. package/dist/files/FileInput.js +1 -1
  42. package/dist/files/FileInput.js.map +1 -1
  43. package/dist/files/createAcceptFromExtensions.d.ts +5 -0
  44. package/dist/files/createAcceptFromExtensions.js +15 -0
  45. package/dist/files/createAcceptFromExtensions.js.map +1 -0
  46. package/dist/files/useFileUpload.js +45 -41
  47. package/dist/files/useFileUpload.js.map +1 -1
  48. package/dist/files/utils.js +14 -10
  49. package/dist/files/utils.js.map +1 -1
  50. package/dist/files/validation.js +7 -8
  51. package/dist/files/validation.js.map +1 -1
  52. package/dist/focus/useFocusContainer.js +1 -1
  53. package/dist/focus/useFocusContainer.js.map +1 -1
  54. package/dist/focus/utils.js +12 -7
  55. package/dist/focus/utils.js.map +1 -1
  56. package/dist/form/InputToggleIcon.js +5 -1
  57. package/dist/form/InputToggleIcon.js.map +1 -1
  58. package/dist/form/NativeSelect.js +1 -1
  59. package/dist/form/NativeSelect.js.map +1 -1
  60. package/dist/form/Select.d.ts +24 -0
  61. package/dist/form/Select.js +19 -8
  62. package/dist/form/Select.js.map +1 -1
  63. package/dist/form/SelectedOption.d.ts +1 -2
  64. package/dist/form/SelectedOption.js +2 -2
  65. package/dist/form/SelectedOption.js.map +1 -1
  66. package/dist/form/_input-toggle.scss +6 -5
  67. package/dist/form/_label.scss +2 -2
  68. package/dist/form/_legend.scss +22 -13
  69. package/dist/form/_slider.scss +7 -5
  70. package/dist/form/_switch.scss +7 -5
  71. package/dist/form/_text-field.scss +13 -11
  72. package/dist/form/formConfig.js +1 -1
  73. package/dist/form/formConfig.js.map +1 -1
  74. package/dist/form/inputToggleStyles.js +7 -1
  75. package/dist/form/inputToggleStyles.js.map +1 -1
  76. package/dist/form/legendStyles.d.ts +1 -1
  77. package/dist/form/legendStyles.js.map +1 -1
  78. package/dist/form/selectUtils.js +2 -2
  79. package/dist/form/selectUtils.js.map +1 -1
  80. package/dist/form/useCombobox.js +1 -0
  81. package/dist/form/useCombobox.js.map +1 -1
  82. package/dist/form/useFormReset.js +2 -2
  83. package/dist/form/useFormReset.js.map +1 -1
  84. package/dist/form/useNumberField.js +1 -1
  85. package/dist/form/useNumberField.js.map +1 -1
  86. package/dist/form/useResizingTextArea.js +4 -4
  87. package/dist/form/useResizingTextArea.js.map +1 -1
  88. package/dist/form/useSelectCombobox.js +1 -1
  89. package/dist/form/useSelectCombobox.js.map +1 -1
  90. package/dist/form/validation.js +1 -1
  91. package/dist/form/validation.js.map +1 -1
  92. package/dist/hoverMode/useHoverMode.js +8 -8
  93. package/dist/hoverMode/useHoverMode.js.map +1 -1
  94. package/dist/hoverMode/useHoverModeProvider.js +3 -3
  95. package/dist/hoverMode/useHoverModeProvider.js.map +1 -1
  96. package/dist/icon/config.js +3 -3
  97. package/dist/icon/config.js.map +1 -1
  98. package/dist/icon/materialConfig.js +1 -1
  99. package/dist/icon/materialConfig.js.map +1 -1
  100. package/dist/interaction/UserInteractionModeProvider.js +11 -10
  101. package/dist/interaction/UserInteractionModeProvider.js.map +1 -1
  102. package/dist/interaction/_interaction.scss +5 -3
  103. package/dist/interaction/utils.js +7 -3
  104. package/dist/interaction/utils.js.map +1 -1
  105. package/dist/layout/useExpandableLayout.js +3 -4
  106. package/dist/layout/useExpandableLayout.js.map +1 -1
  107. package/dist/layout/useMainTabIndex.js +1 -1
  108. package/dist/layout/useMainTabIndex.js.map +1 -1
  109. package/dist/list/ListItem.js +1 -1
  110. package/dist/list/ListItem.js.map +1 -1
  111. package/dist/media-queries/AppSizeProvider.js +1 -1
  112. package/dist/media-queries/AppSizeProvider.js.map +1 -1
  113. package/dist/media-queries/config.js +2 -2
  114. package/dist/media-queries/config.js.map +1 -1
  115. package/dist/media-queries/useMediaQuery.js +3 -3
  116. package/dist/media-queries/useMediaQuery.js.map +1 -1
  117. package/dist/menu/Menu.js +4 -4
  118. package/dist/menu/Menu.js.map +1 -1
  119. package/dist/menu/MenuItemButton.js +1 -1
  120. package/dist/menu/MenuItemButton.js.map +1 -1
  121. package/dist/menu/MenuItemFileInput.js +1 -1
  122. package/dist/menu/MenuItemFileInput.js.map +1 -1
  123. package/dist/menu/MenuWidget.js +2 -2
  124. package/dist/menu/MenuWidget.js.map +1 -1
  125. package/dist/movement/findMatchIndex.js +2 -2
  126. package/dist/movement/findMatchIndex.js.map +1 -1
  127. package/dist/movement/useKeyboardMovementProvider.js +2 -2
  128. package/dist/movement/useKeyboardMovementProvider.js.map +1 -1
  129. package/dist/movement/utils.js +12 -10
  130. package/dist/movement/utils.js.map +1 -1
  131. package/dist/navigation/getTableOfContentsHeadings.js +4 -3
  132. package/dist/navigation/getTableOfContentsHeadings.js.map +1 -1
  133. package/dist/navigation/useActiveHeadingId.js +9 -9
  134. package/dist/navigation/useActiveHeadingId.js.map +1 -1
  135. package/dist/navigation/useTableOfContentsHeadings.js +1 -1
  136. package/dist/navigation/useTableOfContentsHeadings.js.map +1 -1
  137. package/dist/navigation/utils.js +6 -5
  138. package/dist/navigation/utils.js.map +1 -1
  139. package/dist/portal/PortalContainerProvider.js +5 -3
  140. package/dist/portal/PortalContainerProvider.js.map +1 -1
  141. package/dist/positioning/getFixedPosition.js +2 -4
  142. package/dist/positioning/getFixedPosition.js.map +1 -1
  143. package/dist/positioning/useFixedPositioning.js +2 -2
  144. package/dist/positioning/useFixedPositioning.js.map +1 -1
  145. package/dist/positioning/utils.js +3 -3
  146. package/dist/positioning/utils.js.map +1 -1
  147. package/dist/scroll/getScrollbarWidth.js +4 -4
  148. package/dist/scroll/getScrollbarWidth.js.map +1 -1
  149. package/dist/searching/fuzzy.js +3 -2
  150. package/dist/searching/fuzzy.js.map +1 -1
  151. package/dist/searching/toSearchQuery.js +1 -1
  152. package/dist/searching/toSearchQuery.js.map +1 -1
  153. package/dist/searching/utils.js +1 -1
  154. package/dist/searching/utils.js.map +1 -1
  155. package/dist/snackbar/Toast.js +1 -1
  156. package/dist/snackbar/Toast.js.map +1 -1
  157. package/dist/snackbar/ToastContent.js +2 -2
  158. package/dist/snackbar/ToastContent.js.map +1 -1
  159. package/dist/snackbar/ToastManager.d.ts +1 -1
  160. package/dist/snackbar/ToastManager.js +11 -11
  161. package/dist/snackbar/ToastManager.js.map +1 -1
  162. package/dist/snackbar/_snackbar.scss +3 -3
  163. package/dist/spinbutton/useSpinButton.js +1 -1
  164. package/dist/spinbutton/useSpinButton.js.map +1 -1
  165. package/dist/spinbutton/utils/deselectNode.js +1 -1
  166. package/dist/spinbutton/utils/deselectNode.js.map +1 -1
  167. package/dist/spinbutton/utils/resolveInputEvent.js +1 -1
  168. package/dist/spinbutton/utils/resolveInputEvent.js.map +1 -1
  169. package/dist/spinbutton/utils/selectNode.js +1 -1
  170. package/dist/spinbutton/utils/selectNode.js.map +1 -1
  171. package/dist/storage/useStorage.js +8 -3
  172. package/dist/storage/useStorage.js.map +1 -1
  173. package/dist/table/useStickyTableSection.js +1 -1
  174. package/dist/table/useStickyTableSection.js.map +1 -1
  175. package/dist/tabs/TabList.js +2 -2
  176. package/dist/tabs/TabList.js.map +1 -1
  177. package/dist/tabs/_tabs.scss +5 -6
  178. package/dist/tabs/useMaxTabPanelHeight.js +4 -3
  179. package/dist/tabs/useMaxTabPanelHeight.js.map +1 -1
  180. package/dist/tabs/useTabList.js +1 -1
  181. package/dist/tabs/useTabList.js.map +1 -1
  182. package/dist/test-utils/jest-globals/match-media.d.ts +1 -1
  183. package/dist/test-utils/jest-globals/match-media.js +1 -1
  184. package/dist/test-utils/jest-globals/match-media.js.map +1 -1
  185. package/dist/test-utils/jest-globals/timers.js +1 -1
  186. package/dist/test-utils/jest-globals/timers.js.map +1 -1
  187. package/dist/test-utils/jest-globals/uploadMenuItemFileInput.js +1 -1
  188. package/dist/test-utils/jest-globals/uploadMenuItemFileInput.js.map +1 -1
  189. package/dist/test-utils/mocks/ResizeObserver.js +2 -2
  190. package/dist/test-utils/mocks/ResizeObserver.js.map +1 -1
  191. package/dist/test-utils/polyfills/IntersectionObserver.js +2 -2
  192. package/dist/test-utils/polyfills/IntersectionObserver.js.map +1 -1
  193. package/dist/test-utils/polyfills/ResizeObserver.js +2 -2
  194. package/dist/test-utils/polyfills/ResizeObserver.js.map +1 -1
  195. package/dist/test-utils/polyfills/TextDecoder.js +2 -2
  196. package/dist/test-utils/polyfills/TextDecoder.js.map +1 -1
  197. package/dist/test-utils/polyfills/TextEncoder.js +2 -2
  198. package/dist/test-utils/polyfills/TextEncoder.js.map +1 -1
  199. package/dist/test-utils/polyfills/matchMedia.js +2 -2
  200. package/dist/test-utils/polyfills/matchMedia.js.map +1 -1
  201. package/dist/test-utils/polyfills/offsetParent.js +2 -2
  202. package/dist/test-utils/polyfills/offsetParent.js.map +1 -1
  203. package/dist/test-utils/polyfills/scrollIntoView.js +1 -1
  204. package/dist/test-utils/polyfills/scrollIntoView.js.map +1 -1
  205. package/dist/test-utils/queries/select.js +2 -2
  206. package/dist/test-utils/queries/select.js.map +1 -1
  207. package/dist/test-utils/queries/slider.js +1 -1
  208. package/dist/test-utils/queries/slider.js.map +1 -1
  209. package/dist/test-utils/utils/createFileList.js +2 -0
  210. package/dist/test-utils/utils/createFileList.js.map +1 -1
  211. package/dist/test-utils/utils/createMatchMediaSpy.d.ts +1 -1
  212. package/dist/test-utils/utils/createMatchMediaSpy.js +3 -3
  213. package/dist/test-utils/utils/createMatchMediaSpy.js.map +1 -1
  214. package/dist/test-utils/vitest/match-media.d.ts +1 -1
  215. package/dist/test-utils/vitest/match-media.js +1 -1
  216. package/dist/test-utils/vitest/match-media.js.map +1 -1
  217. package/dist/test-utils/vitest/timers.js +1 -1
  218. package/dist/test-utils/vitest/timers.js.map +1 -1
  219. package/dist/test-utils/vitest/uploadMenuItemFileInput.js +1 -1
  220. package/dist/test-utils/vitest/uploadMenuItemFileInput.js.map +1 -1
  221. package/dist/theme/ThemeProvider.js +2 -2
  222. package/dist/theme/ThemeProvider.js.map +1 -1
  223. package/dist/theme/_a11y.scss +3 -1
  224. package/dist/theme/_theme.scss +16 -12
  225. package/dist/theme/getDerivedTheme.js +1 -1
  226. package/dist/theme/getDerivedTheme.js.map +1 -1
  227. package/dist/theme/useCSSVariables.js +5 -5
  228. package/dist/theme/useCSSVariables.js.map +1 -1
  229. package/dist/theme/useColorSchemeMetaTag.js +2 -2
  230. package/dist/theme/useColorSchemeMetaTag.js.map +1 -1
  231. package/dist/theme/useInlineCSSVariables.js +4 -3
  232. package/dist/theme/useInlineCSSVariables.js.map +1 -1
  233. package/dist/theme/utils.js +8 -8
  234. package/dist/theme/utils.js.map +1 -1
  235. package/dist/tooltip/useTooltip.js +7 -7
  236. package/dist/tooltip/useTooltip.js.map +1 -1
  237. package/dist/tooltip/useTooltipPosition.js +1 -1
  238. package/dist/tooltip/useTooltipPosition.js.map +1 -1
  239. package/dist/transition/useCarousel.js +2 -2
  240. package/dist/transition/useCarousel.js.map +1 -1
  241. package/dist/transition/useCollapseTransition.js +1 -1
  242. package/dist/transition/useCollapseTransition.js.map +1 -1
  243. package/dist/transition/useSkeletonPlaceholder.js +4 -4
  244. package/dist/transition/useSkeletonPlaceholder.js.map +1 -1
  245. package/dist/transition/useTransition.js +2 -2
  246. package/dist/transition/useTransition.js.map +1 -1
  247. package/dist/transition/utils.js +5 -5
  248. package/dist/transition/utils.js.map +1 -1
  249. package/dist/tree/TreeItem.js +1 -1
  250. package/dist/tree/TreeItem.js.map +1 -1
  251. package/dist/tree/useTreeItems.js +7 -5
  252. package/dist/tree/useTreeItems.js.map +1 -1
  253. package/dist/tree/useTreeMovement.js +1 -1
  254. package/dist/tree/useTreeMovement.js.map +1 -1
  255. package/dist/tree/utils.js +6 -9
  256. package/dist/tree/utils.js.map +1 -1
  257. package/dist/typography/HighlightText.js +2 -1
  258. package/dist/typography/HighlightText.js.map +1 -1
  259. package/dist/typography/SrOnly.js +7 -1
  260. package/dist/typography/SrOnly.js.map +1 -1
  261. package/dist/useDebouncedFunction.js +4 -4
  262. package/dist/useDebouncedFunction.js.map +1 -1
  263. package/dist/useDropzone.js +9 -9
  264. package/dist/useDropzone.js.map +1 -1
  265. package/dist/useEnsuredState.js +5 -5
  266. package/dist/useEnsuredState.js.map +1 -1
  267. package/dist/useIntersectionObserver.js +3 -3
  268. package/dist/useIntersectionObserver.js.map +1 -1
  269. package/dist/useIsomorphicLayoutEffect.js +1 -1
  270. package/dist/useIsomorphicLayoutEffect.js.map +1 -1
  271. package/dist/useOrientation.js +1 -1
  272. package/dist/useOrientation.js.map +1 -1
  273. package/dist/useReadonlySet.js +1 -1
  274. package/dist/useReadonlySet.js.map +1 -1
  275. package/dist/useResizeListener.js +2 -2
  276. package/dist/useResizeListener.js.map +1 -1
  277. package/dist/useResizeObserver.js +3 -4
  278. package/dist/useResizeObserver.js.map +1 -1
  279. package/dist/useThrottledFunction.js +3 -3
  280. package/dist/useThrottledFunction.js.map +1 -1
  281. package/dist/useWindowSize.js +1 -1
  282. package/dist/useWindowSize.js.map +1 -1
  283. package/dist/utils/alphaNumericSort.js +3 -1
  284. package/dist/utils/alphaNumericSort.js.map +1 -1
  285. package/dist/utils/bem.js +9 -12
  286. package/dist/utils/bem.js.map +1 -1
  287. package/dist/utils/getNumberOfDigits.js +1 -0
  288. package/dist/utils/getNumberOfDigits.js.map +1 -1
  289. package/dist/utils/getRangeDefaultValue.js +1 -1
  290. package/dist/utils/getRangeDefaultValue.js.map +1 -1
  291. package/dist/utils/nearest.js +2 -2
  292. package/dist/utils/nearest.js.map +1 -1
  293. package/dist/utils/parseCssLengthUnit.js +3 -3
  294. package/dist/utils/parseCssLengthUnit.js.map +1 -1
  295. package/dist/utils/trigonometry.js +1 -1
  296. package/dist/utils/trigonometry.js.map +1 -1
  297. package/dist/window-splitter/_window-splitter.scss +15 -17
  298. package/package.json +9 -7
  299. package/src/autocomplete/AutocompleteChip.tsx +2 -2
  300. package/src/autocomplete/AutocompleteListboxChildren.tsx +1 -1
  301. package/src/autocomplete/useAutocomplete.ts +4 -4
  302. package/src/autocomplete/utils.ts +3 -3
  303. package/src/box/styles.ts +2 -2
  304. package/src/button/AsyncButton.tsx +1 -3
  305. package/src/chip/Chip.tsx +1 -2
  306. package/src/cssUtils.ts +12 -6
  307. package/src/datetime/useTimeField.ts +1 -1
  308. package/src/delegateEvent.ts +9 -9
  309. package/src/draggable/useDraggable.ts +4 -4
  310. package/src/draggable/utils.ts +1 -1
  311. package/src/expansion-panel/ExpansionPanel.tsx +1 -1
  312. package/src/expansion-panel/useExpansionPanels.ts +1 -1
  313. package/src/files/FileInput.tsx +1 -1
  314. package/src/files/createAcceptFromExtensions.ts +18 -0
  315. package/src/files/useFileUpload.ts +36 -37
  316. package/src/files/utils.ts +15 -11
  317. package/src/files/validation.ts +7 -9
  318. package/src/focus/useFocusContainer.ts +1 -1
  319. package/src/focus/utils.ts +11 -6
  320. package/src/form/InputToggleIcon.tsx +5 -5
  321. package/src/form/NativeSelect.tsx +1 -1
  322. package/src/form/Select.tsx +58 -7
  323. package/src/form/SelectedOption.tsx +2 -4
  324. package/src/form/formConfig.ts +1 -1
  325. package/src/form/inputToggleStyles.ts +9 -4
  326. package/src/form/legendStyles.ts +1 -1
  327. package/src/form/selectUtils.ts +2 -2
  328. package/src/form/useCombobox.ts +1 -0
  329. package/src/form/useFormReset.ts +2 -2
  330. package/src/form/useNumberField.ts +1 -1
  331. package/src/form/useResizingTextArea.ts +5 -5
  332. package/src/form/useSelectCombobox.ts +1 -4
  333. package/src/form/validation.ts +1 -1
  334. package/src/hoverMode/useHoverMode.ts +9 -9
  335. package/src/hoverMode/useHoverModeProvider.ts +4 -4
  336. package/src/icon/config.tsx +3 -3
  337. package/src/icon/materialConfig.ts +1 -1
  338. package/src/interaction/UserInteractionModeProvider.tsx +11 -10
  339. package/src/interaction/utils.ts +3 -3
  340. package/src/layout/useExpandableLayout.ts +3 -4
  341. package/src/layout/useMainTabIndex.ts +1 -1
  342. package/src/list/ListItem.tsx +1 -1
  343. package/src/media-queries/AppSizeProvider.tsx +1 -1
  344. package/src/media-queries/config.ts +2 -2
  345. package/src/media-queries/useMediaQuery.ts +3 -3
  346. package/src/menu/Menu.tsx +4 -4
  347. package/src/menu/MenuItemButton.tsx +1 -1
  348. package/src/menu/MenuItemFileInput.tsx +1 -1
  349. package/src/menu/MenuWidget.tsx +6 -4
  350. package/src/movement/findMatchIndex.ts +2 -2
  351. package/src/movement/useKeyboardMovementProvider.ts +2 -2
  352. package/src/movement/utils.ts +15 -14
  353. package/src/navigation/getTableOfContentsHeadings.ts +4 -3
  354. package/src/navigation/useActiveHeadingId.ts +8 -8
  355. package/src/navigation/useTableOfContentsHeadings.ts +1 -1
  356. package/src/navigation/utils.ts +6 -5
  357. package/src/portal/PortalContainerProvider.tsx +5 -3
  358. package/src/positioning/getFixedPosition.ts +9 -6
  359. package/src/positioning/useFixedPositioning.ts +2 -2
  360. package/src/positioning/utils.ts +3 -3
  361. package/src/scroll/getScrollbarWidth.ts +4 -4
  362. package/src/searching/fuzzy.ts +7 -3
  363. package/src/searching/toSearchQuery.ts +1 -1
  364. package/src/searching/utils.ts +1 -1
  365. package/src/snackbar/Toast.tsx +1 -1
  366. package/src/snackbar/ToastContent.tsx +2 -2
  367. package/src/snackbar/ToastManager.ts +11 -12
  368. package/src/spinbutton/useSpinButton.ts +1 -1
  369. package/src/spinbutton/utils/deselectNode.ts +1 -1
  370. package/src/spinbutton/utils/resolveInputEvent.ts +1 -1
  371. package/src/spinbutton/utils/selectNode.ts +1 -1
  372. package/src/storage/useStorage.ts +7 -2
  373. package/src/table/useStickyTableSection.tsx +1 -1
  374. package/src/tabs/TabList.tsx +2 -2
  375. package/src/tabs/useMaxTabPanelHeight.ts +6 -3
  376. package/src/tabs/useTabList.ts +2 -2
  377. package/src/test-utils/jest-globals/match-media.ts +5 -2
  378. package/src/test-utils/jest-globals/timers.ts +1 -1
  379. package/src/test-utils/jest-globals/uploadMenuItemFileInput.ts +1 -1
  380. package/src/test-utils/mocks/ResizeObserver.ts +2 -2
  381. package/src/test-utils/polyfills/IntersectionObserver.ts +2 -2
  382. package/src/test-utils/polyfills/ResizeObserver.ts +2 -2
  383. package/src/test-utils/polyfills/TextDecoder.ts +2 -2
  384. package/src/test-utils/polyfills/TextEncoder.ts +2 -2
  385. package/src/test-utils/polyfills/matchMedia.ts +5 -2
  386. package/src/test-utils/polyfills/offsetParent.ts +2 -2
  387. package/src/test-utils/polyfills/scrollIntoView.ts +1 -1
  388. package/src/test-utils/queries/select.ts +2 -2
  389. package/src/test-utils/queries/slider.ts +1 -1
  390. package/src/test-utils/utils/createFileList.ts +2 -0
  391. package/src/test-utils/utils/createMatchMediaSpy.ts +4 -4
  392. package/src/test-utils/vitest/match-media.ts +2 -2
  393. package/src/test-utils/vitest/timers.ts +1 -1
  394. package/src/test-utils/vitest/uploadMenuItemFileInput.ts +1 -1
  395. package/src/theme/ThemeProvider.tsx +2 -2
  396. package/src/theme/getDerivedTheme.ts +1 -1
  397. package/src/theme/useCSSVariables.ts +5 -5
  398. package/src/theme/useColorSchemeMetaTag.ts +2 -2
  399. package/src/theme/useInlineCSSVariables.ts +6 -7
  400. package/src/theme/utils.ts +8 -8
  401. package/src/tooltip/useTooltip.ts +7 -7
  402. package/src/tooltip/useTooltipPosition.ts +1 -1
  403. package/src/transition/useCarousel.ts +2 -2
  404. package/src/transition/useCollapseTransition.ts +1 -1
  405. package/src/transition/useSkeletonPlaceholder.ts +4 -4
  406. package/src/transition/useTransition.ts +2 -2
  407. package/src/transition/utils.ts +5 -5
  408. package/src/tree/TreeItem.tsx +1 -1
  409. package/src/tree/useTreeItems.ts +5 -5
  410. package/src/tree/useTreeMovement.ts +1 -1
  411. package/src/tree/utils.ts +9 -9
  412. package/src/typography/HighlightText.tsx +4 -3
  413. package/src/typography/SrOnly.tsx +9 -2
  414. package/src/useDebouncedFunction.ts +5 -5
  415. package/src/useDropzone.ts +10 -10
  416. package/src/useEnsuredState.ts +5 -5
  417. package/src/useIntersectionObserver.ts +3 -3
  418. package/src/useIsomorphicLayoutEffect.ts +3 -3
  419. package/src/useOrientation.ts +1 -1
  420. package/src/useReadonlySet.ts +3 -1
  421. package/src/useResizeListener.ts +2 -2
  422. package/src/useResizeObserver.ts +3 -4
  423. package/src/useThrottledFunction.ts +4 -4
  424. package/src/useWindowSize.ts +1 -1
  425. package/src/utils/alphaNumericSort.ts +1 -1
  426. package/src/utils/bem.ts +15 -16
  427. package/src/utils/getNumberOfDigits.ts +1 -0
  428. package/src/utils/getRangeDefaultValue.ts +1 -1
  429. package/src/utils/nearest.ts +5 -2
  430. package/src/utils/parseCssLengthUnit.ts +5 -4
  431. package/src/utils/trigonometry.ts +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/useCombobox.ts"],"sourcesContent":["\"use client\";\n\nimport {\n type FocusEventHandler,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n type InputHTMLAttributes,\n type KeyboardEventHandler,\n type MouseEventHandler,\n type Ref,\n type RefCallback,\n type RefObject,\n useCallback,\n useRef,\n} from \"react\";\n\nimport { type MenuProps } from \"../menu/Menu.js\";\nimport { type MenuSheetConfigurableProps } from \"../menu/MenuSheet.js\";\nimport {\n type GetDefaultFocusedIndex,\n type GetFocusableElements,\n type KeyboardMovementExtensionData,\n type KeyboardMovementProviderImplementation,\n type KeyboardMovementProviderOptions,\n} from \"../movement/types.js\";\nimport { useKeyboardMovementProvider } from \"../movement/useKeyboardMovementProvider.js\";\nimport { BELOW_CENTER_ANCHOR } from \"../positioning/constants.js\";\nimport {\n type PositionAnchor,\n type PositionWidth,\n} from \"../positioning/types.js\";\nimport { getTransitionCallbacks } from \"../transition/getTransitionCallbacks.js\";\nimport { type TransitionCallbacks } from \"../transition/types.js\";\nimport {\n type NonNullMutableRef,\n type UseStateInitializer,\n type UseStateSetter,\n} from \"../types.js\";\nimport { useEnsuredId } from \"../useEnsuredId.js\";\nimport { useEnsuredRef } from \"../useEnsuredRef.js\";\nimport { useEnsuredState } from \"../useEnsuredState.js\";\nimport { tryToSubmitRelatedForm } from \"./utils.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n * @since 6.0.0\n */\nexport const getNonDisabledOptions = (\n container: HTMLElement\n): readonly HTMLElement[] => [\n ...container.querySelectorAll<HTMLLIElement>(\n '[role=\"option\"]:not([aria-disabled])'\n ),\n];\n\n/**\n * @since 6.0.0\n */\nexport type SupportedComboboxPopup = \"listbox\" | \"grid\" | \"dialog\";\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxKeyboardMovementData<\n E extends HTMLElement = HTMLInputElement,\n> extends KeyboardMovementExtensionData<E> {\n show: () => void;\n hide: () => void;\n visible: boolean;\n\n /**\n * @since 6.3.0 Renamed from `focusLast` to `focusLastRef` to support the new\n * actions.\n */\n focusLastRef: NonNullMutableRef<boolean>;\n}\n\n/**\n * @since 6.0.0\n */\nexport type ExtendComboboxKeyDown<E extends HTMLElement = HTMLInputElement> = (\n movementData: ComboboxKeyboardMovementData<E>\n) => void;\n\n/**\n * @since 6.0.0\n */\nexport type ComboboxKeyboardMovementOptions<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n> = Pick<\n KeyboardMovementProviderOptions<ComboboxEl>,\n | \"onClick\"\n | \"onFocus\"\n | \"onKeyDown\"\n | \"disabled\"\n | \"loopable\"\n | \"searchable\"\n | \"onFocusChange\"\n | \"isNegativeOneAllowed\"\n>;\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxVisibilityOptions {\n /**\n * This can be used to control the popup's visibility and **must** be used\n * along with {@link setVisible}.\n */\n visible?: boolean;\n\n /**\n * Used to control the popup's visibility and should generally be a `useState`\n * setter.\n *\n * @example Controlling the Visibility\n * ```tsx\n * const [visible, setVisible] = useState(false);\n *\n * useCombobox({\n * visible,\n * setVisible,\n * });\n * ```\n */\n setVisible?: UseStateSetter<boolean>;\n\n /**\n * Set this to `true` to have the combobox's popup visible by default.\n *\n * @defaultValue `false`\n */\n defaultVisible?: UseStateInitializer<boolean>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ConfigurableComboboxOptions<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n>\n extends\n ComboboxKeyboardMovementOptions<ComboboxEl>,\n ComboboxVisibilityOptions {\n /**\n * This is the {@link InputHTMLAttributes.form} attribute and is used to\n * attempt submitting a form when the enter key is pressed.\n */\n form?: string;\n\n /**\n * @defaultValue `\"combobox-popup-\" + useId()`\n */\n popupId?: string;\n popupRef?: Ref<PopupEl>;\n\n /**\n * @defaultValue `\"combobox-\" + useId()`\n */\n comboboxId?: string;\n comboboxRef?: Ref<ComboboxEl>;\n\n /**\n * @defaultValue `\"listbox\"`\n */\n popup?: \"listbox\" | \"grid\" | \"dialog\";\n\n /**\n * @defaultValue `false`\n */\n multiselect?: boolean;\n\n extendKeyDown?: ExtendComboboxKeyDown<ComboboxEl>;\n\n /**\n * @defaultValue {@link getNonDisabledOptions}\n */\n getFocusableElements?: GetFocusableElements;\n\n getDefaultFocusedIndex?: GetDefaultFocusedIndex;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxGetEnterDefaultFocusedIndexOptions {\n focusLast: boolean;\n focusables: readonly HTMLElement[];\n currentFocusIndex: number;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxOptions<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n> extends ConfigurableComboboxOptions<ComboboxEl, PopupEl> {\n getEnterDefaultFocusedIndex: (\n options: ComboboxGetEnterDefaultFocusedIndexOptions\n ) => number;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxWidgetProps<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n> {\n \"aria-controls\": string;\n \"aria-disabled\": true | undefined;\n \"aria-expanded\": boolean;\n \"aria-haspopup\": SupportedComboboxPopup;\n id: string;\n ref: RefCallback<ComboboxEl>;\n role: \"combobox\";\n onClick: MouseEventHandler<ComboboxEl>;\n onFocus: FocusEventHandler<ComboboxEl>;\n onKeyDown: KeyboardEventHandler<ComboboxEl>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxWidgetPopupProps<\n PopupEl extends HTMLElement = HTMLElement,\n> {\n \"aria-multiselectable\": true | undefined;\n id: string;\n ref: RefCallback<PopupEl>;\n role: \"listbox\" | \"dialog\" | \"grid\";\n}\n\n/**\n * @since 6.0.0\n */\nexport type ComboboxTransitionCallbacks = Pick<\n TransitionCallbacks,\n \"onEntering\" | \"onEntered\" | \"onExiting\" | \"onExited\"\n>;\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxTransitionOptions extends ComboboxTransitionCallbacks {\n disableTransition?: boolean;\n}\n\n/**\n * @since 6.0.0\n */\nexport type ConfigurableComboboxMenuProps = Partial<\n Omit<MenuProps, \"visible\" | \"onRequestClose\" | keyof ComboboxWidgetPopupProps>\n>;\n\n/**\n * @since 6.0.0\n */\nexport interface ProvidedComboboxMenuProps<\n PopupEl extends HTMLElement = HTMLDivElement,\n>\n extends\n Required<ComboboxTransitionCallbacks>,\n ComboboxWidgetPopupProps<PopupEl> {\n visible: boolean;\n onRequestClose: () => void;\n /** @defaultValue `\"min\"` */\n width: PositionWidth;\n /** @defaultValue `BELOW_CENTER_ANCHOR` */\n anchor: PositionAnchor;\n fixedTo: RefObject<HTMLElement>;\n sheetProps: MenuSheetConfigurableProps &\n Required<ComboboxTransitionCallbacks>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxMenuProps<PopupEl extends HTMLElement = HTMLDivElement>\n extends\n Omit<ConfigurableComboboxMenuProps, keyof ProvidedComboboxMenuProps>,\n ProvidedComboboxMenuProps<PopupEl> {}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxImplementation<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n> extends Omit<KeyboardMovementProviderImplementation<ComboboxEl>, \"nodeRef\"> {\n show: () => void;\n hide: () => void;\n visible: boolean;\n setVisible: UseStateSetter<boolean>;\n focusLast: NonNullMutableRef<boolean>;\n popupRef: RefObject<PopupEl>;\n popupProps: ComboboxWidgetPopupProps<PopupEl>;\n comboboxRef: RefObject<ComboboxEl>;\n comboboxProps: ComboboxWidgetProps<ComboboxEl>;\n /**\n * Since the combobox usually uses the `Menu` as a popup element, this is a\n * helper util to create the required props and merge any additional props\n * with reasonable defaults.\n */\n getMenuProps: (\n overrides?: ConfigurableComboboxMenuProps\n ) => ComboboxMenuProps<PopupEl>;\n}\n\n/**\n * @since 6.0.0\n */\nexport function useCombobox<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n>(\n options: ComboboxOptions<ComboboxEl, PopupEl>\n): ComboboxImplementation<ComboboxEl, PopupEl> {\n const {\n form,\n popup = \"listbox\",\n onClick = noop,\n onFocus,\n onKeyDown,\n searchable,\n multiselect,\n isNegativeOneAllowed,\n loopable,\n disabled,\n visible: propVisible,\n setVisible: propSetVisible,\n defaultVisible = false,\n comboboxId: propComboboxId,\n comboboxRef: propComboboxRef,\n popupId: propPopupId,\n popupRef: propPopupRef,\n onFocusChange = noop,\n extendKeyDown = noop,\n getFocusableElements = getNonDisabledOptions,\n getEnterDefaultFocusedIndex,\n getDefaultFocusedIndex,\n } = options;\n\n const [visible, setVisible] = useEnsuredState({\n name: \"visible\",\n value: propVisible,\n setValue: propSetVisible,\n defaultValue: defaultVisible,\n });\n const show = useCallback(() => {\n setVisible(true);\n }, [setVisible]);\n const hide = useCallback(() => {\n setVisible(false);\n }, [setVisible]);\n\n const popupId = useEnsuredId(propPopupId, \"combobox-popup\");\n const comboboxId = useEnsuredId(propComboboxId, \"combobox\");\n const [popupRef, popupRefCallback] = useEnsuredRef(propPopupRef);\n const focusLastRef = useRef(false);\n const {\n nodeRef: comboboxRef,\n movementProps,\n movementContext,\n currentFocusIndex,\n activeDescendantId,\n setActiveDescendantId,\n } = useKeyboardMovementProvider<ComboboxEl>({\n ref: propComboboxRef,\n onFocus,\n onKeyDown,\n onClick(event) {\n onClick(event);\n if (disabled) {\n return;\n }\n\n show();\n },\n extendKeyDown(movementData) {\n extendKeyDown({\n ...movementData,\n show,\n hide,\n visible,\n focusLastRef,\n });\n const { event } = movementData;\n if (event.isPropagationStopped()) {\n return;\n }\n\n if (visible) {\n switch (event.key) {\n case \"Tab\":\n // do not stop propagation for tab so that shift+tab works correctly in dialogs\n hide();\n break;\n case \"Escape\":\n event.stopPropagation();\n hide();\n break;\n case \"Enter\":\n event.preventDefault();\n break;\n }\n\n // while visible, always use the default keyboard movement behavior\n return;\n }\n\n switch (event.key) {\n case \"ArrowUp\":\n case \"ArrowDown\":\n event.preventDefault();\n event.stopPropagation();\n focusLastRef.current = event.key === \"ArrowUp\";\n show();\n break;\n case \"Enter\":\n tryToSubmitRelatedForm(event, form);\n break;\n }\n },\n disabled,\n loopable,\n searchable,\n onFocusChange,\n programmatic: true,\n includeDisabled: false,\n tabIndexBehavior: \"virtual\",\n getFocusableElements(container, programmatic) {\n const popup = popupRef.current;\n if (!popup) {\n return [];\n }\n\n return getFocusableElements(popup || container, programmatic);\n },\n isNegativeOneAllowed,\n getDefaultFocusedIndex,\n });\n\n const popupProps: ComboboxWidgetPopupProps<PopupEl> = {\n \"aria-multiselectable\": multiselect || undefined,\n id: popupId,\n ref: popupRefCallback,\n role: popup,\n };\n\n return {\n show,\n hide,\n visible,\n setVisible,\n focusLast: focusLastRef,\n popupRef,\n popupProps,\n comboboxRef,\n comboboxProps: {\n ...movementProps,\n \"aria-controls\": popupId,\n \"aria-disabled\": disabled || undefined,\n \"aria-expanded\": visible,\n \"aria-haspopup\": popup,\n id: comboboxId,\n role: \"combobox\",\n },\n movementProps,\n movementContext,\n currentFocusIndex,\n activeDescendantId,\n setActiveDescendantId,\n getMenuProps(props = {}) {\n const {\n sheetProps,\n disableTransition,\n onEnter,\n onEntering,\n onEntered = noop,\n onExited,\n onExiting,\n onExit,\n } = props;\n\n // Chrome does not trigger the scrollIntoView behavior correctly while\n // using a scale transition, so need to trigger this on the entered flow\n // to really make sure the item is in view. An alternative would be to\n // implement a custom scrollIntoView behavior again like the previous\n // versions of react-md, but this is less lines of code\n const attemptScroll = (): void => {\n const activeOption = document.getElementById(activeDescendantId);\n if (activeOption) {\n activeOption.scrollIntoView({ block: \"nearest\" });\n }\n };\n const onEnterOnce = (): void => {\n const popup = popupRef.current;\n if (!popup) {\n attemptScroll();\n return;\n }\n\n const focusables = getFocusableElements(popup, true);\n const index = getEnterDefaultFocusedIndex({\n focusLast: focusLastRef.current,\n focusables,\n currentFocusIndex: currentFocusIndex.current,\n });\n focusLastRef.current = false;\n currentFocusIndex.current = index;\n\n const option = focusables[index];\n if (!option) {\n return;\n }\n\n onFocusChange({\n index,\n element: option,\n });\n\n option.scrollIntoView({ block: \"nearest\" });\n setActiveDescendantId(option.id || \"\");\n };\n\n return {\n anchor: BELOW_CENTER_ANCHOR,\n width: \"min\",\n fixedTo: comboboxRef,\n ...props,\n ...popupProps,\n visible,\n onRequestClose: hide,\n ...getTransitionCallbacks({\n disableTransition,\n onEnter,\n onEntered: (appearing) => {\n onEntered(appearing);\n attemptScroll();\n },\n onEntering,\n onEnterOnce,\n onExit,\n onExiting,\n onExited,\n onExitOnce: () => {\n // since the menu is unmounted or set to hidden while not visible, need\n // to clear the aria-activedescendant and current focus index when\n // hiding\n currentFocusIndex.current = -1;\n setActiveDescendantId(\"\");\n },\n }),\n sheetProps: {\n ...sheetProps,\n ...getTransitionCallbacks({\n ...sheetProps,\n onEnterOnce,\n disableTransition:\n sheetProps?.disableTransition ?? disableTransition,\n }),\n },\n };\n },\n };\n}\n"],"names":["useCallback","useRef","useKeyboardMovementProvider","BELOW_CENTER_ANCHOR","getTransitionCallbacks","useEnsuredId","useEnsuredRef","useEnsuredState","tryToSubmitRelatedForm","noop","getNonDisabledOptions","container","querySelectorAll","useCombobox","options","form","popup","onClick","onFocus","onKeyDown","searchable","multiselect","isNegativeOneAllowed","loopable","disabled","visible","propVisible","setVisible","propSetVisible","defaultVisible","comboboxId","propComboboxId","comboboxRef","propComboboxRef","popupId","propPopupId","popupRef","propPopupRef","onFocusChange","extendKeyDown","getFocusableElements","getEnterDefaultFocusedIndex","getDefaultFocusedIndex","name","value","setValue","defaultValue","show","hide","popupRefCallback","focusLastRef","nodeRef","movementProps","movementContext","currentFocusIndex","activeDescendantId","setActiveDescendantId","ref","event","movementData","isPropagationStopped","key","stopPropagation","preventDefault","current","programmatic","includeDisabled","tabIndexBehavior","popupProps","undefined","id","role","focusLast","comboboxProps","getMenuProps","props","sheetProps","disableTransition","onEnter","onEntering","onEntered","onExited","onExiting","onExit","attemptScroll","activeOption","document","getElementById","scrollIntoView","block","onEnterOnce","focusables","index","option","element","anchor","width","fixedTo","onRequestClose","appearing","onExitOnce"],"mappings":"AAAA;AAEA,SASEA,WAAW,EACXC,MAAM,QACD,QAAQ;AAWf,SAASC,2BAA2B,QAAQ,6CAA6C;AACzF,SAASC,mBAAmB,QAAQ,8BAA8B;AAKlE,SAASC,sBAAsB,QAAQ,0CAA0C;AAOjF,SAASC,YAAY,QAAQ,qBAAqB;AAClD,SAASC,aAAa,QAAQ,sBAAsB;AACpD,SAASC,eAAe,QAAQ,wBAAwB;AACxD,SAASC,sBAAsB,QAAQ,aAAa;AAEpD,MAAMC,OAAO;AACX,aAAa;AACf;AAEA;;CAEC,GACD,OAAO,MAAMC,wBAAwB,CACnCC,YAC2B;WACxBA,UAAUC,gBAAgB,CAC3B;KAEH,CAAC;AAiQF;;CAEC,GACD,OAAO,SAASC,YAIdC,OAA6C;IAE7C,MAAM,EACJC,IAAI,EACJC,QAAQ,SAAS,EACjBC,UAAUR,IAAI,EACdS,OAAO,EACPC,SAAS,EACTC,UAAU,EACVC,WAAW,EACXC,oBAAoB,EACpBC,QAAQ,EACRC,QAAQ,EACRC,SAASC,WAAW,EACpBC,YAAYC,cAAc,EAC1BC,iBAAiB,KAAK,EACtBC,YAAYC,cAAc,EAC1BC,aAAaC,eAAe,EAC5BC,SAASC,WAAW,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BACVoE;oBACA;gBACF;gBAEA,MAAMO,aAAanD,qBAAqBxB,OAAO;gBAC/C,MAAM4E,QAAQnD,4BAA4B;oBACxC+B,WAAWtB,aAAac,OAAO;oBAC/B2B;oBACArC,mBAAmBA,kBAAkBU,OAAO;gBAC9C;gBACAd,aAAac,OAAO,GAAG;gBACvBV,kBAAkBU,OAAO,GAAG4B;gBAE5B,MAAMC,SAASF,UAAU,CAACC,MAAM;gBAChC,IAAI,CAACC,QAAQ;oBACX;gBACF;gBAEAvD,cAAc;oBACZsD;oBACAE,SAASD;gBACX;gBAEAA,OAAOL,cAAc,CAAC;oBAAEC,OAAO;gBAAU;gBACzCjC,sBAAsBqC,OAAOvB,EAAE,IAAI;YACrC;YAEA,OAAO;gBACLyB,QAAQ5F;gBACR6F,OAAO;gBACPC,SAASjE;gBACT,GAAG2C,KAAK;gBACR,GAAGP,UAAU;gBACb3C;gBACAyE,gBAAgBlD;gBAChB,GAAG5C,uBAAuB;oBACxByE;oBACAC;oBACAE,WAAW,CAACmB;wBACVnB,UAAUmB;wBACVf;oBACF;oBACAL;oBACAW;oBACAP;oBACAD;oBACAD;oBACAmB,YAAY;wBACV,uEAAuE;wBACvE,kEAAkE;wBAClE,SAAS;wBACT9C,kBAAkBU,OAAO,GAAG,CAAC;wBAC7BR,sBAAsB;oBACxB;gBACF,EAAE;gBACFoB,YAAY;oBACV,GAAGA,UAAU;oBACb,GAAGxE,uBAAuB;wBACxB,GAAGwE,UAAU;wBACbc;wBACAb,mBACED,YAAYC,qBAAqBA;oBACrC,EAAE;gBACJ;YACF;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/form/useCombobox.ts"],"sourcesContent":["\"use client\";\n\nimport {\n type FocusEventHandler,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n type InputHTMLAttributes,\n type KeyboardEventHandler,\n type MouseEventHandler,\n type Ref,\n type RefCallback,\n type RefObject,\n useCallback,\n useRef,\n} from \"react\";\n\nimport { type MenuProps } from \"../menu/Menu.js\";\nimport { type MenuSheetConfigurableProps } from \"../menu/MenuSheet.js\";\nimport {\n type GetDefaultFocusedIndex,\n type GetFocusableElements,\n type KeyboardMovementExtensionData,\n type KeyboardMovementProviderImplementation,\n type KeyboardMovementProviderOptions,\n} from \"../movement/types.js\";\nimport { useKeyboardMovementProvider } from \"../movement/useKeyboardMovementProvider.js\";\nimport { BELOW_CENTER_ANCHOR } from \"../positioning/constants.js\";\nimport {\n type PositionAnchor,\n type PositionWidth,\n} from \"../positioning/types.js\";\nimport { getTransitionCallbacks } from \"../transition/getTransitionCallbacks.js\";\nimport { type TransitionCallbacks } from \"../transition/types.js\";\nimport {\n type NonNullMutableRef,\n type UseStateInitializer,\n type UseStateSetter,\n} from \"../types.js\";\nimport { useEnsuredId } from \"../useEnsuredId.js\";\nimport { useEnsuredRef } from \"../useEnsuredRef.js\";\nimport { useEnsuredState } from \"../useEnsuredState.js\";\nimport { tryToSubmitRelatedForm } from \"./utils.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n * @since 6.0.0\n */\nexport const getNonDisabledOptions = (\n container: HTMLElement\n): readonly HTMLElement[] => [\n ...container.querySelectorAll<HTMLLIElement>(\n '[role=\"option\"]:not([aria-disabled])'\n ),\n];\n\n/**\n * @since 6.0.0\n */\nexport type SupportedComboboxPopup = \"listbox\" | \"grid\" | \"dialog\";\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxKeyboardMovementData<\n E extends HTMLElement = HTMLInputElement,\n> extends KeyboardMovementExtensionData<E> {\n show: () => void;\n hide: () => void;\n visible: boolean;\n\n /**\n * @since 6.3.0 Renamed from `focusLast` to `focusLastRef` to support the new\n * actions.\n */\n focusLastRef: NonNullMutableRef<boolean>;\n}\n\n/**\n * @since 6.0.0\n */\nexport type ExtendComboboxKeyDown<E extends HTMLElement = HTMLInputElement> = (\n movementData: ComboboxKeyboardMovementData<E>\n) => void;\n\n/**\n * @since 6.0.0\n */\nexport type ComboboxKeyboardMovementOptions<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n> = Pick<\n KeyboardMovementProviderOptions<ComboboxEl>,\n | \"onClick\"\n | \"onFocus\"\n | \"onKeyDown\"\n | \"disabled\"\n | \"loopable\"\n | \"searchable\"\n | \"onFocusChange\"\n | \"isNegativeOneAllowed\"\n>;\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxVisibilityOptions {\n /**\n * This can be used to control the popup's visibility and **must** be used\n * along with {@link setVisible}.\n */\n visible?: boolean;\n\n /**\n * Used to control the popup's visibility and should generally be a `useState`\n * setter.\n *\n * @example Controlling the Visibility\n * ```tsx\n * const [visible, setVisible] = useState(false);\n *\n * useCombobox({\n * visible,\n * setVisible,\n * });\n * ```\n */\n setVisible?: UseStateSetter<boolean>;\n\n /**\n * Set this to `true` to have the combobox's popup visible by default.\n *\n * @defaultValue `false`\n */\n defaultVisible?: UseStateInitializer<boolean>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ConfigurableComboboxOptions<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n>\n extends\n ComboboxKeyboardMovementOptions<ComboboxEl>,\n ComboboxVisibilityOptions {\n /**\n * This is the {@link InputHTMLAttributes.form} attribute and is used to\n * attempt submitting a form when the enter key is pressed.\n */\n form?: string;\n\n /**\n * @defaultValue `\"combobox-popup-\" + useId()`\n */\n popupId?: string;\n popupRef?: Ref<PopupEl>;\n\n /**\n * @defaultValue `\"combobox-\" + useId()`\n */\n comboboxId?: string;\n comboboxRef?: Ref<ComboboxEl>;\n\n /**\n * @defaultValue `\"listbox\"`\n */\n popup?: \"listbox\" | \"grid\" | \"dialog\";\n\n /**\n * @defaultValue `false`\n */\n multiselect?: boolean;\n\n extendKeyDown?: ExtendComboboxKeyDown<ComboboxEl>;\n\n /**\n * @defaultValue {@link getNonDisabledOptions}\n */\n getFocusableElements?: GetFocusableElements;\n\n getDefaultFocusedIndex?: GetDefaultFocusedIndex;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxGetEnterDefaultFocusedIndexOptions {\n focusLast: boolean;\n focusables: readonly HTMLElement[];\n currentFocusIndex: number;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxOptions<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n> extends ConfigurableComboboxOptions<ComboboxEl, PopupEl> {\n getEnterDefaultFocusedIndex: (\n options: ComboboxGetEnterDefaultFocusedIndexOptions\n ) => number;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxWidgetProps<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n> {\n \"aria-controls\": string;\n \"aria-disabled\": true | undefined;\n \"aria-expanded\": boolean;\n \"aria-haspopup\": SupportedComboboxPopup;\n id: string;\n ref: RefCallback<ComboboxEl>;\n role: \"combobox\";\n onClick: MouseEventHandler<ComboboxEl>;\n onFocus: FocusEventHandler<ComboboxEl>;\n onKeyDown: KeyboardEventHandler<ComboboxEl>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxWidgetPopupProps<\n PopupEl extends HTMLElement = HTMLElement,\n> {\n \"aria-multiselectable\": true | undefined;\n id: string;\n ref: RefCallback<PopupEl>;\n role: \"listbox\" | \"dialog\" | \"grid\";\n}\n\n/**\n * @since 6.0.0\n */\nexport type ComboboxTransitionCallbacks = Pick<\n TransitionCallbacks,\n \"onEntering\" | \"onEntered\" | \"onExiting\" | \"onExited\"\n>;\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxTransitionOptions extends ComboboxTransitionCallbacks {\n disableTransition?: boolean;\n}\n\n/**\n * @since 6.0.0\n */\nexport type ConfigurableComboboxMenuProps = Partial<\n Omit<MenuProps, \"visible\" | \"onRequestClose\" | keyof ComboboxWidgetPopupProps>\n>;\n\n/**\n * @since 6.0.0\n */\nexport interface ProvidedComboboxMenuProps<\n PopupEl extends HTMLElement = HTMLDivElement,\n>\n extends\n Required<ComboboxTransitionCallbacks>,\n ComboboxWidgetPopupProps<PopupEl> {\n visible: boolean;\n onRequestClose: () => void;\n /** @defaultValue `\"min\"` */\n width: PositionWidth;\n /** @defaultValue `BELOW_CENTER_ANCHOR` */\n anchor: PositionAnchor;\n fixedTo: RefObject<HTMLElement>;\n sheetProps: MenuSheetConfigurableProps &\n Required<ComboboxTransitionCallbacks>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxMenuProps<PopupEl extends HTMLElement = HTMLDivElement>\n extends\n Omit<ConfigurableComboboxMenuProps, keyof ProvidedComboboxMenuProps>,\n ProvidedComboboxMenuProps<PopupEl> {}\n\n/**\n * @since 6.0.0\n */\nexport interface ComboboxImplementation<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n> extends Omit<KeyboardMovementProviderImplementation<ComboboxEl>, \"nodeRef\"> {\n show: () => void;\n hide: () => void;\n visible: boolean;\n setVisible: UseStateSetter<boolean>;\n focusLast: NonNullMutableRef<boolean>;\n popupRef: RefObject<PopupEl>;\n popupProps: ComboboxWidgetPopupProps<PopupEl>;\n comboboxRef: RefObject<ComboboxEl>;\n comboboxProps: ComboboxWidgetProps<ComboboxEl>;\n /**\n * Since the combobox usually uses the `Menu` as a popup element, this is a\n * helper util to create the required props and merge any additional props\n * with reasonable defaults.\n */\n getMenuProps: (\n overrides?: ConfigurableComboboxMenuProps\n ) => ComboboxMenuProps<PopupEl>;\n}\n\n/**\n * @since 6.0.0\n */\nexport function useCombobox<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n>(\n options: ComboboxOptions<ComboboxEl, PopupEl>\n): ComboboxImplementation<ComboboxEl, PopupEl> {\n const {\n form,\n popup = \"listbox\",\n onClick = noop,\n onFocus,\n onKeyDown,\n searchable,\n multiselect,\n isNegativeOneAllowed,\n loopable,\n disabled,\n visible: propVisible,\n setVisible: propSetVisible,\n defaultVisible = false,\n comboboxId: propComboboxId,\n comboboxRef: propComboboxRef,\n popupId: propPopupId,\n popupRef: propPopupRef,\n onFocusChange = noop,\n extendKeyDown = noop,\n getFocusableElements = getNonDisabledOptions,\n getEnterDefaultFocusedIndex,\n getDefaultFocusedIndex,\n } = options;\n\n const [visible, setVisible] = useEnsuredState({\n name: \"visible\",\n value: propVisible,\n setValue: propSetVisible,\n defaultValue: defaultVisible,\n });\n const show = useCallback(() => {\n setVisible(true);\n }, [setVisible]);\n const hide = useCallback(() => {\n setVisible(false);\n }, [setVisible]);\n\n const popupId = useEnsuredId(propPopupId, \"combobox-popup\");\n const comboboxId = useEnsuredId(propComboboxId, \"combobox\");\n const [popupRef, popupRefCallback] = useEnsuredRef(propPopupRef);\n const focusLastRef = useRef(false);\n const {\n nodeRef: comboboxRef,\n movementProps,\n movementContext,\n currentFocusIndex,\n activeDescendantId,\n setActiveDescendantId,\n } = useKeyboardMovementProvider<ComboboxEl>({\n ref: propComboboxRef,\n onFocus,\n onKeyDown,\n onClick(event) {\n onClick(event);\n if (disabled) {\n return;\n }\n\n show();\n },\n extendKeyDown(movementData) {\n extendKeyDown({\n ...movementData,\n show,\n hide,\n visible,\n focusLastRef,\n });\n const { event } = movementData;\n if (event.isPropagationStopped()) {\n return;\n }\n\n if (visible) {\n switch (event.key) {\n case \"Tab\":\n // do not stop propagation for tab so that shift+tab works correctly in dialogs\n hide();\n break;\n case \"Escape\":\n event.stopPropagation();\n hide();\n break;\n case \"Enter\":\n event.preventDefault();\n break;\n }\n\n // while visible, always use the default keyboard movement behavior\n return;\n }\n\n switch (event.key) {\n case \"ArrowUp\":\n case \"ArrowDown\":\n event.preventDefault();\n event.stopPropagation();\n focusLastRef.current = event.key === \"ArrowUp\";\n show();\n break;\n case \"Enter\":\n tryToSubmitRelatedForm(event, form);\n break;\n }\n },\n disabled,\n loopable,\n searchable,\n onFocusChange,\n programmatic: true,\n includeDisabled: false,\n tabIndexBehavior: \"virtual\",\n getFocusableElements(container, programmatic) {\n const popup = popupRef.current;\n if (!popup) {\n return [];\n }\n\n return getFocusableElements(popup || container, programmatic);\n },\n isNegativeOneAllowed,\n getDefaultFocusedIndex,\n });\n\n const popupProps: ComboboxWidgetPopupProps<PopupEl> = {\n \"aria-multiselectable\": multiselect || undefined,\n id: popupId,\n ref: popupRefCallback,\n role: popup,\n };\n\n return {\n show,\n hide,\n visible,\n setVisible,\n focusLast: focusLastRef,\n popupRef,\n popupProps,\n comboboxRef,\n comboboxProps: {\n ...movementProps,\n \"aria-controls\": popupId,\n \"aria-disabled\": disabled || undefined,\n \"aria-expanded\": visible,\n \"aria-haspopup\": popup,\n id: comboboxId,\n role: \"combobox\",\n },\n movementProps,\n movementContext,\n currentFocusIndex,\n activeDescendantId,\n setActiveDescendantId,\n getMenuProps(props = {}) {\n const {\n sheetProps,\n disableTransition,\n onEnter,\n onEntering,\n onEntered = noop,\n onExited,\n onExiting,\n onExit,\n } = props;\n\n // Chrome does not trigger the scrollIntoView behavior correctly while\n // using a scale transition, so need to trigger this on the entered flow\n // to really make sure the item is in view. An alternative would be to\n // implement a custom scrollIntoView behavior again like the previous\n // versions of react-md, but this is less lines of code\n // eslint-disable-next-line unicorn/consistent-function-scoping\n const attemptScroll = (): void => {\n const activeOption = document.getElementById(activeDescendantId);\n if (activeOption) {\n activeOption.scrollIntoView({ block: \"nearest\" });\n }\n };\n const onEnterOnce = (): void => {\n const popup = popupRef.current;\n if (!popup) {\n attemptScroll();\n return;\n }\n\n const focusables = getFocusableElements(popup, true);\n const index = getEnterDefaultFocusedIndex({\n focusLast: focusLastRef.current,\n focusables,\n currentFocusIndex: currentFocusIndex.current,\n });\n focusLastRef.current = false;\n currentFocusIndex.current = index;\n\n const option = focusables[index];\n if (!option) {\n return;\n }\n\n onFocusChange({\n index,\n element: option,\n });\n\n option.scrollIntoView({ block: \"nearest\" });\n setActiveDescendantId(option.id || \"\");\n };\n\n return {\n anchor: BELOW_CENTER_ANCHOR,\n width: \"min\",\n fixedTo: comboboxRef,\n ...props,\n ...popupProps,\n visible,\n onRequestClose: hide,\n ...getTransitionCallbacks({\n disableTransition,\n onEnter,\n onEntered: (appearing) => {\n onEntered(appearing);\n attemptScroll();\n },\n onEntering,\n onEnterOnce,\n onExit,\n onExiting,\n onExited,\n onExitOnce: () => {\n // since the menu is unmounted or set to hidden while not visible, need\n // to clear the aria-activedescendant and current focus index when\n // hiding\n currentFocusIndex.current = -1;\n setActiveDescendantId(\"\");\n },\n }),\n sheetProps: {\n ...sheetProps,\n ...getTransitionCallbacks({\n ...sheetProps,\n onEnterOnce,\n disableTransition:\n sheetProps?.disableTransition ?? disableTransition,\n }),\n },\n };\n },\n };\n}\n"],"names":["useCallback","useRef","useKeyboardMovementProvider","BELOW_CENTER_ANCHOR","getTransitionCallbacks","useEnsuredId","useEnsuredRef","useEnsuredState","tryToSubmitRelatedForm","noop","getNonDisabledOptions","container","querySelectorAll","useCombobox","options","form","popup","onClick","onFocus","onKeyDown","searchable","multiselect","isNegativeOneAllowed","loopable","disabled","visible","propVisible","setVisible","propSetVisible","defaultVisible","comboboxId","propComboboxId","comboboxRef","propComboboxRef","popupId","propPopupId","popupRef","propPopupRef","onFocusChange","extendKeyDown","getFocusableElements","getEnterDefaultFocusedIndex","getDefaultFocusedIndex","name","value","setValue","defaultValue","show","hide","popupRefCallback","focusLastRef","nodeRef","movementProps","movementContext","currentFocusIndex","activeDescendantId","setActiveDescendantId","ref","event","movementData","isPropagationStopped","key","stopPropagation","preventDefault","current","programmatic","includeDisabled","tabIndexBehavior","popupProps","undefined","id","role","focusLast","comboboxProps","getMenuProps","props","sheetProps","disableTransition","onEnter","onEntering","onEntered","onExited","onExiting","onExit","attemptScroll","activeOption","document","getElementById","scrollIntoView","block","onEnterOnce","focusables","index","option","element","anchor","width","fixedTo","onRequestClose","appearing","onExitOnce"],"mappings":"AAAA;AAEA,SASEA,WAAW,EACXC,MAAM,QACD,QAAQ;AAWf,SAASC,2BAA2B,QAAQ,6CAA6C;AACzF,SAASC,mBAAmB,QAAQ,8BAA8B;AAKlE,SAASC,sBAAsB,QAAQ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C;oBACAE,WAAW,CAACmB;wBACVnB,UAAUmB;wBACVf;oBACF;oBACAL;oBACAW;oBACAP;oBACAD;oBACAD;oBACAmB,YAAY;wBACV,uEAAuE;wBACvE,kEAAkE;wBAClE,SAAS;wBACT9C,kBAAkBU,OAAO,GAAG,CAAC;wBAC7BR,sBAAsB;oBACxB;gBACF,EAAE;gBACFoB,YAAY;oBACV,GAAGA,UAAU;oBACb,GAAGxE,uBAAuB;wBACxB,GAAGwE,UAAU;wBACbc;wBACAb,mBACED,YAAYC,qBAAqBA;oBACrC,EAAE;gBACJ;YACF;QACF;IACF;AACF"}
@@ -8,7 +8,7 @@ import { triggerManualChangeEvent } from "./utils.js";
8
8
  const { form, elementRef, defaultValue, onReset } = options;
9
9
  useEffect(()=>{
10
10
  const element = elementRef.current;
11
- if (!element || typeof defaultValue === "undefined" && !onReset) {
11
+ if (!element || defaultValue === undefined && !onReset) {
12
12
  return;
13
13
  }
14
14
  const formElement = form && document.getElementById(form) || element.closest("form") || null;
@@ -18,7 +18,7 @@ import { triggerManualChangeEvent } from "./utils.js";
18
18
  const handleReset = ()=>{
19
19
  if (onReset) {
20
20
  onReset();
21
- } else if (typeof defaultValue !== "undefined") {
21
+ } else if (defaultValue !== undefined) {
22
22
  triggerManualChangeEvent(element, defaultValue);
23
23
  }
24
24
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/useFormReset.ts"],"sourcesContent":["\"use client\";\n\nimport { type RefObject, useEffect } from \"react\";\n\nimport {\n type ChangeableHTMLElement,\n triggerManualChangeEvent,\n} from \"./utils.js\";\n\n/**\n * @since 6.0.0\n * @since 6.3.0 Added the optional `onReset` callback and updated\n * `defaultValue` to be optional.\n * @internal\n */\nexport interface FormResetOptions {\n form?: string;\n elementRef: RefObject<ChangeableHTMLElement>;\n onReset?: () => void;\n defaultValue?: string;\n}\n\n/**\n * @since 6.0.0\n * @internal\n */\nexport function useFormReset(options: FormResetOptions): void {\n const { form, elementRef, defaultValue, onReset } = options;\n\n useEffect(() => {\n const element = elementRef.current;\n if (!element || (typeof defaultValue === \"undefined\" && !onReset)) {\n return;\n }\n\n const formElement =\n (form && document.getElementById(form)) ||\n element.closest<HTMLFormElement>(\"form\") ||\n null;\n if (!formElement) {\n return;\n }\n\n const handleReset = (): void => {\n if (onReset) {\n onReset();\n } else if (typeof defaultValue !== \"undefined\") {\n triggerManualChangeEvent(element, defaultValue);\n }\n };\n\n formElement.addEventListener(\"reset\", handleReset);\n return () => {\n formElement.removeEventListener(\"reset\", handleReset);\n };\n }, [defaultValue, elementRef, form, onReset]);\n}\n"],"names":["useEffect","triggerManualChangeEvent","useFormReset","options","form","elementRef","defaultValue","onReset","element","current","formElement","document","getElementById","closest","handleReset","addEventListener","removeEventListener"],"mappings":"AAAA;AAEA,SAAyBA,SAAS,QAAQ,QAAQ;AAElD,SAEEC,wBAAwB,QACnB,aAAa;AAepB;;;CAGC,GACD,OAAO,SAASC,aAAaC,OAAyB;IACpD,MAAM,EAAEC,IAAI,EAAEC,UAAU,EAAEC,YAAY,EAAEC,OAAO,EAAE,GAAGJ;IAEpDH,UAAU;QACR,MAAMQ,UAAUH,WAAWI,OAAO;QAClC,IAAI,CAACD,WAAY,OAAOF,iBAAiB,eAAe,CAACC,SAAU;YACjE;QACF;QAEA,MAAMG,cACJ,AAACN,QAAQO,SAASC,cAAc,CAACR,SACjCI,QAAQK,OAAO,CAAkB,WACjC;QACF,IAAI,CAACH,aAAa;YAChB;QACF;QAEA,MAAMI,cAAc;YAClB,IAAIP,SAAS;gBACXA;YACF,OAAO,IAAI,OAAOD,iBAAiB,aAAa;gBAC9CL,yBAAyBO,SAASF;YACpC;QACF;QAEAI,YAAYK,gBAAgB,CAAC,SAASD;QACtC,OAAO;YACLJ,YAAYM,mBAAmB,CAAC,SAASF;QAC3C;IACF,GAAG;QAACR;QAAcD;QAAYD;QAAMG;KAAQ;AAC9C"}
1
+ {"version":3,"sources":["../../src/form/useFormReset.ts"],"sourcesContent":["\"use client\";\n\nimport { type RefObject, useEffect } from \"react\";\n\nimport {\n type ChangeableHTMLElement,\n triggerManualChangeEvent,\n} from \"./utils.js\";\n\n/**\n * @since 6.0.0\n * @since 6.3.0 Added the optional `onReset` callback and updated\n * `defaultValue` to be optional.\n * @internal\n */\nexport interface FormResetOptions {\n form?: string;\n elementRef: RefObject<ChangeableHTMLElement>;\n onReset?: () => void;\n defaultValue?: string;\n}\n\n/**\n * @since 6.0.0\n * @internal\n */\nexport function useFormReset(options: FormResetOptions): void {\n const { form, elementRef, defaultValue, onReset } = options;\n\n useEffect(() => {\n const element = elementRef.current;\n if (!element || (defaultValue === undefined && !onReset)) {\n return;\n }\n\n const formElement =\n (form && document.getElementById(form)) ||\n element.closest<HTMLFormElement>(\"form\") ||\n null;\n if (!formElement) {\n return;\n }\n\n const handleReset = (): void => {\n if (onReset) {\n onReset();\n } else if (defaultValue !== undefined) {\n triggerManualChangeEvent(element, defaultValue);\n }\n };\n\n formElement.addEventListener(\"reset\", handleReset);\n return () => {\n formElement.removeEventListener(\"reset\", handleReset);\n };\n }, [defaultValue, elementRef, form, onReset]);\n}\n"],"names":["useEffect","triggerManualChangeEvent","useFormReset","options","form","elementRef","defaultValue","onReset","element","current","undefined","formElement","document","getElementById","closest","handleReset","addEventListener","removeEventListener"],"mappings":"AAAA;AAEA,SAAyBA,SAAS,QAAQ,QAAQ;AAElD,SAEEC,wBAAwB,QACnB,aAAa;AAepB;;;CAGC,GACD,OAAO,SAASC,aAAaC,OAAyB;IACpD,MAAM,EAAEC,IAAI,EAAEC,UAAU,EAAEC,YAAY,EAAEC,OAAO,EAAE,GAAGJ;IAEpDH,UAAU;QACR,MAAMQ,UAAUH,WAAWI,OAAO;QAClC,IAAI,CAACD,WAAYF,iBAAiBI,aAAa,CAACH,SAAU;YACxD;QACF;QAEA,MAAMI,cACJ,AAACP,QAAQQ,SAASC,cAAc,CAACT,SACjCI,QAAQM,OAAO,CAAkB,WACjC;QACF,IAAI,CAACH,aAAa;YAChB;QACF;QAEA,MAAMI,cAAc;YAClB,IAAIR,SAAS;gBACXA;YACF,OAAO,IAAID,iBAAiBI,WAAW;gBACrCT,yBAAyBO,SAASF;YACpC;QACF;QAEAK,YAAYK,gBAAgB,CAAC,SAASD;QACtC,OAAO;YACLJ,YAAYM,mBAAmB,CAAC,SAASF;QAC3C;IACF,GAAG;QAACT;QAAcD;QAAYD;QAAMG;KAAQ;AAC9C"}
@@ -49,7 +49,7 @@ const noop = ()=>{
49
49
  if (!Number.isNaN(value)) {
50
50
  setNumber(value);
51
51
  input.value = `${value}`;
52
- } else if (typeof initial.current === "undefined") {
52
+ } else if (initial.current === undefined) {
53
53
  setNumber(undefined);
54
54
  }
55
55
  },
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/useNumberField.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useRef, useState } from \"react\";\n\nimport { type UseStateInitializer, type UseStateSetter } from \"../types.js\";\nimport { useIsomorphicLayoutEffect } from \"../useIsomorphicLayoutEffect.js\";\nimport { withinRange } from \"../utils/withinRange.js\";\nimport { useFormReset } from \"./useFormReset.js\";\nimport {\n type ProvidedTextFieldMessageProps,\n type ProvidedTextFieldProps,\n type TextFieldHookOptions,\n type TextFieldHookState,\n type TextFieldImplementation,\n type ValidatedTextFieldImplementation,\n useTextField,\n} from \"./useTextField.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/** @since 2.5.0 */\nexport interface NumberFieldConstraints {\n /**\n * An optional min value for the number field.\n */\n min?: number;\n\n /**\n * An optional max value for the number field.\n */\n max?: number;\n\n /**\n * An optional step amount to use.\n *\n * Note: The `min` and `max` values must be divisible by this value when any\n * are defined.\n */\n step?: number;\n}\n\n/**\n * @since 2.5.0\n * @since 6.0.0\n * - Removed `updateOnChange` in favor of `updateValue`\n * - Renamed `fixOnBlur` to `updateValueOnBlur`\n */\nexport interface NumberFieldHookOptions\n extends\n Omit<TextFieldHookOptions, \"defaultValue\" | \"isNumber\">,\n NumberFieldConstraints {\n /**\n * @defaultValue `undefined`\n */\n defaultValue?: UseStateInitializer<number>;\n\n /**\n * This controls the behavior for the `value` returned by this hook. If you\n * need access to the current value immediately as the user types to update\n * other components, keep this as the default of `\"change\"`. Otherwise, set\n * this to `\"blur\"`.\n *\n * @example Deferring Updates on Blur\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * min: 0,\n * max: 100,\n * name: \"someName\",\n * defaultValue: 0,\n * updateValue: \"blur\",\n * });\n *\n * const result = useMemo(() => someExpensiveComputation(value), [value]);\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @defaultValue `\"change\"`\n */\n updateValue?: \"blur\" | \"change\";\n\n /**\n * This option is used to update the `number` value and text field value to be\n * within the `min` and `max` range or just format the text field value when\n * the input is blurred. This update will only be applied if the text field\n * contains a valid number. Using `min = 0` and `max = 10`:\n *\n * | text value | updated value |\n * | ---------- | ------------- |\n * | 000001 | 1 |\n * | -1 | 0 |\n * | 20 | 10 |\n * | -12 | 0 |\n * | --1 | --1 |\n * | fjdka | fjdka |\n *\n *\n * Set this to `false` if no changed should be applied and force the user to\n * fix any min/max errors manually and maintain weird formatting.\n *\n * @defaultValue `true`\n * @since 6.0.0 This was renamed from `fixOnBlur` and removed the\n * `\"min\"` and `\"max\"` behavior.\n */\n updateValueOnBlur?: boolean;\n}\n\n/** @since 6.0.0 */\nexport interface NumberFieldHookState extends Omit<\n TextFieldHookState,\n \"value\"\n> {\n value: number | undefined;\n}\n\n/** @since 2.5.6 */\nexport interface ProvidedNumberFieldProps\n extends ProvidedTextFieldProps, NumberFieldConstraints {\n type: \"number\";\n}\n\n/** @since 2.5.6 */\nexport interface ProvidedNumberFieldMessageProps\n extends ProvidedTextFieldMessageProps, NumberFieldConstraints {\n type: \"number\";\n}\n\n/** @since 6.0.0 */\nexport interface NumberFieldImplementation extends Omit<\n TextFieldImplementation,\n \"value\" | \"setState\"\n> {\n value: number | undefined;\n setState: UseStateSetter<NumberFieldHookState>;\n fieldProps: ProvidedNumberFieldProps;\n}\n\n/** @since 6.0.0 */\nexport interface NumberFieldWithMessageImplementation extends NumberFieldImplementation {\n fieldProps: ProvidedNumberFieldMessageProps;\n}\n\n/** @since 6.0.0 */\nexport interface ValidatedNumberFieldImplementation extends Omit<\n ValidatedTextFieldImplementation,\n \"value\" | \"setState\"\n> {\n value: number | undefined;\n setState: UseStateSetter<NumberFieldHookState>;\n fieldProps: ProvidedNumberFieldProps | ProvidedNumberFieldMessageProps;\n}\n\n/**\n * @example Enforce Number Value and No Error Messages\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * min: 0,\n * max: 100,\n * name: \"someName\",\n * defaultValue: 0,\n * disableMessage: true,\n * });\n *\n * // this is safe since `value` will always be a number even if there is a\n * // validation error. since the min and max options were provided as well,\n * // number will be between that range as well.\n * const computed = value * 10;\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @see {@link useTextField}\n * @see {@link useNumberField} overrides for other examples.\n * ```\n */\nexport function useNumberField(\n options: NumberFieldHookOptions & {\n disableMessage: true;\n defaultValue: UseStateInitializer<number>;\n }\n): NumberFieldImplementation & {\n value: number;\n setState: UseStateSetter<NumberFieldHookState & { value: number }>;\n};\n\n/**\n * @example No Error Messages\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * min: 0,\n * max: 100,\n * name: \"someName\",\n * disableMessage: true,\n * });\n *\n * // `value` will be `undefined` until the user enters a valid value once\n * // there is a valid value, `value` will be a `number`. So this might cause\n * // `computed` to be `NaN | number`\n * //\n * // const computed = value * 10;\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @see {@link useTextField}\n * @see {@link useNumberField} overrides for other examples.\n */\nexport function useNumberField(\n options: NumberFieldHookOptions & { disableMessage: true }\n): NumberFieldImplementation;\n\n/**\n * @example Enforce Number Value\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * min: 0,\n * max: 100,\n * name: \"someName\",\n * defaultValue: 0,\n * });\n *\n * // this is safe since `value` will always be a number even if there is a\n * // validation error. since the min and max options were provided as well,\n * // number will be between that range as well.\n * const computed = value * 10;\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @example Enforce Number Value and Deferring Updates\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * min: 0,\n * max: 100,\n * name: \"someName\",\n * defaultValue: 0,\n * updateValue: \"blur\",\n * });\n *\n * // the `value` will only be updated whenever the `TextField` is blurred.\n * // This is helpful if the `value` is used in expensive computations or\n * // updates that do not need to be updated as the user types\n * const computed = value * 10;\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @see {@link useTextField}\n * @see {@link useNumberField} overrides for other examples.\n */\nexport function useNumberField(\n options: NumberFieldHookOptions & {\n defaultValue: UseStateInitializer<number>;\n }\n): NumberFieldWithMessageImplementation & {\n value: number;\n setState: UseStateSetter<NumberFieldHookState & { value: number }>;\n};\n\n/**\n * The `useNumberField` hook is used to control the state of a `TextField` or\n * `<input type=\"number\">`\n *\n * @example Default Implementation\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * name: \"someName\",\n * });\n *\n * // `value` will be `undefined` until the user enters a valid value once\n * // there is a valid value, `value` will be a `number`. So this might cause\n * // `computed` to be `NaN | number`\n * //\n * // const computed = value * 10;\n *\n * // whenever there is an error, an error message will be displayed below the\n * // `TextField`\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @example Adding Constraints\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * name: \"someName\",\n * min: 0,\n * max: 100,\n * step: 2,\n * required: true,\n * });\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation\n * @see {@link https://react-md.dev/components/text-field#number | Number TextField Demos}\n * @see {@link https://react-md.dev/hooks/use-number-field | useNumberField Demos}\n * @see {@link useTextField}\n */\nexport function useNumberField(\n options: NumberFieldHookOptions\n): NumberFieldWithMessageImplementation;\n\n/**\n * @internal\n * @see {@link https://react-md.dev/components/text-field#number | Number TextField Demos}\n * @see {@link https://react-md.dev/hooks/use-number-field | useNumberField Demos}\n * @see {@link useTextField}\n * @see {@link useNumberField} overrides for other examples.\n */\nexport function useNumberField(\n options: NumberFieldHookOptions\n): ValidatedNumberFieldImplementation {\n const {\n min,\n max,\n step,\n form,\n onBlur = noop,\n onChange = noop,\n updateValue = \"change\",\n updateValueOnBlur = true,\n disableReset,\n defaultValue,\n ...textOptions\n } = options;\n\n const [number, setNumber] = useState(defaultValue);\n const initial = useRef(number);\n const {\n value: _value,\n reset: resetTextField,\n fieldRef,\n fieldProps,\n setState: setTextFieldState,\n ...remaining\n } = useTextField({\n ...textOptions,\n isNumber: true,\n defaultValue: `${number ?? \"\"}`,\n disableReset: true,\n onBlur(event) {\n onBlur(event);\n if (event.isPropagationStopped()) {\n return;\n }\n\n const input = event.currentTarget;\n input.setCustomValidity(\"\");\n input.checkValidity();\n if (\n !updateValueOnBlur ||\n // do nothing else since it's a weird value like: `\"--0\"` which causes\n // the value to be `\"\"` and `numberAsValue` to be `NaN`\n input.validity.badInput\n ) {\n return;\n }\n\n let value = input.valueAsNumber;\n if (input.value === \"\" && typeof initial.current === \"number\") {\n value = min ?? initial.current;\n }\n\n // can't have both rangeUnderflow and rangeOverflow at the same time, so\n // it's \"safe\" to always provide both\n value = withinRange({ min, max, value });\n if (!Number.isNaN(value)) {\n setNumber(value);\n input.value = `${value}`;\n } else if (typeof initial.current === \"undefined\") {\n setNumber(undefined);\n }\n },\n onChange(event) {\n onChange(event);\n if (event.isPropagationStopped() || updateValue === \"blur\") {\n return;\n }\n\n const input = event.currentTarget;\n input.checkValidity();\n const value = withinRange({\n min,\n max,\n value: event.currentTarget.valueAsNumber,\n });\n if (\n !input.validity.valid &&\n !input.validity.rangeUnderflow &&\n !input.validity.rangeOverflow\n ) {\n return;\n }\n\n if (!Number.isNaN(value)) {\n setNumber(value);\n } else if (initial.current === undefined) {\n setNumber(undefined);\n }\n },\n });\n\n const { error, errorMessage } = remaining;\n const prevState = useRef({\n error,\n errorMessage,\n value: number,\n } satisfies NumberFieldHookState);\n useIsomorphicLayoutEffect(() => {\n prevState.current = {\n error,\n errorMessage,\n value: number,\n };\n });\n const reset = useCallback(() => {\n resetTextField();\n setNumber(initial.current);\n }, [resetTextField]);\n const setState = useCallback<UseStateSetter<NumberFieldHookState>>(\n (nextState) => {\n const resolvedNextState =\n typeof nextState === \"function\"\n ? nextState(prevState.current)\n : nextState;\n\n const { value, error, errorMessage } = resolvedNextState;\n setNumber(value);\n setTextFieldState({\n value: `${value ?? \"\"}`,\n error,\n errorMessage,\n });\n },\n [setTextFieldState]\n );\n\n useFormReset({\n form,\n elementRef: fieldRef,\n onReset: disableReset ? undefined : reset,\n });\n\n return {\n ...remaining,\n reset,\n value: number,\n setState,\n fieldRef,\n fieldProps: {\n ...fieldProps,\n min,\n max,\n step,\n type: \"number\",\n },\n };\n}\n"],"names":["useCallback","useRef","useState","useIsomorphicLayoutEffect","withinRange","useFormReset","useTextField","noop","useNumberField","options","min","max","step","form","onBlur","onChange","updateValue","updateValueOnBlur","disableReset","defaultValue","textOptions","number","setNumber","initial","value","_value","reset","resetTextField","fieldRef","fieldProps","setState","setTextFieldState","remaining","isNumber","event","isPropagationStopped","input","currentTarget","setCustomValidity","checkValidity","validity","badInput","valueAsNumber","current","Number","isNaN","undefined","valid","rangeUnderflow","rangeOverflow","error","errorMessage","prevState","nextState","resolvedNextState","elementRef","onReset","type"],"mappings":"AAAA;AAEA,SAASA,WAAW,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAQ;AAGtD,SAASC,yBAAyB,QAAQ,kCAAkC;AAC5E,SAASC,WAAW,QAAQ,0BAA0B;AACtD,SAASC,YAAY,QAAQ,oBAAoB;AACjD,SAOEC,YAAY,QACP,oBAAoB;AAE3B,MAAMC,OAAO;AACX,aAAa;AACf;AAsUA;;;;;;CAMC,GACD,OAAO,SAASC,eACdC,OAA+B;IAE/B,MAAM,EACJC,GAAG,EACHC,GAAG,EACHC,IAAI,EACJC,IAAI,EACJC,SAASP,IAAI,EACbQ,WAAWR,IAAI,EACfS,cAAc,QAAQ,EACtBC,oBAAoB,IAAI,EACxBC,YAAY,EACZC,YAAY,EACZ,GAAGC,aACJ,GAAGX;IAEJ,MAAM,CAACY,QAAQC,UAAU,GAAGpB,SAASiB;IACrC,MAAMI,UAAUtB,OAAOoB;IACvB,MAAM,EACJG,OAAOC,MAAM,EACbC,OAAOC,cAAc,EACrBC,QAAQ,EACRC,UAAU,EACVC,UAAUC,iBAAiB,EAC3B,GAAGC,WACJ,GAAG1B,aAAa;QACf,GAAGc,WAAW;QACda,UAAU;QACVd,cAA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wB;YACZ;QACF;IACF;IAEA,MAAM,EAAEI,KAAK,EAAEC,YAAY,EAAE,GAAGnB;IAChC,MAAMoB,YAAYnD,OAAO;QACvBiD;QACAC;QACA3B,OAAOH;IACT;IACAlB,0BAA0B;QACxBiD,UAAUT,OAAO,GAAG;YAClBO;YACAC;YACA3B,OAAOH;QACT;IACF;IACA,MAAMK,QAAQ1B,YAAY;QACxB2B;QACAL,UAAUC,QAAQoB,OAAO;IAC3B,GAAG;QAAChB;KAAe;IACnB,MAAMG,WAAW9B,YACf,CAACqD;QACC,MAAMC,oBACJ,OAAOD,cAAc,aACjBA,UAAUD,UAAUT,OAAO,IAC3BU;QAEN,MAAM,EAAE7B,KAAK,EAAE0B,KAAK,EAAEC,YAAY,EAAE,GAAGG;QACvChC,UAAUE;QACVO,kBAAkB;YAChBP,OAAO,GAAGA,SAAS,IAAI;YACvB0B;YACAC;QACF;IACF,GACA;QAACpB;KAAkB;IAGrB1B,aAAa;QACXQ;QACA0C,YAAY3B;QACZ4B,SAAStC,eAAe4B,YAAYpB;IACtC;IAEA,OAAO;QACL,GAAGM,SAAS;QACZN;QACAF,OAAOH;QACPS;QACAF;QACAC,YAAY;YACV,GAAGA,UAAU;YACbnB;YACAC;YACAC;YACA6C,MAAM;QACR;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/form/useNumberField.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useRef, useState } from \"react\";\n\nimport { type UseStateInitializer, type UseStateSetter } from \"../types.js\";\nimport { useIsomorphicLayoutEffect } from \"../useIsomorphicLayoutEffect.js\";\nimport { withinRange } from \"../utils/withinRange.js\";\nimport { useFormReset } from \"./useFormReset.js\";\nimport {\n type ProvidedTextFieldMessageProps,\n type ProvidedTextFieldProps,\n type TextFieldHookOptions,\n type TextFieldHookState,\n type TextFieldImplementation,\n type ValidatedTextFieldImplementation,\n useTextField,\n} from \"./useTextField.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/** @since 2.5.0 */\nexport interface NumberFieldConstraints {\n /**\n * An optional min value for the number field.\n */\n min?: number;\n\n /**\n * An optional max value for the number field.\n */\n max?: number;\n\n /**\n * An optional step amount to use.\n *\n * Note: The `min` and `max` values must be divisible by this value when any\n * are defined.\n */\n step?: number;\n}\n\n/**\n * @since 2.5.0\n * @since 6.0.0\n * - Removed `updateOnChange` in favor of `updateValue`\n * - Renamed `fixOnBlur` to `updateValueOnBlur`\n */\nexport interface NumberFieldHookOptions\n extends\n Omit<TextFieldHookOptions, \"defaultValue\" | \"isNumber\">,\n NumberFieldConstraints {\n /**\n * @defaultValue `undefined`\n */\n defaultValue?: UseStateInitializer<number>;\n\n /**\n * This controls the behavior for the `value` returned by this hook. If you\n * need access to the current value immediately as the user types to update\n * other components, keep this as the default of `\"change\"`. Otherwise, set\n * this to `\"blur\"`.\n *\n * @example Deferring Updates on Blur\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * min: 0,\n * max: 100,\n * name: \"someName\",\n * defaultValue: 0,\n * updateValue: \"blur\",\n * });\n *\n * const result = useMemo(() => someExpensiveComputation(value), [value]);\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @defaultValue `\"change\"`\n */\n updateValue?: \"blur\" | \"change\";\n\n /**\n * This option is used to update the `number` value and text field value to be\n * within the `min` and `max` range or just format the text field value when\n * the input is blurred. This update will only be applied if the text field\n * contains a valid number. Using `min = 0` and `max = 10`:\n *\n * | text value | updated value |\n * | ---------- | ------------- |\n * | 000001 | 1 |\n * | -1 | 0 |\n * | 20 | 10 |\n * | -12 | 0 |\n * | --1 | --1 |\n * | fjdka | fjdka |\n *\n *\n * Set this to `false` if no changed should be applied and force the user to\n * fix any min/max errors manually and maintain weird formatting.\n *\n * @defaultValue `true`\n * @since 6.0.0 This was renamed from `fixOnBlur` and removed the\n * `\"min\"` and `\"max\"` behavior.\n */\n updateValueOnBlur?: boolean;\n}\n\n/** @since 6.0.0 */\nexport interface NumberFieldHookState extends Omit<\n TextFieldHookState,\n \"value\"\n> {\n value: number | undefined;\n}\n\n/** @since 2.5.6 */\nexport interface ProvidedNumberFieldProps\n extends ProvidedTextFieldProps, NumberFieldConstraints {\n type: \"number\";\n}\n\n/** @since 2.5.6 */\nexport interface ProvidedNumberFieldMessageProps\n extends ProvidedTextFieldMessageProps, NumberFieldConstraints {\n type: \"number\";\n}\n\n/** @since 6.0.0 */\nexport interface NumberFieldImplementation extends Omit<\n TextFieldImplementation,\n \"value\" | \"setState\"\n> {\n value: number | undefined;\n setState: UseStateSetter<NumberFieldHookState>;\n fieldProps: ProvidedNumberFieldProps;\n}\n\n/** @since 6.0.0 */\nexport interface NumberFieldWithMessageImplementation extends NumberFieldImplementation {\n fieldProps: ProvidedNumberFieldMessageProps;\n}\n\n/** @since 6.0.0 */\nexport interface ValidatedNumberFieldImplementation extends Omit<\n ValidatedTextFieldImplementation,\n \"value\" | \"setState\"\n> {\n value: number | undefined;\n setState: UseStateSetter<NumberFieldHookState>;\n fieldProps: ProvidedNumberFieldProps | ProvidedNumberFieldMessageProps;\n}\n\n/**\n * @example Enforce Number Value and No Error Messages\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * min: 0,\n * max: 100,\n * name: \"someName\",\n * defaultValue: 0,\n * disableMessage: true,\n * });\n *\n * // this is safe since `value` will always be a number even if there is a\n * // validation error. since the min and max options were provided as well,\n * // number will be between that range as well.\n * const computed = value * 10;\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @see {@link useTextField}\n * @see {@link useNumberField} overrides for other examples.\n * ```\n */\nexport function useNumberField(\n options: NumberFieldHookOptions & {\n disableMessage: true;\n defaultValue: UseStateInitializer<number>;\n }\n): NumberFieldImplementation & {\n value: number;\n setState: UseStateSetter<NumberFieldHookState & { value: number }>;\n};\n\n/**\n * @example No Error Messages\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * min: 0,\n * max: 100,\n * name: \"someName\",\n * disableMessage: true,\n * });\n *\n * // `value` will be `undefined` until the user enters a valid value once\n * // there is a valid value, `value` will be a `number`. So this might cause\n * // `computed` to be `NaN | number`\n * //\n * // const computed = value * 10;\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @see {@link useTextField}\n * @see {@link useNumberField} overrides for other examples.\n */\nexport function useNumberField(\n options: NumberFieldHookOptions & { disableMessage: true }\n): NumberFieldImplementation;\n\n/**\n * @example Enforce Number Value\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * min: 0,\n * max: 100,\n * name: \"someName\",\n * defaultValue: 0,\n * });\n *\n * // this is safe since `value` will always be a number even if there is a\n * // validation error. since the min and max options were provided as well,\n * // number will be between that range as well.\n * const computed = value * 10;\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @example Enforce Number Value and Deferring Updates\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * min: 0,\n * max: 100,\n * name: \"someName\",\n * defaultValue: 0,\n * updateValue: \"blur\",\n * });\n *\n * // the `value` will only be updated whenever the `TextField` is blurred.\n * // This is helpful if the `value` is used in expensive computations or\n * // updates that do not need to be updated as the user types\n * const computed = value * 10;\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @see {@link useTextField}\n * @see {@link useNumberField} overrides for other examples.\n */\nexport function useNumberField(\n options: NumberFieldHookOptions & {\n defaultValue: UseStateInitializer<number>;\n }\n): NumberFieldWithMessageImplementation & {\n value: number;\n setState: UseStateSetter<NumberFieldHookState & { value: number }>;\n};\n\n/**\n * The `useNumberField` hook is used to control the state of a `TextField` or\n * `<input type=\"number\">`\n *\n * @example Default Implementation\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * name: \"someName\",\n * });\n *\n * // `value` will be `undefined` until the user enters a valid value once\n * // there is a valid value, `value` will be a `number`. So this might cause\n * // `computed` to be `NaN | number`\n * //\n * // const computed = value * 10;\n *\n * // whenever there is an error, an error message will be displayed below the\n * // `TextField`\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @example Adding Constraints\n * ```tsx\n * import { TextField } from \"@react-md/core/form/TextField\";\n * import { useNumberField } from \"@react-md/core/form/useNumberField\";\n * import type { ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { fieldProps, value } = useNumberField({\n * name: \"someName\",\n * min: 0,\n * max: 100,\n * step: 2,\n * required: true,\n * });\n *\n * return <TextField {...fieldProps} label=\"Label\" />;\n * }\n * ```\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation\n * @see {@link https://react-md.dev/components/text-field#number | Number TextField Demos}\n * @see {@link https://react-md.dev/hooks/use-number-field | useNumberField Demos}\n * @see {@link useTextField}\n */\nexport function useNumberField(\n options: NumberFieldHookOptions\n): NumberFieldWithMessageImplementation;\n\n/**\n * @internal\n * @see {@link https://react-md.dev/components/text-field#number | Number TextField Demos}\n * @see {@link https://react-md.dev/hooks/use-number-field | useNumberField Demos}\n * @see {@link useTextField}\n * @see {@link useNumberField} overrides for other examples.\n */\nexport function useNumberField(\n options: NumberFieldHookOptions\n): ValidatedNumberFieldImplementation {\n const {\n min,\n max,\n step,\n form,\n onBlur = noop,\n onChange = noop,\n updateValue = \"change\",\n updateValueOnBlur = true,\n disableReset,\n defaultValue,\n ...textOptions\n } = options;\n\n const [number, setNumber] = useState(defaultValue);\n const initial = useRef(number);\n const {\n value: _value,\n reset: resetTextField,\n fieldRef,\n fieldProps,\n setState: setTextFieldState,\n ...remaining\n } = useTextField({\n ...textOptions,\n isNumber: true,\n defaultValue: `${number ?? \"\"}`,\n disableReset: true,\n onBlur(event) {\n onBlur(event);\n if (event.isPropagationStopped()) {\n return;\n }\n\n const input = event.currentTarget;\n input.setCustomValidity(\"\");\n input.checkValidity();\n if (\n !updateValueOnBlur ||\n // do nothing else since it's a weird value like: `\"--0\"` which causes\n // the value to be `\"\"` and `numberAsValue` to be `NaN`\n input.validity.badInput\n ) {\n return;\n }\n\n let value = input.valueAsNumber;\n if (input.value === \"\" && typeof initial.current === \"number\") {\n value = min ?? initial.current;\n }\n\n // can't have both rangeUnderflow and rangeOverflow at the same time, so\n // it's \"safe\" to always provide both\n value = withinRange({ min, max, value });\n if (!Number.isNaN(value)) {\n setNumber(value);\n input.value = `${value}`;\n } else if (initial.current === undefined) {\n setNumber(undefined);\n }\n },\n onChange(event) {\n onChange(event);\n if (event.isPropagationStopped() || updateValue === \"blur\") {\n return;\n }\n\n const input = event.currentTarget;\n input.checkValidity();\n const value = withinRange({\n min,\n max,\n value: event.currentTarget.valueAsNumber,\n });\n if (\n !input.validity.valid &&\n !input.validity.rangeUnderflow &&\n !input.validity.rangeOverflow\n ) {\n return;\n }\n\n if (!Number.isNaN(value)) {\n setNumber(value);\n } else if (initial.current === undefined) {\n setNumber(undefined);\n }\n },\n });\n\n const { error, errorMessage } = remaining;\n const prevState = useRef({\n error,\n errorMessage,\n value: number,\n } satisfies NumberFieldHookState);\n useIsomorphicLayoutEffect(() => {\n prevState.current = {\n error,\n errorMessage,\n value: number,\n };\n });\n const reset = useCallback(() => {\n resetTextField();\n setNumber(initial.current);\n }, [resetTextField]);\n const setState = useCallback<UseStateSetter<NumberFieldHookState>>(\n (nextState) => {\n const resolvedNextState =\n typeof nextState === \"function\"\n ? nextState(prevState.current)\n : nextState;\n\n const { value, error, errorMessage } = resolvedNextState;\n setNumber(value);\n setTextFieldState({\n value: `${value ?? \"\"}`,\n error,\n errorMessage,\n });\n },\n [setTextFieldState]\n );\n\n useFormReset({\n form,\n elementRef: fieldRef,\n onReset: disableReset ? undefined : reset,\n });\n\n return {\n ...remaining,\n reset,\n value: number,\n setState,\n fieldRef,\n fieldProps: {\n ...fieldProps,\n min,\n max,\n step,\n type: \"number\",\n },\n };\n}\n"],"names":["useCallback","useRef","useState","useIsomorphicLayoutEffect","withinRange","useFormReset","useTextField","noop","useNumberField","options","min","max","step","form","onBlur","onChange","updateValue","updateValueOnBlur","disableReset","defaultValue","textOptions","number","setNumber","initial","value","_value","reset","resetTextField","fieldRef","fieldProps","setState","setTextFieldState","remaining","isNumber","event","isPropagationStopped","input","currentTarget","setCustomValidity","checkValidity","validity","badInput","valueAsNumber","current","Number","isNaN","undefined","valid","rangeUnderflow","rangeOverflow","error","errorMessage","prevState","nextState","resolvedNextState","elementRef","onReset","type"],"mappings":"AAAA;AAEA,SAASA,WAAW,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAQ;AAGtD,SAASC,yBAAyB,QAAQ,kCAAkC;AAC5E,SAASC,WAAW,QAAQ,0BAA0B;AACtD,SAASC,YAAY,QAAQ,oBAAoB;AACjD,SAOEC,YAAY,QACP,oBAAoB;AAE3B,MAAMC,OAAO;AACX,aAAa;AACf;AAsUA;;;;;;CAMC,GACD,OAAO,SAASC,eACdC,OAA+B;IAE/B,MAAM,EACJC,GAAG,EACHC,GAAG,EACHC,IAAI,EACJC,IAAI,EACJC,SAASP,IAAI,EACbQ,WAAWR,I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f,QAAQpB,YAAY;gBACxBM;gBACAC;gBACAa,OAAOU,MAAMG,aAAa,CAACK,aAAa;YAC1C;YACA,IACE,CAACN,MAAMI,QAAQ,CAACO,KAAK,IACrB,CAACX,MAAMI,QAAQ,CAACQ,cAAc,IAC9B,CAACZ,MAAMI,QAAQ,CAACS,aAAa,EAC7B;gBACA;YACF;YAEA,IAAI,CAACL,OAAOC,KAAK,CAACrB,QAAQ;gBACxBF,UAAUE;YACZ,OAAO,IAAID,QAAQoB,OAAO,KAAKG,WAAW;gBACxCxB,UAAUwB;YACZ;QACF;IACF;IAEA,MAAM,EAAEI,KAAK,EAAEC,YAAY,EAAE,GAAGnB;IAChC,MAAMoB,YAAYnD,OAAO;QACvBiD;QACAC;QACA3B,OAAOH;IACT;IACAlB,0BAA0B;QACxBiD,UAAUT,OAAO,GAAG;YAClBO;YACAC;YACA3B,OAAOH;QACT;IACF;IACA,MAAMK,QAAQ1B,YAAY;QACxB2B;QACAL,UAAUC,QAAQoB,OAAO;IAC3B,GAAG;QAAChB;KAAe;IACnB,MAAMG,WAAW9B,YACf,CAACqD;QACC,MAAMC,oBACJ,OAAOD,cAAc,aACjBA,UAAUD,UAAUT,OAAO,IAC3BU;QAEN,MAAM,EAAE7B,KAAK,EAAE0B,KAAK,EAAEC,YAAY,EAAE,GAAGG;QACvChC,UAAUE;QACVO,kBAAkB;YAChBP,OAAO,GAAGA,SAAS,IAAI;YACvB0B;YACAC;QACF;IACF,GACA;QAACpB;KAAkB;IAGrB1B,aAAa;QACXQ;QACA0C,YAAY3B;QACZ4B,SAAStC,eAAe4B,YAAYpB;IACtC;IAEA,OAAO;QACL,GAAGM,SAAS;QACZN;QACAF,OAAOH;QACPS;QACAF;QACAC,YAAY;YACV,GAAGA,UAAU;YACbnB;YACAC;YACAC;YACA6C,MAAM;QACR;IACF;AACF"}
@@ -45,18 +45,18 @@ const noop = ()=>{
45
45
  /* c8 ignore start */ if (!mask || !container) {
46
46
  return;
47
47
  }
48
- /* c8 ignore stop */ const containerStyles = window.getComputedStyle(container);
48
+ /* c8 ignore stop */ const containerStyles = globalThis.getComputedStyle(container);
49
49
  const isBorderBox = containerStyles.boxSizing === "border-box";
50
50
  let borderHeight = 0;
51
51
  if (isBorderBox) {
52
- borderHeight = parseFloat(containerStyles.borderTopWidth) + parseFloat(containerStyles.borderBottomWidth);
52
+ borderHeight = Number.parseFloat(containerStyles.borderTopWidth) + Number.parseFloat(containerStyles.borderBottomWidth);
53
53
  }
54
54
  let nextHeight = mask.scrollHeight + borderHeight;
55
55
  if (maxRows > 0) {
56
56
  nextHeight -= borderHeight;
57
- const maskStyles = window.getComputedStyle(mask);
57
+ const maskStyles = globalThis.getComputedStyle(mask);
58
58
  // in tests, this is `"normal"` by default instead of a number
59
- let lineHeight = parseFloat(maskStyles.lineHeight);
59
+ let lineHeight = Number.parseFloat(maskStyles.lineHeight);
60
60
  if (Number.isNaN(lineHeight)) {
61
61
  lineHeight = DEFAULT_LINE_HEIGHT;
62
62
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/useResizingTextArea.ts"],"sourcesContent":["\"use client\";\n\nimport {\n type ChangeEventHandler,\n type Ref,\n type RefCallback,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\n\nimport { useEnsuredRef } from \"../useEnsuredRef.js\";\nimport { useResizeObserver } from \"../useResizeObserver.js\";\n\n// this is the default of 1.5rem line-height in the styles\nconst DEFAULT_LINE_HEIGHT = 24;\n\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n * A textarea is normally resizable in browsers by default by dragging the\n * bottom right corner to the desired size which will set inline styles for\n * `height` and `width`. Since this makes creating layouts a bit more difficult,\n * this is disabled by default but can be configured using one of these values:\n *\n * - `\"auto\"` - The textarea will automatically grow in in height as the user\n * types until a max number of rows have been added. If there is additional\n * text, a scrollbar will appear in the textarea. The browser's native resize\n * behavior is disabled.\n * - `\"none\"` - The textarea's height and width will remain static\n * - `\"horizontal\"` - The textarea's width can be resized by the browser's\n * native resize behavior.\n * - `\"vertical\"` - The textarea's height can be resized by the browser's native\n * resize behavior.\n * - `\"both\"` - The browser's native resize behavior will be allowed.\n */\nexport type TextAreaResize =\n | \"none\"\n | \"auto\"\n | \"horizontal\"\n | \"vertical\"\n | \"both\";\n\n/** @internal */\nexport interface ResizingTextAreaOptions {\n resize: TextAreaResize;\n maxRows: number;\n onChange: ChangeEventHandler<HTMLTextAreaElement> | undefined;\n containerRef?: Ref<HTMLDivElement>;\n disableTransition: boolean | undefined;\n}\n\n/** @internal */\nexport interface ResizingTextAreaReturnValue {\n height: string | undefined;\n maskRef: RefCallback<HTMLTextAreaElement>;\n containerRef: RefCallback<HTMLDivElement>;\n onChange: ChangeEventHandler<HTMLTextAreaElement>;\n scrollable: boolean;\n disableTransition: boolean;\n}\n\n/** @internal */\nexport function useResizingTextArea(\n options: ResizingTextAreaOptions\n): ResizingTextAreaReturnValue {\n const {\n maxRows,\n resize,\n onChange = noop,\n containerRef: propContainerRef,\n disableTransition,\n } = options;\n\n const maskRef = useRef<HTMLTextAreaElement>(null);\n const [containerRef, containerRefCallback] = useEnsuredRef(propContainerRef);\n const [height, setHeight] = useState<number>();\n useEffect(() => {\n if (resize !== \"auto\") {\n setHeight(undefined);\n }\n }, [resize]);\n\n // Since access to the DOM is required to calculate the current height of the\n // textarea, do not enable the height transition until it has been calculated\n // once.\n const isHeightSet = useRef(true);\n useEffect(() => {\n isHeightSet.current = !height;\n }, [height]);\n\n // Do not enable the scrollbar until the max height has been reached since\n // it'll flash as the user types on OS that display scrollbars.\n //\n // Note: This does cause an infinite loop issue on browsers that display OS\n // when rendered in a flex/grid container and a \"fluid\" width since:\n // - the width changes when the overflow changes to `auto`\n // - the resize observer triggers since there was a width change\n // - the number of rows imght change because of this width change\n // - it might no longer be at the max height, so remove the scrollbar\n // - restart\n const [isMaxHeightReached, setMaxHeightReached] = useState(false);\n const updateHeight = useCallback(() => {\n const mask = maskRef.current;\n const container = containerRef.current;\n /* c8 ignore start */\n if (!mask || !container) {\n return;\n }\n /* c8 ignore stop */\n\n const containerStyles = window.getComputedStyle(container);\n const isBorderBox = containerStyles.boxSizing === \"border-box\";\n let borderHeight = 0;\n if (isBorderBox) {\n borderHeight =\n parseFloat(containerStyles.borderTopWidth) +\n parseFloat(containerStyles.borderBottomWidth);\n }\n\n let nextHeight = mask.scrollHeight + borderHeight;\n if (maxRows > 0) {\n nextHeight -= borderHeight;\n const maskStyles = window.getComputedStyle(mask);\n // in tests, this is `\"normal\"` by default instead of a number\n let lineHeight = parseFloat(maskStyles.lineHeight);\n if (Number.isNaN(lineHeight)) {\n lineHeight = DEFAULT_LINE_HEIGHT;\n }\n\n const maxHeight = maxRows * lineHeight;\n setMaxHeightReached(nextHeight > maxHeight + borderHeight);\n nextHeight = Math.min(maxHeight, nextHeight) + borderHeight;\n }\n\n // This just makes snapshots look nicer since `nextHeight` will be 0 in\n // tests unless the user mocks out all the DOM properties\n if (nextHeight) {\n setHeight(nextHeight);\n }\n }, [containerRef, maxRows]);\n\n const maskRefCallback = useResizeObserver({\n ref: maskRef,\n onUpdate: updateHeight,\n disableHeight: true,\n });\n\n return {\n height: typeof height === \"number\" ? `${height}px` : undefined,\n maskRef: maskRefCallback,\n containerRef: containerRefCallback,\n scrollable: maxRows > 0 && isMaxHeightReached,\n disableTransition: disableTransition || isHeightSet.current,\n onChange(event) {\n onChange(event);\n\n const mask = maskRef.current;\n if (!mask || resize !== \"auto\") {\n return;\n }\n\n // to get the height transition to work, you have to set the height on:\n // - the main container element (including padding) that has the height\n // transition enabled\n // - a child div wrapper (without padding) that has the height transition\n // enabled\n // - the textarea element (without padding) and without a height transition\n //\n // if it isn't done this way, the height transition will look weird since\n // the text will be fixed to the bottom of the area and more text at the top\n // will become visible as the height transition completes. applying the\n // transition on the two parent elements work because:\n // - the height is set immediately on the text field so it expands to show all\n // the text\n // - the height is correctly applied to both parent elements, but their height\n // haven't fully been adjusted due to the animation\n // - the parent divs have overflow visible by default, so the textarea's text\n // will expand past the boundaries of the divs and not cause the upwards\n // animation weirdness.\n mask.value = event.currentTarget.value;\n updateHeight();\n },\n };\n}\n"],"names":["useCallback","useEffect","useRef","useState","useEnsuredRef","useResizeObserver","DEFAULT_LINE_HEIGHT","noop","useResizingTextArea","options","maxRows","resize","onChange","containerRef","propContainerRef","disableTransition","maskRef","containerRefCallback","height","setHeight","undefined","isHeightSet","current","isMaxHeightReached","setMaxHeightReached","updateHeight","mask","container","containerStyles","window","getComputedStyle","isBorderBox","boxSizing","borderHeight","parseFloat","borderTopWidth","borderBottomWidth","nextHeight","scrollHeight","maskStyles","lineHeight","Number","isNaN","maxHeight","Math","min","maskRefCallback","ref","onUpdate","disableHeight","scrollable","event","value","currentTarget"],"mappings":"AAAA;AAEA,SAIEA,WAAW,EACXC,SAAS,EACTC,MAAM,EACNC,QAAQ,QACH,QAAQ;AAEf,SAASC,aAAa,QAAQ,sBAAsB;AACpD,SAASC,iBAAiB,QAAQ,0BAA0B;AAE5D,0DAA0D;AAC1D,MAAMC,sBAAsB;AAE5B,MAAMC,OAAO;AACX,aAAa;AACf;AA6CA,cAAc,GACd,OAAO,SAASC,oBACdC,OAAgC;IAEhC,MAAM,EACJC,OAAO,EACPC,MAAM,EACNC,WAAWL,IAAI,EACfM,cAAcC,gBAAgB,EAC9BC,iBAAiB,EAClB,GAAGN;IAEJ,MAAMO,UAAUd,OAA4B;IAC5C,MAAM,CAACW,cAAcI,qBAAqB,GAAGb,cAAcU;IAC3D,MAAM,CAACI,QAAQC,UAAU,GAAGhB;IAC5BF,UAAU;QACR,IAAIU,WAAW,QAAQ;YACrBQ,UAAUC;QACZ;IACF,GAAG;QAACT;KAAO;IAEX,6EAA6E;IAC7E,6EAA6E;IAC7E,QAAQ;IACR,MAAMU,cAAcnB,OAAO;IAC3BD,UAAU;QACRoB,YAAYC,OAAO,GAAG,CAACJ;IACzB,GAAG;QAACA;KAAO;IAEX,0EAA0E;IAC1E,+DAA+D;IAC/D,EAAE;IACF,2EAA2E;IAC3E,oEA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;QAC3DV,UAASuC,KAAK;YACZvC,SAASuC;YAET,MAAMzB,OAAOV,QAAQM,OAAO;YAC5B,IAAI,CAACI,QAAQf,WAAW,QAAQ;gBAC9B;YACF;YAEA,uEAAuE;YACvE,uEAAuE;YACvE,wBAAwB;YACxB,yEAAyE;YACzE,aAAa;YACb,2EAA2E;YAC3E,EAAE;YACF,yEAAyE;YACzE,4EAA4E;YAC5E,uEAAuE;YACvE,sDAAsD;YACtD,8EAA8E;YAC9E,cAAc;YACd,8EAA8E;YAC9E,sDAAsD;YACtD,6EAA6E;YAC7E,2EAA2E;YAC3E,0BAA0B;YAC1Be,KAAK0B,KAAK,GAAGD,MAAME,aAAa,CAACD,KAAK;YACtC3B;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/form/useResizingTextArea.ts"],"sourcesContent":["\"use client\";\n\nimport {\n type ChangeEventHandler,\n type Ref,\n type RefCallback,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\n\nimport { useEnsuredRef } from \"../useEnsuredRef.js\";\nimport { useResizeObserver } from \"../useResizeObserver.js\";\n\n// this is the default of 1.5rem line-height in the styles\nconst DEFAULT_LINE_HEIGHT = 24;\n\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n * A textarea is normally resizable in browsers by default by dragging the\n * bottom right corner to the desired size which will set inline styles for\n * `height` and `width`. Since this makes creating layouts a bit more difficult,\n * this is disabled by default but can be configured using one of these values:\n *\n * - `\"auto\"` - The textarea will automatically grow in in height as the user\n * types until a max number of rows have been added. If there is additional\n * text, a scrollbar will appear in the textarea. The browser's native resize\n * behavior is disabled.\n * - `\"none\"` - The textarea's height and width will remain static\n * - `\"horizontal\"` - The textarea's width can be resized by the browser's\n * native resize behavior.\n * - `\"vertical\"` - The textarea's height can be resized by the browser's native\n * resize behavior.\n * - `\"both\"` - The browser's native resize behavior will be allowed.\n */\nexport type TextAreaResize =\n | \"none\"\n | \"auto\"\n | \"horizontal\"\n | \"vertical\"\n | \"both\";\n\n/** @internal */\nexport interface ResizingTextAreaOptions {\n resize: TextAreaResize;\n maxRows: number;\n onChange: ChangeEventHandler<HTMLTextAreaElement> | undefined;\n containerRef?: Ref<HTMLDivElement>;\n disableTransition: boolean | undefined;\n}\n\n/** @internal */\nexport interface ResizingTextAreaReturnValue {\n height: string | undefined;\n maskRef: RefCallback<HTMLTextAreaElement>;\n containerRef: RefCallback<HTMLDivElement>;\n onChange: ChangeEventHandler<HTMLTextAreaElement>;\n scrollable: boolean;\n disableTransition: boolean;\n}\n\n/** @internal */\nexport function useResizingTextArea(\n options: ResizingTextAreaOptions\n): ResizingTextAreaReturnValue {\n const {\n maxRows,\n resize,\n onChange = noop,\n containerRef: propContainerRef,\n disableTransition,\n } = options;\n\n const maskRef = useRef<HTMLTextAreaElement>(null);\n const [containerRef, containerRefCallback] = useEnsuredRef(propContainerRef);\n const [height, setHeight] = useState<number>();\n useEffect(() => {\n if (resize !== \"auto\") {\n setHeight(undefined);\n }\n }, [resize]);\n\n // Since access to the DOM is required to calculate the current height of the\n // textarea, do not enable the height transition until it has been calculated\n // once.\n const isHeightSet = useRef(true);\n useEffect(() => {\n isHeightSet.current = !height;\n }, [height]);\n\n // Do not enable the scrollbar until the max height has been reached since\n // it'll flash as the user types on OS that display scrollbars.\n //\n // Note: This does cause an infinite loop issue on browsers that display OS\n // when rendered in a flex/grid container and a \"fluid\" width since:\n // - the width changes when the overflow changes to `auto`\n // - the resize observer triggers since there was a width change\n // - the number of rows imght change because of this width change\n // - it might no longer be at the max height, so remove the scrollbar\n // - restart\n const [isMaxHeightReached, setMaxHeightReached] = useState(false);\n const updateHeight = useCallback(() => {\n const mask = maskRef.current;\n const container = containerRef.current;\n /* c8 ignore start */\n if (!mask || !container) {\n return;\n }\n /* c8 ignore stop */\n\n const containerStyles = globalThis.getComputedStyle(container);\n const isBorderBox = containerStyles.boxSizing === \"border-box\";\n let borderHeight = 0;\n if (isBorderBox) {\n borderHeight =\n Number.parseFloat(containerStyles.borderTopWidth) +\n Number.parseFloat(containerStyles.borderBottomWidth);\n }\n\n let nextHeight = mask.scrollHeight + borderHeight;\n if (maxRows > 0) {\n nextHeight -= borderHeight;\n const maskStyles = globalThis.getComputedStyle(mask);\n // in tests, this is `\"normal\"` by default instead of a number\n let lineHeight = Number.parseFloat(maskStyles.lineHeight);\n if (Number.isNaN(lineHeight)) {\n lineHeight = DEFAULT_LINE_HEIGHT;\n }\n\n const maxHeight = maxRows * lineHeight;\n setMaxHeightReached(nextHeight > maxHeight + borderHeight);\n nextHeight = Math.min(maxHeight, nextHeight) + borderHeight;\n }\n\n // This just makes snapshots look nicer since `nextHeight` will be 0 in\n // tests unless the user mocks out all the DOM properties\n if (nextHeight) {\n setHeight(nextHeight);\n }\n }, [containerRef, maxRows]);\n\n const maskRefCallback = useResizeObserver({\n ref: maskRef,\n onUpdate: updateHeight,\n disableHeight: true,\n });\n\n return {\n height: typeof height === \"number\" ? `${height}px` : undefined,\n maskRef: maskRefCallback,\n containerRef: containerRefCallback,\n scrollable: maxRows > 0 && isMaxHeightReached,\n disableTransition: disableTransition || isHeightSet.current,\n onChange(event) {\n onChange(event);\n\n const mask = maskRef.current;\n if (!mask || resize !== \"auto\") {\n return;\n }\n\n // to get the height transition to work, you have to set the height on:\n // - the main container element (including padding) that has the height\n // transition enabled\n // - a child div wrapper (without padding) that has the height transition\n // enabled\n // - the textarea element (without padding) and without a height transition\n //\n // if it isn't done this way, the height transition will look weird since\n // the text will be fixed to the bottom of the area and more text at the top\n // will become visible as the height transition completes. applying the\n // transition on the two parent elements work because:\n // - the height is set immediately on the text field so it expands to show all\n // the text\n // - the height is correctly applied to both parent elements, but their height\n // haven't fully been adjusted due to the animation\n // - the parent divs have overflow visible by default, so the textarea's text\n // will expand past the boundaries of the divs and not cause the upwards\n // animation weirdness.\n mask.value = event.currentTarget.value;\n updateHeight();\n },\n };\n}\n"],"names":["useCallback","useEffect","useRef","useState","useEnsuredRef","useResizeObserver","DEFAULT_LINE_HEIGHT","noop","useResizingTextArea","options","maxRows","resize","onChange","containerRef","propContainerRef","disableTransition","maskRef","containerRefCallback","height","setHeight","undefined","isHeightSet","current","isMaxHeightReached","setMaxHeightReached","updateHeight","mask","container","containerStyles","globalThis","getComputedStyle","isBorderBox","boxSizing","borderHeight","Number","parseFloat","borderTopWidth","borderBottomWidth","nextHeight","scrollHeight","maskStyles","lineHeight","isNaN","maxHeight","Math","min","maskRefCallback","ref","onUpdate","disableHeight","scrollable","event","value","currentTarget"],"mappings":"AAAA;AAEA,SAIEA,WAAW,EACXC,SAAS,EACTC,MAAM,EACNC,QAAQ,QACH,QAAQ;AAEf,SAASC,aAAa,QAAQ,sBAAsB;AACpD,SAASC,iBAAiB,QAAQ,0BAA0B;AAE5D,0DAA0D;AAC1D,MAAMC,sBAAsB;AAE5B,MAAMC,OAAO;AACX,aAAa;AACf;AA6CA,cAAc,GACd,OAAO,SAASC,oBACdC,OAAgC;IAEhC,MAAM,EACJC,OAAO,EACPC,MAAM,EACNC,WAAWL,IAAI,EACfM,cAAcC,gBAAgB,EAC9BC,iBAAiB,EAClB,GAAGN;IAEJ,MAAMO,UAAUd,OAA4B;IAC5C,MAAM,CAACW,cAAcI,qBAAqB,GAAGb,cAAcU;IAC3D,MAAM,CAACI,QAAQC,UAAU,GAAGhB;IAC5BF,UAAU;QACR,IAAIU,WAAW,QAAQ;YACrBQ,UAAUC;QACZ;IACF,GAAG;QAACT;KAAO;IAEX,6EAA6E;IAC7E,6EAA6E;IAC7E,QAAQ;IACR,MAAMU,cAAcnB,OAAO;IAC3BD,UAAU;QACRoB,YAAYC,OAAO,GAAG,CAACJ;IACzB,GAAG;QAACA;KAAO;IAEX,0EAA0E;IAC1E,+DAA+D;IAC/D,EAAE;IACF,2EAA2E;IAC3E,oEAAoE;IACpE,0DAA0D;IAC1D,gEAAgE;IAChE,iEAAiE;IACjE,qEAAqE;IACrE,YAAY;IACZ,MAAM,CAACK,oBAAoBC,oBAAoB,GAAGrB,SAAS;IAC3D,MAAMsB,eAAezB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gBAC9B;YACF;YAEA,uEAAuE;YACvE,uEAAuE;YACvE,wBAAwB;YACxB,yEAAyE;YACzE,aAAa;YACb,2EAA2E;YAC3E,EAAE;YACF,yEAAyE;YACzE,4EAA4E;YAC5E,uEAAuE;YACvE,sDAAsD;YACtD,8EAA8E;YAC9E,cAAc;YACd,8EAA8E;YAC9E,sDAAsD;YACtD,6EAA6E;YAC7E,2EAA2E;YAC3E,0BAA0B;YAC1Be,KAAK0B,KAAK,GAAGD,MAAME,aAAa,CAACD,KAAK;YACtC3B;QACF;IACF;AACF"}
@@ -28,7 +28,7 @@ import { useCombobox } from "./useCombobox.js";
28
28
  if (focusLast && !value) {
29
29
  return values.length - 1;
30
30
  }
31
- return Math.max(0, values.findIndex((option)=>option === value));
31
+ return Math.max(0, values.indexOf(value));
32
32
  }
33
33
  });
34
34
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/useSelectCombobox.ts"],"sourcesContent":["\"use client\";\n\nimport {\n type ComboboxImplementation,\n type ConfigurableComboboxOptions,\n useCombobox,\n} from \"./useCombobox.js\";\n\n/**\n * @since 6.0.0\n */\nexport interface SelectComboboxOptions<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n> extends ConfigurableComboboxOptions<ComboboxEl, PopupEl> {\n value: string;\n values: readonly string[];\n}\n\n/**\n * @since 6.0.0\n */\nexport type SelectComboboxImplementation<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n> = ComboboxImplementation<ComboboxEl, PopupEl>;\n\n/**\n * @since 6.0.0\n */\nexport function useSelectCombobox<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n>(\n options: SelectComboboxOptions<ComboboxEl, PopupEl>\n): SelectComboboxImplementation<ComboboxEl, PopupEl> {\n const { value, values, ...comboboxOptions } = options;\n\n return useCombobox({\n ...comboboxOptions,\n searchable: true,\n extendKeyDown(movementData) {\n const { event, show, focusLastRef, visible } = movementData;\n if (visible) {\n return;\n }\n\n switch (event.key) {\n case \" \":\n case \"Home\":\n case \"End\":\n event.preventDefault();\n event.stopPropagation();\n focusLastRef.current = event.key === \"End\";\n show();\n break;\n }\n },\n getEnterDefaultFocusedIndex(options) {\n const { focusLast } = options;\n if (focusLast && !value) {\n return values.length - 1;\n }\n\n return Math.max(\n 0,\n values.findIndex((option) => option === value)\n );\n },\n });\n}\n"],"names":["useCombobox","useSelectCombobox","options","value","values","comboboxOptions","searchable","extendKeyDown","movementData","event","show","focusLastRef","visible","key","preventDefault","stopPropagation","current","getEnterDefaultFocusedIndex","focusLast","length","Math","max","findIndex","option"],"mappings":"AAAA;AAEA,SAGEA,WAAW,QACN,mBAAmB;AAqB1B;;CAEC,GACD,OAAO,SAASC,kBAIdC,OAAmD;IAEnD,MAAM,EAAEC,KAAK,EAAEC,MAAM,EAAE,GAAGC,iBAAiB,GAAGH;IAE9C,OAAOF,YAAY;QACjB,GAAGK,eAAe;QAClBC,YAAY;QACZC,eAAcC,YAAY;YACxB,MAAM,EAAEC,KAAK,EAAEC,IAAI,EAAEC,YAAY,EAAEC,OAAO,EAAE,GAAGJ;YAC/C,IAAII,SAAS;gBACX;YACF;YAEA,OAAQH,MAAMI,GAAG;gBACf,KAAK;gBACL,KAAK;gBACL,KAAK;oBACHJ,MAAMK,cAAc;oBACpBL,MAAMM,eAAe;oBACrBJ,aAAaK,OAAO,GAAGP,MAAMI,GAAG,KAAK;oBACrCH;oBACA;YACJ;QACF;QACAO,6BAA4Bf,OAAO;YACjC,MAAM,EAAEgB,SAAS,EAAE,GAAGhB;YACtB,IAAIgB,aAAa,CAACf,OAAO;gBACvB,OAAOC,OAAOe,MAAM,GAAG;YACzB;YAEA,OAAOC,KAAKC,GAAG,CACb,GACAjB,OAAOkB,SAAS,CAAC,CAACC,SAAWA,WAAWpB;QAE5C;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/form/useSelectCombobox.ts"],"sourcesContent":["\"use client\";\n\nimport {\n type ComboboxImplementation,\n type ConfigurableComboboxOptions,\n useCombobox,\n} from \"./useCombobox.js\";\n\n/**\n * @since 6.0.0\n */\nexport interface SelectComboboxOptions<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n> extends ConfigurableComboboxOptions<ComboboxEl, PopupEl> {\n value: string;\n values: readonly string[];\n}\n\n/**\n * @since 6.0.0\n */\nexport type SelectComboboxImplementation<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n> = ComboboxImplementation<ComboboxEl, PopupEl>;\n\n/**\n * @since 6.0.0\n */\nexport function useSelectCombobox<\n ComboboxEl extends HTMLElement = HTMLInputElement,\n PopupEl extends HTMLElement = HTMLElement,\n>(\n options: SelectComboboxOptions<ComboboxEl, PopupEl>\n): SelectComboboxImplementation<ComboboxEl, PopupEl> {\n const { value, values, ...comboboxOptions } = options;\n\n return useCombobox({\n ...comboboxOptions,\n searchable: true,\n extendKeyDown(movementData) {\n const { event, show, focusLastRef, visible } = movementData;\n if (visible) {\n return;\n }\n\n switch (event.key) {\n case \" \":\n case \"Home\":\n case \"End\":\n event.preventDefault();\n event.stopPropagation();\n focusLastRef.current = event.key === \"End\";\n show();\n break;\n }\n },\n getEnterDefaultFocusedIndex(options) {\n const { focusLast } = options;\n if (focusLast && !value) {\n return values.length - 1;\n }\n\n return Math.max(0, values.indexOf(value));\n },\n });\n}\n"],"names":["useCombobox","useSelectCombobox","options","value","values","comboboxOptions","searchable","extendKeyDown","movementData","event","show","focusLastRef","visible","key","preventDefault","stopPropagation","current","getEnterDefaultFocusedIndex","focusLast","length","Math","max","indexOf"],"mappings":"AAAA;AAEA,SAGEA,WAAW,QACN,mBAAmB;AAqB1B;;CAEC,GACD,OAAO,SAASC,kBAIdC,OAAmD;IAEnD,MAAM,EAAEC,KAAK,EAAEC,MAAM,EAAE,GAAGC,iBAAiB,GAAGH;IAE9C,OAAOF,YAAY;QACjB,GAAGK,eAAe;QAClBC,YAAY;QACZC,eAAcC,YAAY;YACxB,MAAM,EAAEC,KAAK,EAAEC,IAAI,EAAEC,YAAY,EAAEC,OAAO,EAAE,GAAGJ;YAC/C,IAAII,SAAS;gBACX;YACF;YAEA,OAAQH,MAAMI,GAAG;gBACf,KAAK;gBACL,KAAK;gBACL,KAAK;oBACHJ,MAAMK,cAAc;oBACpBL,MAAMM,eAAe;oBACrBJ,aAAaK,OAAO,GAAGP,MAAMI,GAAG,KAAK;oBACrCH;oBACA;YACJ;QACF;QACAO,6BAA4Bf,OAAO;YACjC,MAAM,EAAEgB,SAAS,EAAE,GAAGhB;YACtB,IAAIgB,aAAa,CAACf,OAAO;gBACvB,OAAOC,OAAOe,MAAM,GAAG;YACzB;YAEA,OAAOC,KAAKC,GAAG,CAAC,GAAGjB,OAAOkB,OAAO,CAACnB;QACpC;IACF;AACF"}
@@ -69,7 +69,7 @@
69
69
  const keys = typeof validate === "string" ? [
70
70
  validate
71
71
  ] : validate;
72
- return keys.length && VALIDITY_STATE_KEYS.some((key)=>validity[key] && keys.includes(key)) ? validationMessage : "";
72
+ return keys.length > 0 && VALIDITY_STATE_KEYS.some((key)=>validity[key] && keys.includes(key)) ? validationMessage : "";
73
73
  };
74
74
  /**
75
75
  * The default implementation for checking if a `TextField` or `TextArea` is
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/validation.ts"],"sourcesContent":["import { type InputHTMLAttributes, type ReactNode } from \"react\";\n\n/**\n * @since 2.5.6\n * @since 6.0.0 Renamed from `TextConstraints` to\n * `TextFieldValidationOptions`\n */\nexport type TextFieldValidationOptions = Pick<\n InputHTMLAttributes<HTMLInputElement>,\n \"minLength\" | \"maxLength\" | \"required\" | \"pattern\"\n>;\n\n/**\n * Since the default validation messages can be verbose, this type is used to\n * configure when/how to display the native browser messages when the validation\n * state changes during the `change` event phase. The validation message will\n * always be shown on blur.\n *\n * When this is:\n *\n * - `true` -&gt; always show the browser message when it exists\n * - `false` -&gt; never show the browser message\n * - `\"recommended\"` -&gt; only shows the browser message if it is one of the\n * `RECOMMENDED_STATE_KEYS`/`RECOMMENDED_NUMBER_STATE_KEYS` validation errors\n * - `keyof ValidityState` -&gt; only shows the browser message if it is not the\n * specific validation error\n * - `(keyof ValidityState)[]` -&gt; only shows the browser message if it is not\n * the specific validation errors\n *\n * @see {@link RECOMMENDED_STATE_KEYS}\n * @see {@link RECOMMENDED_NUMBER_STATE_KEYS}\n * @since 2.5.6\n * @since 6.0.0 Renamed from `ChangeValidationBehavior` to\n * `TextFieldValidationType`\n */\nexport type TextFieldValidationType =\n | \"blur\"\n | \"change\"\n | \"recommended\"\n | keyof ValidityState\n | readonly (keyof ValidityState)[];\n\n/**\n * @since 2.5.0\n * @since 6.0.0 Renamed `validateOnChange` to `validationType`\n */\nexport interface ErrorMessageOptions extends TextFieldValidationOptions {\n /**\n * The current input or textarea's validity state.\n */\n validity: ValidityState;\n\n /**\n * The browser defined validation message based on the validity state. This\n * will be the empty string when there are no errors.\n */\n validationMessage: string;\n\n /**\n * The current `TextField` or `TextArea` value.\n */\n value: string;\n\n /**\n * This will only be `true` if called by the `useNumberField` hook.\n */\n isNumber: boolean;\n\n /**\n * Boolean if this is triggered from a blur event instead of a change event.\n */\n isBlurEvent: boolean;\n\n /**\n * The validation type defined by the `useTextField` hook.\n */\n validationType: TextFieldValidationType;\n}\n\n/**\n * A function to get a custom error message for specific errors. This is really\n * useful when using the `pattern` attribute to give additional information or\n * changing the native \"language translated\" error message.\n *\n * @param options - An object containing metadata that can be used to create an\n * error message for your `TextField` or `TextArea`.\n * @returns An error message to display or an empty string.\n * @since 2.5.0\n */\nexport type GetErrorMessage = (options: ErrorMessageOptions) => string;\n\n/**\n * @internal\n * @since 2.5.0\n * @since 6.0.0 Added `\"valid\"` since it exists in the type definition\n */\nconst VALIDITY_STATE_KEYS: readonly (keyof ValidityState)[] = [\n \"badInput\",\n \"customError\",\n \"patternMismatch\",\n \"rangeOverflow\",\n \"rangeUnderflow\",\n \"stepMismatch\",\n \"tooLong\",\n \"tooShort\",\n \"typeMismatch\",\n \"valid\",\n \"valueMissing\",\n];\n\n/**\n * @internal\n * @since 2.5.0\n */\nexport const RECOMMENDED_STATE_KEYS: readonly (keyof ValidityState)[] = [\n \"badInput\",\n \"tooLong\",\n \"valueMissing\",\n];\n\n/**\n * @internal\n * @since 2.5.0\n */\nexport const RECOMMENDED_NUMBER_STATE_KEYS: readonly (keyof ValidityState)[] = [\n ...RECOMMENDED_STATE_KEYS,\n \"rangeOverflow\",\n \"rangeUnderflow\",\n \"tooShort\",\n \"typeMismatch\",\n];\n\n/**\n * The validation message is actually kind of weird since it's possible for a\n * form element to have multiple errors at once. The validation message will be\n * the first error that appears, so need to make sure that the first error is\n * one of the recommended state keys so the message appears for only those types\n * of errors.\n *\n * @internal\n * @since 2.5.0\n */\nconst isRecommended = (validity: ValidityState, isNumber: boolean): boolean => {\n const errorable = isNumber\n ? RECOMMENDED_NUMBER_STATE_KEYS\n : RECOMMENDED_STATE_KEYS;\n\n return VALIDITY_STATE_KEYS.every((key) => {\n const errored = validity[key];\n return !errored || errorable.includes(key);\n });\n};\n\n/**\n * The default implementation for getting an error message for the `TextField`\n * or `TextArea` components that relies on the behavior of the\n * {@link ChangeValidationBehavior}\n *\n * @since 2.5.0\n */\nexport const defaultGetErrorMessage: GetErrorMessage = (options) => {\n const {\n isNumber,\n isBlurEvent,\n validity,\n validationMessage,\n validationType: validate,\n } = options;\n\n if (isBlurEvent || !validationMessage || validate === \"change\") {\n return validationMessage;\n }\n\n if (validate === \"blur\") {\n return \"\";\n }\n\n if (validate === \"recommended\") {\n return isRecommended(validity, isNumber) ? validationMessage : \"\";\n }\n\n const keys = typeof validate === \"string\" ? [validate] : validate;\n\n return keys.length &&\n VALIDITY_STATE_KEYS.some((key) => validity[key] && keys.includes(key))\n ? validationMessage\n : \"\";\n};\n\n/**\n * @since 2.5.0\n */\nexport interface IsErroredOptions extends ErrorMessageOptions {\n /**\n * The current error message or an empty string.\n */\n errorMessage: string;\n}\n\n/**\n * A function that is used to determine if a `TextField` or `TextArea` is in an\n * errored state.\n *\n * @param options - All the current options that can be used to determine the\n * error state.\n * @returns True if the component is considered to be in an errored state.\n * @since 2.5.0\n */\nexport type IsErrored = (options: IsErroredOptions) => boolean;\n\n/**\n * The default implementation for checking if a `TextField` or `TextArea` is\n * errored by returning `true` if the `errorMessage` string is truthy or the\n * value is not within the `minLength` and `maxLength` constraints when they\n * exist.\n *\n * @since 2.5.0\n */\nexport const defaultIsErrored: IsErrored = (options) => {\n const { value, errorMessage, minLength, maxLength, isBlurEvent } = options;\n\n return (\n !!errorMessage ||\n (typeof maxLength === \"number\" && value.length > maxLength) ||\n (isBlurEvent && typeof minLength === \"number\" && value.length < minLength)\n );\n};\n\n/**\n * @since 6.0.0\n */\nexport interface GetErrorIconOptions {\n /**\n * This will be `true` if the `TextField` or `TextArea` is in an errored state.\n */\n error: boolean;\n\n /**\n * The current error icon that was provided.\n */\n errorIcon: ReactNode;\n\n /**\n * The current error message or an empty string.\n */\n errorMessage: string;\n}\n\n/**\n * A function that can be used to dynamically get an error icon based on the\n * current visible error.\n *\n * @param options - The {@link GetErrorIconOptions}\n * @returns An icon to render or falsey to render nothing.\n * @since 2.5.0\n * @since 6.0.0 Updated to accept a single object argument\n */\nexport type GetErrorIcon = (options: GetErrorIconOptions) => ReactNode;\n\n/**\n * The default implementation for showing an error icon in `TextField` and\n * `TextArea` components that will only display when the error flag is enabled.\n *\n * @since 2.5.0\n */\nexport const defaultGetErrorIcon: GetErrorIcon = (options) => {\n const { error, errorIcon } = options;\n\n return error && errorIcon;\n};\n"],"names":["VALIDITY_STATE_KEYS","RECOMMENDED_STATE_KEYS","RECOMMENDED_NUMBER_STATE_KEYS","isRecommended","validity","isNumber","errorable","every","key","errored","includes","defaultGetErrorMessage","options","isBlurEvent","validationMessage","validationType","validate","keys","length","some","defaultIsErrored","value","errorMessage","minLength","maxLength","defaultGetErrorIcon","error","errorI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AAM,GAAGM,aAChDX,eAAe,OAAOU,cAAc,YAAYF,MAAMH,MAAM,GAAGK;AAEpE,EAAE;AAiCF;;;;;CAKC,GACD,OAAO,MAAME,sBAAoC,CAACb;IAChD,MAAM,EAAEc,KAAK,EAAEC,SAAS,EAAE,GAAGf;IAE7B,OAAOc,SAASC;AAClB,EAAE"}
1
+ {"version":3,"sources":["../../src/form/validation.ts"],"sourcesContent":["import { type InputHTMLAttributes, type ReactNode } from \"react\";\n\n/**\n * @since 2.5.6\n * @since 6.0.0 Renamed from `TextConstraints` to\n * `TextFieldValidationOptions`\n */\nexport type TextFieldValidationOptions = Pick<\n InputHTMLAttributes<HTMLInputElement>,\n \"minLength\" | \"maxLength\" | \"required\" | \"pattern\"\n>;\n\n/**\n * Since the default validation messages can be verbose, this type is used to\n * configure when/how to display the native browser messages when the validation\n * state changes during the `change` event phase. The validation message will\n * always be shown on blur.\n *\n * When this is:\n *\n * - `true` -&gt; always show the browser message when it exists\n * - `false` -&gt; never show the browser message\n * - `\"recommended\"` -&gt; only shows the browser message if it is one of the\n * `RECOMMENDED_STATE_KEYS`/`RECOMMENDED_NUMBER_STATE_KEYS` validation errors\n * - `keyof ValidityState` -&gt; only shows the browser message if it is not the\n * specific validation error\n * - `(keyof ValidityState)[]` -&gt; only shows the browser message if it is not\n * the specific validation errors\n *\n * @see {@link RECOMMENDED_STATE_KEYS}\n * @see {@link RECOMMENDED_NUMBER_STATE_KEYS}\n * @since 2.5.6\n * @since 6.0.0 Renamed from `ChangeValidationBehavior` to\n * `TextFieldValidationType`\n */\nexport type TextFieldValidationType =\n | \"blur\"\n | \"change\"\n | \"recommended\"\n | keyof ValidityState\n | readonly (keyof ValidityState)[];\n\n/**\n * @since 2.5.0\n * @since 6.0.0 Renamed `validateOnChange` to `validationType`\n */\nexport interface ErrorMessageOptions extends TextFieldValidationOptions {\n /**\n * The current input or textarea's validity state.\n */\n validity: ValidityState;\n\n /**\n * The browser defined validation message based on the validity state. This\n * will be the empty string when there are no errors.\n */\n validationMessage: string;\n\n /**\n * The current `TextField` or `TextArea` value.\n */\n value: string;\n\n /**\n * This will only be `true` if called by the `useNumberField` hook.\n */\n isNumber: boolean;\n\n /**\n * Boolean if this is triggered from a blur event instead of a change event.\n */\n isBlurEvent: boolean;\n\n /**\n * The validation type defined by the `useTextField` hook.\n */\n validationType: TextFieldValidationType;\n}\n\n/**\n * A function to get a custom error message for specific errors. This is really\n * useful when using the `pattern` attribute to give additional information or\n * changing the native \"language translated\" error message.\n *\n * @param options - An object containing metadata that can be used to create an\n * error message for your `TextField` or `TextArea`.\n * @returns An error message to display or an empty string.\n * @since 2.5.0\n */\nexport type GetErrorMessage = (options: ErrorMessageOptions) => string;\n\n/**\n * @internal\n * @since 2.5.0\n * @since 6.0.0 Added `\"valid\"` since it exists in the type definition\n */\nconst VALIDITY_STATE_KEYS: readonly (keyof ValidityState)[] = [\n \"badInput\",\n \"customError\",\n \"patternMismatch\",\n \"rangeOverflow\",\n \"rangeUnderflow\",\n \"stepMismatch\",\n \"tooLong\",\n \"tooShort\",\n \"typeMismatch\",\n \"valid\",\n \"valueMissing\",\n];\n\n/**\n * @internal\n * @since 2.5.0\n */\nexport const RECOMMENDED_STATE_KEYS: readonly (keyof ValidityState)[] = [\n \"badInput\",\n \"tooLong\",\n \"valueMissing\",\n];\n\n/**\n * @internal\n * @since 2.5.0\n */\nexport const RECOMMENDED_NUMBER_STATE_KEYS: readonly (keyof ValidityState)[] = [\n ...RECOMMENDED_STATE_KEYS,\n \"rangeOverflow\",\n \"rangeUnderflow\",\n \"tooShort\",\n \"typeMismatch\",\n];\n\n/**\n * The validation message is actually kind of weird since it's possible for a\n * form element to have multiple errors at once. The validation message will be\n * the first error that appears, so need to make sure that the first error is\n * one of the recommended state keys so the message appears for only those types\n * of errors.\n *\n * @internal\n * @since 2.5.0\n */\nconst isRecommended = (validity: ValidityState, isNumber: boolean): boolean => {\n const errorable = isNumber\n ? RECOMMENDED_NUMBER_STATE_KEYS\n : RECOMMENDED_STATE_KEYS;\n\n return VALIDITY_STATE_KEYS.every((key) => {\n const errored = validity[key];\n return !errored || errorable.includes(key);\n });\n};\n\n/**\n * The default implementation for getting an error message for the `TextField`\n * or `TextArea` components that relies on the behavior of the\n * {@link ChangeValidationBehavior}\n *\n * @since 2.5.0\n */\nexport const defaultGetErrorMessage: GetErrorMessage = (options) => {\n const {\n isNumber,\n isBlurEvent,\n validity,\n validationMessage,\n validationType: validate,\n } = options;\n\n if (isBlurEvent || !validationMessage || validate === \"change\") {\n return validationMessage;\n }\n\n if (validate === \"blur\") {\n return \"\";\n }\n\n if (validate === \"recommended\") {\n return isRecommended(validity, isNumber) ? validationMessage : \"\";\n }\n\n const keys = typeof validate === \"string\" ? [validate] : validate;\n\n return keys.length > 0 &&\n VALIDITY_STATE_KEYS.some((key) => validity[key] && keys.includes(key))\n ? validationMessage\n : \"\";\n};\n\n/**\n * @since 2.5.0\n */\nexport interface IsErroredOptions extends ErrorMessageOptions {\n /**\n * The current error message or an empty string.\n */\n errorMessage: string;\n}\n\n/**\n * A function that is used to determine if a `TextField` or `TextArea` is in an\n * errored state.\n *\n * @param options - All the current options that can be used to determine the\n * error state.\n * @returns True if the component is considered to be in an errored state.\n * @since 2.5.0\n */\nexport type IsErrored = (options: IsErroredOptions) => boolean;\n\n/**\n * The default implementation for checking if a `TextField` or `TextArea` is\n * errored by returning `true` if the `errorMessage` string is truthy or the\n * value is not within the `minLength` and `maxLength` constraints when they\n * exist.\n *\n * @since 2.5.0\n */\nexport const defaultIsErrored: IsErrored = (options) => {\n const { value, errorMessage, minLength, maxLength, isBlurEvent } = options;\n\n return (\n !!errorMessage ||\n (typeof maxLength === \"number\" && value.length > maxLength) ||\n (isBlurEvent && typeof minLength === \"number\" && value.length < minLength)\n );\n};\n\n/**\n * @since 6.0.0\n */\nexport interface GetErrorIconOptions {\n /**\n * This will be `true` if the `TextField` or `TextArea` is in an errored state.\n */\n error: boolean;\n\n /**\n * The current error icon that was provided.\n */\n errorIcon: ReactNode;\n\n /**\n * The current error message or an empty string.\n */\n errorMessage: string;\n}\n\n/**\n * A function that can be used to dynamically get an error icon based on the\n * current visible error.\n *\n * @param options - The {@link GetErrorIconOptions}\n * @returns An icon to render or falsey to render nothing.\n * @since 2.5.0\n * @since 6.0.0 Updated to accept a single object argument\n */\nexport type GetErrorIcon = (options: GetErrorIconOptions) => ReactNode;\n\n/**\n * The default implementation for showing an error icon in `TextField` and\n * `TextArea` components that will only display when the error flag is enabled.\n *\n * @since 2.5.0\n */\nexport const defaultGetErrorIcon: GetErrorIcon = (options) => {\n const { error, errorIcon } = options;\n\n return error && errorIcon;\n};\n"],"names":["VALIDITY_STATE_KEYS","RECOMMENDED_STATE_KEYS","RECOMMENDED_NUMBER_STATE_KEYS","isRecommended","validity","isNumber","errorable","every","key","errored","includes","defaultGetErrorMessage","options","isBlurEvent","validationMessage","validationType","validate","keys","length","some","defaultIsErrored","value","errorMessage","minLength","maxLength","defaultGetErrorIcon","error","errorIcon"],"mappings":"AA2FA;;;;CAIC,GACD,MAAMA,sBAAwD;IAC5D;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED;;;CAGC,GACD,OAAO,MAAMC,yBAA2D;IACtE;IACA;IACA;CACD,CAAC;AAEF;;;CAGC,GACD,OAAO,MAAMC,gCAAkE;OAC1ED;IACH;IACA;IACA;IACA;CACD,CAAC;AAEF;;;;;;;;;CASC,GACD,MAAME,gBAAgB,CAACC,UAAyBC;IAC9C,MAAMC,YAAYD,WACdH,gCACAD;IAEJ,OAAOD,oBAAoBO,KAAK,CAAC,CAACC;QAChC,MAAMC,UAAUL,QAAQ,CAACI,IAAI;QAC7B,OAAO,CAACC,WAAWH,UAAUI,QAAQ,CAACF;IACxC;AACF;AAEA;;;;;;CAMC,GACD,OAAO,MAAMG,yBAA0C,CAACC;IACtD,MAAM,EACJP,QAAQ,EACRQ,WAAW,EACXT,QAAQ,EACRU,iBAAiB,EACjBC,gBAAgBC,QAAQ,EACzB,GAAGJ;IAEJ,IAAIC,eAAe,CAACC,qBAAqBE,aAAa,UAAU;QAC9D,OAAOF;IACT;IAEA,IAAIE,aAAa,QAAQ;QACvB,OAAO;IACT;IAEA,IAAIA,aAAa,eAAe;QAC9B,OAAOb,cAAcC,UAAUC,YAAYS,oBAAoB;IACjE;IAEA,MAAMG,OAAO,OAAOD,aAAa,WAAW;QAACA;KAAS,GAAGA;IAEzD,OAAOC,KAAKC,MAAM,GAAG,KACnBlB,oBAAoBmB,IAAI,CAAC,CAACX,MAAQJ,QAAQ,CAACI,IAAI,IAAIS,KAAKP,QAAQ,CAACF,QAC/DM,oBACA;AACN,EAAE;AAuBF;;;;;;;CAOC,GACD,OAAO,MAAMM,mBAA8B,CAACR;IAC1C,MAAM,EAAES,KAAK,EAAEC,YAAY,EAAEC,SAAS,EAAEC,SAAS,EAAEX,WAAW,EAAE,GAAGD;IAEnE,OACE,CAAC,CAACU,gBACD,OAAOE,cAAc,YAAYH,MAAMH,MAAM,GAAGM,aAChDX,eAAe,OAAOU,cAAc,YAAYF,MAAMH,MAAM,GAAGK;AAEpE,EAAE;AAiCF;;;;;CAKC,GACD,OAAO,MAAME,sBAAoC,CAACb;IAChD,MAAM,EAAEc,KAAK,EAAEC,SAAS,EAAE,GAAGf;IAE7B,OAAOc,SAASC;AAClB,EAAE"}
@@ -5,14 +5,14 @@ export function useHoverMode(options) {
5
5
  const state = useState(defaultVisible);
6
6
  let visible;
7
7
  let setVisible;
8
- if (typeof propSetVisible !== "undefined") {
8
+ if (propSetVisible !== undefined) {
9
9
  setVisible = propSetVisible;
10
10
  } else {
11
11
  [visible, setVisible] = state;
12
12
  }
13
13
  const visibilityTimeout = useRef();
14
14
  const clearVisibilityTimeout = useCallback(()=>{
15
- window.clearTimeout(visibilityTimeout.current);
15
+ globalThis.clearTimeout(visibilityTimeout.current);
16
16
  }, []);
17
17
  // if the element is near the viewport edge, the mouseleave event might not
18
18
  // trigger correctly. for these cases, just clear any timeouts to be safe.
@@ -23,7 +23,7 @@ export function useHoverMode(options) {
23
23
  return;
24
24
  }
25
25
  const handler = ()=>{
26
- window.clearTimeout(visibilityTimeout.current);
26
+ globalThis.clearTimeout(visibilityTimeout.current);
27
27
  // might need to play with this more or make it configurable. if the mouse
28
28
  // leaves the window, you're _normally_ not interacting with the app
29
29
  // anymore and state should reset.
@@ -39,7 +39,7 @@ export function useHoverMode(options) {
39
39
  ]);
40
40
  useEffect(()=>{
41
41
  return ()=>{
42
- window.clearTimeout(visibilityTimeout.current);
42
+ globalThis.clearTimeout(visibilityTimeout.current);
43
43
  };
44
44
  }, []);
45
45
  return {
@@ -47,18 +47,18 @@ export function useHoverMode(options) {
47
47
  setVisible: setVisible === propSetVisible ? undefined : setVisible,
48
48
  startShowFlow: useCallback((eventOrId)=>{
49
49
  const hoverTimeout = hoverTime ?? hoverTimeoutRef.current;
50
- if (disabled || typeof hoverTimeout === "undefined") {
50
+ if (disabled || hoverTimeout === undefined) {
51
51
  return;
52
52
  }
53
53
  let id;
54
- if (typeof eventOrId === "string" || typeof eventOrId === "undefined") {
54
+ if (typeof eventOrId === "string" || eventOrId === undefined) {
55
55
  id = eventOrId || "";
56
56
  } else {
57
57
  id = eventOrId.currentTarget.id;
58
58
  }
59
59
  clearDisableTimer();
60
60
  clearVisibilityTimeout();
61
- visibilityTimeout.current = window.setTimeout(()=>{
61
+ visibilityTimeout.current = globalThis.setTimeout(()=>{
62
62
  enableHoverMode(id);
63
63
  setVisible(true);
64
64
  }, hoverTimeout);
@@ -77,7 +77,7 @@ export function useHoverMode(options) {
77
77
  }
78
78
  startDisableTimer();
79
79
  clearVisibilityTimeout();
80
- visibilityTimeout.current = window.setTimeout(()=>{
80
+ visibilityTimeout.current = globalThis.setTimeout(()=>{
81
81
  setVisible(false);
82
82
  }, leaveTime ?? leaveTimeoutRef.current);
83
83
  }, [
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hoverMode/useHoverMode.ts"],"sourcesContent":["\"use client\";\n\nimport {\n type MouseEvent,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\n\nimport { type UseStateInitializer, type UseStateSetter } from \"../types.js\";\nimport {\n type SimpleHoverModeContext,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n type useHoverModeProvider,\n} from \"./useHoverModeProvider.js\";\n\n/**\n * @since 6.0.0\n */\nexport interface HoverModeConfigurationOptions extends SimpleHoverModeContext {\n /** @defaultValue `false` */\n disabled?: boolean;\n\n /**\n * This can be used to override the `HoverModeContext`'s hover time.\n */\n hoverTimeout?: number;\n\n /**\n * This can be used to override the `HoverModeContext`'s leave time.\n */\n leaveTimeout?: number;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ControlledHoverModeOptions extends HoverModeConfigurationOptions {\n setVisible: UseStateSetter<boolean>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ControlledHoverModeImplementation {\n startShowFlow: (id?: string | MouseEvent) => void;\n startHideFlow: () => void;\n clearVisibilityTimeout: () => void;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface UncontrolledHoverModeOptions extends HoverModeConfigurationOptions {\n defaultVisible?: UseStateInitializer<boolean>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface UncontrolledHoverModeImplementation extends ControlledHoverModeImplementation {\n visible: boolean;\n setVisible: UseStateSetter<boolean>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface HoverModeImplementation extends ControlledHoverModeImplementation {\n visible?: boolean;\n setVisible?: UseStateSetter<boolean>;\n}\n\n/**\n * The `useHoverMode` hook is used to implement an immediate hover state after\n * hovering related elements for a short duration. The main use-case is for\n * showing tooltips immediately after hovering another tooltipped element.\n *\n * This relies on creating a context provider using {@link useHoverModeProvider}\n * to link related elements together.\n *\n * @example Example Usage\n * ```ts\n * import { type MouseEvent } from \"react\";\n *\n * import {\n * type CustomHoverContext,\n * useCustomHoverContext,\n * } from \"./useCustomHoverContext.jsx\";\n *\n * interface CustomHoverModeImplementation {\n * onMouseEnter: <E extends HTMLElement>(event: MouseEvent<E>) => void;\n * onMouseLeave: <E extends HTMLElement>(event: MouseEvent<E>) => void;\n * }\n *\n * function useCustomHoverMode(): CustomHoverModeImplementation {\n * const {\n * animatedOnceRef,\n * hoverTimeoutRef,\n * leaveTimeoutRef,\n * enableHoverMode,\n * disableHoverMode,\n * startDisableTimer,\n * clearDisableTimer,\n * } = useCustomHoverContext();\n * const {\n * visible,\n * setVisible,\n * startShowFlow,\n * startHideFlow,\n * clearVisibilityTimeout,\n * } = useHoverMode({\n * hoverTimeout,\n * hoverTimeoutRef,\n * leaveTimeout,\n * leaveTimeoutRef,\n * enableHoverMode,\n * disableHoverMode,\n * startDisableTimer,\n * clearDisableTimer,\n * });\n *\n * return {\n * onMouseEnter(event) {\n * startShowFlow(event.currentTarget.id);\n * },\n * onMouseLeave(event) {\n * startHideFlow();\n * },\n * };\n * }\n * ```\n *\n * @see The `useTooltip` source code for a real world example.\n *\n * @since 2.8.0\n * @since 5.0.0 This hook no longer returns `handlers` or\n * `stickyHandlers` and does not hide when an element on the page is clicked.\n * @since 6.0.0 Requires passing the custom hover mode context to\n * work.\n */\nexport function useHoverMode(\n options: ControlledHoverModeOptions\n): ControlledHoverModeImplementation;\nexport function useHoverMode(\n options: UncontrolledHoverModeOptions\n): UncontrolledHoverModeImplementation;\nexport function useHoverMode(\n options: ControlledHoverModeOptions | UncontrolledHoverModeOptions\n): HoverModeImplementation {\n const {\n disabled,\n hoverTimeout: hoverTime,\n hoverTimeoutRef,\n leaveTimeout: leaveTime,\n leaveTimeoutRef,\n enableHoverMode,\n disableHoverMode,\n startDisableTimer,\n clearDisableTimer,\n setVisible: propSetVisible,\n defaultVisible = false,\n } = options as ControlledHoverModeOptions & UncontrolledHoverModeOptions;\n\n const state = useState(defaultVisible);\n let visible: boolean | undefined;\n let setVisible: UseStateSetter<boolean>;\n if (typeof propSetVisible !== \"undefined\") {\n setVisible = propSetVisible;\n } else {\n [visible, setVisible] = state;\n }\n\n const visibilityTimeout = useRef<number | undefined>();\n const clearVisibilityTimeout = useCallback(() => {\n window.clearTimeout(visibilityTimeout.current);\n }, []);\n\n // if the element is near the viewport edge, the mouseleave event might not\n // trigger correctly. for these cases, just clear any timeouts to be safe.\n // do not hide the visibility so that you can still inspect things in the\n // devtools\n useEffect(() => {\n if (disabled) {\n return;\n }\n\n const handler = (): void => {\n window.clearTimeout(visibilityTimeout.current);\n\n // might need to play with this more or make it configurable. if the mouse\n // leaves the window, you're _normally_ not interacting with the app\n // anymore and state should reset.\n disableHoverMode();\n };\n\n document.addEventListener(\"mouseleave\", handler);\n return () => {\n document.removeEventListener(\"mouseleave\", handler);\n };\n }, [disableHoverMode, disabled]);\n\n useEffect(() => {\n return () => {\n window.clearTimeout(visibilityTimeout.current);\n };\n }, []);\n\n return {\n visible,\n setVisible: setVisible === propSetVisible ? undefined : setVisible,\n startShowFlow: useCallback(\n (eventOrId) => {\n const hoverTimeout = hoverTime ?? hoverTimeoutRef.current;\n if (disabled || typeof hoverTimeout === \"undefined\") {\n return;\n }\n\n let id: string;\n if (typeof eventOrId === \"string\" || typeof eventOrId === \"undefined\") {\n id = eventOrId || \"\";\n } else {\n id = eventOrId.currentTarget.id;\n }\n\n clearDisableTimer();\n clearVisibilityTimeout();\n visibilityTimeout.current = window.setTimeout(() => {\n enableHoverMode(id);\n setVisible(true);\n }, hoverTimeout);\n },\n [\n clearDisableTimer,\n clearVisibilityTimeout,\n disabled,\n enableHoverMode,\n hoverTime,\n hoverTimeoutRef,\n setVisible,\n ]\n ),\n startHideFlow: useCallback(() => {\n if (disabled) {\n return;\n }\n\n startDisableTimer();\n clearVisibilityTimeout();\n visibilityTimeout.current = window.setTimeout(() => {\n setVisible(false);\n }, leaveTime ?? leaveTimeoutRef.current);\n }, [\n clearVisibilityTimeout,\n disabled,\n leaveTime,\n leaveTimeoutRef,\n setVisible,\n startDisableTimer,\n ]),\n clearVisibilityTimeout,\n };\n}\n"],"names":["useCallback","useEffect","useRef","useState","useHoverMode","options","disabled","hoverTimeout","hoverTime","hoverTimeoutRef","leaveTimeout","leaveTime","leaveTimeoutRef","enableHoverMode","disableHoverMode","startDisableTimer","clearDisableTimer","setVisible","propSetVisible","defaultVisible","state","visible","visibilityTimeout","clearVisibilityTimeout","window","clearTimeout","current","handler","document","addEventListener","removeEventListener","undefined","startShowFlow","eventOrId","id","currentTarget","setTimeout","startHideFlow"],"mappings":"AAAA;AAEA,SAEEA,WAAW,EACXC,SAAS,EACTC,MAAM,EACNC,QAAQ,QACH,QAAQ;AA4If,OAAO,SAASC,aACdC,OAAkE;IAElE,MAAM,EACJC,QAAQ,EACRC,cAAcC,SAAS,EACvBC,eAAe,EACfC,cAAcC,SAAS,EACvBC,eAAe,EACfC,eAAe,EACfC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,EACjBC,YAAYC,cAAc,EAC1BC,iBAAiB,KAAK,EACvB,GAAGd;IAEJ,MAAMe,QAAQjB,SAASgB;IACvB,IAAIE;IACJ,IAAIJ;IACJ,IAAI,OAAOC,mBAAmB,aAAa;QACzCD,aAAaC;IACf,OAAO;QACL,CAACG,SAASJ,WAAW,GAAGG;IAC1B;IAEA,MAAME,oBAAoBpB;IAC1B,MAAMqB,yBAAyBvB,YAAY;QACzCwB,OAAOC,YAAY,CAACH,kBAAkBI,OAAO;IAC/C,GAAG,EAAE;IAEL,2EAA2E;IAC3E,0EAA0E;IAC1E,yEAAyE;IACzE,WAAW;IACXzB,UAAU;QACR,IAAIK,UAAU;YACZ;QACF;QAEA,MAAMqB,UAAU;YACdH,OAAOC,YAAY,CAACH,kBAAkBI,OAAO;YAE7C,0EAA0E;YAC1E,oEAAoE;YACpE,kCAAkC;YAClCZ;QACF;QAEAc,SAASC,gBAAgB,CAAC,cAAcF;QACxC,OAAO;YACLC,SAASE,mBAAmB,CAAC,cAAcH;QAC7C;IACF,GAAG;QAACb;QAAkBR;KAAS;IAE/BL,UAAU;QACR,OAAO;YACLuB,OAAOC,YAAY,CAACH,kBAAkBI,OAAO;QAC/C;IACF,GAAG,EAAE;IAEL,OAAO;QACLL;QACAJ,YAAYA,eAAeC,iBAAiBa,YAAYd;QACxDe,eAAehC,YACb,CAACiC;YACC,MAAM1B,eAAeC,aAAaC,gBAAgBiB,OAAO;YACzD,IAAIpB,YAAY,OAAOC,iBAAiB,aAAa;gBACnD;YACF;YAEA,IAAI2B;YACJ,IAAI,OAAOD,cAAc,YAAY,OAAOA,cAAc,aAAa;gBACrEC,KAAKD,aAAa;YACpB,OAAO;gBACLC,KAAKD,UAAUE,aAAa,CAACD,EAAE;YACjC;YAEAlB;YACAO;YACAD,kBAAkBI,OAAO,GAAGF,OAAOY,UAAU,CAAC;gBAC5CvB,gBAAgBqB;gBAChBjB,WAAW;YACb,GAAGV;QACL,GACA;YACES;YACAO;YACAjB;YACAO;YACAL;YACAC;YACAQ;SACD;QAEHoB,eAAerC,YAAY;YACzB,IAAIM,UAAU;gBACZ;YACF;YAEAS;YACAQ;YACAD,kBAAkBI,OAAO,GAAGF,OAAOY,UAAU,CAAC;gBAC5CnB,WAAW;YACb,GAAGN,aAAaC,gBAAgBc,OAAO;QACzC,GAAG;YACDH;YACAjB;YACAK;YACAC;YACAK;YACAF;SACD;QACDQ;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/hoverMode/useHoverMode.ts"],"sourcesContent":["\"use client\";\n\nimport {\n type MouseEvent,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\n\nimport { type UseStateInitializer, type UseStateSetter } from \"../types.js\";\nimport {\n type SimpleHoverModeContext,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n type useHoverModeProvider,\n} from \"./useHoverModeProvider.js\";\n\n/**\n * @since 6.0.0\n */\nexport interface HoverModeConfigurationOptions extends SimpleHoverModeContext {\n /** @defaultValue `false` */\n disabled?: boolean;\n\n /**\n * This can be used to override the `HoverModeContext`'s hover time.\n */\n hoverTimeout?: number;\n\n /**\n * This can be used to override the `HoverModeContext`'s leave time.\n */\n leaveTimeout?: number;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ControlledHoverModeOptions extends HoverModeConfigurationOptions {\n setVisible: UseStateSetter<boolean>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface ControlledHoverModeImplementation {\n startShowFlow: (id?: string | MouseEvent) => void;\n startHideFlow: () => void;\n clearVisibilityTimeout: () => void;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface UncontrolledHoverModeOptions extends HoverModeConfigurationOptions {\n defaultVisible?: UseStateInitializer<boolean>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface UncontrolledHoverModeImplementation extends ControlledHoverModeImplementation {\n visible: boolean;\n setVisible: UseStateSetter<boolean>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface HoverModeImplementation extends ControlledHoverModeImplementation {\n visible?: boolean;\n setVisible?: UseStateSetter<boolean>;\n}\n\n/**\n * The `useHoverMode` hook is used to implement an immediate hover state after\n * hovering related elements for a short duration. The main use-case is for\n * showing tooltips immediately after hovering another tooltipped element.\n *\n * This relies on creating a context provider using {@link useHoverModeProvider}\n * to link related elements together.\n *\n * @example Example Usage\n * ```ts\n * import { type MouseEvent } from \"react\";\n *\n * import {\n * type CustomHoverContext,\n * useCustomHoverContext,\n * } from \"./useCustomHoverContext.jsx\";\n *\n * interface CustomHoverModeImplementation {\n * onMouseEnter: <E extends HTMLElement>(event: MouseEvent<E>) => void;\n * onMouseLeave: <E extends HTMLElement>(event: MouseEvent<E>) => void;\n * }\n *\n * function useCustomHoverMode(): CustomHoverModeImplementation {\n * const {\n * animatedOnceRef,\n * hoverTimeoutRef,\n * leaveTimeoutRef,\n * enableHoverMode,\n * disableHoverMode,\n * startDisableTimer,\n * clearDisableTimer,\n * } = useCustomHoverContext();\n * const {\n * visible,\n * setVisible,\n * startShowFlow,\n * startHideFlow,\n * clearVisibilityTimeout,\n * } = useHoverMode({\n * hoverTimeout,\n * hoverTimeoutRef,\n * leaveTimeout,\n * leaveTimeoutRef,\n * enableHoverMode,\n * disableHoverMode,\n * startDisableTimer,\n * clearDisableTimer,\n * });\n *\n * return {\n * onMouseEnter(event) {\n * startShowFlow(event.currentTarget.id);\n * },\n * onMouseLeave(event) {\n * startHideFlow();\n * },\n * };\n * }\n * ```\n *\n * @see The `useTooltip` source code for a real world example.\n *\n * @since 2.8.0\n * @since 5.0.0 This hook no longer returns `handlers` or\n * `stickyHandlers` and does not hide when an element on the page is clicked.\n * @since 6.0.0 Requires passing the custom hover mode context to\n * work.\n */\nexport function useHoverMode(\n options: ControlledHoverModeOptions\n): ControlledHoverModeImplementation;\nexport function useHoverMode(\n options: UncontrolledHoverModeOptions\n): UncontrolledHoverModeImplementation;\nexport function useHoverMode(\n options: ControlledHoverModeOptions | UncontrolledHoverModeOptions\n): HoverModeImplementation {\n const {\n disabled,\n hoverTimeout: hoverTime,\n hoverTimeoutRef,\n leaveTimeout: leaveTime,\n leaveTimeoutRef,\n enableHoverMode,\n disableHoverMode,\n startDisableTimer,\n clearDisableTimer,\n setVisible: propSetVisible,\n defaultVisible = false,\n } = options as ControlledHoverModeOptions & UncontrolledHoverModeOptions;\n\n const state = useState(defaultVisible);\n let visible: boolean | undefined;\n let setVisible: UseStateSetter<boolean>;\n if (propSetVisible !== undefined) {\n setVisible = propSetVisible;\n } else {\n [visible, setVisible] = state;\n }\n\n const visibilityTimeout = useRef<NodeJS.Timeout>();\n const clearVisibilityTimeout = useCallback(() => {\n globalThis.clearTimeout(visibilityTimeout.current);\n }, []);\n\n // if the element is near the viewport edge, the mouseleave event might not\n // trigger correctly. for these cases, just clear any timeouts to be safe.\n // do not hide the visibility so that you can still inspect things in the\n // devtools\n useEffect(() => {\n if (disabled) {\n return;\n }\n\n const handler = (): void => {\n globalThis.clearTimeout(visibilityTimeout.current);\n\n // might need to play with this more or make it configurable. if the mouse\n // leaves the window, you're _normally_ not interacting with the app\n // anymore and state should reset.\n disableHoverMode();\n };\n\n document.addEventListener(\"mouseleave\", handler);\n return () => {\n document.removeEventListener(\"mouseleave\", handler);\n };\n }, [disableHoverMode, disabled]);\n\n useEffect(() => {\n return () => {\n globalThis.clearTimeout(visibilityTimeout.current);\n };\n }, []);\n\n return {\n visible,\n setVisible: setVisible === propSetVisible ? undefined : setVisible,\n startShowFlow: useCallback(\n (eventOrId) => {\n const hoverTimeout = hoverTime ?? hoverTimeoutRef.current;\n if (disabled || hoverTimeout === undefined) {\n return;\n }\n\n let id: string;\n if (typeof eventOrId === \"string\" || eventOrId === undefined) {\n id = eventOrId || \"\";\n } else {\n id = eventOrId.currentTarget.id;\n }\n\n clearDisableTimer();\n clearVisibilityTimeout();\n visibilityTimeout.current = globalThis.setTimeout(() => {\n enableHoverMode(id);\n setVisible(true);\n }, hoverTimeout);\n },\n [\n clearDisableTimer,\n clearVisibilityTimeout,\n disabled,\n enableHoverMode,\n hoverTime,\n hoverTimeoutRef,\n setVisible,\n ]\n ),\n startHideFlow: useCallback(() => {\n if (disabled) {\n return;\n }\n\n startDisableTimer();\n clearVisibilityTimeout();\n visibilityTimeout.current = globalThis.setTimeout(() => {\n setVisible(false);\n }, leaveTime ?? leaveTimeoutRef.current);\n }, [\n clearVisibilityTimeout,\n disabled,\n leaveTime,\n leaveTimeoutRef,\n setVisible,\n startDisableTimer,\n ]),\n clearVisibilityTimeout,\n };\n}\n"],"names":["useCallback","useEffect","useRef","useState","useHoverMode","options","disabled","hoverTimeout","hoverTime","hoverTimeoutRef","leaveTimeout","leaveTime","leaveTimeoutRef","enableHoverMode","disableHoverMode","startDisableTimer","clearDisableTimer","setVisible","propSetVisible","defaultVisible","state","visible","undefined","visibilityTimeout","clearVisibilityTimeout","globalThis","clearTimeout","current","handler","document","addEventListener","removeEventListener","startShowFlow","eventOrId","id","currentTarget","setTimeout","startHideFlow"],"mappings":"AAAA;AAEA,SAEEA,WAAW,EACXC,SAAS,EACTC,MAAM,EACNC,QAAQ,QACH,QAAQ;AA4If,OAAO,SAASC,aACdC,OAAkE;IAElE,MAAM,EACJC,QAAQ,EACRC,cAAcC,SAAS,EACvBC,eAA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DvB,gBAAgBqB;gBAChBjB,WAAW;YACb,GAAGV;QACL,GACA;YACES;YACAQ;YACAlB;YACAO;YACAL;YACAC;YACAQ;SACD;QAEHoB,eAAerC,YAAY;YACzB,IAAIM,UAAU;gBACZ;YACF;YAEAS;YACAS;YACAD,kBAAkBI,OAAO,GAAGF,WAAWW,UAAU,CAAC;gBAChDnB,WAAW;YACb,GAAGN,aAAaC,gBAAgBe,OAAO;QACzC,GAAG;YACDH;YACAlB;YACAK;YACAC;YACAK;YACAF;SACD;QACDS;IACF;AACF"}
@@ -96,7 +96,7 @@ const noop = ()=>{
96
96
  const animatedOnceRef = useRef(!!defaultActiveId);
97
97
  const disableHoverModeTimeout = useRef();
98
98
  const clearDisableTimer = useCallback(()=>{
99
- window.clearTimeout(disableHoverModeTimeout.current);
99
+ globalThis.clearTimeout(disableHoverModeTimeout.current);
100
100
  }, []);
101
101
  const enableHoverMode = useCallback((activeId)=>{
102
102
  clearDisableTimer();
@@ -127,7 +127,7 @@ const noop = ()=>{
127
127
  return;
128
128
  }
129
129
  clearDisableTimer();
130
- disableHoverModeTimeout.current = window.setTimeout(()=>{
130
+ disableHoverModeTimeout.current = globalThis.setTimeout(()=>{
131
131
  disableHoverMode();
132
132
  }, disableTimeout);
133
133
  }, [
@@ -138,7 +138,7 @@ const noop = ()=>{
138
138
  useEffect(()=>{
139
139
  hoverTimeoutRef.current = hoverTimeout;
140
140
  return ()=>{
141
- window.clearTimeout(disableHoverModeTimeout.current);
141
+ globalThis.clearTimeout(disableHoverModeTimeout.current);
142
142
  };
143
143
  }, [
144
144
  hoverTimeout