@react-md/core 6.3.4 → 6.4.0

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 (450) hide show
  1. package/dist/CoreProviders.d.ts +1 -0
  2. package/dist/CoreProviders.js.map +1 -1
  3. package/dist/_base.scss +3 -0
  4. package/dist/_core.scss +1 -0
  5. package/dist/_utils.scss +15 -7
  6. package/dist/app-bar/AppBar.js.map +1 -1
  7. package/dist/app-bar/AppBarTitle.js.map +1 -1
  8. package/dist/autocomplete/AutocompleteListboxChildren.js.map +1 -1
  9. package/dist/autocomplete/types.js.map +1 -1
  10. package/dist/autocomplete/utils.js.map +1 -1
  11. package/dist/avatar/Avatar.js.map +1 -1
  12. package/dist/button/Button.js.map +1 -1
  13. package/dist/button/FloatingActionButton.js.map +1 -1
  14. package/dist/card/Card.js.map +1 -1
  15. package/dist/card/CardContent.js.map +1 -1
  16. package/dist/card/ClickableCard.js.map +1 -1
  17. package/dist/chip/Chip.js.map +1 -1
  18. package/dist/datetime/NativeDateField.js.map +1 -1
  19. package/dist/datetime/NativeTimeField.js.map +1 -1
  20. package/dist/datetime/useDateField.js.map +1 -1
  21. package/dist/datetime/useTimeField.js.map +1 -1
  22. package/dist/dialog/Dialog.js.map +1 -1
  23. package/dist/dialog/DialogContainer.js.map +1 -1
  24. package/dist/dialog/DialogContent.js.map +1 -1
  25. package/dist/dialog/DialogFooter.js.map +1 -1
  26. package/dist/divider/Divider.js.map +1 -1
  27. package/dist/draggable/useDraggable.js.map +1 -1
  28. package/dist/draggable/utils.js.map +1 -1
  29. package/dist/expansion-panel/ExpansionPanelHeader.js.map +1 -1
  30. package/dist/files/FileInput.js.map +1 -1
  31. package/dist/files/useFileUpload.js.map +1 -1
  32. package/dist/files/validation.js.map +1 -1
  33. package/dist/focus/useFocusContainer.js.map +1 -1
  34. package/dist/form/Fieldset.d.ts +19 -0
  35. package/dist/form/Fieldset.js +22 -2
  36. package/dist/form/Fieldset.js.map +1 -1
  37. package/dist/form/FormMessageContainer.js.map +1 -1
  38. package/dist/form/FormMessageCounter.js.map +1 -1
  39. package/dist/form/InputToggle.js.map +1 -1
  40. package/dist/form/Legend.d.ts +27 -5
  41. package/dist/form/Legend.js +39 -6
  42. package/dist/form/Legend.js.map +1 -1
  43. package/dist/form/Listbox.js.map +1 -1
  44. package/dist/form/ListboxProvider.js.map +1 -1
  45. package/dist/form/NativeSelect.js.map +1 -1
  46. package/dist/form/Password.js.map +1 -1
  47. package/dist/form/ResizingTextAreaWrapper.js.map +1 -1
  48. package/dist/form/Select.js.map +1 -1
  49. package/dist/form/Slider.js.map +1 -1
  50. package/dist/form/SliderContainer.js.map +1 -1
  51. package/dist/form/SliderThumb.js.map +1 -1
  52. package/dist/form/SliderTrack.js.map +1 -1
  53. package/dist/form/SliderValueMarks.js.map +1 -1
  54. package/dist/form/Switch.js.map +1 -1
  55. package/dist/form/TextArea.js.map +1 -1
  56. package/dist/form/TextField.js.map +1 -1
  57. package/dist/form/TextFieldContainer.js.map +1 -1
  58. package/dist/form/_fieldset.scss +7 -0
  59. package/dist/form/_legend.scss +68 -0
  60. package/dist/form/_text-field.scss +39 -4
  61. package/dist/form/fieldsetStyles.d.ts +6 -1
  62. package/dist/form/fieldsetStyles.js +3 -2
  63. package/dist/form/fieldsetStyles.js.map +1 -1
  64. package/dist/form/inputToggleStyles.js.map +1 -1
  65. package/dist/form/labelStyles.d.ts +1 -1
  66. package/dist/form/labelStyles.js +1 -1
  67. package/dist/form/labelStyles.js.map +1 -1
  68. package/dist/form/legendStyles.d.ts +83 -0
  69. package/dist/form/legendStyles.js +25 -0
  70. package/dist/form/legendStyles.js.map +1 -0
  71. package/dist/form/selectUtils.js.map +1 -1
  72. package/dist/form/textFieldContainerStyles.js.map +1 -1
  73. package/dist/form/types.d.ts +28 -6
  74. package/dist/form/types.js.map +1 -1
  75. package/dist/form/useCheckboxGroup.js.map +1 -1
  76. package/dist/form/useCombobox.js.map +1 -1
  77. package/dist/form/useNumberField.js +16 -19
  78. package/dist/form/useNumberField.js.map +1 -1
  79. package/dist/form/useRangeSlider.js.map +1 -1
  80. package/dist/form/useSlider.js.map +1 -1
  81. package/dist/form/useTextField.js.map +1 -1
  82. package/dist/hoverMode/useHoverMode.js.map +1 -1
  83. package/dist/icon/FontIcon.js.map +1 -1
  84. package/dist/icon/IconRotator.js.map +1 -1
  85. package/dist/icon/MaterialIcon.js.map +1 -1
  86. package/dist/icon/MaterialSymbol.js.map +1 -1
  87. package/dist/icon/SVGIcon.js.map +1 -1
  88. package/dist/icon/config.d.ts +0 -1
  89. package/dist/icon/config.js +10 -7
  90. package/dist/icon/config.js.map +1 -1
  91. package/dist/icon/materialConfig.js.map +1 -1
  92. package/dist/icon/styles.js.map +1 -1
  93. package/dist/interaction/UserInteractionModeProvider.js +6 -4
  94. package/dist/interaction/UserInteractionModeProvider.js.map +1 -1
  95. package/dist/interaction/types.js.map +1 -1
  96. package/dist/interaction/useElementInteraction.js.map +1 -1
  97. package/dist/layout/LayoutAppBar.d.ts +6 -6
  98. package/dist/layout/LayoutAppBar.js +6 -6
  99. package/dist/layout/LayoutAppBar.js.map +1 -1
  100. package/dist/layout/LayoutNav.js.map +1 -1
  101. package/dist/layout/LayoutWindowSplitter.js.map +1 -1
  102. package/dist/layout/Main.js.map +1 -1
  103. package/dist/layout/useExpandableLayout.js +43 -0
  104. package/dist/layout/useExpandableLayout.js.map +1 -1
  105. package/dist/layout/useHorizontalLayoutTransition.js.map +1 -1
  106. package/dist/layout/useLayoutTree.js.map +1 -1
  107. package/dist/layout/useLayoutWindowSplitter.js.map +1 -1
  108. package/dist/layout/useResizableLayout.js.map +1 -1
  109. package/dist/link/Link.js.map +1 -1
  110. package/dist/link/SkipToMainContent.js +19 -21
  111. package/dist/link/SkipToMainContent.js.map +1 -1
  112. package/dist/list/List.js.map +1 -1
  113. package/dist/list/ListItem.js.map +1 -1
  114. package/dist/list/ListItemAddon.js.map +1 -1
  115. package/dist/list/ListItemLink.js.map +1 -1
  116. package/dist/list/ListSubheader.js.map +1 -1
  117. package/dist/list/getListItemHeight.js.map +1 -1
  118. package/dist/list/listItemStyles.js.map +1 -1
  119. package/dist/list/types.js.map +1 -1
  120. package/dist/media-queries/AppSizeProvider.d.ts +2 -0
  121. package/dist/media-queries/AppSizeProvider.js +3 -2
  122. package/dist/media-queries/AppSizeProvider.js.map +1 -1
  123. package/dist/media-queries/appSize.d.ts +3 -0
  124. package/dist/media-queries/appSize.js +3 -1
  125. package/dist/media-queries/appSize.js.map +1 -1
  126. package/dist/media-queries/config.d.ts +11 -0
  127. package/dist/media-queries/config.js +26 -0
  128. package/dist/media-queries/config.js.map +1 -0
  129. package/dist/menu/DropdownMenu.js.map +1 -1
  130. package/dist/menu/Menu.js.map +1 -1
  131. package/dist/menu/MenuItemButton.js.map +1 -1
  132. package/dist/menu/MenuItemFileInput.js.map +1 -1
  133. package/dist/menu/MenuItemInputToggle.js.map +1 -1
  134. package/dist/menu/MenuItemSeparator.js.map +1 -1
  135. package/dist/menu/MenuVisibilityProvider.js.map +1 -1
  136. package/dist/menu/MenuWidget.js.map +1 -1
  137. package/dist/menu/useContextMenu.js.map +1 -1
  138. package/dist/movement/types.d.ts +28 -3
  139. package/dist/movement/types.js.map +1 -1
  140. package/dist/movement/useKeyboardMovementProvider.js +96 -47
  141. package/dist/movement/useKeyboardMovementProvider.js.map +1 -1
  142. package/dist/navigation/CollapsibleNavGroup.js.map +1 -1
  143. package/dist/navigation/NavItem.js.map +1 -1
  144. package/dist/navigation/NavItemButton.js.map +1 -1
  145. package/dist/navigation/NavItemLink.js.map +1 -1
  146. package/dist/navigation/getTableOfContentsHeadings.js.map +1 -1
  147. package/dist/navigation/types.js.map +1 -1
  148. package/dist/overlay/Overlay.js.map +1 -1
  149. package/dist/positioning/createHorizontalPosition.js.map +1 -1
  150. package/dist/positioning/createVerticalPosition.js.map +1 -1
  151. package/dist/positioning/useFixedPositioning.js.map +1 -1
  152. package/dist/progress/CircularProgress.js.map +1 -1
  153. package/dist/progress/LinearProgress.js.map +1 -1
  154. package/dist/progress/linearProgressStyles.js.map +1 -1
  155. package/dist/responsive-item/ResponsiveItem.js.map +1 -1
  156. package/dist/responsive-item/ResponsiveItemOverlay.js.map +1 -1
  157. package/dist/searching/caseInsensitive.js.map +1 -1
  158. package/dist/segmented-button/SegmentedButton.js.map +1 -1
  159. package/dist/segmented-button/SegmentedButtonContainer.js.map +1 -1
  160. package/dist/segmented-button/segmentedButtonStyles.js.map +1 -1
  161. package/dist/sheet/Sheet.js.map +1 -1
  162. package/dist/snackbar/Toast.js.map +1 -1
  163. package/dist/spinbutton/SpinButton.d.ts +16 -0
  164. package/dist/spinbutton/SpinButton.js +55 -0
  165. package/dist/spinbutton/SpinButton.js.map +1 -0
  166. package/dist/spinbutton/SpinButtonGroupProvider.d.ts +17 -0
  167. package/dist/spinbutton/SpinButtonGroupProvider.js +19 -0
  168. package/dist/spinbutton/SpinButtonGroupProvider.js.map +1 -0
  169. package/dist/spinbutton/defaults.d.ts +9 -0
  170. package/dist/spinbutton/defaults.js +25 -0
  171. package/dist/spinbutton/defaults.js.map +1 -0
  172. package/dist/spinbutton/types.d.ts +324 -0
  173. package/dist/spinbutton/types.js +5 -0
  174. package/dist/spinbutton/types.js.map +1 -0
  175. package/dist/spinbutton/useSpinButton.d.ts +5 -0
  176. package/dist/spinbutton/useSpinButton.js +260 -0
  177. package/dist/spinbutton/useSpinButton.js.map +1 -0
  178. package/dist/spinbutton/useSpinButtonGroupProvider.d.ts +27 -0
  179. package/dist/spinbutton/useSpinButtonGroupProvider.js +49 -0
  180. package/dist/spinbutton/useSpinButtonGroupProvider.js.map +1 -0
  181. package/dist/spinbutton/utils/deselectNode.d.ts +5 -0
  182. package/dist/spinbutton/utils/deselectNode.js +17 -0
  183. package/dist/spinbutton/utils/deselectNode.js.map +1 -0
  184. package/dist/spinbutton/utils/resolveInputEvent.d.ts +30 -0
  185. package/dist/spinbutton/utils/resolveInputEvent.js +53 -0
  186. package/dist/spinbutton/utils/resolveInputEvent.js.map +1 -0
  187. package/dist/spinbutton/utils/selectNode.d.ts +5 -0
  188. package/dist/spinbutton/utils/selectNode.js +15 -0
  189. package/dist/spinbutton/utils/selectNode.js.map +1 -0
  190. package/dist/table/StickyTableSection.js.map +1 -1
  191. package/dist/table/Table.js.map +1 -1
  192. package/dist/table/TableBody.js.map +1 -1
  193. package/dist/table/TableCellContent.js.map +1 -1
  194. package/dist/table/TableCheckbox.js.map +1 -1
  195. package/dist/table/TableFooter.js.map +1 -1
  196. package/dist/table/TableHeader.js.map +1 -1
  197. package/dist/table/TableRadio.js.map +1 -1
  198. package/dist/table/TableRow.js.map +1 -1
  199. package/dist/table/useStickyTableSection.js.map +1 -1
  200. package/dist/tabs/SimpleTabPanel.js.map +1 -1
  201. package/dist/tabs/SimpleTabPanels.js.map +1 -1
  202. package/dist/tabs/Tab.js.map +1 -1
  203. package/dist/tabs/TabList.js.map +1 -1
  204. package/dist/tabs/TabListScrollButton.js.map +1 -1
  205. package/dist/tabs/useMaxTabPanelHeight.js.map +1 -1
  206. package/dist/test-utils/data-testid.js.map +1 -1
  207. package/dist/test-utils/mocks/match-media.js +5 -5
  208. package/dist/test-utils/mocks/match-media.js.map +1 -1
  209. package/dist/test-utils/vitest/timers.d.ts +1 -1
  210. package/dist/test-utils/vitest/timers.js +1 -1
  211. package/dist/test-utils/vitest/timers.js.map +1 -1
  212. package/dist/tooltip/Tooltip.js.map +1 -1
  213. package/dist/tooltip/TooltipHoverModeProvider.js.map +1 -1
  214. package/dist/tooltip/useTooltip.js.map +1 -1
  215. package/dist/transition/CSSTransition.js.map +1 -1
  216. package/dist/transition/Collapse.js.map +1 -1
  217. package/dist/transition/CrossFade.js.map +1 -1
  218. package/dist/transition/ScaleTransition.js.map +1 -1
  219. package/dist/transition/SkeletonPlaceholder.js.map +1 -1
  220. package/dist/transition/Slide.js.map +1 -1
  221. package/dist/transition/SlideContainer.js.map +1 -1
  222. package/dist/transition/types.js.map +1 -1
  223. package/dist/transition/useCollapseTransition.js.map +1 -1
  224. package/dist/transition/useCrossFadeTransition.js.map +1 -1
  225. package/dist/transition/useMaxWidthTransition.js.map +1 -1
  226. package/dist/transition/useScaleTransition.js.map +1 -1
  227. package/dist/transition/useSkeletonPlaceholder.js.map +1 -1
  228. package/dist/tree/Tree.js.map +1 -1
  229. package/dist/tree/TreeItem.js.map +1 -1
  230. package/dist/tree/TreeProvider.js.map +1 -1
  231. package/dist/tree/styles.js.map +1 -1
  232. package/dist/tree/types.js.map +1 -1
  233. package/dist/tree/useTreeMovement.js.map +1 -1
  234. package/dist/typography/HighlightTextMark.js.map +1 -1
  235. package/dist/typography/Mark.js.map +1 -1
  236. package/dist/typography/TextContainer.js.map +1 -1
  237. package/dist/typography/Typography.js.map +1 -1
  238. package/dist/typography/_typography.scss +0 -1
  239. package/dist/useElementSize.js.map +1 -1
  240. package/dist/useIntersectionObserver.js.map +1 -1
  241. package/dist/useMutationObserver.js.map +1 -1
  242. package/dist/useWindowSize.js.map +1 -1
  243. package/dist/utils/getNumberOfDigits.d.ts +7 -0
  244. package/dist/utils/getNumberOfDigits.js +11 -0
  245. package/dist/utils/getNumberOfDigits.js.map +1 -0
  246. package/dist/utils/nearest.js +2 -1
  247. package/dist/utils/nearest.js.map +1 -1
  248. package/dist/utils/useDevEffect.d.ts +7 -0
  249. package/dist/utils/useDevEffect.js +8 -0
  250. package/dist/utils/useDevEffect.js.map +1 -0
  251. package/dist/window-splitter/WindowSplitter.js +3 -2
  252. package/dist/window-splitter/WindowSplitter.js.map +1 -1
  253. package/dist/window-splitter/_window-splitter.scss +60 -12
  254. package/dist/window-splitter/styles.d.ts +9 -0
  255. package/dist/window-splitter/styles.js +3 -2
  256. package/dist/window-splitter/styles.js.map +1 -1
  257. package/dist/window-splitter/useWindowSplitter.js.map +1 -1
  258. package/package.json +37 -29
  259. package/src/CoreProviders.tsx +1 -0
  260. package/src/app-bar/AppBar.tsx +1 -2
  261. package/src/app-bar/AppBarTitle.tsx +1 -2
  262. package/src/autocomplete/AutocompleteListboxChildren.tsx +3 -1
  263. package/src/autocomplete/types.ts +24 -19
  264. package/src/autocomplete/utils.ts +9 -6
  265. package/src/avatar/Avatar.tsx +2 -1
  266. package/src/button/Button.tsx +2 -1
  267. package/src/button/FloatingActionButton.tsx +2 -1
  268. package/src/card/Card.tsx +2 -1
  269. package/src/card/CardContent.tsx +1 -2
  270. package/src/card/ClickableCard.tsx +1 -2
  271. package/src/chip/Chip.tsx +2 -1
  272. package/src/datetime/NativeDateField.tsx +2 -1
  273. package/src/datetime/NativeTimeField.tsx +2 -1
  274. package/src/datetime/useDateField.ts +13 -8
  275. package/src/datetime/useTimeField.ts +13 -8
  276. package/src/dialog/Dialog.tsx +2 -1
  277. package/src/dialog/DialogContainer.tsx +1 -2
  278. package/src/dialog/DialogContent.tsx +1 -2
  279. package/src/dialog/DialogFooter.tsx +1 -2
  280. package/src/divider/Divider.tsx +1 -2
  281. package/src/draggable/useDraggable.ts +4 -4
  282. package/src/draggable/utils.ts +4 -2
  283. package/src/expansion-panel/ExpansionPanelHeader.tsx +1 -2
  284. package/src/files/FileInput.tsx +2 -1
  285. package/src/files/useFileUpload.ts +6 -6
  286. package/src/files/validation.ts +1 -2
  287. package/src/focus/useFocusContainer.ts +4 -4
  288. package/src/form/Fieldset.tsx +25 -3
  289. package/src/form/FormMessageContainer.tsx +1 -2
  290. package/src/form/FormMessageCounter.tsx +1 -2
  291. package/src/form/InputToggle.tsx +3 -3
  292. package/src/form/Legend.tsx +55 -10
  293. package/src/form/Listbox.tsx +1 -2
  294. package/src/form/ListboxProvider.ts +3 -2
  295. package/src/form/NativeSelect.tsx +2 -1
  296. package/src/form/Password.tsx +4 -2
  297. package/src/form/ResizingTextAreaWrapper.tsx +1 -2
  298. package/src/form/Select.tsx +2 -1
  299. package/src/form/Slider.tsx +2 -1
  300. package/src/form/SliderContainer.tsx +1 -2
  301. package/src/form/SliderThumb.tsx +6 -3
  302. package/src/form/SliderTrack.tsx +2 -1
  303. package/src/form/SliderValueMarks.tsx +1 -2
  304. package/src/form/Switch.tsx +2 -1
  305. package/src/form/TextArea.tsx +1 -2
  306. package/src/form/TextField.tsx +2 -1
  307. package/src/form/TextFieldContainer.tsx +1 -2
  308. package/src/form/fieldsetStyles.ts +18 -3
  309. package/src/form/inputToggleStyles.ts +4 -2
  310. package/src/form/labelStyles.ts +1 -1
  311. package/src/form/legendStyles.ts +132 -0
  312. package/src/form/selectUtils.ts +3 -2
  313. package/src/form/textFieldContainerStyles.ts +1 -2
  314. package/src/form/types.ts +35 -17
  315. package/src/form/useCheckboxGroup.ts +3 -2
  316. package/src/form/useCombobox.ts +8 -3
  317. package/src/form/useNumberField.ts +36 -35
  318. package/src/form/useRangeSlider.ts +1 -2
  319. package/src/form/useSlider.ts +1 -2
  320. package/src/form/useTextField.ts +8 -3
  321. package/src/hoverMode/useHoverMode.ts +4 -8
  322. package/src/icon/FontIcon.tsx +1 -2
  323. package/src/icon/IconRotator.tsx +1 -2
  324. package/src/icon/MaterialIcon.tsx +2 -1
  325. package/src/icon/MaterialSymbol.tsx +2 -1
  326. package/src/icon/SVGIcon.tsx +1 -2
  327. package/src/icon/config.tsx +10 -7
  328. package/src/icon/materialConfig.ts +1 -2
  329. package/src/icon/styles.ts +1 -2
  330. package/src/interaction/UserInteractionModeProvider.tsx +9 -4
  331. package/src/interaction/types.ts +1 -2
  332. package/src/interaction/useElementInteraction.tsx +3 -2
  333. package/src/layout/LayoutAppBar.tsx +6 -6
  334. package/src/layout/LayoutNav.tsx +2 -1
  335. package/src/layout/LayoutWindowSplitter.tsx +2 -1
  336. package/src/layout/Main.tsx +1 -2
  337. package/src/layout/useExpandableLayout.ts +63 -5
  338. package/src/layout/useHorizontalLayoutTransition.ts +1 -2
  339. package/src/layout/useLayoutTree.ts +2 -2
  340. package/src/layout/useLayoutWindowSplitter.ts +6 -6
  341. package/src/layout/useResizableLayout.ts +3 -6
  342. package/src/link/Link.tsx +1 -2
  343. package/src/link/SkipToMainContent.tsx +20 -23
  344. package/src/list/List.tsx +1 -2
  345. package/src/list/ListItem.tsx +2 -1
  346. package/src/list/ListItemAddon.tsx +2 -1
  347. package/src/list/ListItemLink.tsx +2 -1
  348. package/src/list/ListSubheader.tsx +1 -2
  349. package/src/list/getListItemHeight.ts +8 -9
  350. package/src/list/listItemStyles.ts +1 -2
  351. package/src/list/types.ts +1 -2
  352. package/src/media-queries/AppSizeProvider.tsx +8 -10
  353. package/src/media-queries/appSize.ts +3 -0
  354. package/src/media-queries/config.ts +41 -0
  355. package/src/menu/DropdownMenu.tsx +4 -5
  356. package/src/menu/Menu.tsx +2 -1
  357. package/src/menu/MenuItemButton.tsx +1 -2
  358. package/src/menu/MenuItemFileInput.tsx +2 -1
  359. package/src/menu/MenuItemInputToggle.tsx +3 -3
  360. package/src/menu/MenuItemSeparator.tsx +2 -1
  361. package/src/menu/MenuVisibilityProvider.tsx +4 -2
  362. package/src/menu/MenuWidget.tsx +1 -2
  363. package/src/menu/useContextMenu.ts +4 -2
  364. package/src/movement/types.ts +52 -13
  365. package/src/movement/useKeyboardMovementProvider.ts +77 -38
  366. package/src/navigation/CollapsibleNavGroup.tsx +1 -2
  367. package/src/navigation/NavItem.tsx +1 -2
  368. package/src/navigation/NavItemButton.tsx +2 -1
  369. package/src/navigation/NavItemLink.tsx +2 -1
  370. package/src/navigation/getTableOfContentsHeadings.ts +1 -2
  371. package/src/navigation/types.ts +1 -2
  372. package/src/overlay/Overlay.tsx +2 -1
  373. package/src/positioning/createHorizontalPosition.ts +10 -12
  374. package/src/positioning/createVerticalPosition.ts +10 -11
  375. package/src/positioning/useFixedPositioning.ts +6 -3
  376. package/src/progress/CircularProgress.tsx +2 -1
  377. package/src/progress/LinearProgress.tsx +2 -1
  378. package/src/progress/linearProgressStyles.ts +1 -2
  379. package/src/responsive-item/ResponsiveItem.tsx +1 -2
  380. package/src/responsive-item/ResponsiveItemOverlay.tsx +2 -1
  381. package/src/searching/caseInsensitive.ts +2 -4
  382. package/src/segmented-button/SegmentedButton.tsx +2 -1
  383. package/src/segmented-button/SegmentedButtonContainer.tsx +2 -1
  384. package/src/segmented-button/segmentedButtonStyles.ts +1 -2
  385. package/src/sheet/Sheet.tsx +1 -2
  386. package/src/snackbar/Toast.tsx +2 -1
  387. package/src/spinbutton/SpinButton.tsx +98 -0
  388. package/src/spinbutton/SpinButtonGroupProvider.tsx +32 -0
  389. package/src/spinbutton/defaults.ts +45 -0
  390. package/src/spinbutton/types.ts +413 -0
  391. package/src/spinbutton/useSpinButton.ts +311 -0
  392. package/src/spinbutton/useSpinButtonGroupProvider.ts +104 -0
  393. package/src/spinbutton/utils/deselectNode.ts +17 -0
  394. package/src/spinbutton/utils/resolveInputEvent.ts +112 -0
  395. package/src/spinbutton/utils/selectNode.ts +15 -0
  396. package/src/table/StickyTableSection.tsx +2 -1
  397. package/src/table/Table.tsx +1 -2
  398. package/src/table/TableBody.tsx +2 -1
  399. package/src/table/TableCellContent.tsx +1 -2
  400. package/src/table/TableCheckbox.tsx +1 -2
  401. package/src/table/TableFooter.tsx +1 -2
  402. package/src/table/TableHeader.tsx +1 -2
  403. package/src/table/TableRadio.tsx +1 -2
  404. package/src/table/TableRow.tsx +1 -2
  405. package/src/table/useStickyTableSection.tsx +1 -2
  406. package/src/tabs/SimpleTabPanel.tsx +2 -1
  407. package/src/tabs/SimpleTabPanels.tsx +2 -1
  408. package/src/tabs/Tab.tsx +3 -6
  409. package/src/tabs/TabList.tsx +2 -1
  410. package/src/tabs/TabListScrollButton.tsx +1 -2
  411. package/src/tabs/useMaxTabPanelHeight.ts +7 -4
  412. package/src/test-utils/data-testid.ts +1 -2
  413. package/src/test-utils/mocks/match-media.ts +5 -10
  414. package/src/test-utils/vitest/timers.ts +1 -1
  415. package/src/tooltip/Tooltip.tsx +2 -1
  416. package/src/tooltip/TooltipHoverModeProvider.tsx +1 -2
  417. package/src/tooltip/useTooltip.ts +9 -5
  418. package/src/transition/CSSTransition.tsx +2 -1
  419. package/src/transition/Collapse.tsx +4 -2
  420. package/src/transition/CrossFade.tsx +2 -1
  421. package/src/transition/ScaleTransition.tsx +2 -1
  422. package/src/transition/SkeletonPlaceholder.tsx +1 -2
  423. package/src/transition/Slide.tsx +2 -1
  424. package/src/transition/SlideContainer.tsx +1 -2
  425. package/src/transition/types.ts +15 -16
  426. package/src/transition/useCollapseTransition.ts +6 -5
  427. package/src/transition/useCrossFadeTransition.ts +3 -2
  428. package/src/transition/useMaxWidthTransition.ts +1 -2
  429. package/src/transition/useScaleTransition.ts +3 -2
  430. package/src/transition/useSkeletonPlaceholder.ts +1 -2
  431. package/src/tree/Tree.tsx +2 -1
  432. package/src/tree/TreeItem.tsx +2 -1
  433. package/src/tree/TreeProvider.tsx +4 -4
  434. package/src/tree/styles.ts +1 -2
  435. package/src/tree/types.ts +1 -2
  436. package/src/tree/useTreeMovement.ts +1 -2
  437. package/src/typography/HighlightTextMark.tsx +1 -2
  438. package/src/typography/Mark.tsx +1 -2
  439. package/src/typography/TextContainer.tsx +1 -2
  440. package/src/typography/Typography.tsx +1 -2
  441. package/src/useElementSize.ts +7 -4
  442. package/src/useIntersectionObserver.ts +3 -2
  443. package/src/useMutationObserver.ts +3 -2
  444. package/src/useWindowSize.ts +4 -2
  445. package/src/utils/getNumberOfDigits.ts +18 -0
  446. package/src/utils/nearest.ts +2 -1
  447. package/src/utils/useDevEffect.ts +9 -0
  448. package/src/window-splitter/WindowSplitter.tsx +5 -2
  449. package/src/window-splitter/styles.ts +13 -2
  450. package/src/window-splitter/useWindowSplitter.ts +3 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/files/useFileUpload.ts"],"sourcesContent":["\"use client\";\n\nimport { nanoid } from \"nanoid\";\nimport {\n type ChangeEvent,\n type DragEvent,\n useCallback,\n useEffect,\n useReducer,\n} from \"react\";\n\nimport {\n type CompletedFileUploadStats,\n type FileReaderResult,\n type FileUploadHandlers,\n type FileUploadStats,\n type GetFileParser,\n type ProcessingFileUploadStats,\n getFileParser as defaultGetFileParser,\n} from \"./utils.js\";\nimport {\n FileAccessError,\n type FileValidationError,\n type FileValidationOptions,\n type FilesValidator,\n isValidFileName as defaultIsValidFileName,\n validateFiles as defaultValidateFiles,\n} from \"./validation.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n *\n * @typeParam CustomError - An optional error type that gets returned from the\n * {@link FilesValidator}.\n * @since 2.9.0\n */\nexport interface FileUploadState<CustomError = never> {\n /**\n * All the files that have been validated and are either:\n * - pending upload\n * - uploading\n * - complete\n *\n * Each key in this object is the {@link BaseFileUploadStats.key} generated\n * once the upload starts pending.\n */\n stats: Readonly<Record<string, Readonly<FileUploadStats>>>;\n\n /**\n * A list of validation errors that have occurred before starting the upload\n * process.\n *\n * @see {@link FileAccessError}\n * @see {@link TooManyFilesError}\n * @see {@link FileValidationError}\n */\n errors: readonly FileValidationError<CustomError>[];\n}\n\n/**\n *\n * @typeParam CustomError - An optional error type that gets returned from the\n * {@link FilesValidator}.\n * @since 2.9.0\n * @internal\n */\nexport interface FileUploadHookState<CustomError = never>\n extends FileUploadState<CustomError> {\n /**\n * All the current readers used for uploading files to the browser.\n *\n * Note: Once an upload has completed, the reader will be removed.\n */\n readers: Readonly<Record<string, FileReader>>;\n}\n\n/**\n *\n * @typeParam E - An optional HTMLElement type that is used for the\n * {@link FileUploadHandlers}.\n * @typeParam CustomError - An optional error type that gets returned from the\n * {@link FilesValidator}.\n * @since 2.9.0\n */\nexport interface FileUploadOptions<E extends HTMLElement, CustomError = never>\n extends FileUploadHandlers<E>,\n FileValidationOptions {\n /**\n * Setting this value to a number greater than `0` will update the browser\n * upload process to queue the uploads in chunks instead of all at once. This\n * can help prevent the browser from freezing if dealing with large files that\n * are being converted to data urls.\n *\n * @defaultValue `-1`\n */\n concurrency?: number;\n\n /** {@inheritDoc FilesValidator} */\n validateFiles?: FilesValidator<CustomError>;\n /** {@inheritDoc GetFileParser} */\n getFileParser?: GetFileParser;\n}\n\n/** @internal */\ntype Action<E = never> =\n | {\n type: \"queue\";\n errors: readonly FileValidationError<E>[];\n files: readonly File[];\n }\n | { type: \"reset\" }\n | { type: \"remove\"; files: readonly string[] }\n | { type: \"start\"; key: string; reader: FileReader }\n | { type: \"progress\"; key: string; progress: number }\n | { type: \"complete\"; key: string; result: FileReaderResult }\n | { type: \"clearErrors\" };\n\n/** @since 2.9.0 */\nexport interface FileUploadActions {\n /**\n * Reset everything related to uploads ensuring that all file readers have\n * been aborted.\n */\n reset: () => void;\n\n /**\n * Removes all the errors that exist in state without canceling any of the\n * uploads already in progress.\n */\n clearErrors: () => void;\n\n /**\n * This function is used to cancel pending and uploading files or removing\n * completed files.\n *\n * @param keyOrKeys - A single or list of {@link BaseFileUploadStats.key} to\n * remove from state.\n */\n remove: (keyOrKeys: string | readonly string[]) => void;\n}\n\n/**\n *\n * @typeParam E - An optional HTMLElement type that is used for the\n * {@link FileUploadHandlers}.\n * @typeParam CustomError - An optional error type that gets returned from the\n * {@link FilesValidator}.\n * @since 2.9.0\n */\nexport interface FileUploadHookReturnValue<\n E extends HTMLElement = HTMLElement,\n CustomError = never,\n> extends FileUploadActions,\n Required<FileUploadHandlers<E>> {\n /** {@inheritDoc FileUploadState.errors} */\n errors: readonly FileValidationError<CustomError>[];\n\n /**\n * A list of all the {@link FileUploadStats}.\n *\n * @see {@link getSplitFileUploads} for separating by status\n */\n stats: readonly Readonly<FileUploadStats>[];\n\n /**\n * The total number of bytes for all the files that exist in the\n * {@link stats} list.\n */\n totalBytes: number;\n\n /**\n * The total number of files in the {@link stats} list.\n */\n totalFiles: number;\n\n /**\n * An `accept` string that can be passed to the {@link FileInput} component\n * when the {@link FileValidationOptions.extensions} list has been provided to\n * limit which files the OS will _attempt_ to allow access to.\n *\n * @example Simple example\n * ```ts\n * const extensions = ['pdf', 'docx', 'ppt'];\n * const { accept } = useFileUpload({ extensions, ...others });\n *\n * expect(accept).toBe(\"*.pdf,*.docx,*.ppt\")\n * ```\n *\n * @defaultValue `\"*\"`\n */\n accept: string;\n}\n\n/** @internal */\nconst EMPTY_LIST = [] as const;\n/** @internal */\nconst EMPTY_OBJECT = {} as const;\n\n/**\n * This hook is generally used to upload files **to the browser** in different\n * formats to be previewed `<img>`, `<video>`, `<embed>`, etc tags. However, it\n * can also be used to upload the files as an `ArrayBuffer` and then uploaded to\n * a server.\n *\n * @see {@link https://react-md.dev/components/file-input | FileInput Demos}\n * @see {@link https://react-md.dev/hooks/use-file-input | useFileInput Demos}\n * @typeParam E - An optional HTMLElement type that is used for the\n * {@link FileUploadHandlers}.\n * @typeParam CustomError - An optional error type that gets returned from the\n * {@link FilesValidator}.\n * @param options - All the {@link FileUploadOptions}\n * @returns the {@link FileUploadHookReturnValue}\n * @since 2.9.0\n */\nexport function useFileUpload<E extends HTMLElement, CustomError = never>(\n options: FileUploadOptions<E, CustomError> = {}\n): Readonly<FileUploadHookReturnValue<E, CustomError>> {\n const {\n maxFiles = -1,\n extensions = EMPTY_LIST,\n minFileSize = -1,\n maxFileSize = -1,\n totalFileSize = -1,\n concurrency = -1,\n onDrop: propOnDrop = noop,\n onChange: propOnChange = noop,\n validateFiles = defaultValidateFiles,\n getFileParser = defaultGetFileParser,\n isValidFileName = defaultIsValidFileName,\n } = options;\n\n const [state, dispatch] = useReducer(\n function reducer(\n state: FileUploadHookState<CustomError>,\n action: Action<CustomError>\n ): FileUploadHookState<CustomError> {\n switch (action.type) {\n case \"reset\":\n // need to reuse constants so that calling reset doesn't cause an\n // infinite loop in an effect\n return {\n stats: EMPTY_OBJECT,\n errors: EMPTY_LIST,\n readers: EMPTY_OBJECT,\n };\n case \"remove\": {\n const stats: Record<string, FileUploadStats> = {};\n for (const key in state.stats) {\n if (!action.files.includes(key)) {\n stats[key] = state.stats[key];\n }\n }\n\n return {\n ...state,\n stats,\n };\n }\n case \"queue\":\n return {\n ...state,\n stats: {\n ...state.stats,\n ...action.files.reduce<Record<string, ProcessingFileUploadStats>>(\n (files, file) => {\n const key = nanoid();\n files[key] = {\n key,\n file,\n progress: 0,\n status: \"pending\",\n };\n\n return files;\n },\n {}\n ),\n },\n errors: [...state.errors, ...action.errors],\n };\n case \"start\": {\n const { key, reader } = action;\n const fileStats: ProcessingFileUploadStats = {\n key,\n file: state.stats[key].file,\n progress: 0,\n status: \"uploading\",\n };\n\n return {\n ...state,\n readers: {\n ...state.readers,\n [key]: reader,\n },\n stats: {\n ...state.stats,\n [key]: fileStats,\n },\n };\n }\n case \"progress\": {\n const { key, progress } = action;\n return {\n ...state,\n stats: {\n ...state.stats,\n [key]: {\n ...state.stats[key],\n progress,\n },\n },\n };\n }\n case \"complete\": {\n const { key, result } = action;\n const file: CompletedFileUploadStats = {\n key,\n file: state.stats[key].file,\n status: \"complete\",\n result,\n progress: 100,\n };\n const { [key]: _reader, ...readers } = state.readers;\n\n return {\n ...state,\n readers,\n stats: {\n ...state.stats,\n [key]: file,\n },\n };\n }\n case \"clearErrors\":\n return { ...state, errors: [] };\n }\n },\n {\n stats: EMPTY_OBJECT,\n errors: EMPTY_LIST,\n readers: EMPTY_OBJECT,\n }\n );\n const { stats, errors, readers } = state;\n\n const statsList = Object.values(stats);\n const totalFiles = statsList.length;\n const totalBytes = statsList.reduce(\n (result, { file: { size } }) => result + size,\n 0\n );\n const queueFiles = useCallback(\n (files: readonly File[]) => {\n const { pending, errors } = validateFiles(files, {\n maxFiles,\n extensions,\n minFileSize,\n maxFileSize,\n totalBytes,\n totalFiles,\n totalFileSize,\n isValidFileName,\n });\n\n dispatch({ type: \"queue\", errors, files: pending });\n },\n [\n validateFiles,\n maxFiles,\n extensions,\n minFileSize,\n maxFileSize,\n totalBytes,\n totalFiles,\n totalFileSize,\n isValidFileName,\n ]\n );\n const onDrop = useCallback(\n (event: DragEvent<E>) => {\n propOnDrop(event);\n event.preventDefault();\n event.stopPropagation();\n\n try {\n const files = event.dataTransfer.files;\n if (files) {\n queueFiles(Array.from(files));\n }\n } catch (e) {\n dispatch({\n type: \"queue\",\n files: [],\n errors: [\n new FileAccessError(e instanceof Error ? e.message : undefined),\n ],\n });\n }\n },\n [queueFiles, propOnDrop]\n );\n const onChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n propOnChange(event);\n try {\n const files = event.currentTarget.files;\n if (files) {\n queueFiles(Array.from(files));\n } else {\n throw new Error();\n }\n } catch (e) {\n dispatch({\n type: \"queue\",\n files: [],\n errors: [\n new FileAccessError(e instanceof Error ? e.message : undefined),\n ],\n });\n }\n },\n [queueFiles, propOnChange]\n );\n\n const remove = useCallback(\n (keyOrKeys: string | readonly string[]) => {\n const files = typeof keyOrKeys === \"string\" ? [keyOrKeys] : keyOrKeys;\n files.forEach((fileKey) => {\n readers[fileKey]?.abort();\n });\n\n dispatch({ type: \"remove\", files });\n },\n [readers]\n );\n const reset = useCallback(() => {\n Object.values(readers).forEach((reader) => {\n reader.abort();\n });\n\n dispatch({ type: \"reset\" });\n }, [readers]);\n const clearErrors = useCallback(() => {\n dispatch({ type: \"clearErrors\" });\n }, []);\n const start = useCallback((key: string, reader: FileReader) => {\n dispatch({ type: \"start\", key, reader });\n }, []);\n const complete = useCallback(\n (key: string, result: FileReaderResult = null) => {\n dispatch({ type: \"complete\", key, result });\n },\n []\n );\n const createProgressEventHandler = useCallback(\n (key: string) => (event: ProgressEvent) => {\n if (event.lengthComputable) {\n const percentage = Math.round((event.loaded * 100) / event.total);\n dispatch({ type: \"progress\", key, progress: percentage });\n }\n },\n []\n );\n\n useEffect(() => {\n const pending: ProcessingFileUploadStats[] = [];\n const uploading: ProcessingFileUploadStats[] = [];\n Object.values(stats).forEach((file) => {\n if (file.status === \"pending\") {\n pending.push(file);\n } else if (file.status === \"uploading\") {\n uploading.push(file);\n }\n });\n\n const lastIndex =\n concurrency === -1\n ? pending.length\n : Math.max(0, concurrency - uploading.length);\n const queue = pending.slice(0, lastIndex);\n if (!queue.length) {\n return;\n }\n\n queue.forEach((stats) => {\n const { key, file } = stats;\n const reader = new FileReader();\n\n // using `addEventListener` instead of directly setting to\n // `reader.progress`/`reader.load` so it's easier to test\n reader.addEventListener(\"progress\", createProgressEventHandler(key));\n reader.addEventListener(\"load\", () => {\n complete(key, reader.result);\n });\n\n start(key, reader);\n const parser = getFileParser(file);\n /* istanbul ignore next */\n if (\n process.env.NODE_ENV !== \"production\" &&\n ![\"readAsText\", \"readAsDataURL\", \"readAsArrayBuffer\"].includes(parser)\n ) {\n throw new Error(\"Invalid file reader parser\");\n }\n\n reader[parser](file);\n });\n }, [\n concurrency,\n stats,\n getFileParser,\n createProgressEventHandler,\n start,\n complete,\n ]);\n\n let accept = \"\";\n if (extensions.length) {\n accept = extensions.reduce((s, ext) => `${s ? `${s},` : \"\"}.${ext}`, \"\");\n }\n\n return {\n stats: statsList,\n errors,\n accept,\n totalBytes,\n totalFiles,\n onDrop,\n onChange,\n reset,\n remove,\n clearErrors,\n };\n}\n"],"names":["nanoid","useCallback","useEffect","useReducer","getFileParser","defaultGetFileParser","FileAccessError","isValidFileName","defaultIsValidFileName","validateFiles","defaultValidateFiles","noop","EMPTY_LIST","EMPTY_OBJECT","useFileUpload","options","maxFiles","extensions","minFileSize","maxFileSize","totalFileSize","concurrency","onDrop","propOnDrop","onChange","propOnChange","state","dispatch","reducer","action","type","stats","errors","readers","key","files","includes","reduce","file","progress","status","reader","fileStats","result","_reader","statsList","Object","values","totalFiles","length","totalBytes","size","queueFiles","pending","event","preventDefault","stopPropagation","dataTransfer","Array","from","e","Error","message","undefined","currentTarget","remove","keyOrKeys","forEach","fileKey","abort","reset","clearErrors","start","complete","createProgressEventHandler","lengthComputable","percentage","Math","round","loaded","total","uploading","push","lastIndex","max","queue","slice","FileReader","addEventListener","parser","process","env","NODE_ENV","accept","s","ext"],"mappings":"AAAA;AAEA,SAASA,MAAM,QAAQ,SAAS;AAChC,SAGEC,WAAW,EACXC,SAAS,EACTC,UAAU,QACL,QAAQ;AAEf,SAOEC,iBAAiBC,oBAAoB,QAChC,aAAa;AACpB,SACEC,eAAe,EAIfC,mBAAmBC,sBAAsB,EACzCC,iBAAiBC,oB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hE,OAAOc;QACPb;QACA6D;QACA3C;QACAF;QACA1B;QACAE;QACA8C;QACAL;QACAM;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/files/useFileUpload.ts"],"sourcesContent":["\"use client\";\n\nimport { nanoid } from \"nanoid\";\nimport {\n type ChangeEvent,\n type DragEvent,\n useCallback,\n useEffect,\n useReducer,\n} from \"react\";\n\nimport {\n type CompletedFileUploadStats,\n type FileReaderResult,\n type FileUploadHandlers,\n type FileUploadStats,\n type GetFileParser,\n type ProcessingFileUploadStats,\n getFileParser as defaultGetFileParser,\n} from \"./utils.js\";\nimport {\n FileAccessError,\n type FileValidationError,\n type FileValidationOptions,\n type FilesValidator,\n isValidFileName as defaultIsValidFileName,\n validateFiles as defaultValidateFiles,\n} from \"./validation.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n *\n * @typeParam CustomError - An optional error type that gets returned from the\n * {@link FilesValidator}.\n * @since 2.9.0\n */\nexport interface FileUploadState<CustomError = never> {\n /**\n * All the files that have been validated and are either:\n * - pending upload\n * - uploading\n * - complete\n *\n * Each key in this object is the {@link BaseFileUploadStats.key} generated\n * once the upload starts pending.\n */\n stats: Readonly<Record<string, Readonly<FileUploadStats>>>;\n\n /**\n * A list of validation errors that have occurred before starting the upload\n * process.\n *\n * @see {@link FileAccessError}\n * @see {@link TooManyFilesError}\n * @see {@link FileValidationError}\n */\n errors: readonly FileValidationError<CustomError>[];\n}\n\n/**\n *\n * @typeParam CustomError - An optional error type that gets returned from the\n * {@link FilesValidator}.\n * @since 2.9.0\n * @internal\n */\nexport interface FileUploadHookState<\n CustomError = never,\n> extends FileUploadState<CustomError> {\n /**\n * All the current readers used for uploading files to the browser.\n *\n * Note: Once an upload has completed, the reader will be removed.\n */\n readers: Readonly<Record<string, FileReader>>;\n}\n\n/**\n *\n * @typeParam E - An optional HTMLElement type that is used for the\n * {@link FileUploadHandlers}.\n * @typeParam CustomError - An optional error type that gets returned from the\n * {@link FilesValidator}.\n * @since 2.9.0\n */\nexport interface FileUploadOptions<E extends HTMLElement, CustomError = never>\n extends FileUploadHandlers<E>, FileValidationOptions {\n /**\n * Setting this value to a number greater than `0` will update the browser\n * upload process to queue the uploads in chunks instead of all at once. This\n * can help prevent the browser from freezing if dealing with large files that\n * are being converted to data urls.\n *\n * @defaultValue `-1`\n */\n concurrency?: number;\n\n /** {@inheritDoc FilesValidator} */\n validateFiles?: FilesValidator<CustomError>;\n /** {@inheritDoc GetFileParser} */\n getFileParser?: GetFileParser;\n}\n\n/** @internal */\ntype Action<E = never> =\n | {\n type: \"queue\";\n errors: readonly FileValidationError<E>[];\n files: readonly File[];\n }\n | { type: \"reset\" }\n | { type: \"remove\"; files: readonly string[] }\n | { type: \"start\"; key: string; reader: FileReader }\n | { type: \"progress\"; key: string; progress: number }\n | { type: \"complete\"; key: string; result: FileReaderResult }\n | { type: \"clearErrors\" };\n\n/** @since 2.9.0 */\nexport interface FileUploadActions {\n /**\n * Reset everything related to uploads ensuring that all file readers have\n * been aborted.\n */\n reset: () => void;\n\n /**\n * Removes all the errors that exist in state without canceling any of the\n * uploads already in progress.\n */\n clearErrors: () => void;\n\n /**\n * This function is used to cancel pending and uploading files or removing\n * completed files.\n *\n * @param keyOrKeys - A single or list of {@link BaseFileUploadStats.key} to\n * remove from state.\n */\n remove: (keyOrKeys: string | readonly string[]) => void;\n}\n\n/**\n *\n * @typeParam E - An optional HTMLElement type that is used for the\n * {@link FileUploadHandlers}.\n * @typeParam CustomError - An optional error type that gets returned from the\n * {@link FilesValidator}.\n * @since 2.9.0\n */\nexport interface FileUploadHookReturnValue<\n E extends HTMLElement = HTMLElement,\n CustomError = never,\n>\n extends FileUploadActions, Required<FileUploadHandlers<E>> {\n /** {@inheritDoc FileUploadState.errors} */\n errors: readonly FileValidationError<CustomError>[];\n\n /**\n * A list of all the {@link FileUploadStats}.\n *\n * @see {@link getSplitFileUploads} for separating by status\n */\n stats: readonly Readonly<FileUploadStats>[];\n\n /**\n * The total number of bytes for all the files that exist in the\n * {@link stats} list.\n */\n totalBytes: number;\n\n /**\n * The total number of files in the {@link stats} list.\n */\n totalFiles: number;\n\n /**\n * An `accept` string that can be passed to the {@link FileInput} component\n * when the {@link FileValidationOptions.extensions} list has been provided to\n * limit which files the OS will _attempt_ to allow access to.\n *\n * @example Simple example\n * ```ts\n * const extensions = ['pdf', 'docx', 'ppt'];\n * const { accept } = useFileUpload({ extensions, ...others });\n *\n * expect(accept).toBe(\"*.pdf,*.docx,*.ppt\")\n * ```\n *\n * @defaultValue `\"*\"`\n */\n accept: string;\n}\n\n/** @internal */\nconst EMPTY_LIST = [] as const;\n/** @internal */\nconst EMPTY_OBJECT = {} as const;\n\n/**\n * This hook is generally used to upload files **to the browser** in different\n * formats to be previewed `<img>`, `<video>`, `<embed>`, etc tags. However, it\n * can also be used to upload the files as an `ArrayBuffer` and then uploaded to\n * a server.\n *\n * @see {@link https://react-md.dev/components/file-input | FileInput Demos}\n * @see {@link https://react-md.dev/hooks/use-file-input | useFileInput Demos}\n * @typeParam E - An optional HTMLElement type that is used for the\n * {@link FileUploadHandlers}.\n * @typeParam CustomError - An optional error type that gets returned from the\n * {@link FilesValidator}.\n * @param options - All the {@link FileUploadOptions}\n * @returns the {@link FileUploadHookReturnValue}\n * @since 2.9.0\n */\nexport function useFileUpload<E extends HTMLElement, CustomError = never>(\n options: FileUploadOptions<E, CustomError> = {}\n): Readonly<FileUploadHookReturnValue<E, CustomError>> {\n const {\n maxFiles = -1,\n extensions = EMPTY_LIST,\n minFileSize = -1,\n maxFileSize = -1,\n totalFileSize = -1,\n concurrency = -1,\n onDrop: propOnDrop = noop,\n onChange: propOnChange = noop,\n validateFiles = defaultValidateFiles,\n getFileParser = defaultGetFileParser,\n isValidFileName = defaultIsValidFileName,\n } = options;\n\n const [state, dispatch] = useReducer(\n function reducer(\n state: FileUploadHookState<CustomError>,\n action: Action<CustomError>\n ): FileUploadHookState<CustomError> {\n switch (action.type) {\n case \"reset\":\n // need to reuse constants so that calling reset doesn't cause an\n // infinite loop in an effect\n return {\n stats: EMPTY_OBJECT,\n errors: EMPTY_LIST,\n readers: EMPTY_OBJECT,\n };\n case \"remove\": {\n const stats: Record<string, FileUploadStats> = {};\n for (const key in state.stats) {\n if (!action.files.includes(key)) {\n stats[key] = state.stats[key];\n }\n }\n\n return {\n ...state,\n stats,\n };\n }\n case \"queue\":\n return {\n ...state,\n stats: {\n ...state.stats,\n ...action.files.reduce<Record<string, ProcessingFileUploadStats>>(\n (files, file) => {\n const key = nanoid();\n files[key] = {\n key,\n file,\n progress: 0,\n status: \"pending\",\n };\n\n return files;\n },\n {}\n ),\n },\n errors: [...state.errors, ...action.errors],\n };\n case \"start\": {\n const { key, reader } = action;\n const fileStats: ProcessingFileUploadStats = {\n key,\n file: state.stats[key].file,\n progress: 0,\n status: \"uploading\",\n };\n\n return {\n ...state,\n readers: {\n ...state.readers,\n [key]: reader,\n },\n stats: {\n ...state.stats,\n [key]: fileStats,\n },\n };\n }\n case \"progress\": {\n const { key, progress } = action;\n return {\n ...state,\n stats: {\n ...state.stats,\n [key]: {\n ...state.stats[key],\n progress,\n },\n },\n };\n }\n case \"complete\": {\n const { key, result } = action;\n const file: CompletedFileUploadStats = {\n key,\n file: state.stats[key].file,\n status: \"complete\",\n result,\n progress: 100,\n };\n const { [key]: _reader, ...readers } = state.readers;\n\n return {\n ...state,\n readers,\n stats: {\n ...state.stats,\n [key]: file,\n },\n };\n }\n case \"clearErrors\":\n return { ...state, errors: [] };\n }\n },\n {\n stats: EMPTY_OBJECT,\n errors: EMPTY_LIST,\n readers: EMPTY_OBJECT,\n }\n );\n const { stats, errors, readers } = state;\n\n const statsList = Object.values(stats);\n const totalFiles = statsList.length;\n const totalBytes = statsList.reduce(\n (result, { file: { size } }) => result + size,\n 0\n );\n const queueFiles = useCallback(\n (files: readonly File[]) => {\n const { pending, errors } = validateFiles(files, {\n maxFiles,\n extensions,\n minFileSize,\n maxFileSize,\n totalBytes,\n totalFiles,\n totalFileSize,\n isValidFileName,\n });\n\n dispatch({ type: \"queue\", errors, files: pending });\n },\n [\n validateFiles,\n maxFiles,\n extensions,\n minFileSize,\n maxFileSize,\n totalBytes,\n totalFiles,\n totalFileSize,\n isValidFileName,\n ]\n );\n const onDrop = useCallback(\n (event: DragEvent<E>) => {\n propOnDrop(event);\n event.preventDefault();\n event.stopPropagation();\n\n try {\n const files = event.dataTransfer.files;\n if (files) {\n queueFiles(Array.from(files));\n }\n } catch (e) {\n dispatch({\n type: \"queue\",\n files: [],\n errors: [\n new FileAccessError(e instanceof Error ? e.message : undefined),\n ],\n });\n }\n },\n [queueFiles, propOnDrop]\n );\n const onChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n propOnChange(event);\n try {\n const files = event.currentTarget.files;\n if (files) {\n queueFiles(Array.from(files));\n } else {\n throw new Error();\n }\n } catch (e) {\n dispatch({\n type: \"queue\",\n files: [],\n errors: [\n new FileAccessError(e instanceof Error ? e.message : undefined),\n ],\n });\n }\n },\n [queueFiles, propOnChange]\n );\n\n const remove = useCallback(\n (keyOrKeys: string | readonly string[]) => {\n const files = typeof keyOrKeys === \"string\" ? [keyOrKeys] : keyOrKeys;\n files.forEach((fileKey) => {\n readers[fileKey]?.abort();\n });\n\n dispatch({ type: \"remove\", files });\n },\n [readers]\n );\n const reset = useCallback(() => {\n Object.values(readers).forEach((reader) => {\n reader.abort();\n });\n\n dispatch({ type: \"reset\" });\n }, [readers]);\n const clearErrors = useCallback(() => {\n dispatch({ type: \"clearErrors\" });\n }, []);\n const start = useCallback((key: string, reader: FileReader) => {\n dispatch({ type: \"start\", key, reader });\n }, []);\n const complete = useCallback(\n (key: string, result: FileReaderResult = null) => {\n dispatch({ type: \"complete\", key, result });\n },\n []\n );\n const createProgressEventHandler = useCallback(\n (key: string) => (event: ProgressEvent) => {\n if (event.lengthComputable) {\n const percentage = Math.round((event.loaded * 100) / event.total);\n dispatch({ type: \"progress\", key, progress: percentage });\n }\n },\n []\n );\n\n useEffect(() => {\n const pending: ProcessingFileUploadStats[] = [];\n const uploading: ProcessingFileUploadStats[] = [];\n Object.values(stats).forEach((file) => {\n if (file.status === \"pending\") {\n pending.push(file);\n } else if (file.status === \"uploading\") {\n uploading.push(file);\n }\n });\n\n const lastIndex =\n concurrency === -1\n ? pending.length\n : Math.max(0, concurrency - uploading.length);\n const queue = pending.slice(0, lastIndex);\n if (!queue.length) {\n return;\n }\n\n queue.forEach((stats) => {\n const { key, file } = stats;\n const reader = new FileReader();\n\n // using `addEventListener` instead of directly setting to\n // `reader.progress`/`reader.load` so it's easier to test\n reader.addEventListener(\"progress\", createProgressEventHandler(key));\n reader.addEventListener(\"load\", () => {\n complete(key, reader.result);\n });\n\n start(key, reader);\n const parser = getFileParser(file);\n /* istanbul ignore next */\n if (\n process.env.NODE_ENV !== \"production\" &&\n ![\"readAsText\", \"readAsDataURL\", \"readAsArrayBuffer\"].includes(parser)\n ) {\n throw new Error(\"Invalid file reader parser\");\n }\n\n reader[parser](file);\n });\n }, [\n concurrency,\n stats,\n getFileParser,\n createProgressEventHandler,\n start,\n complete,\n ]);\n\n let accept = \"\";\n if (extensions.length) {\n accept = extensions.reduce((s, ext) => `${s ? `${s},` : \"\"}.${ext}`, \"\");\n }\n\n return {\n stats: statsList,\n errors,\n accept,\n totalBytes,\n totalFiles,\n onDrop,\n onChange,\n reset,\n remove,\n clearErrors,\n };\n}\n"],"names":["nanoid","useCallback","useEffect","useReducer","getFileParser","defaultGetFileParser","FileAccessError","isValidFileName","defaultIsValidFileName","validateFiles","defaultValidateFiles","noop","EMPTY_LIST","EMPTY_OBJECT","useFileUpload","options","maxFiles","extensions","minFileSize","maxFileSize","totalFileSize","concurrency","onDrop","propOnDrop","onChange","propOnChange","state","dispatch","reducer","action","type","stats","errors","readers","key","files","includes","reduce","file","progress","status","reader","fileStats","result","_reader","statsList","Object","values","totalFiles","length","totalBytes","size","queueFiles","pending","event","preventDefault","stopPropagation","dataTransfer","Array","from","e","Error","message","undefined","currentTarget","remove","keyOrKeys","forEach","fileKey","abort","reset","clearErrors","start","complete","createProgressEventHandler","lengthComputable","percentage","Math","round","loaded","total","uploading","push","lastIndex","max","queue","slice","FileReader","addEventListener","parser","process","env","NODE_ENV","accept","s","ext"],"mappings":"AAAA;AAEA,SAASA,MAAM,QAAQ,SAAS;AAChC,SAGEC,WAAW,EACXC,SAAS,EACTC,UAAU,QACL,QAAQ;AAEf,SAOEC,iBAAiBC,oBAAoB,QAChC,aAAa;AACpB,SACEC,eAAe,EAIfC,mBAAmBC,sBAAsB,EACzCC,iBAAiBC,oBAAoB,QAChC,kBAAkB;AAEzB,MAAMC,OAAO;AACX,aAAa;AACf;AAqKA,cAAc,GACd,MAAMC,aAAa,EAAE;AACrB,cAAc,GACd,MAAMC,eAAe,CAAC;AAEtB;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASC,cACdC,UAA6C,CAAC,CAAC;IAE/C,MAAM,EACJC,WAAW,CAAC,CAAC,EACbC,aAAaL,UAAU,EACvBM,cAAc,CAAC,CAAC,EAChBC,cAAc,CAAC,CAAC,EAChBC,gBAAgB,CAAC,CAAC,EAClBC,cAAc,CAAC,CAAC,EAChBC,QAAQC,aAAaZ,IAAI,EACzBa,UAAUC,eAAed,IAAI,EAC7BF,gBAAgBC,oBAAoB,EACpCN,gBAAgBC,oBAAoB,EACpCE,kBAAkBC,sBAAsB,EACzC,GAAGO;IAEJ,MAAM,CAACW,OAAOC,SAAS,GAAGxB,WACxB,SAASyB,QACPF,KAAuC,EACvCG,MAA2B;QAE3B,OAAQA,OAAOC,IAAI;YACjB,KAAK;gBACH,iEAAiE;gBACjE,6BAA6B;gBAC7B,OAAO;oBACLC,OAAOlB;oBACPmB,QAAQpB;oBACRqB,SAASpB;gBACX;YACF,KAAK;gBAAU;oBACb,MAAMkB,QAAyC,CAAC;oBAChD,IAAK,MAAMG,OAAOR,MAAMK,KAAK,CAAE;wBAC7B,IAAI,CAACF,OAAOM,KAAK,CAACC,QAAQ,CAACF,MAAM;4BAC/BH,K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C/D;gBACA,MAAM,IAAI5B,MAAM;YAClB;YAEApB,MAAM,CAACgD,OAAO,CAACnD;QACjB;IACF,GAAG;QACDjB;QACAU;QACA3B;QACAsE;QACAF;QACAC;KACD;IAED,IAAIoB,SAAS;IACb,IAAI5E,WAAWgC,MAAM,EAAE;QACrB4C,SAAS5E,WAAWoB,MAAM,CAAC,CAACyD,GAAGC,MAAQ,GAAGD,IAAI,GAAGA,EAAE,CAAC,CAAC,GAAG,GAAG,CAAC,EAAEC,KAAK,EAAE;IACvE;IAEA,OAAO;QACLhE,OAAOc;QACPb;QACA6D;QACA3C;QACAF;QACA1B;QACAE;QACA8C;QACAL;QACAM;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/files/validation.ts"],"sourcesContent":["import { nanoid } from \"nanoid\";\n\n/**\n * An error that will be created if a user tries dragging and dropping files\n * from a shared directory that they do not have access to. This error will not\n * occur much.\n *\n * @since 2.9.0\n */\nexport class FileAccessError extends Error {\n /**\n * A unique key generated by `nanoid` that can be used as a `React` key\n */\n public key: string;\n\n /**\n *\n * @param message - An optional message for the error.\n */\n constructor(message?: string) {\n super(message);\n this.key = nanoid();\n this.name = \"FileAccessError\";\n }\n}\n\n/**\n * An error that just requires a `File` to be passed as the first argument.\n *\n * @since 2.9.0\n */\nexport class GenericFileError extends Error {\n /**\n * A unique key generated by `nanoid` that can be used as a `React` key\n */\n public key: string;\n\n /**\n *\n * @param files - A list of files that caused the error.\n * @param reason - An optional reason for the error\n */\n constructor(\n public files: readonly File[],\n public reason?: string\n ) {\n super(\"Invalid files\");\n this.key = nanoid();\n this.name = \"GenericFileError\";\n }\n}\n\n/**\n * An error that is created during the upload process if the number of files\n * exceeds the {@link FileUploadOptions.maxFiles} amount.\n *\n * @since 2.9.0\n */\nexport class TooManyFilesError extends GenericFileError {\n /**\n *\n * @param files - The list of files that could not be uploaded due to the file\n * limit defined.\n * @param limit - The max limit of files allowed.\n */\n constructor(\n files: readonly File[],\n public limit: number\n ) {\n super(files, \"file limit\");\n this.name = \"TooManyFilesError\";\n }\n}\n\n/**\n * An error that will be created if a user tries to upload a file that\n * is either:\n * - less than the {@link FileValidationOptions.minFileSize}\n * - greater than the {@link FileValidationOptions.maxFileSize}\n * - including the file would be greater than the {@link FileValidationOptions.totalFileSize}\n *\n * @since 2.9.0\n */\nexport class FileSizeError extends GenericFileError {\n /**\n *\n * @param files - The list of files that have the file size error\n * @param type - The file size error type\n * @param limit - The number of bytes allowed based on the type\n */\n constructor(\n files: readonly File[],\n public type: \"min\" | \"max\" | \"total\",\n public limit: number\n ) {\n super(files, \"file size\");\n this.name = \"FileSizeError\";\n }\n}\n\n/**\n * An error that will be created if a user tries to upload a file that does not\n * end with one of the {@link FileValidationOptions.extensions}.\n *\n * @since 2.9.0\n */\nexport class FileExtensionError extends GenericFileError {\n /**\n *\n * @param files - The file that caused the error\n * @param extensions - The allowed list of file extensions\n */\n constructor(\n files: readonly File[],\n public extensions: readonly string[]\n ) {\n super(files, \"extension\");\n this.name = \"FileExtensionError\";\n }\n}\n\n/**\n * Mostly an internal type that is used to allow custom validation errors\n *\n * @since 2.9.0\n */\nexport type FileValidationError<E = GenericFileError> =\n | FileAccessError\n | TooManyFilesError\n | FileSizeError\n | FileExtensionError\n | E;\n\n/**\n * A simple type-guard that can be used to check if the\n * {@link FileValidationError} is the {@link GenericFileError} which can be\n * useful when displaying the errors to the user.\n *\n * @param error - The error to check\n * @returns true if the error is a {@link FileAccessError}\n */\nexport function isGenericFileError<CustomError extends object>(\n error: FileValidationError<CustomError>\n): error is GenericFileError {\n return \"name\" in error && error.name === \"GenericFileError\";\n}\n\n/**\n * A simple type-guard that can be used to check if the\n * {@link FileValidationError} is the {@link FileAccessError} which can be\n * useful when displaying the errors to the user.\n *\n * @param error - The error to check\n * @returns true if the error is a {@link FileAccessError}\n */\nexport function isFileAccessError<CustomError extends object>(\n error: FileValidationError<CustomError>\n): error is FileAccessError {\n return \"name\" in error && error.name === \"FileAccessError\";\n}\n\n/**\n * A simple type-guard that can be used to check if the\n * {@link FileValidationError} is the {@link TooManyFilesError} which can be\n * useful when displaying the errors to the user.\n *\n * @param error - The error to check\n * @returns true if the error is a {@link TooManyFilesError}\n */\nexport function isTooManyFilesError<CustomError extends object>(\n error: FileValidationError<CustomError>\n): error is TooManyFilesError {\n return \"name\" in error && error.name === \"TooManyFilesError\";\n}\n\n/**\n * A simple type-guard that can be used to check if the\n * {@link FileValidationError} is the {@link FileSizeError} which can be\n * useful when displaying the errors to the user.\n *\n * @param error - The error to check\n * @returns true if the error is a {@link FileSizeError}\n */\nexport function isFileSizeError<CustomError extends object>(\n error: FileValidationError<CustomError>\n): error is FileSizeError {\n return \"name\" in error && error.name === \"FileSizeError\";\n}\n\n/**\n * A simple type-guard that can be used to check if the\n * {@link FileValidationError} is the {@link FileExtensionError} which can be\n * useful when displaying the errors to the user.\n *\n * @param error - The error to check\n * @returns true if the error is a {@link FileExtensionError}\n */\nexport function isFileExtensionError<CustomError extends object>(\n error: FileValidationError<CustomError>\n): error is FileExtensionError {\n return \"name\" in error && error.name === \"FileExtensionError\";\n}\n\n/**\n * This function is used to determine if a file should be added to the\n * {@link FileExtensionError}. The default implementation should work for most\n * use cases except when files that do not have extensions can be uploaded. i.e.\n * LICENSE files.\n *\n * @param file - The file being checked\n * @param extensionRegExp - A regex that will only be defined if the\n * `extensions` list had at least one value.\n * @param extensions - The list of extensions allowed\n * @returns true if the file has a valid name.\n * @since 3.1.0\n */\nexport type IsValidFileName = (\n file: File,\n extensionRegExp: RegExp | undefined,\n extensions: readonly string[]\n) => boolean;\n\n/**\n *\n * @defaultValue `matcher?.test(file.name) ?? true`\n * @since 3.1.0\n */\nexport const isValidFileName: IsValidFileName = (file, matcher) =>\n matcher?.test(file.name) ?? true;\n\n/** @since 2.9.0 */\nexport interface FileValidationOptions {\n /**\n * If the number of files should be limited, set this value to a number\n * greater than `0`.\n *\n * Note: This still allows \"infinite\" files when set to `0` since the\n * `<input>` element should normally be set to `disabled` if files should not\n * be able to be uploaded.\n *\n * @defaultValue `-1`\n */\n maxFiles?: number;\n\n /**\n * An optional minimum file size to enforce for each file. This will only be\n * used when it is greater than `0`.\n *\n * @defaultValue `-1`\n */\n minFileSize?: number;\n\n /**\n * An optional maximum file size to enforce for each file. This will only be\n * used when it is greater than `0`.\n *\n * @defaultValue `-1`\n */\n maxFileSize?: number;\n\n /**\n * An optional list of extensions to enforce when uploading files.\n *\n * Note: The extensions and file names will be compared ignoring case.\n *\n * @example Only Allow Images\n * ```ts\n * const extensions = [\"png\", \"jpeg\", \"jpg\", \"gif\"];\n * ```\n */\n extensions?: readonly string[];\n\n /** {@inheritDoc IsValidFileName} */\n isValidFileName?: IsValidFileName;\n\n /**\n * An optional total file size to enforce when the {@link maxFiles} option is\n * not set to `1`.\n *\n * @defaultValue `-1`\n */\n totalFileSize?: number;\n}\n\n/** @since 2.9.0 */\nexport interface FilesValidationOptions\n extends Required<FileValidationOptions> {\n /**\n * The total number of bytes in the {@link FileUploadHookReturnValue.stats}\n * list. This is really just:\n *\n * ```ts\n * const totalBytes = stats.reduce((total, stat) => total + stat.file.size, 0);\n * ```\n */\n totalBytes: number;\n\n /**\n * The total number of files in the {@link FileUploadHookReturnValue.stats}.\n */\n totalFiles: number;\n}\n\n/**\n * @since 2.9.0\n */\nexport interface ValidatedFilesResult<CustomError> {\n /**\n * A filtered list of files that have been validated and can be queued for the\n * upload process.\n */\n pending: readonly File[];\n\n /**\n * A list of {@link FileValidationError} that occurred during the validation\n * step.\n *\n * Note: If an error has occurred, the file **should not** be added to the\n * {@link pending} list of files.\n */\n errors: readonly FileValidationError<CustomError>[];\n}\n\n/**\n * This function will be called whenever a file has been uploaded by the user\n * either through an `<input type=\"file\">` or drag and drop behavior.\n *\n * @example Simple Example\n * ```ts\n * const validateFiles: FilesValidator = (files, options) => {\n * const invalid: File[] = [];\n * const pending: File[] = [];\n * for (const file of files) {\n * if (!/\\.(jpe?g|svg|png)$/i.test(name)) {\n * invalid.push(file);\n * } else {\n * pending.push(file);\n * }\n * }\n *\n * const errors: FileValidationError[] = [];\n * if (invalid.length) {\n * errors.push(new GenericFileError(invalid))\n * }\n *\n * return { pending, errors };\n * };\n * ```\n *\n * @typeParam E - An optional custom file validation error.\n * @param files - The list of files to check\n * @param options - The {@link FilesValidationOptions}\n * @returns the {@link ValidatedFilesResult}\n * @see {@link validateFiles} for the default implementation\n * @since 2.9.0\n */\nexport type FilesValidator<CustomError = never> = (\n files: readonly File[],\n options: FilesValidationOptions\n) => ValidatedFilesResult<CustomError>;\n\n/**\n * A pretty decent default implementation for validating files with the\n * {@link useFileUpload} that ensures the {@link FilesValidationOptions} are\n * enforced before allowing a file to be uploaded.\n *\n * @typeParam E - An optional custom file validation error.\n * @param files - The list of files to check\n * @param options - The {@link FilesValidationOptions}\n * @returns the {@link ValidatedFilesResult}\n * @since 2.9.0\n */\nexport function validateFiles<CustomError>(\n files: readonly File[],\n options: FilesValidationOptions\n): ValidatedFilesResult<CustomError> {\n const {\n maxFiles,\n extensions,\n minFileSize,\n maxFileSize,\n totalBytes,\n totalFiles,\n totalFileSize,\n isValidFileName,\n } = options;\n\n const errors: FileValidationError<CustomError>[] = [];\n const pending: File[] = [];\n const extraFiles: File[] = [];\n const extensionRegExp =\n extensions.length > 0\n ? new RegExp(`\\\\.(${extensions.join(\"|\")})$`, \"i\")\n : undefined;\n\n let maxFilesReached = maxFiles > 0 && totalFiles >= maxFiles;\n let remainingBytes = totalFileSize - totalBytes;\n const extensionErrors: File[] = [];\n const minErrors: File[] = [];\n const maxErrors: File[] = [];\n const totalSizeErrors: File[] = [];\n for (let i = 0; i < files.length; i += 1) {\n const file = files[i];\n\n let valid = true;\n const { size } = file;\n if (!isValidFileName(file, extensionRegExp, extensions)) {\n valid = false;\n extensionErrors.push(file);\n }\n\n if (minFileSize > 0 && size < minFileSize) {\n valid = false;\n minErrors.push(file);\n }\n\n if (maxFileSize > 0 && size > maxFileSize) {\n valid = false;\n maxErrors.push(file);\n } else if (totalFileSize > 0 && remainingBytes - file.size < 0) {\n // don't want both errors displaying\n valid = false;\n totalSizeErrors.push(file);\n }\n\n if (maxFilesReached && valid) {\n extraFiles.push(file);\n } else if (!maxFilesReached && valid) {\n pending.push(file);\n remainingBytes -= file.size;\n maxFilesReached =\n maxFilesReached ||\n (maxFiles > 0 && totalFiles + pending.length >= maxFiles);\n }\n }\n\n if (extensionErrors.length) {\n errors.push(new FileExtensionError(extensionErrors, extensions));\n }\n\n if (minErrors.length) {\n errors.push(new FileSizeError(minErrors, \"min\", minFileSize));\n }\n\n if (maxErrors.length) {\n errors.push(new FileSizeError(maxErrors, \"max\", maxFileSize));\n }\n\n if (totalSizeErrors.length) {\n errors.push(new FileSizeError(totalSizeErrors, \"total\", totalFileSize));\n }\n\n if (extraFiles.length) {\n errors.push(new TooManyFilesError(extraFiles, maxFiles));\n }\n\n return { pending, errors };\n}\n"],"names":["nanoid","FileAccessError","Error","message","key","name","GenericFileError","files","reason","TooManyFilesError","limit","FileSizeError","type","FileExtensionError","extensions","isGenericFileError","error","isFileAccessError","isTooManyFilesError","isFileSizeError","isFileExtensionError","isValidFileName","file","matcher","test","validateFiles","options","maxFiles","minFileSize","maxFileSize","totalBytes","totalFiles","totalFileSize","errors","pending","extraFiles","extensionRegExp","length","RegExp","join","undefined","maxFilesReached","remainingBytes","extensionErrors","minErrors","maxErrors","totalSizeErrors","i","valid","size","push"],"mappings":";;;;;;;;;;;;;AAAA,SAASA,MAAM,QAAQ,SAAS;AAEhC;;;;;;CAMC,GACD,OAAO,MAAMC,wBAAwBC;IAMnC;;;GAGC,GACD,YAAYC,OAAgB,CAAE;QAC5B,KAAK,CAACA,UAVR;;GAEC,GACD,uBAAOC,OAAP,KAAA;QAQE,IAAI,CAACA,GAAG,GAAGJ;QACX,IAAI,CAACK,IAAI,GAAG;IACd;AACF;AAEA;;;;CAIC,GACD,OAAO,MAAMC,yBAAyBJ;IAMpC;;;;GAIC,GACD,YACE,AAAOK,KAAsB,EAC7B,AAAOC,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,KAAKU,iBAAiBpB,KAAK2B,IAAI,GAAG,GAAG;YAC9D,oCAAoC;YACpCD,QAAQ;YACRF,gBAAgBI,IAAI,CAAC5B;QACvB;QAEA,IAAImB,mBAAmBO,OAAO;YAC5Bb,WAAWe,IAAI,CAAC5B;QAClB,OAAO,IAAI,CAACmB,mBAAmBO,OAAO;YACpCd,QAAQgB,IAAI,CAAC5B;YACboB,kBAAkBpB,KAAK2B,IAAI;YAC3BR,kBACEA,mBACCd,WAAW,KAAKI,aAAaG,QAAQG,MAAM,IAAIV;QACpD;IACF;IAEA,IAAIgB,gBAAgBN,MAAM,EAAE;QAC1BJ,OAAOiB,IAAI,CAAC,IAAIrC,mBAAmB8B,iBAAiB7B;IACtD;IAEA,IAAI8B,UAAUP,MAAM,EAAE;QACpBJ,OAAOiB,IAAI,CAAC,IAAIvC,cAAciC,WAAW,OAAOhB;IAClD;IAEA,IAAIiB,UAAUR,MAAM,EAAE;QACpBJ,OAAOiB,IAAI,CAAC,IAAIvC,cAAckC,WAAW,OAAOhB;IAClD;IAEA,IAAIiB,gBAAgBT,MAAM,EAAE;QAC1BJ,OAAOiB,IAAI,CAAC,IAAIvC,cAAcmC,iBAAiB,SAASd;IAC1D;IAEA,IAAIG,WAAWE,MAAM,EAAE;QACrBJ,OAAOiB,IAAI,CAAC,IAAIzC,kBAAkB0B,YAAYR;IAChD;IAEA,OAAO;QAAEO;QAASD;IAAO;AAC3B"}
1
+ {"version":3,"sources":["../../src/files/validation.ts"],"sourcesContent":["import { nanoid } from \"nanoid\";\n\n/**\n * An error that will be created if a user tries dragging and dropping files\n * from a shared directory that they do not have access to. This error will not\n * occur much.\n *\n * @since 2.9.0\n */\nexport class FileAccessError extends Error {\n /**\n * A unique key generated by `nanoid` that can be used as a `React` key\n */\n public key: string;\n\n /**\n *\n * @param message - An optional message for the error.\n */\n constructor(message?: string) {\n super(message);\n this.key = nanoid();\n this.name = \"FileAccessError\";\n }\n}\n\n/**\n * An error that just requires a `File` to be passed as the first argument.\n *\n * @since 2.9.0\n */\nexport class GenericFileError extends Error {\n /**\n * A unique key generated by `nanoid` that can be used as a `React` key\n */\n public key: string;\n\n /**\n *\n * @param files - A list of files that caused the error.\n * @param reason - An optional reason for the error\n */\n constructor(\n public files: readonly File[],\n public reason?: string\n ) {\n super(\"Invalid files\");\n this.key = nanoid();\n this.name = \"GenericFileError\";\n }\n}\n\n/**\n * An error that is created during the upload process if the number of files\n * exceeds the {@link FileUploadOptions.maxFiles} amount.\n *\n * @since 2.9.0\n */\nexport class TooManyFilesError extends GenericFileError {\n /**\n *\n * @param files - The list of files that could not be uploaded due to the file\n * limit defined.\n * @param limit - The max limit of files allowed.\n */\n constructor(\n files: readonly File[],\n public limit: number\n ) {\n super(files, \"file limit\");\n this.name = \"TooManyFilesError\";\n }\n}\n\n/**\n * An error that will be created if a user tries to upload a file that\n * is either:\n * - less than the {@link FileValidationOptions.minFileSize}\n * - greater than the {@link FileValidationOptions.maxFileSize}\n * - including the file would be greater than the {@link FileValidationOptions.totalFileSize}\n *\n * @since 2.9.0\n */\nexport class FileSizeError extends GenericFileError {\n /**\n *\n * @param files - The list of files that have the file size error\n * @param type - The file size error type\n * @param limit - The number of bytes allowed based on the type\n */\n constructor(\n files: readonly File[],\n public type: \"min\" | \"max\" | \"total\",\n public limit: number\n ) {\n super(files, \"file size\");\n this.name = \"FileSizeError\";\n }\n}\n\n/**\n * An error that will be created if a user tries to upload a file that does not\n * end with one of the {@link FileValidationOptions.extensions}.\n *\n * @since 2.9.0\n */\nexport class FileExtensionError extends GenericFileError {\n /**\n *\n * @param files - The file that caused the error\n * @param extensions - The allowed list of file extensions\n */\n constructor(\n files: readonly File[],\n public extensions: readonly string[]\n ) {\n super(files, \"extension\");\n this.name = \"FileExtensionError\";\n }\n}\n\n/**\n * Mostly an internal type that is used to allow custom validation errors\n *\n * @since 2.9.0\n */\nexport type FileValidationError<E = GenericFileError> =\n | FileAccessError\n | TooManyFilesError\n | FileSizeError\n | FileExtensionError\n | E;\n\n/**\n * A simple type-guard that can be used to check if the\n * {@link FileValidationError} is the {@link GenericFileError} which can be\n * useful when displaying the errors to the user.\n *\n * @param error - The error to check\n * @returns true if the error is a {@link FileAccessError}\n */\nexport function isGenericFileError<CustomError extends object>(\n error: FileValidationError<CustomError>\n): error is GenericFileError {\n return \"name\" in error && error.name === \"GenericFileError\";\n}\n\n/**\n * A simple type-guard that can be used to check if the\n * {@link FileValidationError} is the {@link FileAccessError} which can be\n * useful when displaying the errors to the user.\n *\n * @param error - The error to check\n * @returns true if the error is a {@link FileAccessError}\n */\nexport function isFileAccessError<CustomError extends object>(\n error: FileValidationError<CustomError>\n): error is FileAccessError {\n return \"name\" in error && error.name === \"FileAccessError\";\n}\n\n/**\n * A simple type-guard that can be used to check if the\n * {@link FileValidationError} is the {@link TooManyFilesError} which can be\n * useful when displaying the errors to the user.\n *\n * @param error - The error to check\n * @returns true if the error is a {@link TooManyFilesError}\n */\nexport function isTooManyFilesError<CustomError extends object>(\n error: FileValidationError<CustomError>\n): error is TooManyFilesError {\n return \"name\" in error && error.name === \"TooManyFilesError\";\n}\n\n/**\n * A simple type-guard that can be used to check if the\n * {@link FileValidationError} is the {@link FileSizeError} which can be\n * useful when displaying the errors to the user.\n *\n * @param error - The error to check\n * @returns true if the error is a {@link FileSizeError}\n */\nexport function isFileSizeError<CustomError extends object>(\n error: FileValidationError<CustomError>\n): error is FileSizeError {\n return \"name\" in error && error.name === \"FileSizeError\";\n}\n\n/**\n * A simple type-guard that can be used to check if the\n * {@link FileValidationError} is the {@link FileExtensionError} which can be\n * useful when displaying the errors to the user.\n *\n * @param error - The error to check\n * @returns true if the error is a {@link FileExtensionError}\n */\nexport function isFileExtensionError<CustomError extends object>(\n error: FileValidationError<CustomError>\n): error is FileExtensionError {\n return \"name\" in error && error.name === \"FileExtensionError\";\n}\n\n/**\n * This function is used to determine if a file should be added to the\n * {@link FileExtensionError}. The default implementation should work for most\n * use cases except when files that do not have extensions can be uploaded. i.e.\n * LICENSE files.\n *\n * @param file - The file being checked\n * @param extensionRegExp - A regex that will only be defined if the\n * `extensions` list had at least one value.\n * @param extensions - The list of extensions allowed\n * @returns true if the file has a valid name.\n * @since 3.1.0\n */\nexport type IsValidFileName = (\n file: File,\n extensionRegExp: RegExp | undefined,\n extensions: readonly string[]\n) => boolean;\n\n/**\n *\n * @defaultValue `matcher?.test(file.name) ?? true`\n * @since 3.1.0\n */\nexport const isValidFileName: IsValidFileName = (file, matcher) =>\n matcher?.test(file.name) ?? true;\n\n/** @since 2.9.0 */\nexport interface FileValidationOptions {\n /**\n * If the number of files should be limited, set this value to a number\n * greater than `0`.\n *\n * Note: This still allows \"infinite\" files when set to `0` since the\n * `<input>` element should normally be set to `disabled` if files should not\n * be able to be uploaded.\n *\n * @defaultValue `-1`\n */\n maxFiles?: number;\n\n /**\n * An optional minimum file size to enforce for each file. This will only be\n * used when it is greater than `0`.\n *\n * @defaultValue `-1`\n */\n minFileSize?: number;\n\n /**\n * An optional maximum file size to enforce for each file. This will only be\n * used when it is greater than `0`.\n *\n * @defaultValue `-1`\n */\n maxFileSize?: number;\n\n /**\n * An optional list of extensions to enforce when uploading files.\n *\n * Note: The extensions and file names will be compared ignoring case.\n *\n * @example Only Allow Images\n * ```ts\n * const extensions = [\"png\", \"jpeg\", \"jpg\", \"gif\"];\n * ```\n */\n extensions?: readonly string[];\n\n /** {@inheritDoc IsValidFileName} */\n isValidFileName?: IsValidFileName;\n\n /**\n * An optional total file size to enforce when the {@link maxFiles} option is\n * not set to `1`.\n *\n * @defaultValue `-1`\n */\n totalFileSize?: number;\n}\n\n/** @since 2.9.0 */\nexport interface FilesValidationOptions extends Required<FileValidationOptions> {\n /**\n * The total number of bytes in the {@link FileUploadHookReturnValue.stats}\n * list. This is really just:\n *\n * ```ts\n * const totalBytes = stats.reduce((total, stat) => total + stat.file.size, 0);\n * ```\n */\n totalBytes: number;\n\n /**\n * The total number of files in the {@link FileUploadHookReturnValue.stats}.\n */\n totalFiles: number;\n}\n\n/**\n * @since 2.9.0\n */\nexport interface ValidatedFilesResult<CustomError> {\n /**\n * A filtered list of files that have been validated and can be queued for the\n * upload process.\n */\n pending: readonly File[];\n\n /**\n * A list of {@link FileValidationError} that occurred during the validation\n * step.\n *\n * Note: If an error has occurred, the file **should not** be added to the\n * {@link pending} list of files.\n */\n errors: readonly FileValidationError<CustomError>[];\n}\n\n/**\n * This function will be called whenever a file has been uploaded by the user\n * either through an `<input type=\"file\">` or drag and drop behavior.\n *\n * @example Simple Example\n * ```ts\n * const validateFiles: FilesValidator = (files, options) => {\n * const invalid: File[] = [];\n * const pending: File[] = [];\n * for (const file of files) {\n * if (!/\\.(jpe?g|svg|png)$/i.test(name)) {\n * invalid.push(file);\n * } else {\n * pending.push(file);\n * }\n * }\n *\n * const errors: FileValidationError[] = [];\n * if (invalid.length) {\n * errors.push(new GenericFileError(invalid))\n * }\n *\n * return { pending, errors };\n * };\n * ```\n *\n * @typeParam E - An optional custom file validation error.\n * @param files - The list of files to check\n * @param options - The {@link FilesValidationOptions}\n * @returns the {@link ValidatedFilesResult}\n * @see {@link validateFiles} for the default implementation\n * @since 2.9.0\n */\nexport type FilesValidator<CustomError = never> = (\n files: readonly File[],\n options: FilesValidationOptions\n) => ValidatedFilesResult<CustomError>;\n\n/**\n * A pretty decent default implementation for validating files with the\n * {@link useFileUpload} that ensures the {@link FilesValidationOptions} are\n * enforced before allowing a file to be uploaded.\n *\n * @typeParam E - An optional custom file validation error.\n * @param files - The list of files to check\n * @param options - The {@link FilesValidationOptions}\n * @returns the {@link ValidatedFilesResult}\n * @since 2.9.0\n */\nexport function validateFiles<CustomError>(\n files: readonly File[],\n options: FilesValidationOptions\n): ValidatedFilesResult<CustomError> {\n const {\n maxFiles,\n extensions,\n minFileSize,\n maxFileSize,\n totalBytes,\n totalFiles,\n totalFileSize,\n isValidFileName,\n } = options;\n\n const errors: FileValidationError<CustomError>[] = [];\n const pending: File[] = [];\n const extraFiles: File[] = [];\n const extensionRegExp =\n extensions.length > 0\n ? new RegExp(`\\\\.(${extensions.join(\"|\")})$`, \"i\")\n : undefined;\n\n let maxFilesReached = maxFiles > 0 && totalFiles >= maxFiles;\n let remainingBytes = totalFileSize - totalBytes;\n const extensionErrors: File[] = [];\n const minErrors: File[] = [];\n const maxErrors: File[] = [];\n const totalSizeErrors: File[] = [];\n for (let i = 0; i < files.length; i += 1) {\n const file = files[i];\n\n let valid = true;\n const { size } = file;\n if (!isValidFileName(file, extensionRegExp, extensions)) {\n valid = false;\n extensionErrors.push(file);\n }\n\n if (minFileSize > 0 && size < minFileSize) {\n valid = false;\n minErrors.push(file);\n }\n\n if (maxFileSize > 0 && size > maxFileSize) {\n valid = false;\n maxErrors.push(file);\n } else if (totalFileSize > 0 && remainingBytes - file.size < 0) {\n // don't want both errors displaying\n valid = false;\n totalSizeErrors.push(file);\n }\n\n if (maxFilesReached && valid) {\n extraFiles.push(file);\n } else if (!maxFilesReached && valid) {\n pending.push(file);\n remainingBytes -= file.size;\n maxFilesReached =\n maxFilesReached ||\n (maxFiles > 0 && totalFiles + pending.length >= maxFiles);\n }\n }\n\n if (extensionErrors.length) {\n errors.push(new FileExtensionError(extensionErrors, extensions));\n }\n\n if (minErrors.length) {\n errors.push(new FileSizeError(minErrors, \"min\", minFileSize));\n }\n\n if (maxErrors.length) {\n errors.push(new FileSizeError(maxErrors, \"max\", maxFileSize));\n }\n\n if (totalSizeErrors.length) {\n errors.push(new FileSizeError(totalSizeErrors, \"total\", totalFileSize));\n }\n\n if (extraFiles.length) {\n errors.push(new TooManyFilesError(extraFiles, maxFiles));\n }\n\n return { pending, errors };\n}\n"],"names":["nanoid","FileAccessError","Error","message","key","name","GenericFileError","files","reason","TooManyFilesError","limit","FileSizeError","type","FileExtensionError","extensions","isGenericFileError","error","isFileAccessError","isTooManyFilesError","isFileSizeError","isFileExtensionError","isValidFileName","file","matcher","test","validateFiles","options","maxFiles","minFileSize","maxFileSize","totalBytes","totalFiles","totalFileSize","errors","pending","extraFiles","extensionRegExp","length","RegExp","join","undefined","maxFilesReached","remainingBytes","extensionErrors","minErrors","maxErrors","totalSizeErrors","i","valid","size","push"],"mappings":";;;;;;;;;;;;;AAAA,SAASA,MAAM,QAAQ,SAAS;AAEhC;;;;;;CAMC,GACD,OAAO,MAAMC,wBAAwBC;IAMnC;;;GAGC,GACD,YAAYC,OAAgB,CAAE;QAC5B,KAAK,CAACA,UAVR;;GAEC,GACD,uBAAOC,OAAP,KAAA;QAQE,IAAI,CAACA,GAAG,GAAGJ;QACX,IAAI,CAACK,IAAI,GAAG;IACd;AACF;AAEA;;;;CAIC,GACD,OAAO,MAAMC,yBAAyBJ;IAMpC;;;;GAIC,GACD,YACE,AAAOK,KAAsB,EAC7B,AAAOC,MAAe,CACtB;QACA,KAAK,CAAC,qGAdR;;GAEC,GACD,uBAAOJ,OAAP,KAAA,SAQSG,QAAAA,YACAC,SAAAA;QAGP,IAAI,CAACJ,GAAG,GAAGJ;QACX,IAAI,CAACK,IAAI,GAAG;IACd;AACF;AAEA;;;;;CAKC,GACD,OAAO,MAAMI,0BAA0BH;IACrC;;;;;GAKC,GACD,YACEC,KAAsB,EACtB,AAAOG,KAAa,CACpB;QACA,KAAK,CAACH,OAAO,6DAFNG,QAAAA;QAGP,IAAI,CAACL,IAAI,GAAG;IACd;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,MAAMM,sBAAsBL;IACjC;;;;;GAKC,GACD,YACEC,KAAsB,EACtB,AAAOK,IAA6B,EACpC,AAAOF,KAAa,CACpB;QACA,KAAK,CAACH,OAAO,oGAHNK,OAAAA,WACAF,QAAAA;QAGP,IAAI,CAACL,IAAI,GAAG;IACd;AACF;AAEA;;;;;CAKC,GACD,OAAO,MAAMQ,2BAA2BP;IACtC;;;;GAIC,GACD,YACEC,KAAsB,EACtB,AAAOO,UAA6B,CACpC;QACA,KAAK,CAACP,OAAO,iEAFNO,aAAAA;QAGP,IAAI,CAACT,IAAI,GAAG;IACd;AACF;AAcA;;;;;;;CAOC,GACD,OA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E;QACrBJ,OAAOiB,IAAI,CAAC,IAAIzC,kBAAkB0B,YAAYR;IAChD;IAEA,OAAO;QAAEO;QAASD;IAAO;AAC3B"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/focus/useFocusContainer.ts"],"sourcesContent":["\"use client\";\n\nimport {\n type KeyboardEventHandler,\n type Ref,\n type RefObject,\n useEffect,\n useRef,\n} from \"react\";\n\nimport { getTransitionCallbacks } from \"../transition/getTransitionCallbacks.js\";\nimport { type TransitionCallbacks } from \"../transition/types.js\";\nimport { useEnsuredRef } from \"../useEnsuredRef.js\";\nimport {\n type FocusElementWithinType,\n focusElementWithin,\n getFocusableElements,\n} from \"./utils.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n * `\"mount\"` - this will attempt to focus the container element if:\n * - there is no `document.activeElement`\n * - the container element does not contain the `document.activeElement`\n *\n * `\"unmount\"` - attempts to re-focus the element that was focused before the\n * focus container became active. The previous focus element is captured\n * whenever the `activate` option on the `useFocusContainer` hook is set to\n * `true`. This is normally when an element becomes `visible`.\n *\n * `\"keyboard\"` - refocuses the first focusable element if pressing `Tab` would\n * move the focus outside of the container element. If `Shift + Tab` was used,\n * the last focusable element will be used instead.\n *\n * @since 6.0.0\n */\nexport type FocusType = \"mount\" | \"unmount\" | \"keyboard\";\n\n/**\n * @since 6.0.0\n * @deprecated Use `TransitionCallbacks` instead.\n */\nexport type FocusContainerTransitionCallbacks = TransitionCallbacks;\n\n/**\n * @since 6.0.0\n * @since 6.3.2 Fixed by extending `TransitionCallbacks` after the\n * `onEnteredOnce` and `onExitedOnce` support was added to CSS transitions.\n */\nexport interface FocusContainerTransitionOptions<E extends HTMLElement>\n extends TransitionCallbacks {\n /**\n * An optional ref that will be merged with the\n * {@link FocusContainerImplementation.nodeRef}\n */\n nodeRef?: Ref<E>;\n}\n\n/** @since 6.0.0 */\nexport interface FocusContainerEventHandlers<E extends HTMLElement> {\n onKeyDown?: KeyboardEventHandler<E>;\n}\n\n/**\n * @since 6.0.0\n */\nexport type IsFocusTypeDisabled = (type: FocusType) => boolean;\n\nexport interface FocusContainerComponentProps {\n /**\n * @defaultValue `() => false`\n */\n isFocusTypeDisabled?: IsFocusTypeDisabled;\n\n /**\n * @defaultValue `false`\n */\n disableTransition?: boolean;\n}\n\n/** @since 6.0.0 */\nexport interface FocusContainerOptions<E extends HTMLElement>\n extends FocusContainerTransitionOptions<E>,\n FocusContainerComponentProps {\n onKeyDown?: KeyboardEventHandler<E>;\n /**\n * This to `true` will capture the current focused element as a focus target\n * once the `onExited` hook is fired. This should usually be set to the\n * `transitionIn` prop for `useTransition`.\n */\n activate: boolean;\n\n /**\n * Set this to true if elements that can be programmatically focused should be\n * included. These would be elements with a `tabIndex={-1}`.\n *\n * @defaultValue `false`\n */\n programmatic?: boolean;\n}\n\n/** @since 6.0.0 */\nexport interface FocusContainerImplementation<E extends HTMLElement> {\n nodeRef: RefObject<E>;\n eventHandlers: Required<FocusContainerEventHandlers<E>>;\n transitionOptions: Required<FocusContainerTransitionOptions<E>>;\n}\n\n/**\n * This hook is mostly for internal use only for dialog accessibility behavior\n * to prevent the focus from moving outside of the dialog while it is visible.\n * This API was developed to be used with the `useCSSTransition`/`useTransition`\n * hooks as well.\n *\n * @example Main Usage\n * ```tsx\n * import { Button } from \"@react-md/core/button/Button\"\n * import { useFocusContainer } from \"@react-md/core/focus/useFocusContainer\"\n * import { useScaleTransition } from \"@react-md/core/transition/useScaleTransition\"\n * import { useToggle } from \"@react-md/core/useToggle\"\n * import { type ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { toggled, enable, disable } = useToggle(false);\n *\n * const { eventHandlers, transitionOptions } = useFocusContainer({\n * activate: toggled,\n * });\n * const { elementProps, rendered } = useScaleTransition({\n * transitionIn: toggled,\n * temporary: true,\n * ...transitionOptions,\n * });\n *\n * return (\n * <>\n * <Button onClick={enable}>Toggle</Button>\n * {rendered && (\n * <div {...eventHandlers} {...elementProps}>\n * <Button onClick={disable}>Button 1</Button>\n * <Button onClick={disable}>Button 2</Button>\n * <Button onClick={disable}>Button 3</Button>\n * <Button onClick={disable}>Button 4</Button>\n * </div>\n * )}\n * </>\n * );\n * }\n * ```\n *\n * @since 6.0.0\n */\nexport function useFocusContainer<E extends HTMLElement>(\n options: FocusContainerOptions<E>\n): FocusContainerImplementation<E> {\n const {\n nodeRef,\n activate,\n onEnter,\n onEntering,\n onEntered,\n onExit,\n onExiting,\n onExited,\n onKeyDown = noop,\n programmatic = false,\n disableTransition = false,\n isFocusTypeDisabled = noop,\n } = options;\n\n const [ref, refCallback] = useEnsuredRef(nodeRef);\n const prevFocus = useRef<HTMLElement | null>(null);\n\n useEffect(() => {\n if (!activate || !(document.activeElement instanceof HTMLElement)) {\n return;\n }\n\n prevFocus.current = document.activeElement;\n }, [activate]);\n\n return {\n nodeRef: ref,\n transitionOptions: {\n nodeRef: refCallback,\n ...getTransitionCallbacks({\n onEnter,\n onEnterOnce: () => {\n const instance = ref.current;\n if (\n instance &&\n !isFocusTypeDisabled(\"mount\") &&\n (!document.activeElement ||\n !instance.contains(document.activeElement))\n ) {\n instance.focus();\n }\n },\n onEntering,\n onEntered,\n onExitOnce: () => {\n if (isFocusTypeDisabled(\"unmount\")) {\n return;\n }\n\n // For some reason, the `\"Enter\"` keydown event fires at a different timing\n // than the Space keydown event.\n window.requestAnimationFrame(() => {\n prevFocus.current?.focus();\n });\n },\n onExit,\n onExiting,\n onExited,\n disableTransition,\n }),\n },\n eventHandlers: {\n onKeyDown(event) {\n onKeyDown(event);\n if (\n event.isPropagationStopped() ||\n event.key !== \"Tab\" ||\n isFocusTypeDisabled(\"keyboard\")\n ) {\n return;\n }\n\n const { target, shiftKey, currentTarget } = event;\n const elements = getFocusableElements(currentTarget, programmatic);\n const count = elements.length;\n if (count === 0) {\n event.preventDefault();\n return;\n }\n\n // if the container element is the current focus, need to either focus\n // the first or last element so focus doesn't escape\n let type: FocusElementWithinType | undefined;\n if (\n count === 1 ||\n (!shiftKey &&\n (target === currentTarget || target === elements[count - 1]))\n ) {\n type = \"first\";\n } else if (\n shiftKey &&\n (target === currentTarget || target === elements[0])\n ) {\n type = \"last\";\n }\n\n if (type) {\n event.preventDefault();\n focusElementWithin({\n type,\n elements,\n container: currentTarget,\n });\n }\n },\n },\n };\n}\n"],"names":["useEffect","useRef","getTransitionCallbacks","useEnsuredRef","focusElementWithin","getFocusableElements","noop","useFocusContainer","options","nodeRef","activate","onEnter","onEntering","onEntered","onExit","onExiting","onExited","onKeyDown","programmatic","disableTransition","isFocusTypeDisabled","ref","refCallback","prevFocus","document","activeElement","HTMLElement","current","transitionOptions","onEnterOnce","instance","contains","focus","onExitOnce","window","requestAnimationFrame","eventHandlers","event","isPropagationStopped","key","target","shiftKey","currentTarget","elements","count","length","preventDefault","type","container"],"mappings":"AAAA;AAEA,SAIEA,SAAS,EACTC,MAAM,QACD,QAAQ;AAEf,SAASC,sBAAsB,QAAQ,0CAA0C;AAEjF,SAASC,aAAa,QAAQ,sBAAsB;AACpD,SAEEC,kBAAkB,EAClBC,oBAAoB,QACf,aAAa;AAEpB,MAAMC,OAAO;AACX,aAAa;AACf;AA0FA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GACD,OAAO,SAASC,kBACdC,OAAiC;IAEjC,MAAM,EACJC,OAAO,EACPC,QAAQ,EACRC,OAAO,EACPC,UAAU,EACVC,SAAS,EACTC,MAAM,EACNC,SAAS,EACTC,QAAQ,EACRC,YAAYX,IAAI,EAChBY,eAAe,KAAK,EACpBC,oBAAoB,KAAK,EACzBC,sBAAsBd,IAAI,EAC3B,GAAGE;IAEJ,MAAM,CAACa,KAAKC,YAAY,GAAGnB,cAAcM;IACzC,MAAMc,YAAYtB,OAA2B;IAE7CD,UAAU;QACR,IAAI,CAACU,YAAY,CAAEc,CAAAA,SAASC,aAAa,YAAYC,WAAU,GAAI;YACjE;QACF;QAEAH,UAAUI,OAAO,GAAGH,SAASC,aAAa;IAC5C,GAAG;QAACf;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F;YACF;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/focus/useFocusContainer.ts"],"sourcesContent":["\"use client\";\n\nimport {\n type KeyboardEventHandler,\n type Ref,\n type RefObject,\n useEffect,\n useRef,\n} from \"react\";\n\nimport { getTransitionCallbacks } from \"../transition/getTransitionCallbacks.js\";\nimport { type TransitionCallbacks } from \"../transition/types.js\";\nimport { useEnsuredRef } from \"../useEnsuredRef.js\";\nimport {\n type FocusElementWithinType,\n focusElementWithin,\n getFocusableElements,\n} from \"./utils.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n * `\"mount\"` - this will attempt to focus the container element if:\n * - there is no `document.activeElement`\n * - the container element does not contain the `document.activeElement`\n *\n * `\"unmount\"` - attempts to re-focus the element that was focused before the\n * focus container became active. The previous focus element is captured\n * whenever the `activate` option on the `useFocusContainer` hook is set to\n * `true`. This is normally when an element becomes `visible`.\n *\n * `\"keyboard\"` - refocuses the first focusable element if pressing `Tab` would\n * move the focus outside of the container element. If `Shift + Tab` was used,\n * the last focusable element will be used instead.\n *\n * @since 6.0.0\n */\nexport type FocusType = \"mount\" | \"unmount\" | \"keyboard\";\n\n/**\n * @since 6.0.0\n * @deprecated Use `TransitionCallbacks` instead.\n */\nexport type FocusContainerTransitionCallbacks = TransitionCallbacks;\n\n/**\n * @since 6.0.0\n * @since 6.3.2 Fixed by extending `TransitionCallbacks` after the\n * `onEnteredOnce` and `onExitedOnce` support was added to CSS transitions.\n */\nexport interface FocusContainerTransitionOptions<\n E extends HTMLElement,\n> extends TransitionCallbacks {\n /**\n * An optional ref that will be merged with the\n * {@link FocusContainerImplementation.nodeRef}\n */\n nodeRef?: Ref<E>;\n}\n\n/** @since 6.0.0 */\nexport interface FocusContainerEventHandlers<E extends HTMLElement> {\n onKeyDown?: KeyboardEventHandler<E>;\n}\n\n/**\n * @since 6.0.0\n */\nexport type IsFocusTypeDisabled = (type: FocusType) => boolean;\n\nexport interface FocusContainerComponentProps {\n /**\n * @defaultValue `() => false`\n */\n isFocusTypeDisabled?: IsFocusTypeDisabled;\n\n /**\n * @defaultValue `false`\n */\n disableTransition?: boolean;\n}\n\n/** @since 6.0.0 */\nexport interface FocusContainerOptions<E extends HTMLElement>\n extends FocusContainerTransitionOptions<E>, FocusContainerComponentProps {\n onKeyDown?: KeyboardEventHandler<E>;\n /**\n * This to `true` will capture the current focused element as a focus target\n * once the `onExited` hook is fired. This should usually be set to the\n * `transitionIn` prop for `useTransition`.\n */\n activate: boolean;\n\n /**\n * Set this to true if elements that can be programmatically focused should be\n * included. These would be elements with a `tabIndex={-1}`.\n *\n * @defaultValue `false`\n */\n programmatic?: boolean;\n}\n\n/** @since 6.0.0 */\nexport interface FocusContainerImplementation<E extends HTMLElement> {\n nodeRef: RefObject<E>;\n eventHandlers: Required<FocusContainerEventHandlers<E>>;\n transitionOptions: Required<FocusContainerTransitionOptions<E>>;\n}\n\n/**\n * This hook is mostly for internal use only for dialog accessibility behavior\n * to prevent the focus from moving outside of the dialog while it is visible.\n * This API was developed to be used with the `useCSSTransition`/`useTransition`\n * hooks as well.\n *\n * @example Main Usage\n * ```tsx\n * import { Button } from \"@react-md/core/button/Button\"\n * import { useFocusContainer } from \"@react-md/core/focus/useFocusContainer\"\n * import { useScaleTransition } from \"@react-md/core/transition/useScaleTransition\"\n * import { useToggle } from \"@react-md/core/useToggle\"\n * import { type ReactElement } from \"react\";\n *\n * function Example(): ReactElement {\n * const { toggled, enable, disable } = useToggle(false);\n *\n * const { eventHandlers, transitionOptions } = useFocusContainer({\n * activate: toggled,\n * });\n * const { elementProps, rendered } = useScaleTransition({\n * transitionIn: toggled,\n * temporary: true,\n * ...transitionOptions,\n * });\n *\n * return (\n * <>\n * <Button onClick={enable}>Toggle</Button>\n * {rendered && (\n * <div {...eventHandlers} {...elementProps}>\n * <Button onClick={disable}>Button 1</Button>\n * <Button onClick={disable}>Button 2</Button>\n * <Button onClick={disable}>Button 3</Button>\n * <Button onClick={disable}>Button 4</Button>\n * </div>\n * )}\n * </>\n * );\n * }\n * ```\n *\n * @since 6.0.0\n */\nexport function useFocusContainer<E extends HTMLElement>(\n options: FocusContainerOptions<E>\n): FocusContainerImplementation<E> {\n const {\n nodeRef,\n activate,\n onEnter,\n onEntering,\n onEntered,\n onExit,\n onExiting,\n onExited,\n onKeyDown = noop,\n programmatic = false,\n disableTransition = false,\n isFocusTypeDisabled = noop,\n } = options;\n\n const [ref, refCallback] = useEnsuredRef(nodeRef);\n const prevFocus = useRef<HTMLElement | null>(null);\n\n useEffect(() => {\n if (!activate || !(document.activeElement instanceof HTMLElement)) {\n return;\n }\n\n prevFocus.current = document.activeElement;\n }, [activate]);\n\n return {\n nodeRef: ref,\n transitionOptions: {\n nodeRef: refCallback,\n ...getTransitionCallbacks({\n onEnter,\n onEnterOnce: () => {\n const instance = ref.current;\n if (\n instance &&\n !isFocusTypeDisabled(\"mount\") &&\n (!document.activeElement ||\n !instance.contains(document.activeElement))\n ) {\n instance.focus();\n }\n },\n onEntering,\n onEntered,\n onExitOnce: () => {\n if (isFocusTypeDisabled(\"unmount\")) {\n return;\n }\n\n // For some reason, the `\"Enter\"` keydown event fires at a different timing\n // than the Space keydown event.\n window.requestAnimationFrame(() => {\n prevFocus.current?.focus();\n });\n },\n onExit,\n onExiting,\n onExited,\n disableTransition,\n }),\n },\n eventHandlers: {\n onKeyDown(event) {\n onKeyDown(event);\n if (\n event.isPropagationStopped() ||\n event.key !== \"Tab\" ||\n isFocusTypeDisabled(\"keyboard\")\n ) {\n return;\n }\n\n const { target, shiftKey, currentTarget } = event;\n const elements = getFocusableElements(currentTarget, programmatic);\n const count = elements.length;\n if (count === 0) {\n event.preventDefault();\n return;\n }\n\n // if the container element is the current focus, need to either focus\n // the first or last element so focus doesn't escape\n let type: FocusElementWithinType | undefined;\n if (\n count === 1 ||\n (!shiftKey &&\n (target === currentTarget || target === elements[count - 1]))\n ) {\n type = \"first\";\n } else if (\n shiftKey &&\n (target === currentTarget || target === elements[0])\n ) {\n type = \"last\";\n }\n\n if (type) {\n event.preventDefault();\n focusElementWithin({\n type,\n elements,\n container: currentTarget,\n });\n }\n },\n },\n };\n}\n"],"names":["useEffect","useRef","getTransitionCallbacks","useEnsuredRef","focusElementWithin","getFocusableElements","noop","useFocusContainer","options","nodeRef","activate","onEnter","onEntering","onEntered","onExit","onExiting","onExited","onKeyDown","programmatic","disableTransition","isFocusTypeDisabled","ref","refCallback","prevFocus","document","activeElement","HTMLElement","current","transitionOptions","onEnterOnce","instance","contains","focus","onExitOnce","window","requestAnimationFrame","eventHandlers","event","isPropagationStopped","key","target","shiftKey","currentTarget","elements","count","length","preventDefault","type","container"],"mappings":"AAAA;AAEA,SAIEA,SAAS,EACTC,MAAM,QACD,QAAQ;AAEf,SAASC,sBAAsB,QAAQ,0CAA0C;AAEjF,SAASC,aAAa,QAAQ,sBAAsB;AACpD,SAEEC,kBAAkB,EAClBC,oBAAoB,QACf,aAAa;AAEpB,MAAMC,OAAO;AACX,aAAa;AACf;AA0FA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GACD,OAAO,SAASC,kBACdC,OAAiC;IAEjC,MAAM,EACJC,OAAO,EACPC,QAAQ,EACRC,OAAO,EACPC,UAAU,EACVC,SAAS,EACTC,MAAM,EACNC,SAAS,EACTC,QAAQ,EACRC,YAAYX,IAAI,EAChBY,eAAe,KAAK,EACpBC,oBAAoB,KAAK,EACzBC,sBAAsBd,IAAI,EAC3B,GAAGE;IAEJ,MAAM,CAACa,KAAKC,YAAY,GAAGnB,cAAcM;IACzC,MAAMc,YAAYtB,OAA2B;IAE7CD,UAAU;QACR,IAAI,CAACU,YAAY,CAAEc,CAAAA,SAASC,aAAa,YAAYC,WAAU,GAAI;YACjE;QACF;QAEAH,UAAUI,OAAO,GAAGH,SAASC,aAAa;IAC5C,GAAG;QAACf;KAAS;IAEb,OAAO;QACLD,SAASY;QACTO,mBAAmB;YACjBnB,SAASa;YACT,GAAGpB,uBAAuB;gBACxBS;gBACAkB,aAAa;oBACX,MAAMC,WAAWT,IAAIM,OAAO;oBAC5B,IACEG,YACA,CAACV,oBAAoB,YACpB,CAAA,CAACI,SAASC,aAAa,IACtB,CAACK,SAASC,QAAQ,CAACP,SAASC,aAAa,CAAA,GAC3C;wBACAK,SAASE,KAAK;oBAChB;gBACF;gBACApB;gBACAC;gBACAoB,YAAY;oBACV,IAAIb,oBAAoB,YAAY;wBAClC;oBACF;oBAEA,2EAA2E;oBAC3E,iCAAiC;oBACjCc,OAAOC,qBAAqB,CAAC;wBAC3BZ,UAAUI,OAAO,EAAEK;oBACrB;gBACF;gBACAlB;gBACAC;gBACAC;gBACAG;YACF,EAAE;QACJ;QACAiB,eAAe;YACbnB,WAAUoB,KAAK;gBACbpB,UAAUoB;gBACV,IACEA,MAAMC,oBAAoB,MAC1BD,MAAME,GAAG,KAAK,SACdnB,oBAAoB,aACpB;oBACA;gBACF;gBAEA,MAAM,EAAEoB,MAAM,EAAEC,QAAQ,EAAEC,aAAa,EAAE,GAAGL;gBAC5C,MAAMM,WAAWtC,qBAAqBqC,eAAexB;gBACrD,MAAM0B,QAAQD,SAASE,MAAM;gBAC7B,IAAID,UAAU,GAAG;oBACfP,MAAMS,cAAc;oBACpB;gBACF;gBAEA,sEAAsE;gBACtE,oDAAoD;gBACpD,IAAIC;gBACJ,IACEH,UAAU,KACT,CAACH,YACCD,CAAAA,WAAWE,iBAAiBF,WAAWG,QAAQ,CAACC,QAAQ,EAAE,AAAD,GAC5D;oBACAG,OAAO;gBACT,OAAO,IACLN,YACCD,CAAAA,WAAWE,iBAAiBF,WAAWG,QAAQ,CAAC,EAAE,AAAD,GAClD;oBACAI,OAAO;gBACT;gBAEA,IAAIA,MAAM;oBACRV,MAAMS,cAAc;oBACpB1C,mBAAmB;wBACjB2C;wBACAJ;wBACAK,WAAWN;oBACb;gBACF;YACF;QACF;IACF;AACF"}
@@ -26,6 +26,25 @@ export interface FieldsetProps extends FieldsetHTMLAttributes<HTMLFieldSetElemen
26
26
  * }
27
27
  * ```
28
28
  *
29
+ * @example Floating Legend Example
30
+ * ```tsx
31
+ * import { Form } from "@react-md/core/form/Form";
32
+ * import { Fieldset } from "@react-md/core/form/Fieldset";
33
+ * import { Legend } from "@react-md/core/form/Legend";
34
+ *
35
+ * function Example(): ReactElement {
36
+ * return (
37
+ * <Form>
38
+ * <Fieldset floatingLegend>
39
+ * <Legend floating>Some Title</Legend>
40
+ * // form components
41
+ * </Fieldset>
42
+ * </Form>
43
+ * );
44
+ * }
45
+ * ```
46
+ * ```
47
+ *
29
48
  * @see {@link https://react-md.dev/components/fieldset | Fieldset Demos}
30
49
  */
31
50
  export declare const Fieldset: import("react").ForwardRefExoticComponent<FieldsetProps & import("react").RefAttributes<HTMLFieldSetElement>>;
@@ -20,16 +20,36 @@ import { fieldset } from "./fieldsetStyles.js";
20
20
  * }
21
21
  * ```
22
22
  *
23
+ * @example Floating Legend Example
24
+ * ```tsx
25
+ * import { Form } from "@react-md/core/form/Form";
26
+ * import { Fieldset } from "@react-md/core/form/Fieldset";
27
+ * import { Legend } from "@react-md/core/form/Legend";
28
+ *
29
+ * function Example(): ReactElement {
30
+ * return (
31
+ * <Form>
32
+ * <Fieldset floatingLegend>
33
+ * <Legend floating>Some Title</Legend>
34
+ * // form components
35
+ * </Fieldset>
36
+ * </Form>
37
+ * );
38
+ * }
39
+ * ```
40
+ * ```
41
+ *
23
42
  * @see {@link https://react-md.dev/components/fieldset | Fieldset Demos}
24
43
  */ export const Fieldset = /*#__PURE__*/ forwardRef(function Fieldset(props, ref) {
25
- const { className, fullWidth = false, browserStyles = false, children, ...remaining } = props;
44
+ const { className, fullWidth, browserStyles, floatingLegend, children, ...remaining } = props;
26
45
  return /*#__PURE__*/ _jsx("fieldset", {
27
46
  ...remaining,
28
47
  ref: ref,
29
48
  className: fieldset({
30
49
  className,
31
50
  fullWidth,
32
- browserStyles
51
+ browserStyles,
52
+ floatingLegend
33
53
  }),
34
54
  children: children
35
55
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/Fieldset.tsx"],"sourcesContent":["import { type FieldsetHTMLAttributes, forwardRef } from \"react\";\n\nimport { type FieldsetClassNameOptions, fieldset } from \"./fieldsetStyles.js\";\n\n/**\n * @since 6.0.0 Removed the `legend`, `legendStyle`,\n * `legendClassName`, and `legendSROnly` props. You must provide a `Legend`\n * yourself manually instead of using a prop.\n */\nexport interface FieldsetProps\n extends FieldsetHTMLAttributes<HTMLFieldSetElement>,\n FieldsetClassNameOptions {}\n\n/**\n * @example Simple Example\n * ```tsx\n * import { Form } from \"@react-md/core/form/Form\";\n * import { Fieldset } from \"@react-md/core/form/Fieldset\";\n * import { Legend } from \"@react-md/core/form/Legend\";\n *\n * function Example(): ReactElement {\n * return (\n * <Form>\n * <Fieldset>\n * <Legend>Some Title</Legend>\n * // form components\n * </Fieldset>\n * </Form>\n * );\n * }\n * ```\n *\n * @see {@link https://react-md.dev/components/fieldset | Fieldset Demos}\n */\nexport const Fieldset = forwardRef<HTMLFieldSetElement, FieldsetProps>(\n function Fieldset(props, ref) {\n const {\n className,\n fullWidth = false,\n browserStyles = false,\n children,\n ...remaining\n } = props;\n\n return (\n <fieldset\n {...remaining}\n ref={ref}\n className={fieldset({\n className,\n fullWidth,\n browserStyles,\n })}\n >\n {children}\n </fieldset>\n );\n }\n);\n"],"names":["forwardRef","fieldset","Fieldset","props","ref","className","fullWidth","browserStyles","children","remaining"],"mappings":";AAAA,SAAsCA,UAAU,QAAQ,QAAQ;AAEhE,SAAwCC,QAAQ,QAAQ,sBAAsB;AAW9E;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,MAAMC,yBAAWF,WACtB,SAASE,SAASC,KAAK,EAAEC,GAAG;IAC1B,MAAM,EACJC,SAAS,EACTC,YAAY,KAAK,EACjBC,gBAAgB,KAAK,EACrBC,QAAQ,EACR,GAAGC,WACJ,GAAGN;IAEJ,qBACE,KAACF;QACE,GAAGQ,SAAS;QACbL,KAAKA;QACLC,WAAWJ,SAAS;YAClBI;YACAC;YACAC;QACF;kBAECC;;AAGP,GACA"}
1
+ {"version":3,"sources":["../../src/form/Fieldset.tsx"],"sourcesContent":["import { type FieldsetHTMLAttributes, forwardRef } from \"react\";\n\nimport { type FieldsetClassNameOptions, fieldset } from \"./fieldsetStyles.js\";\n\n/**\n * @since 6.0.0 Removed the `legend`, `legendStyle`,\n * `legendClassName`, and `legendSROnly` props. You must provide a `Legend`\n * yourself manually instead of using a prop.\n */\nexport interface FieldsetProps\n extends\n FieldsetHTMLAttributes<HTMLFieldSetElement>,\n FieldsetClassNameOptions {}\n\n/**\n * @example Simple Example\n * ```tsx\n * import { Form } from \"@react-md/core/form/Form\";\n * import { Fieldset } from \"@react-md/core/form/Fieldset\";\n * import { Legend } from \"@react-md/core/form/Legend\";\n *\n * function Example(): ReactElement {\n * return (\n * <Form>\n * <Fieldset>\n * <Legend>Some Title</Legend>\n * // form components\n * </Fieldset>\n * </Form>\n * );\n * }\n * ```\n *\n * @example Floating Legend Example\n * ```tsx\n * import { Form } from \"@react-md/core/form/Form\";\n * import { Fieldset } from \"@react-md/core/form/Fieldset\";\n * import { Legend } from \"@react-md/core/form/Legend\";\n *\n * function Example(): ReactElement {\n * return (\n * <Form>\n * <Fieldset floatingLegend>\n * <Legend floating>Some Title</Legend>\n * // form components\n * </Fieldset>\n * </Form>\n * );\n * }\n * ```\n * ```\n *\n * @see {@link https://react-md.dev/components/fieldset | Fieldset Demos}\n */\nexport const Fieldset = forwardRef<HTMLFieldSetElement, FieldsetProps>(\n function Fieldset(props, ref) {\n const {\n className,\n fullWidth,\n browserStyles,\n floatingLegend,\n children,\n ...remaining\n } = props;\n\n return (\n <fieldset\n {...remaining}\n ref={ref}\n className={fieldset({\n className,\n fullWidth,\n browserStyles,\n floatingLegend,\n })}\n >\n {children}\n </fieldset>\n );\n }\n);\n"],"names":["forwardRef","fieldset","Fieldset","props","ref","className","fullWidth","browserStyles","floatingLegend","children","remaining"],"mappings":";AAAA,SAAsCA,UAAU,QAAQ,QAAQ;AAEhE,SAAwCC,QAAQ,QAAQ,sBAAsB;AAY9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GACD,OAAO,MAAMC,yBAAWF,WACtB,SAASE,SAASC,KAAK,EAAEC,GAAG;IAC1B,MAAM,EACJC,SAAS,EACTC,SAAS,EACTC,aAAa,EACbC,cAAc,EACdC,QAAQ,EACR,GAAGC,WACJ,GAAGP;IAEJ,qBACE,KAACF;QACE,GAAGS,SAAS;QACbN,KAAKA;QACLC,WAAWJ,SAAS;YAClBI;YACAC;YACAC;YACAC;QACF;kBAECC;;AAGP,GACA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/FormMessageContainer.tsx"],"sourcesContent":["import { type HTMLAttributes, forwardRef } from \"react\";\n\nimport { type PropsWithRef } from \"../types.js\";\nimport { FormMessage } from \"./FormMessage.js\";\nimport {\n type FormMessageContainerClassNameOptions,\n formMessageContainer,\n} from \"./formMessageContainerStyles.js\";\nimport { type FormMessageProps } from \"./types.js\";\n\n/**\n * @since 2.5.0\n */\nexport interface FormMessageContainerProps\n extends HTMLAttributes<HTMLDivElement>,\n FormMessageContainerClassNameOptions {\n /**\n * If the extension doesn't actually want to render the `FormMessage`\n * component, these props are optional. It kind of eliminates the whole\n * purpose of this component though.\n */\n messageProps?: PropsWithRef<FormMessageProps>;\n}\n\n/**\n * Conditionally wraps the `children` in a `.rmd-form-message-container` wrapper\n * and renders the {@link FormMessage} component.\n *\n * @see {@link https://react-md.dev/components/form-message | FormMessage Demos}\n * @since 2.5.0\n */\nexport const FormMessageContainer = forwardRef<\n HTMLDivElement,\n FormMessageContainerProps\n>(function FormMessageContainer(props, ref) {\n const { className, children, inline, messageProps, ...remaining } = props;\n if (!messageProps) {\n return <>{children}</>;\n }\n\n return (\n <div\n {...remaining}\n ref={ref}\n className={formMessageContainer({ className, inline })}\n >\n {children}\n <FormMessage {...messageProps} />\n </div>\n );\n});\n"],"names":["forwardRef","FormMessage","formMessageContainer","FormMessageContainer","props","ref","className","children","inline","messageProps","remaining","div"],"mappings":";AAAA,SAA8BA,UAAU,QAAQ,QAAQ;AAGxD,SAASC,WAAW,QAAQ,mBAAmB;AAC/C,SAEEC,oBAAoB,QACf,kCAAkC;AAiBzC;;;;;;CAMC,GACD,OAAO,MAAMC,qCAAuBH,WAGlC,SAASG,qBAAqBC,KAAK,EAAEC,GAAG;IACxC,MAAM,EAAEC,SAAS,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,YAAY,EAAE,GAAGC,WAAW,GAAGN;IACpE,IAAI,CAACK,cAAc;QACjB,qBAAO;sBAAGF;;IACZ;IAEA,qBACE,MAACI;QACE,GAAGD,SAAS;QACbL,KAAKA;QACLC,WAAWJ,qBAAqB;YAAEI;YAAWE;QAAO;;YAEnDD;0BACD,KAACN;gBAAa,GAAGQ,YAAY;;;;AAGnC,GAAG"}
1
+ {"version":3,"sources":["../../src/form/FormMessageContainer.tsx"],"sourcesContent":["import { type HTMLAttributes, forwardRef } from \"react\";\n\nimport { type PropsWithRef } from \"../types.js\";\nimport { FormMessage } from \"./FormMessage.js\";\nimport {\n type FormMessageContainerClassNameOptions,\n formMessageContainer,\n} from \"./formMessageContainerStyles.js\";\nimport { type FormMessageProps } from \"./types.js\";\n\n/**\n * @since 2.5.0\n */\nexport interface FormMessageContainerProps\n extends HTMLAttributes<HTMLDivElement>, FormMessageContainerClassNameOptions {\n /**\n * If the extension doesn't actually want to render the `FormMessage`\n * component, these props are optional. It kind of eliminates the whole\n * purpose of this component though.\n */\n messageProps?: PropsWithRef<FormMessageProps>;\n}\n\n/**\n * Conditionally wraps the `children` in a `.rmd-form-message-container` wrapper\n * and renders the {@link FormMessage} component.\n *\n * @see {@link https://react-md.dev/components/form-message | FormMessage Demos}\n * @since 2.5.0\n */\nexport const FormMessageContainer = forwardRef<\n HTMLDivElement,\n FormMessageContainerProps\n>(function FormMessageContainer(props, ref) {\n const { className, children, inline, messageProps, ...remaining } = props;\n if (!messageProps) {\n return <>{children}</>;\n }\n\n return (\n <div\n {...remaining}\n ref={ref}\n className={formMessageContainer({ className, inline })}\n >\n {children}\n <FormMessage {...messageProps} />\n </div>\n );\n});\n"],"names":["forwardRef","FormMessage","formMessageContainer","FormMessageContainer","props","ref","className","children","inline","messageProps","remaining","div"],"mappings":";AAAA,SAA8BA,UAAU,QAAQ,QAAQ;AAGxD,SAASC,WAAW,QAAQ,mBAAmB;AAC/C,SAEEC,oBAAoB,QACf,kCAAkC;AAgBzC;;;;;;CAMC,GACD,OAAO,MAAMC,qCAAuBH,WAGlC,SAASG,qBAAqBC,KAAK,EAAEC,GAAG;IACxC,MAAM,EAAEC,SAAS,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,YAAY,EAAE,GAAGC,WAAW,GAAGN;IACpE,IAAI,CAACK,cAAc;QACjB,qBAAO;sBAAGF;;IACZ;IAEA,qBACE,MAACI;QACE,GAAGD,SAAS;QACbL,KAAKA;QACLC,WAAWJ,qBAAqB;YAAEI;YAAWE;QAAO;;YAEnDD;0BACD,KAACN;gBAAa,GAAGQ,YAAY;;;;AAGnC,GAAG"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/FormMessageCounter.tsx"],"sourcesContent":["import {\n type HTMLAttributes,\n type ReactElement,\n type ReactNode,\n forwardRef,\n} from \"react\";\n\nimport { formMessageCounter } from \"./formMessageStyles.js\";\n\n/** @since 2.9.0 */\nexport interface FormMessageCounterProps\n extends HTMLAttributes<HTMLSpanElement> {\n /**\n * The children to display in the counter. This is normally a string like:\n *\n * @example String Example\n * ```ts\n * `${min} / ${max}`\n * ```\n */\n children: ReactNode;\n}\n\n/**\n * This component can be used to create a \"counter\" within the\n * {@link FormMessage} component.\n *\n * Note: This is really only useful when using the {@link FormMessage} component\n * without a {@link TextField}.\n *\n * @example Example Usage\n * ```ts\n * interface ExampleProps {\n * min: number;\n * max: number;\n * }\n *\n * function Example({ min, max }: ExampleProps) {\n * return (\n * <FormMessage disableWrap>\n * <FormMessageCounter>\n * {`${min} / ${max}`}\n * </FormMessageCounter>\n * </FormMessage>\n * );\n * }\n * ```\n *\n * @see {@link https://react-md.dev/components/form-message | FormMessage Demos}\n * @see {@link https://react-md.dev/components/text-field | TextField Demos}\n * @since 2.9.0\n * @since 6.3.0 Supports refs.\n */\nexport const FormMessageCounter = forwardRef<\n HTMLSpanElement,\n FormMessageCounterProps\n>(function FormMessageCounter(props, ref): ReactElement {\n const { children, className, ...remaining } = props;\n\n return (\n <span\n ref={ref}\n {...remaining}\n className={formMessageCounter({ className })}\n >\n {children}\n </span>\n );\n});\n"],"names":["forwardRef","formMessageCounter","FormMessageCounter","props","ref","children","className","remaining","span"],"mappings":";AAAA,SAIEA,UAAU,QACL,QAAQ;AAEf,SAASC,kBAAkB,QAAQ,yBAAyB;AAgB5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD,OAAO,MAAMC,mCAAqBF,WAGhC,SAASE,mBAAmBC,KAAK,EAAEC,GAAG;IACtC,MAAM,EAAEC,QAAQ,EAAEC,SAAS,EAAE,GAAGC,WAAW,GAAGJ;IAE9C,qBACE,KAACK;QACCJ,KAAKA;QACJ,GAAGG,SAAS;QACbD,WAAWL,mBAAmB;YAAEK;QAAU;kBAEzCD;;AAGP,GAAG"}
1
+ {"version":3,"sources":["../../src/form/FormMessageCounter.tsx"],"sourcesContent":["import {\n type HTMLAttributes,\n type ReactElement,\n type ReactNode,\n forwardRef,\n} from \"react\";\n\nimport { formMessageCounter } from \"./formMessageStyles.js\";\n\n/** @since 2.9.0 */\nexport interface FormMessageCounterProps extends HTMLAttributes<HTMLSpanElement> {\n /**\n * The children to display in the counter. This is normally a string like:\n *\n * @example String Example\n * ```ts\n * `${min} / ${max}`\n * ```\n */\n children: ReactNode;\n}\n\n/**\n * This component can be used to create a \"counter\" within the\n * {@link FormMessage} component.\n *\n * Note: This is really only useful when using the {@link FormMessage} component\n * without a {@link TextField}.\n *\n * @example Example Usage\n * ```ts\n * interface ExampleProps {\n * min: number;\n * max: number;\n * }\n *\n * function Example({ min, max }: ExampleProps) {\n * return (\n * <FormMessage disableWrap>\n * <FormMessageCounter>\n * {`${min} / ${max}`}\n * </FormMessageCounter>\n * </FormMessage>\n * );\n * }\n * ```\n *\n * @see {@link https://react-md.dev/components/form-message | FormMessage Demos}\n * @see {@link https://react-md.dev/components/text-field | TextField Demos}\n * @since 2.9.0\n * @since 6.3.0 Supports refs.\n */\nexport const FormMessageCounter = forwardRef<\n HTMLSpanElement,\n FormMessageCounterProps\n>(function FormMessageCounter(props, ref): ReactElement {\n const { children, className, ...remaining } = props;\n\n return (\n <span\n ref={ref}\n {...remaining}\n className={formMessageCounter({ className })}\n >\n {children}\n </span>\n );\n});\n"],"names":["forwardRef","formMessageCounter","FormMessageCounter","props","ref","children","className","remaining","span"],"mappings":";AAAA,SAIEA,UAAU,QACL,QAAQ;AAEf,SAASC,kBAAkB,QAAQ,yBAAyB;AAe5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD,OAAO,MAAMC,mCAAqBF,WAGhC,SAASE,mBAAmBC,KAAK,EAAEC,GAAG;IACtC,MAAM,EAAEC,QAAQ,EAAEC,SAAS,EAAE,GAAGC,WAAW,GAAGJ;IAE9C,qBACE,KAACK;QACCJ,KAAKA;QACJ,GAAGG,SAAS;QACbD,WAAWL,mBAAmB;YAAEK;QAAU;kBAEzCD;;AAGP,GAAG"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/InputToggle.tsx"],"sourcesContent":["\"use client\";\n\nimport { cnb } from \"cnbuilder\";\nimport {\n type CSSProperties,\n type HTMLAttributes,\n type InputHTMLAttributes,\n type LabelHTMLAttributes,\n type ReactNode,\n forwardRef,\n} from \"react\";\n\nimport { type ComponentWithRippleProps } from \"../interaction/types.js\";\nimport { useElementInteraction } from \"../interaction/useElementInteraction.js\";\nimport { type PropsWithRef } from \"../types.js\";\nimport { useEnsuredId } from \"../useEnsuredId.js\";\nimport { FormMessageContainer } from \"./FormMessageContainer.js\";\nimport { InputToggleIcon } from \"./InputToggleIcon.js\";\nimport { Label } from \"./Label.js\";\nimport { type InputToggleSize } from \"./inputToggleStyles.js\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { type LabelClassNameOptions } from \"./types.js\";\nimport {\n type FormComponentStates,\n type FormMessageContainerExtension,\n} from \"./types.js\";\n\n/**\n * @since 6.0.0\n */\nexport interface ConfigurableInputToggleIconProps {\n /**\n * @see {@link InputToggleSize}\n * @defaultValue `\"normal\"`\n */\n size?: InputToggleSize;\n\n /**\n * The icon to use while unchecked. This defaults to the unchecked\n * checkbox/radio icon from the `ICON_CONFIG`.\n *\n * @defaultValue `getIcon(props.type)`\n */\n icon?: ReactNode;\n\n /**\n * The icon to use while unchecked. This defaults to the unchecked\n * checkbox/radio icon from the `ICON_CONFIG`.\n *\n * @defaultValue `getIcon(``${props.type}Checked``)`\n */\n checkedIcon?: ReactNode;\n\n /**\n * Any props that should be passed to the `<span>` that surrounds the current\n * icon element.\n */\n iconProps?: PropsWithRef<HTMLAttributes<HTMLSpanElement>>;\n\n /**\n * Optional style to set on the `<span>` that surrounds the current icon\n * element.\n */\n iconStyle?: CSSProperties;\n\n /**\n * Optional className to set on the `<span>` that surrounds the current icon\n * element.\n */\n iconClassName?: string;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface InputToggleLabelProps {\n /**\n * An optional label to display with the checkbox. If this is omitted, it is\n * recommended to provide an `aria-label` for accessibility.\n */\n label?: ReactNode;\n\n /**\n * Any props that should be passed to the `<Label>` component.\n *\n * Note: If `style` or `className` are provided in this object, they will be\n * ignored. Use the top-level `style` and `className` props instead.\n *\n * @example\n * ```\n * // bad\n * labelProps={{\n * \"aria-label\": \"checkbox\",\n * style: { color: \"red\" },\n * className: \"custom\"\n * }}\n *\n * // good\n * style={{ color: \"red\" }}\n * className=\"custom\"\n * labelProps={{\n * \"aria-label\": \"checkbox\",\n * }}\n * ```\n */\n labelProps?: PropsWithRef<LabelHTMLAttributes<HTMLLabelElement>>;\n\n /**\n * @see {@link LabelClassNameOptions.gap}\n * @defaultValue `false`\n */\n disableLabelGap?: boolean;\n\n /**\n * Set this to `true` to swap the position of the {@link label} and the current\n * icon. This prop can be used with the {@link stacked} prop to change the\n * position if the icon and label:\n *\n * ____________________________________\n * | stacked | iconAfter | position |\n * ____________________________________\n * | | | icon label |\n * ____________________________________\n * | | X | label icon |\n * ____________________________________\n * | X | | icon |\n * | | | label |\n * ____________________________________\n * | X | X | label |\n * | | | icon |\n * ____________________________________\n *\n *\n * @defaultValue `false`\n */\n iconAfter?: boolean;\n\n /**\n * Set this to `true` if the label should be stacked instead of inline with\n * the current icon.\n *\n * @see {@link iconAfter}\n * @defaultValue `false`\n */\n stacked?: boolean;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface BaseInputToggleProps\n extends Omit<InputHTMLAttributes<HTMLInputElement>, \"size\">,\n FormMessageContainerExtension,\n FormComponentStates,\n ConfigurableInputToggleIconProps,\n InputToggleLabelProps,\n ComponentWithRippleProps {\n /**\n * @see https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing\n * @defaultValue `type === \"checkbox\" ? \"off\" : undefined`\n */\n autoComplete?: string;\n}\n\n/**\n * @since 2.8.5\n * @since 6.0.0 Removed the `aria-controls` prop and added the\n * `indeterminateIcon` prop.\n */\nexport interface IndeterminateCheckboxProps {\n /**\n * Set this value to `true` if the checkbox is in an \"indeterminate\" state:\n *\n * - this checkbox controls the select all/select none behavior of other\n * checkboxes in a group\n * - at least one of the checkboxes have been checked\n * - the `checked` prop for this Checkbox should also be `true`\n *\n * You should normally use the `useCheckboxGroup` hook to handle this\n * behavior.\n *\n * @defaultValue `false`\n */\n indeterminate?: boolean;\n\n /**\n * The icon to display when the checkbox is checked and the\n * {@link indeterminate} prop is `true`.\n *\n * @defaultValue `getIcon(\"checkboxIndeterminate\")`\n * @since 6.0.0\n */\n indeterminateIcon?: ReactNode;\n}\n\nexport interface CheckboxProps\n extends BaseInputToggleProps,\n IndeterminateCheckboxProps {}\n\n/** @since 6.0.0 */\nexport interface CheckboxInputToggleProps extends CheckboxProps {\n type: \"checkbox\";\n}\n\nexport interface RadioProps extends BaseInputToggleProps {\n /**\n * The value for the radio button.\n *\n * @since 6.0.0 This is now optional and no longer supports\n * `string[]` since there isn't much of a use case for array values.\n */\n value?: string | number;\n}\n\n/** @since 6.0.0 */\nexport interface RadioInputToggleProps extends RadioProps {\n type: \"radio\";\n}\n\n/**\n * @since 6.0.0 Updated to be a union between\n * `CheckboxInputToggleProps` and `RadioInputToggleProps`\n */\nexport type InputToggleProps = CheckboxInputToggleProps | RadioInputToggleProps;\n\n/**\n * **Client Component**\n *\n * @see {@link https://react-md.dev/components/checkbox | Checkbox Demos}\n * @see {@link https://react-md.dev/components/radio | Radio Demos}\n * @since 6.0.0 Now supports the `FormMessage` behavior and requires\n * different icons for each checked state.\n */\nexport const InputToggle = forwardRef<HTMLInputElement, InputToggleProps>(\n function InputToggle(props, ref) {\n const {\n id: propId,\n type,\n label,\n labelProps,\n style,\n className,\n autoComplete = type === \"checkbox\" ? \"off\" : undefined,\n disableLabelGap = false,\n stacked = false,\n iconAfter = false,\n size = \"normal\",\n error = false,\n active = false,\n indeterminate = false,\n messageProps,\n messageContainerProps,\n icon,\n checkedIcon,\n indeterminateIcon,\n iconProps,\n iconStyle,\n iconClassName,\n onBlur,\n onClick,\n onKeyDown,\n onKeyUp,\n onMouseDown,\n onMouseLeave,\n onDragStart,\n onMouseUp,\n onTouchEnd,\n onTouchMove,\n onTouchStart,\n disableRipple,\n ...remaining\n } = props as CheckboxInputToggleProps;\n const { disabled = false, checked } = props;\n\n const id = useEnsuredId(propId, type);\n const { pressedClassName, ripples, handlers } = useElementInteraction({\n mode: disableRipple ? \"none\" : undefined,\n disabled,\n onBlur,\n onClick,\n onKeyDown,\n onKeyUp,\n onMouseDown,\n onMouseLeave,\n onDragStart,\n onMouseUp,\n onTouchEnd,\n onTouchMove,\n onTouchStart,\n });\n\n // set on the `remaining` object to bypass the eslint rule about\n // aria-checked not being valid for textbox role\n remaining[\"aria-checked\"] =\n (remaining[\"aria-checked\"] ?? indeterminate) ? \"mixed\" : undefined;\n\n return (\n <FormMessageContainer\n {...messageContainerProps}\n messageProps={messageProps}\n >\n <Label\n {...labelProps}\n gap={!disableLabelGap}\n style={style}\n stacked={stacked}\n reversed={!iconAfter}\n active={active}\n error={error}\n disabled={disabled}\n className={className}\n >\n {label}\n <InputToggleIcon\n style={iconStyle}\n {...iconProps}\n className={cnb(\n pressedClassName,\n iconClassName,\n iconProps?.className\n )}\n error={error}\n checked={checked}\n disabled={disabled}\n size={size}\n type={type}\n icon={icon}\n checkedIcon={checkedIcon}\n indeterminate={indeterminate}\n indeterminateIcon={indeterminateIcon}\n >\n <input\n {...remaining}\n {...handlers}\n autoComplete={autoComplete}\n id={id}\n ref={ref}\n type={type}\n className=\"rmd-hidden-input\"\n />\n {ripples}\n </InputToggleIcon>\n </Label>\n </FormMessageContainer>\n );\n }\n);\n"],"names":["cnb","forwardRef","useElementInteraction","useEnsuredId","FormMessageContainer","InputToggleIcon","Label","InputToggle","props","ref","id","propId","type","label","labelProps","style","className","autoComplete","undefined","disableLabelGap","stacked","iconAfter","size","error","active","indeterminate","messageProps","messageContainerProps","icon","checkedIcon","indeterminateIcon","iconProps","iconStyle","iconClassName","onBlur","onClick","onKeyDown","onKeyUp","onMouseDown","onMouseLeave","onDragStart","onMouseUp","onTouchEnd","onTouchMove","onTouchStart","disableRipple","remaining","disabled","checked","pressedClassName","ripples","handlers","mode","gap","reversed","input"],"mappings":"AAAA;;AAEA,SAASA,GAAG,QAAQ,YAAY;AAChC,SAMEC,UAAU,QACL,QAAQ;AAGf,SAASC,qBAAqB,QAAQ,0CAA0C;AAEhF,SAASC,YAAY,QAAQ,qBAAqB;AAClD,SAASC,oBAAoB,QAAQ,4BAA4B;AACjE,SAASC,eAAe,QAAQ,uBAAuB;AACvD,SAASC,KAAK,QA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,UAAUA;YACV/B,WAAWA;;gBAEVH;8BACD,MAACR;oBACCU,OAAOiB;oBACN,GAAGD,SAAS;oBACbf,WAAWhB,IACTiD,kBACAhB,eACAF,WAAWf;oBAEbO,OAAOA;oBACPyB,SAASA;oBACTD,UAAUA;oBACVzB,MAAMA;oBACNV,MAAMA;oBACNgB,MAAMA;oBACNC,aAAaA;oBACbJ,eAAeA;oBACfK,mBAAmBA;;sCAEnB,KAACyB;4BACE,GAAGT,SAAS;4BACZ,GAAGK,QAAQ;4BACZlC,cAAcA;4BACdP,IAAIA;4BACJD,KAAKA;4BACLG,MAAMA;4BACNI,WAAU;;wBAEXkC;;;;;;AAKX,GACA"}
1
+ {"version":3,"sources":["../../src/form/InputToggle.tsx"],"sourcesContent":["\"use client\";\n\nimport { cnb } from \"cnbuilder\";\nimport {\n type CSSProperties,\n type HTMLAttributes,\n type InputHTMLAttributes,\n type LabelHTMLAttributes,\n type ReactNode,\n forwardRef,\n} from \"react\";\n\nimport { type ComponentWithRippleProps } from \"../interaction/types.js\";\nimport { useElementInteraction } from \"../interaction/useElementInteraction.js\";\nimport { type PropsWithRef } from \"../types.js\";\nimport { useEnsuredId } from \"../useEnsuredId.js\";\nimport { FormMessageContainer } from \"./FormMessageContainer.js\";\nimport { InputToggleIcon } from \"./InputToggleIcon.js\";\nimport { Label } from \"./Label.js\";\nimport { type InputToggleSize } from \"./inputToggleStyles.js\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { type LabelClassNameOptions } from \"./types.js\";\nimport {\n type FormComponentStates,\n type FormMessageContainerExtension,\n} from \"./types.js\";\n\n/**\n * @since 6.0.0\n */\nexport interface ConfigurableInputToggleIconProps {\n /**\n * @see {@link InputToggleSize}\n * @defaultValue `\"normal\"`\n */\n size?: InputToggleSize;\n\n /**\n * The icon to use while unchecked. This defaults to the unchecked\n * checkbox/radio icon from the `ICON_CONFIG`.\n *\n * @defaultValue `getIcon(props.type)`\n */\n icon?: ReactNode;\n\n /**\n * The icon to use while unchecked. This defaults to the unchecked\n * checkbox/radio icon from the `ICON_CONFIG`.\n *\n * @defaultValue `getIcon(``${props.type}Checked``)`\n */\n checkedIcon?: ReactNode;\n\n /**\n * Any props that should be passed to the `<span>` that surrounds the current\n * icon element.\n */\n iconProps?: PropsWithRef<HTMLAttributes<HTMLSpanElement>>;\n\n /**\n * Optional style to set on the `<span>` that surrounds the current icon\n * element.\n */\n iconStyle?: CSSProperties;\n\n /**\n * Optional className to set on the `<span>` that surrounds the current icon\n * element.\n */\n iconClassName?: string;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface InputToggleLabelProps {\n /**\n * An optional label to display with the checkbox. If this is omitted, it is\n * recommended to provide an `aria-label` for accessibility.\n */\n label?: ReactNode;\n\n /**\n * Any props that should be passed to the `<Label>` component.\n *\n * Note: If `style` or `className` are provided in this object, they will be\n * ignored. Use the top-level `style` and `className` props instead.\n *\n * @example\n * ```\n * // bad\n * labelProps={{\n * \"aria-label\": \"checkbox\",\n * style: { color: \"red\" },\n * className: \"custom\"\n * }}\n *\n * // good\n * style={{ color: \"red\" }}\n * className=\"custom\"\n * labelProps={{\n * \"aria-label\": \"checkbox\",\n * }}\n * ```\n */\n labelProps?: PropsWithRef<LabelHTMLAttributes<HTMLLabelElement>>;\n\n /**\n * @see {@link LabelClassNameOptions.gap}\n * @defaultValue `false`\n */\n disableLabelGap?: boolean;\n\n /**\n * Set this to `true` to swap the position of the {@link label} and the current\n * icon. This prop can be used with the {@link stacked} prop to change the\n * position if the icon and label:\n *\n * ____________________________________\n * | stacked | iconAfter | position |\n * ____________________________________\n * | | | icon label |\n * ____________________________________\n * | | X | label icon |\n * ____________________________________\n * | X | | icon |\n * | | | label |\n * ____________________________________\n * | X | X | label |\n * | | | icon |\n * ____________________________________\n *\n *\n * @defaultValue `false`\n */\n iconAfter?: boolean;\n\n /**\n * Set this to `true` if the label should be stacked instead of inline with\n * the current icon.\n *\n * @see {@link iconAfter}\n * @defaultValue `false`\n */\n stacked?: boolean;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface BaseInputToggleProps\n extends\n Omit<InputHTMLAttributes<HTMLInputElement>, \"size\">,\n FormMessageContainerExtension,\n FormComponentStates,\n ConfigurableInputToggleIconProps,\n InputToggleLabelProps,\n ComponentWithRippleProps {\n /**\n * @see https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing\n * @defaultValue `type === \"checkbox\" ? \"off\" : undefined`\n */\n autoComplete?: string;\n}\n\n/**\n * @since 2.8.5\n * @since 6.0.0 Removed the `aria-controls` prop and added the\n * `indeterminateIcon` prop.\n */\nexport interface IndeterminateCheckboxProps {\n /**\n * Set this value to `true` if the checkbox is in an \"indeterminate\" state:\n *\n * - this checkbox controls the select all/select none behavior of other\n * checkboxes in a group\n * - at least one of the checkboxes have been checked\n * - the `checked` prop for this Checkbox should also be `true`\n *\n * You should normally use the `useCheckboxGroup` hook to handle this\n * behavior.\n *\n * @defaultValue `false`\n */\n indeterminate?: boolean;\n\n /**\n * The icon to display when the checkbox is checked and the\n * {@link indeterminate} prop is `true`.\n *\n * @defaultValue `getIcon(\"checkboxIndeterminate\")`\n * @since 6.0.0\n */\n indeterminateIcon?: ReactNode;\n}\n\nexport interface CheckboxProps\n extends BaseInputToggleProps, IndeterminateCheckboxProps {}\n\n/** @since 6.0.0 */\nexport interface CheckboxInputToggleProps extends CheckboxProps {\n type: \"checkbox\";\n}\n\nexport interface RadioProps extends BaseInputToggleProps {\n /**\n * The value for the radio button.\n *\n * @since 6.0.0 This is now optional and no longer supports\n * `string[]` since there isn't much of a use case for array values.\n */\n value?: string | number;\n}\n\n/** @since 6.0.0 */\nexport interface RadioInputToggleProps extends RadioProps {\n type: \"radio\";\n}\n\n/**\n * @since 6.0.0 Updated to be a union between\n * `CheckboxInputToggleProps` and `RadioInputToggleProps`\n */\nexport type InputToggleProps = CheckboxInputToggleProps | RadioInputToggleProps;\n\n/**\n * **Client Component**\n *\n * @see {@link https://react-md.dev/components/checkbox | Checkbox Demos}\n * @see {@link https://react-md.dev/components/radio | Radio Demos}\n * @since 6.0.0 Now supports the `FormMessage` behavior and requires\n * different icons for each checked state.\n */\nexport const InputToggle = forwardRef<HTMLInputElement, InputToggleProps>(\n function InputToggle(props, ref) {\n const {\n id: propId,\n type,\n label,\n labelProps,\n style,\n className,\n autoComplete = type === \"checkbox\" ? \"off\" : undefined,\n disableLabelGap = false,\n stacked = false,\n iconAfter = false,\n size = \"normal\",\n error = false,\n active = false,\n indeterminate = false,\n messageProps,\n messageContainerProps,\n icon,\n checkedIcon,\n indeterminateIcon,\n iconProps,\n iconStyle,\n iconClassName,\n onBlur,\n onClick,\n onKeyDown,\n onKeyUp,\n onMouseDown,\n onMouseLeave,\n onDragStart,\n onMouseUp,\n onTouchEnd,\n onTouchMove,\n onTouchStart,\n disableRipple,\n ...remaining\n } = props as CheckboxInputToggleProps;\n const { disabled = false, checked } = props;\n\n const id = useEnsuredId(propId, type);\n const { pressedClassName, ripples, handlers } = useElementInteraction({\n mode: disableRipple ? \"none\" : undefined,\n disabled,\n onBlur,\n onClick,\n onKeyDown,\n onKeyUp,\n onMouseDown,\n onMouseLeave,\n onDragStart,\n onMouseUp,\n onTouchEnd,\n onTouchMove,\n onTouchStart,\n });\n\n // set on the `remaining` object to bypass the eslint rule about\n // aria-checked not being valid for textbox role\n remaining[\"aria-checked\"] =\n (remaining[\"aria-checked\"] ?? indeterminate) ? \"mixed\" : undefined;\n\n return (\n <FormMessageContainer\n {...messageContainerProps}\n messageProps={messageProps}\n >\n <Label\n {...labelProps}\n gap={!disableLabelGap}\n style={style}\n stacked={stacked}\n reversed={!iconAfter}\n active={active}\n error={error}\n disabled={disabled}\n className={className}\n >\n {label}\n <InputToggleIcon\n style={iconStyle}\n {...iconProps}\n className={cnb(\n pressedClassName,\n iconClassName,\n iconProps?.className\n )}\n error={error}\n checked={checked}\n disabled={disabled}\n size={size}\n type={type}\n icon={icon}\n checkedIcon={checkedIcon}\n indeterminate={indeterminate}\n indeterminateIcon={indeterminateIcon}\n >\n <input\n {...remaining}\n {...handlers}\n autoComplete={autoComplete}\n id={id}\n ref={ref}\n type={type}\n className=\"rmd-hidden-input\"\n />\n {ripples}\n </InputToggleIcon>\n </Label>\n </FormMessageContainer>\n );\n }\n);\n"],"names":["cnb","forwardRef","useElementInteraction","useEnsuredId","FormMessageContainer","InputToggleIcon","Label","InputToggle","props","ref","id","propId","type","label","labelProps","style","className","autoComplete","undefined","disableLabelGap","stacked","iconAfter","size","error","active","indeterminate","messageProps","messageContainerProps","icon","checkedIcon","indeterminateIcon","iconProps","iconStyle","iconClassName","onBlur","onClick","onKeyDown","onKeyUp","onMouseDown","onMouseLeave","onDragStart","onMouseUp","onTouchEnd","onTouchMove","onTouchStart","disableRipple","remaining","disabled","checked","pressedClassName","ripples","handlers","mode","gap","reversed","input"],"mappings":"AAAA;;AAEA,SAASA,GAAG,QAAQ,YAAY;AAChC,SAMEC,UAAU,QACL,QAAQ;AAGf,SAASC,qBAAqB,QAAQ,0CAA0C;AAEhF,SAASC,YAAY,QAAQ,qBAAqB;AAClD,SAASC,oBAAoB,QAAQ,4BAA4B;AACjE,SAASC,eAAe,QAAQ,uBAAuB;AACvD,SAASC,KAAK,QAAQ,aAAa;AA+MnC;;;;;;;CAOC,GACD,OAAO,MAAMC,4BAAcN,WACzB,SAASM,YAAYC,KAAK,EAAEC,GAAG;IAC7B,MAAM,EACJC,IAAIC,MAAM,EACVC,IAAI,EACJC,KAAK,EACLC,UAAU,EACVC,KAAK,EACLC,SAAS,EACTC,eAAeL,SAAS,aAAa,QAAQM,SAAS,EACtDC,kBAAkB,KAAK,EACvBC,UAAU,KAAK,EACfC,YAAY,KAAK,EACjBC,OAAO,QAAQ,EACfC,QAAQ,KAAK,EACbC,SAAS,KAAK,EACdC,gBAAgB,KAAK,EACrBC,YAAY,EACZC,qBAAqB,EACrBC,IAAI,EACJC,WAAW,EACXC,iBAAiB,EACjBC,SAAS,EACTC,SAAS,EACTC,aAAa,EACbC,MAAM,EACNC,OAAO,EACPC,SAAS,EACTC,OAAO,EACPC,WAAW,EACXC,YAAY,EACZC,WAAW,EACXC,SAAS,EACTC,UAAU,EACVC,WAAW,EACXC,YAAY,EACZC,aAAa,EACb,GAAGC,WACJ,GAAGtC;IACJ,MAAM,EAAEuC,WAAW,KAAK,EAAEC,OAAO,EAAE,GAAGxC;IAEtC,MAAME,KAAKP,aAAaQ,QAAQC;IAChC,MAAM,EAAEqC,gBAAgB,EAAEC,OAAO,EAAEC,QAAQ,EAAE,GAAGjD,sBAAsB;QACpEkD,MAAMP,gBAAgB,SAAS3B;QAC/B6B;QACAb;QACAC;QACAC;QACAC;QACAC;QACAC;QACAC;QACAC;QACAC;QACAC;QACAC;IACF;IAEA,gEAAgE;IAChE,gDAAgD;IAChDE,SAAS,CAAC,eAAe,GACvB,AAACA,SAAS,CAAC,eAAe,IAAIrB,gBAAiB,UAAUP;IAE3D,qBACE,KAACd;QACE,GAAGuB,qBAAqB;QACzBD,cAAcA;kBAEd,cAAA,MAACpB;YACE,GAAGQ,UAAU;YACduC,KAAK,CAAClC;YACNJ,OAAOA;YACPK,SAASA;YACTkC,UAAU,CAACjC;YACXG,QAAQA;YACRD,OAAOA;YACPwB,UAAUA;YACV/B,WAAWA;;gBAEVH;8BACD,MAACR;oBACCU,OAAOiB;oBACN,GAAGD,SAAS;oBACbf,WAAWhB,IACTiD,kBACAhB,eACAF,WAAWf;oBAEbO,OAAOA;oBACPyB,SAASA;oBACTD,UAAUA;oBACVzB,MAAMA;oBACNV,MAAMA;oBACNgB,MAAMA;oBACNC,aAAaA;oBACbJ,eAAeA;oBACfK,mBAAmBA;;sCAEnB,KAACyB;4BACE,GAAGT,SAAS;4BACZ,GAAGK,QAAQ;4BACZlC,cAAcA;4BACdP,IAAIA;4BACJD,KAAKA;4BACLG,MAAMA;4BACNI,WAAU;;wBAEXkC;;;;;;AAKX,GACA"}
@@ -1,16 +1,38 @@
1
1
  import { type TypographyProps } from "../typography/Typography.js";
2
+ import { type LegendClassNameOptions } from "./legendStyles.js";
2
3
  /**
3
4
  * @since 6.0.0
5
+ * @since 6.4.0 Extends the `LegendClassNameOptions`
4
6
  */
5
- export interface LegendProps extends TypographyProps {
6
- /**
7
- * @defaultValue `false`
8
- */
9
- srOnly?: boolean;
7
+ export interface LegendProps extends TypographyProps, LegendClassNameOptions {
10
8
  }
11
9
  /**
12
10
  * This should be used within a `Fieldset` to apply a label.
13
11
  *
12
+ * @example Simple Example
13
+ * ```tsx
14
+ * <Fieldset>
15
+ * <Legend>I am legend</Legend>
16
+ * {children}
17
+ * </Fieldset>
18
+ * ```
19
+ *
20
+ * @example Visible to Screen readers only
21
+ * ```tsx
22
+ * <Fieldset>
23
+ * <Legend srOnly>I am legend</Legend>
24
+ * {children}
25
+ * </Fieldset>
26
+ * ```
27
+ *
28
+ * @example Acting as a floating label
29
+ * ```tsx
30
+ * <Fieldset floatingLegend>
31
+ * <Legend floating>I am legend</Legend>
32
+ * {children}
33
+ * </Fieldset>
34
+ * ```
35
+ *
14
36
  * @see {@link https://react-md.dev/components/fieldset | Fieldset Demos}
15
37
  * @since 6.0.0
16
38
  */
@@ -1,22 +1,55 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { cnb } from "cnbuilder";
3
2
  import { forwardRef } from "react";
4
- import { cssUtils } from "../cssUtils.js";
5
3
  import { Typography } from "../typography/Typography.js";
4
+ import { legend } from "./legendStyles.js";
6
5
  /**
7
6
  * This should be used within a `Fieldset` to apply a label.
8
7
  *
8
+ * @example Simple Example
9
+ * ```tsx
10
+ * <Fieldset>
11
+ * <Legend>I am legend</Legend>
12
+ * {children}
13
+ * </Fieldset>
14
+ * ```
15
+ *
16
+ * @example Visible to Screen readers only
17
+ * ```tsx
18
+ * <Fieldset>
19
+ * <Legend srOnly>I am legend</Legend>
20
+ * {children}
21
+ * </Fieldset>
22
+ * ```
23
+ *
24
+ * @example Acting as a floating label
25
+ * ```tsx
26
+ * <Fieldset floatingLegend>
27
+ * <Legend floating>I am legend</Legend>
28
+ * {children}
29
+ * </Fieldset>
30
+ * ```
31
+ *
9
32
  * @see {@link https://react-md.dev/components/fieldset | Fieldset Demos}
10
33
  * @since 6.0.0
11
34
  */ export const Legend = /*#__PURE__*/ forwardRef(function Legend(props, ref) {
12
- const { srOnly = false, className, children, ...remaining } = props;
35
+ const { srOnly, floating, theme, gap, dense, active, error, disabled, stacked, reversed, className, children, ...remaining } = props;
13
36
  return /*#__PURE__*/ _jsx(Typography, {
14
37
  ...remaining,
15
38
  as: "legend",
16
39
  ref: ref,
17
- className: cnb("rmd-legend", cssUtils({
18
- srOnly
19
- }), className),
40
+ className: legend({
41
+ srOnly,
42
+ floating,
43
+ theme,
44
+ gap,
45
+ dense,
46
+ active,
47
+ error,
48
+ disabled,
49
+ stacked,
50
+ reversed,
51
+ className
52
+ }),
20
53
  children: children
21
54
  });
22
55
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/Legend.tsx"],"sourcesContent":["import { cnb } from \"cnbuilder\";\nimport { forwardRef } from \"react\";\n\nimport { cssUtils } from \"../cssUtils.js\";\nimport { Typography, type TypographyProps } from \"../typography/Typography.js\";\n\n/**\n * @since 6.0.0\n */\nexport interface LegendProps extends TypographyProps {\n /**\n * @defaultValue `false`\n */\n srOnly?: boolean;\n}\n\n/**\n * This should be used within a `Fieldset` to apply a label.\n *\n * @see {@link https://react-md.dev/components/fieldset | Fieldset Demos}\n * @since 6.0.0\n */\nexport const Legend = forwardRef<HTMLLegendElement, LegendProps>(\n function Legend(props, ref) {\n const { srOnly = false, className, children, ...remaining } = props;\n\n return (\n <Typography\n {...remaining}\n as=\"legend\"\n ref={ref}\n className={cnb(\"rmd-legend\", cssUtils({ srOnly }), className)}\n >\n {children}\n </Typography>\n );\n }\n);\n"],"names":["cnb","forwardRef","cssUtils","Typography","Legend","props","ref","srOnly","className","children","remaining","as"],"mappings":";AAAA,SAASA,GAAG,QAAQ,YAAY;AAChC,SAASC,UAAU,QAAQ,QAAQ;AAEnC,SAASC,QAAQ,QAAQ,iBAAiB;AAC1C,SAASC,UAAU,QAA8B,8BAA8B;AAY/E;;;;;CAKC,GACD,OAAO,MAAMC,uBAASH,WACpB,SAASG,OAAOC,KAAK,EAAEC,GAAG;IACxB,MAAM,EAAEC,SAAS,KAAK,EAAEC,SAAS,EAAEC,QAAQ,EAAE,GAAGC,WAAW,GAAGL;IAE9D,qBACE,KAACF;QACE,GAAGO,SAAS;QACbC,IAAG;QACHL,KAAKA;QACLE,WAAWR,IAAI,cAAcE,SAAS;YAAEK;QAAO,IAAIC;kBAElDC;;AAGP,GACA"}
1
+ {"version":3,"sources":["../../src/form/Legend.tsx"],"sourcesContent":["import { forwardRef } from \"react\";\n\nimport { Typography, type TypographyProps } from \"../typography/Typography.js\";\nimport { type LegendClassNameOptions, legend } from \"./legendStyles.js\";\n\n/**\n * @since 6.0.0\n * @since 6.4.0 Extends the `LegendClassNameOptions`\n */\nexport interface LegendProps extends TypographyProps, LegendClassNameOptions {}\n\n/**\n * This should be used within a `Fieldset` to apply a label.\n *\n * @example Simple Example\n * ```tsx\n * <Fieldset>\n * <Legend>I am legend</Legend>\n * {children}\n * </Fieldset>\n * ```\n *\n * @example Visible to Screen readers only\n * ```tsx\n * <Fieldset>\n * <Legend srOnly>I am legend</Legend>\n * {children}\n * </Fieldset>\n * ```\n *\n * @example Acting as a floating label\n * ```tsx\n * <Fieldset floatingLegend>\n * <Legend floating>I am legend</Legend>\n * {children}\n * </Fieldset>\n * ```\n *\n * @see {@link https://react-md.dev/components/fieldset | Fieldset Demos}\n * @since 6.0.0\n */\nexport const Legend = forwardRef<HTMLLegendElement, LegendProps>(\n function Legend(props, ref) {\n const {\n srOnly,\n floating,\n theme,\n gap,\n dense,\n active,\n error,\n disabled,\n stacked,\n reversed,\n className,\n children,\n ...remaining\n } = props;\n\n return (\n <Typography\n {...remaining}\n as=\"legend\"\n ref={ref}\n className={legend({\n srOnly,\n floating,\n theme,\n gap,\n dense,\n active,\n error,\n disabled,\n stacked,\n reversed,\n className,\n })}\n >\n {children}\n </Typography>\n );\n }\n);\n"],"names":["forwardRef","Typography","legend","Legend","props","ref","srOnly","floating","theme","gap","dense","active","error","disabled","stacked","reversed","className","children","remaining","as"],"mappings":";AAAA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAASC,UAAU,QAA8B,8BAA8B;AAC/E,SAAsCC,MAAM,QAAQ,oBAAoB;AAQxE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD,OAAO,MAAMC,uBAASH,WACpB,SAASG,OAAOC,KAAK,EAAEC,GAAG;IACxB,MAAM,EACJC,MAAM,EACNC,QAAQ,EACRC,KAAK,EACLC,GAAG,EACHC,KAAK,EACLC,MAAM,EACNC,KAAK,EACLC,QAAQ,EACRC,OAAO,EACPC,QAAQ,EACRC,SAAS,EACTC,QAAQ,EACR,GAAGC,WACJ,GAAGd;IAEJ,qBACE,KAACH;QACE,GAAGiB,SAAS;QACbC,IAAG;QACHd,KAAKA;QACLW,WAAWd,OAAO;YAChBI;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;QACF;kBAECC;;AAGP,GACA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/Listbox.tsx"],"sourcesContent":["\"use client\";\n\nimport { type ReactElement, type ReactNode, type Ref } from \"react\";\n\nimport { Menu, type MenuProps } from \"../menu/Menu.js\";\nimport { type LabelRequiredForA11y } from \"../types.js\";\nimport {\n ListboxProvider,\n type ListboxProviderOptions,\n type ListboxValue,\n useListboxProvider,\n} from \"./ListboxProvider.js\";\n\n/**\n * @since 6.0.0\n * @internal\n */\nexport interface ListboxProps<Value extends ListboxValue>\n extends MenuProps,\n ListboxProviderOptions<Value> {\n nodeRef?: Ref<HTMLDivElement>;\n children: ReactNode;\n}\n\n/**\n * @since 6.0.0\n * @internal\n */\nexport function Listbox<T extends ListboxValue>(\n props: LabelRequiredForA11y<ListboxProps<T>>\n): ReactElement {\n const {\n value,\n setValue,\n children,\n nodeRef,\n selectedIconAfter,\n selectedIcon,\n unselectedIcon,\n disableSelectedIcon,\n ...remaining\n } = props;\n\n return (\n <ListboxProvider\n value={useListboxProvider({\n value,\n setValue,\n selectedIcon,\n selectedIconAfter,\n disableSelectedIcon,\n unselectedIcon,\n })}\n >\n <Menu {...remaining} ref={nodeRef}>\n {children}\n </Menu>\n </ListboxProvider>\n );\n}\n"],"names":["Menu","ListboxProvider","useListboxProvider","Listbox","props","value","setValue","children","nodeRef","selectedIconAfter","selectedIcon","unselectedIcon","disableSelectedIcon","remaining","ref"],"mappings":"AAAA;;AAIA,SAASA,IAAI,QAAwB,kBAAkB;AAEvD,SACEC,eAAe,EAGfC,kBAAkB,QACb,uBAAuB;AAa9B;;;CAGC,GACD,OAAO,SAASC,QACdC,KAA4C;IAE5C,MAAM,EACJC,KAAK,EACLC,QAAQ,EACRC,QAAQ,EACRC,OAAO,EACPC,iBAAiB,EACjBC,YAAY,EACZC,cAAc,EACdC,mBAAmB,EACnB,GAAGC,WACJ,GAAGT;IAEJ,qBACE,KAACH;QACCI,OAAOH,mBAAmB;YACxBG;YACAC;YACAI;YACAD;YACAG;YACAD;QACF;kBAEA,cAAA,KAACX;YAAM,GAAGa,SAAS;YAAEC,KAAKN;sBACvBD;;;AAIT"}
1
+ {"version":3,"sources":["../../src/form/Listbox.tsx"],"sourcesContent":["\"use client\";\n\nimport { type ReactElement, type ReactNode, type Ref } from \"react\";\n\nimport { Menu, type MenuProps } from \"../menu/Menu.js\";\nimport { type LabelRequiredForA11y } from \"../types.js\";\nimport {\n ListboxProvider,\n type ListboxProviderOptions,\n type ListboxValue,\n useListboxProvider,\n} from \"./ListboxProvider.js\";\n\n/**\n * @since 6.0.0\n * @internal\n */\nexport interface ListboxProps<Value extends ListboxValue>\n extends MenuProps, ListboxProviderOptions<Value> {\n nodeRef?: Ref<HTMLDivElement>;\n children: ReactNode;\n}\n\n/**\n * @since 6.0.0\n * @internal\n */\nexport function Listbox<T extends ListboxValue>(\n props: LabelRequiredForA11y<ListboxProps<T>>\n): ReactElement {\n const {\n value,\n setValue,\n children,\n nodeRef,\n selectedIconAfter,\n selectedIcon,\n unselectedIcon,\n disableSelectedIcon,\n ...remaining\n } = props;\n\n return (\n <ListboxProvider\n value={useListboxProvider({\n value,\n setValue,\n selectedIcon,\n selectedIconAfter,\n disableSelectedIcon,\n unselectedIcon,\n })}\n >\n <Menu {...remaining} ref={nodeRef}>\n {children}\n </Menu>\n </ListboxProvider>\n );\n}\n"],"names":["Menu","ListboxProvider","useListboxProvider","Listbox","props","value","setValue","children","nodeRef","selectedIconAfter","selectedIcon","unselectedIcon","disableSelectedIcon","remaining","ref"],"mappings":"AAAA;;AAIA,SAASA,IAAI,QAAwB,kBAAkB;AAEvD,SACEC,eAAe,EAGfC,kBAAkB,QACb,uBAAuB;AAY9B;;;CAGC,GACD,OAAO,SAASC,QACdC,KAA4C;IAE5C,MAAM,EACJC,KAAK,EACLC,QAAQ,EACRC,QAAQ,EACRC,OAAO,EACPC,iBAAiB,EACjBC,YAAY,EACZC,cAAc,EACdC,mBAAmB,EACnB,GAAGC,WACJ,GAAGT;IAEJ,qBACE,KAACH;QACCI,OAAOH,mBAAmB;YACxBG;YACAC;YACAI;YACAD;YACAG;YACAD;QACF;kBAEA,cAAA,KAACX;YAAM,GAAGa,SAAS;YAAEC,KAAKN;sBACvBD;;;AAIT"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/form/ListboxProvider.ts"],"sourcesContent":["\"use client\";\n\nimport { type Dispatch, createContext, useContext, useMemo } from \"react\";\n\nimport { type OptionSelectedIconProps } from \"./Option.js\";\n\n/**\n * @internal\n * @since 6.0.0\n */\nexport interface ListboxContext extends OptionSelectedIconProps {\n // NOTE: These are not converted to arrow functions so the option can be\n // inferred correctly\n selectOption(option: unknown): void;\n isOptionSelected(option: unknown): boolean;\n}\n\nconst context = createContext<ListboxContext | null>(null);\n\n/**\n * **Client Component**\n *\n * @internal\n * @since 6.0.0\n */\nexport const { Provider: ListboxProvider } = context;\n\n/**\n * @internal\n * @since 6.0.0\n */\nexport function useListboxContext(): ListboxContext {\n const value = useContext(context);\n if (!value) {\n throw new Error(\"The `ListboxProvider` must be a parent component\");\n }\n\n return value;\n}\n\n/**\n * @since 6.0.0\n * @internal\n */\nexport type ListboxValue = string | number | null | object;\n\n/**\n * @since 6.3.0\n */\nexport interface ListboxProviderOptions<Value extends ListboxValue>\n extends OptionSelectedIconProps {\n value: ListboxValue | readonly NonNullable<ListboxValue>[];\n setValue: Dispatch<NonNullable<Value>>;\n}\n\n/**\n * @since 6.3.0\n */\nexport function useListboxProvider<Value extends ListboxValue>(\n options: ListboxProviderOptions<Value>\n): ListboxContext {\n const {\n value,\n setValue,\n selectedIconAfter,\n selectedIcon,\n unselectedIcon,\n disableSelectedIcon,\n } = options;\n\n const values = useMemo(() => {\n if (Array.isArray(value)) {\n return new Set(value);\n }\n\n return new Set([value]);\n }, [value]);\n\n return useMemo(\n () => ({\n selectOption: setValue,\n isOptionSelected(option) {\n return values.has(option);\n },\n selectedIcon,\n unselectedIcon,\n selectedIconAfter,\n disableSelectedIcon,\n }),\n [\n disableSelectedIcon,\n selectedIcon,\n selectedIconAfter,\n setValue,\n unselectedIcon,\n values,\n ]\n );\n}\n"],"names":["createContext","useContext","useMemo","context","Provider","ListboxProvider","useListboxContext","value","Error","useListboxProvider","options","setValue","selectedIconAfter","selectedIcon","unselectedIcon","disableSelectedIcon","values","Array","isArray","Set","selectOption","isOptionSelected","option","has"],"mappings":"AAAA;AAEA,SAAwBA,aAAa,EAAEC,UAAU,EAAEC,OAAO,QAAQ,QAAQ;AAe1E,MAAMC,UAAUH,cAAqC;AAErD;;;;;CAKC,GACD,OAAO,MAAM,EAAEI,UAAUC,eAAe,EAAE,GAAGF,QAAQ;AAErD;;;CAGC,GACD,OAAO,SAASG;IACd,MAAMC,QAAQN,WAAWE;IACzB,IAAI,CAACI,OAAO;QACV,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAOD;AACT;AAiBA;;CAEC,GACD,OAAO,SAASE,mBACdC,OAAsC;IAEtC,MAAM,EACJH,KAAK,EACLI,QAAQ,EACRC,iBAAiB,EACjBC,YAAY,EACZC,cAAc,EACdC,mBAAmB,EACpB,GAAGL;IAEJ,MAAMM,SAASd,QAAQ;QACrB,IAAIe,MAAMC,OAAO,CAACX,QAAQ;YACxB,OAAO,IAAIY,IAAIZ;QACjB;QAEA,OAAO,IAAIY,IAAI;YAACZ;SAAM;IACxB,GAAG;QAACA;KAAM;IAEV,OAAOL,QACL,IAAO,CAAA;YACLkB,cAAcT;YACdU,kBAAiBC,MAAM;gBACrB,OAAON,OAAOO,GAAG,CAACD;YACpB;YACAT;YACAC;YACAF;YACAG;QACF,CAAA,GACA;QACEA;QACAF;QACAD;QACAD;QACAG;QACAE;KACD;AAEL"}
1
+ {"version":3,"sources":["../../src/form/ListboxProvider.ts"],"sourcesContent":["\"use client\";\n\nimport { type Dispatch, createContext, useContext, useMemo } from \"react\";\n\nimport { type OptionSelectedIconProps } from \"./Option.js\";\n\n/**\n * @internal\n * @since 6.0.0\n */\nexport interface ListboxContext extends OptionSelectedIconProps {\n // NOTE: These are not converted to arrow functions so the option can be\n // inferred correctly\n selectOption(option: unknown): void;\n isOptionSelected(option: unknown): boolean;\n}\n\nconst context = createContext<ListboxContext | null>(null);\n\n/**\n * **Client Component**\n *\n * @internal\n * @since 6.0.0\n */\nexport const { Provider: ListboxProvider } = context;\n\n/**\n * @internal\n * @since 6.0.0\n */\nexport function useListboxContext(): ListboxContext {\n const value = useContext(context);\n if (!value) {\n throw new Error(\"The `ListboxProvider` must be a parent component\");\n }\n\n return value;\n}\n\n/**\n * @since 6.0.0\n * @internal\n */\nexport type ListboxValue = string | number | null | object;\n\n/**\n * @since 6.3.0\n */\nexport interface ListboxProviderOptions<\n Value extends ListboxValue,\n> extends OptionSelectedIconProps {\n value: ListboxValue | readonly NonNullable<ListboxValue>[];\n setValue: Dispatch<NonNullable<Value>>;\n}\n\n/**\n * @since 6.3.0\n */\nexport function useListboxProvider<Value extends ListboxValue>(\n options: ListboxProviderOptions<Value>\n): ListboxContext {\n const {\n value,\n setValue,\n selectedIconAfter,\n selectedIcon,\n unselectedIcon,\n disableSelectedIcon,\n } = options;\n\n const values = useMemo(() => {\n if (Array.isArray(value)) {\n return new Set(value);\n }\n\n return new Set([value]);\n }, [value]);\n\n return useMemo(\n () => ({\n selectOption: setValue,\n isOptionSelected(option) {\n return values.has(option);\n },\n selectedIcon,\n unselectedIcon,\n selectedIconAfter,\n disableSelectedIcon,\n }),\n [\n disableSelectedIcon,\n selectedIcon,\n selectedIconAfter,\n setValue,\n unselectedIcon,\n values,\n ]\n );\n}\n"],"names":["createContext","useContext","useMemo","context","Provider","ListboxProvider","useListboxContext","value","Error","useListboxProvider","options","setValue","selectedIconAfter","selectedIcon","unselectedIcon","disableSelectedIcon","values","Array","isArray","Set","selectOption","isOptionSelected","option","has"],"mappings":"AAAA;AAEA,SAAwBA,aAAa,EAAEC,UAAU,EAAEC,OAAO,QAAQ,QAAQ;AAe1E,MAAMC,UAAUH,cAAqC;AAErD;;;;;CAKC,GACD,OAAO,MAAM,EAAEI,UAAUC,eAAe,EAAE,GAAGF,QAAQ;AAErD;;;CAGC,GACD,OAAO,SAASG;IACd,MAAMC,QAAQN,WAAWE;IACzB,IAAI,CAACI,OAAO;QACV,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAOD;AACT;AAkBA;;CAEC,GACD,OAAO,SAASE,mBACdC,OAAsC;IAEtC,MAAM,EACJH,KAAK,EACLI,QAAQ,EACRC,iBAAiB,EACjBC,YAAY,EACZC,cAAc,EACdC,mBAAmB,EACpB,GAAGL;IAEJ,MAAMM,SAASd,QAAQ;QACrB,IAAIe,MAAMC,OAAO,CAACX,QAAQ;YACxB,OAAO,IAAIY,IAAIZ;QACjB;QAEA,OAAO,IAAIY,IAAI;YAACZ;SAAM;IACxB,GAAG;QAACA;KAAM;IAEV,OAAOL,QACL,IAAO,CAAA;YACLkB,cAAcT;YACdU,kBAAiBC,MAAM;gBACrB,OAAON,OAAOO,GAAG,CAACD;YACpB;YACAT;YACAC;YACAF;YACAG;QACF,CAAA,GACA;QACEA;QACAF;QACAD;QACAD;QACAG;QACAE;KACD;AAEL"}