@react-md/core 6.5.0 → 6.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_utils.scss +2 -1
- package/dist/autocomplete/AutocompleteChip.js +2 -2
- package/dist/autocomplete/AutocompleteChip.js.map +1 -1
- package/dist/autocomplete/AutocompleteListboxChildren.js +1 -1
- package/dist/autocomplete/AutocompleteListboxChildren.js.map +1 -1
- package/dist/autocomplete/useAutocomplete.js +4 -4
- package/dist/autocomplete/useAutocomplete.js.map +1 -1
- package/dist/autocomplete/utils.js +3 -3
- package/dist/autocomplete/utils.js.map +1 -1
- package/dist/box/styles.js +2 -2
- package/dist/box/styles.js.map +1 -1
- package/dist/button/AsyncButton.js +1 -1
- package/dist/button/AsyncButton.js.map +1 -1
- package/dist/chip/Chip.js +1 -1
- package/dist/chip/Chip.js.map +1 -1
- package/dist/cssUtils.d.ts +11 -6
- package/dist/cssUtils.js.map +1 -1
- package/dist/datetime/useTimeField.js +1 -1
- package/dist/datetime/useTimeField.js.map +1 -1
- package/dist/delegateEvent.js +9 -9
- package/dist/delegateEvent.js.map +1 -1
- package/dist/draggable/useDraggable.js +4 -4
- package/dist/draggable/useDraggable.js.map +1 -1
- package/dist/draggable/utils.js +1 -1
- package/dist/draggable/utils.js.map +1 -1
- package/dist/expansion-panel/ExpansionPanel.js +1 -1
- package/dist/expansion-panel/ExpansionPanel.js.map +1 -1
- package/dist/expansion-panel/useExpansionPanels.js +1 -1
- package/dist/expansion-panel/useExpansionPanels.js.map +1 -1
- package/dist/files/FileInput.js +1 -1
- package/dist/files/FileInput.js.map +1 -1
- package/dist/files/createAcceptFromExtensions.d.ts +5 -0
- package/dist/files/createAcceptFromExtensions.js +15 -0
- package/dist/files/createAcceptFromExtensions.js.map +1 -0
- package/dist/files/useFileUpload.js +45 -41
- package/dist/files/useFileUpload.js.map +1 -1
- package/dist/files/utils.js +14 -10
- package/dist/files/utils.js.map +1 -1
- package/dist/files/validation.js +7 -8
- package/dist/files/validation.js.map +1 -1
- package/dist/focus/useFocusContainer.js +1 -1
- package/dist/focus/useFocusContainer.js.map +1 -1
- package/dist/focus/utils.js +12 -7
- package/dist/focus/utils.js.map +1 -1
- package/dist/form/InputToggleIcon.js +5 -1
- package/dist/form/InputToggleIcon.js.map +1 -1
- package/dist/form/NativeSelect.js +1 -1
- package/dist/form/NativeSelect.js.map +1 -1
- package/dist/form/Select.js +5 -5
- package/dist/form/Select.js.map +1 -1
- package/dist/form/formConfig.js +1 -1
- package/dist/form/formConfig.js.map +1 -1
- package/dist/form/inputToggleStyles.js +7 -1
- package/dist/form/inputToggleStyles.js.map +1 -1
- package/dist/form/selectUtils.js +2 -2
- package/dist/form/selectUtils.js.map +1 -1
- package/dist/form/useCombobox.js +1 -0
- package/dist/form/useCombobox.js.map +1 -1
- package/dist/form/useFormReset.js +2 -2
- package/dist/form/useFormReset.js.map +1 -1
- package/dist/form/useNumberField.js +1 -1
- package/dist/form/useNumberField.js.map +1 -1
- package/dist/form/useResizingTextArea.js +4 -4
- package/dist/form/useResizingTextArea.js.map +1 -1
- package/dist/form/useSelectCombobox.js +1 -1
- package/dist/form/useSelectCombobox.js.map +1 -1
- package/dist/form/validation.js +1 -1
- package/dist/form/validation.js.map +1 -1
- package/dist/hoverMode/useHoverMode.js +8 -8
- package/dist/hoverMode/useHoverMode.js.map +1 -1
- package/dist/hoverMode/useHoverModeProvider.js +3 -3
- package/dist/hoverMode/useHoverModeProvider.js.map +1 -1
- package/dist/icon/config.js +3 -3
- package/dist/icon/config.js.map +1 -1
- package/dist/icon/materialConfig.js +1 -1
- package/dist/icon/materialConfig.js.map +1 -1
- package/dist/interaction/UserInteractionModeProvider.js +11 -10
- package/dist/interaction/UserInteractionModeProvider.js.map +1 -1
- package/dist/interaction/utils.js +7 -3
- package/dist/interaction/utils.js.map +1 -1
- package/dist/layout/useExpandableLayout.js +3 -4
- package/dist/layout/useExpandableLayout.js.map +1 -1
- package/dist/layout/useMainTabIndex.js +1 -1
- package/dist/layout/useMainTabIndex.js.map +1 -1
- package/dist/list/ListItem.js +1 -1
- package/dist/list/ListItem.js.map +1 -1
- package/dist/media-queries/AppSizeProvider.js +1 -1
- package/dist/media-queries/AppSizeProvider.js.map +1 -1
- package/dist/media-queries/config.js +2 -2
- package/dist/media-queries/config.js.map +1 -1
- package/dist/media-queries/useMediaQuery.js +3 -3
- package/dist/media-queries/useMediaQuery.js.map +1 -1
- package/dist/menu/Menu.js +4 -4
- package/dist/menu/Menu.js.map +1 -1
- package/dist/menu/MenuItemButton.js +1 -1
- package/dist/menu/MenuItemButton.js.map +1 -1
- package/dist/menu/MenuItemFileInput.js +1 -1
- package/dist/menu/MenuItemFileInput.js.map +1 -1
- package/dist/menu/MenuWidget.js +2 -2
- package/dist/menu/MenuWidget.js.map +1 -1
- package/dist/movement/findMatchIndex.js +2 -2
- package/dist/movement/findMatchIndex.js.map +1 -1
- package/dist/movement/useKeyboardMovementProvider.js +2 -2
- package/dist/movement/useKeyboardMovementProvider.js.map +1 -1
- package/dist/movement/utils.js +12 -10
- package/dist/movement/utils.js.map +1 -1
- package/dist/navigation/getTableOfContentsHeadings.js +4 -3
- package/dist/navigation/getTableOfContentsHeadings.js.map +1 -1
- package/dist/navigation/useActiveHeadingId.js +9 -9
- package/dist/navigation/useActiveHeadingId.js.map +1 -1
- package/dist/navigation/useTableOfContentsHeadings.js +1 -1
- package/dist/navigation/useTableOfContentsHeadings.js.map +1 -1
- package/dist/navigation/utils.js +6 -5
- package/dist/navigation/utils.js.map +1 -1
- package/dist/portal/PortalContainerProvider.js +5 -3
- package/dist/portal/PortalContainerProvider.js.map +1 -1
- package/dist/positioning/getFixedPosition.js +2 -4
- package/dist/positioning/getFixedPosition.js.map +1 -1
- package/dist/positioning/useFixedPositioning.js +2 -2
- package/dist/positioning/useFixedPositioning.js.map +1 -1
- package/dist/positioning/utils.js +3 -3
- package/dist/positioning/utils.js.map +1 -1
- package/dist/scroll/getScrollbarWidth.js +4 -4
- package/dist/scroll/getScrollbarWidth.js.map +1 -1
- package/dist/searching/fuzzy.js +3 -2
- package/dist/searching/fuzzy.js.map +1 -1
- package/dist/searching/toSearchQuery.js +1 -1
- package/dist/searching/toSearchQuery.js.map +1 -1
- package/dist/searching/utils.js +1 -1
- package/dist/searching/utils.js.map +1 -1
- package/dist/snackbar/Toast.js +1 -1
- package/dist/snackbar/Toast.js.map +1 -1
- package/dist/snackbar/ToastContent.js +2 -2
- package/dist/snackbar/ToastContent.js.map +1 -1
- package/dist/snackbar/ToastManager.d.ts +1 -1
- package/dist/snackbar/ToastManager.js +11 -11
- package/dist/snackbar/ToastManager.js.map +1 -1
- package/dist/spinbutton/useSpinButton.js +1 -1
- package/dist/spinbutton/useSpinButton.js.map +1 -1
- package/dist/spinbutton/utils/deselectNode.js +1 -1
- package/dist/spinbutton/utils/deselectNode.js.map +1 -1
- package/dist/spinbutton/utils/resolveInputEvent.js +1 -1
- package/dist/spinbutton/utils/resolveInputEvent.js.map +1 -1
- package/dist/spinbutton/utils/selectNode.js +1 -1
- package/dist/spinbutton/utils/selectNode.js.map +1 -1
- package/dist/storage/useStorage.js +8 -3
- package/dist/storage/useStorage.js.map +1 -1
- package/dist/table/useStickyTableSection.js +1 -1
- package/dist/table/useStickyTableSection.js.map +1 -1
- package/dist/tabs/TabList.js +2 -2
- package/dist/tabs/TabList.js.map +1 -1
- package/dist/tabs/useMaxTabPanelHeight.js +4 -3
- package/dist/tabs/useMaxTabPanelHeight.js.map +1 -1
- package/dist/tabs/useTabList.js +1 -1
- package/dist/tabs/useTabList.js.map +1 -1
- package/dist/test-utils/jest-globals/match-media.d.ts +1 -1
- package/dist/test-utils/jest-globals/match-media.js +1 -1
- package/dist/test-utils/jest-globals/match-media.js.map +1 -1
- package/dist/test-utils/jest-globals/timers.js +1 -1
- package/dist/test-utils/jest-globals/timers.js.map +1 -1
- package/dist/test-utils/jest-globals/uploadMenuItemFileInput.js +1 -1
- package/dist/test-utils/jest-globals/uploadMenuItemFileInput.js.map +1 -1
- package/dist/test-utils/mocks/ResizeObserver.js +2 -2
- package/dist/test-utils/mocks/ResizeObserver.js.map +1 -1
- package/dist/test-utils/polyfills/IntersectionObserver.js +2 -2
- package/dist/test-utils/polyfills/IntersectionObserver.js.map +1 -1
- package/dist/test-utils/polyfills/ResizeObserver.js +2 -2
- package/dist/test-utils/polyfills/ResizeObserver.js.map +1 -1
- package/dist/test-utils/polyfills/TextDecoder.js +2 -2
- package/dist/test-utils/polyfills/TextDecoder.js.map +1 -1
- package/dist/test-utils/polyfills/TextEncoder.js +2 -2
- package/dist/test-utils/polyfills/TextEncoder.js.map +1 -1
- package/dist/test-utils/polyfills/matchMedia.js +2 -2
- package/dist/test-utils/polyfills/matchMedia.js.map +1 -1
- package/dist/test-utils/polyfills/offsetParent.js +2 -2
- package/dist/test-utils/polyfills/offsetParent.js.map +1 -1
- package/dist/test-utils/polyfills/scrollIntoView.js +1 -1
- package/dist/test-utils/polyfills/scrollIntoView.js.map +1 -1
- package/dist/test-utils/queries/select.js +2 -2
- package/dist/test-utils/queries/select.js.map +1 -1
- package/dist/test-utils/queries/slider.js +1 -1
- package/dist/test-utils/queries/slider.js.map +1 -1
- package/dist/test-utils/utils/createFileList.js +2 -0
- package/dist/test-utils/utils/createFileList.js.map +1 -1
- package/dist/test-utils/utils/createMatchMediaSpy.d.ts +1 -1
- package/dist/test-utils/utils/createMatchMediaSpy.js +3 -3
- package/dist/test-utils/utils/createMatchMediaSpy.js.map +1 -1
- package/dist/test-utils/vitest/match-media.d.ts +1 -1
- package/dist/test-utils/vitest/match-media.js +1 -1
- package/dist/test-utils/vitest/match-media.js.map +1 -1
- package/dist/test-utils/vitest/timers.js +1 -1
- package/dist/test-utils/vitest/timers.js.map +1 -1
- package/dist/test-utils/vitest/uploadMenuItemFileInput.js +1 -1
- package/dist/test-utils/vitest/uploadMenuItemFileInput.js.map +1 -1
- package/dist/theme/ThemeProvider.js +2 -2
- package/dist/theme/ThemeProvider.js.map +1 -1
- package/dist/theme/getDerivedTheme.js +1 -1
- package/dist/theme/getDerivedTheme.js.map +1 -1
- package/dist/theme/useCSSVariables.js +5 -5
- package/dist/theme/useCSSVariables.js.map +1 -1
- package/dist/theme/useColorSchemeMetaTag.js +2 -2
- package/dist/theme/useColorSchemeMetaTag.js.map +1 -1
- package/dist/theme/useInlineCSSVariables.js +4 -3
- package/dist/theme/useInlineCSSVariables.js.map +1 -1
- package/dist/theme/utils.js +8 -8
- package/dist/theme/utils.js.map +1 -1
- package/dist/tooltip/useTooltip.js +7 -7
- package/dist/tooltip/useTooltip.js.map +1 -1
- package/dist/tooltip/useTooltipPosition.js +1 -1
- package/dist/tooltip/useTooltipPosition.js.map +1 -1
- package/dist/transition/useCarousel.js +2 -2
- package/dist/transition/useCarousel.js.map +1 -1
- package/dist/transition/useCollapseTransition.js +1 -1
- package/dist/transition/useCollapseTransition.js.map +1 -1
- package/dist/transition/useSkeletonPlaceholder.js +4 -4
- package/dist/transition/useSkeletonPlaceholder.js.map +1 -1
- package/dist/transition/useTransition.js +2 -2
- package/dist/transition/useTransition.js.map +1 -1
- package/dist/transition/utils.js +5 -5
- package/dist/transition/utils.js.map +1 -1
- package/dist/tree/TreeItem.js +1 -1
- package/dist/tree/TreeItem.js.map +1 -1
- package/dist/tree/useTreeItems.js +7 -5
- package/dist/tree/useTreeItems.js.map +1 -1
- package/dist/tree/useTreeMovement.js +1 -1
- package/dist/tree/useTreeMovement.js.map +1 -1
- package/dist/tree/utils.js +6 -9
- package/dist/tree/utils.js.map +1 -1
- package/dist/typography/HighlightText.js +2 -1
- package/dist/typography/HighlightText.js.map +1 -1
- package/dist/typography/SrOnly.js +7 -1
- package/dist/typography/SrOnly.js.map +1 -1
- package/dist/useDebouncedFunction.js +4 -4
- package/dist/useDebouncedFunction.js.map +1 -1
- package/dist/useDropzone.js +9 -9
- package/dist/useDropzone.js.map +1 -1
- package/dist/useEnsuredState.js +5 -5
- package/dist/useEnsuredState.js.map +1 -1
- package/dist/useIntersectionObserver.js +3 -3
- package/dist/useIntersectionObserver.js.map +1 -1
- package/dist/useIsomorphicLayoutEffect.js +1 -1
- package/dist/useIsomorphicLayoutEffect.js.map +1 -1
- package/dist/useOrientation.js +1 -1
- package/dist/useOrientation.js.map +1 -1
- package/dist/useReadonlySet.js +1 -1
- package/dist/useReadonlySet.js.map +1 -1
- package/dist/useResizeListener.js +2 -2
- package/dist/useResizeListener.js.map +1 -1
- package/dist/useResizeObserver.js +3 -4
- package/dist/useResizeObserver.js.map +1 -1
- package/dist/useThrottledFunction.js +3 -3
- package/dist/useThrottledFunction.js.map +1 -1
- package/dist/useWindowSize.js +1 -1
- package/dist/useWindowSize.js.map +1 -1
- package/dist/utils/alphaNumericSort.js +3 -1
- package/dist/utils/alphaNumericSort.js.map +1 -1
- package/dist/utils/bem.js +9 -12
- package/dist/utils/bem.js.map +1 -1
- package/dist/utils/getNumberOfDigits.js +1 -0
- package/dist/utils/getNumberOfDigits.js.map +1 -1
- package/dist/utils/getRangeDefaultValue.js +1 -1
- package/dist/utils/getRangeDefaultValue.js.map +1 -1
- package/dist/utils/nearest.js +2 -2
- package/dist/utils/nearest.js.map +1 -1
- package/dist/utils/parseCssLengthUnit.js +3 -3
- package/dist/utils/parseCssLengthUnit.js.map +1 -1
- package/dist/utils/trigonometry.js +1 -1
- package/dist/utils/trigonometry.js.map +1 -1
- package/package.json +3 -1
- package/src/autocomplete/AutocompleteChip.tsx +2 -2
- package/src/autocomplete/AutocompleteListboxChildren.tsx +1 -1
- package/src/autocomplete/useAutocomplete.ts +4 -4
- package/src/autocomplete/utils.ts +3 -3
- package/src/box/styles.ts +2 -2
- package/src/button/AsyncButton.tsx +1 -3
- package/src/chip/Chip.tsx +1 -2
- package/src/cssUtils.ts +12 -6
- package/src/datetime/useTimeField.ts +1 -1
- package/src/delegateEvent.ts +9 -9
- package/src/draggable/useDraggable.ts +4 -4
- package/src/draggable/utils.ts +1 -1
- package/src/expansion-panel/ExpansionPanel.tsx +1 -1
- package/src/expansion-panel/useExpansionPanels.ts +1 -1
- package/src/files/FileInput.tsx +1 -1
- package/src/files/createAcceptFromExtensions.ts +18 -0
- package/src/files/useFileUpload.ts +36 -37
- package/src/files/utils.ts +15 -11
- package/src/files/validation.ts +7 -9
- package/src/focus/useFocusContainer.ts +1 -1
- package/src/focus/utils.ts +11 -6
- package/src/form/InputToggleIcon.tsx +5 -5
- package/src/form/NativeSelect.tsx +1 -1
- package/src/form/Select.tsx +5 -5
- package/src/form/formConfig.ts +1 -1
- package/src/form/inputToggleStyles.ts +9 -4
- package/src/form/selectUtils.ts +2 -2
- package/src/form/useCombobox.ts +1 -0
- package/src/form/useFormReset.ts +2 -2
- package/src/form/useNumberField.ts +1 -1
- package/src/form/useResizingTextArea.ts +5 -5
- package/src/form/useSelectCombobox.ts +1 -4
- package/src/form/validation.ts +1 -1
- package/src/hoverMode/useHoverMode.ts +9 -9
- package/src/hoverMode/useHoverModeProvider.ts +4 -4
- package/src/icon/config.tsx +3 -3
- package/src/icon/materialConfig.ts +1 -1
- package/src/interaction/UserInteractionModeProvider.tsx +11 -10
- package/src/interaction/utils.ts +3 -3
- package/src/layout/useExpandableLayout.ts +3 -4
- package/src/layout/useMainTabIndex.ts +1 -1
- package/src/list/ListItem.tsx +1 -1
- package/src/media-queries/AppSizeProvider.tsx +1 -1
- package/src/media-queries/config.ts +2 -2
- package/src/media-queries/useMediaQuery.ts +3 -3
- package/src/menu/Menu.tsx +4 -4
- package/src/menu/MenuItemButton.tsx +1 -1
- package/src/menu/MenuItemFileInput.tsx +1 -1
- package/src/menu/MenuWidget.tsx +6 -4
- package/src/movement/findMatchIndex.ts +2 -2
- package/src/movement/useKeyboardMovementProvider.ts +2 -2
- package/src/movement/utils.ts +15 -14
- package/src/navigation/getTableOfContentsHeadings.ts +4 -3
- package/src/navigation/useActiveHeadingId.ts +8 -8
- package/src/navigation/useTableOfContentsHeadings.ts +1 -1
- package/src/navigation/utils.ts +6 -5
- package/src/portal/PortalContainerProvider.tsx +5 -3
- package/src/positioning/getFixedPosition.ts +9 -6
- package/src/positioning/useFixedPositioning.ts +2 -2
- package/src/positioning/utils.ts +3 -3
- package/src/scroll/getScrollbarWidth.ts +4 -4
- package/src/searching/fuzzy.ts +7 -3
- package/src/searching/toSearchQuery.ts +1 -1
- package/src/searching/utils.ts +1 -1
- package/src/snackbar/Toast.tsx +1 -1
- package/src/snackbar/ToastContent.tsx +2 -2
- package/src/snackbar/ToastManager.ts +11 -12
- package/src/spinbutton/useSpinButton.ts +1 -1
- package/src/spinbutton/utils/deselectNode.ts +1 -1
- package/src/spinbutton/utils/resolveInputEvent.ts +1 -1
- package/src/spinbutton/utils/selectNode.ts +1 -1
- package/src/storage/useStorage.ts +7 -2
- package/src/table/useStickyTableSection.tsx +1 -1
- package/src/tabs/TabList.tsx +2 -2
- package/src/tabs/useMaxTabPanelHeight.ts +6 -3
- package/src/tabs/useTabList.ts +2 -2
- package/src/test-utils/jest-globals/match-media.ts +5 -2
- package/src/test-utils/jest-globals/timers.ts +1 -1
- package/src/test-utils/jest-globals/uploadMenuItemFileInput.ts +1 -1
- package/src/test-utils/mocks/ResizeObserver.ts +2 -2
- package/src/test-utils/polyfills/IntersectionObserver.ts +2 -2
- package/src/test-utils/polyfills/ResizeObserver.ts +2 -2
- package/src/test-utils/polyfills/TextDecoder.ts +2 -2
- package/src/test-utils/polyfills/TextEncoder.ts +2 -2
- package/src/test-utils/polyfills/matchMedia.ts +5 -2
- package/src/test-utils/polyfills/offsetParent.ts +2 -2
- package/src/test-utils/polyfills/scrollIntoView.ts +1 -1
- package/src/test-utils/queries/select.ts +2 -2
- package/src/test-utils/queries/slider.ts +1 -1
- package/src/test-utils/utils/createFileList.ts +2 -0
- package/src/test-utils/utils/createMatchMediaSpy.ts +4 -4
- package/src/test-utils/vitest/match-media.ts +2 -2
- package/src/test-utils/vitest/timers.ts +1 -1
- package/src/test-utils/vitest/uploadMenuItemFileInput.ts +1 -1
- package/src/theme/ThemeProvider.tsx +2 -2
- package/src/theme/getDerivedTheme.ts +1 -1
- package/src/theme/useCSSVariables.ts +5 -5
- package/src/theme/useColorSchemeMetaTag.ts +2 -2
- package/src/theme/useInlineCSSVariables.ts +6 -7
- package/src/theme/utils.ts +8 -8
- package/src/tooltip/useTooltip.ts +7 -7
- package/src/tooltip/useTooltipPosition.ts +1 -1
- package/src/transition/useCarousel.ts +2 -2
- package/src/transition/useCollapseTransition.ts +1 -1
- package/src/transition/useSkeletonPlaceholder.ts +4 -4
- package/src/transition/useTransition.ts +2 -2
- package/src/transition/utils.ts +5 -5
- package/src/tree/TreeItem.tsx +1 -1
- package/src/tree/useTreeItems.ts +5 -5
- package/src/tree/useTreeMovement.ts +1 -1
- package/src/tree/utils.ts +9 -9
- package/src/typography/HighlightText.tsx +4 -3
- package/src/typography/SrOnly.tsx +9 -2
- package/src/useDebouncedFunction.ts +5 -5
- package/src/useDropzone.ts +10 -10
- package/src/useEnsuredState.ts +5 -5
- package/src/useIntersectionObserver.ts +3 -3
- package/src/useIsomorphicLayoutEffect.ts +3 -3
- package/src/useOrientation.ts +1 -1
- package/src/useReadonlySet.ts +3 -1
- package/src/useResizeListener.ts +2 -2
- package/src/useResizeObserver.ts +3 -4
- package/src/useThrottledFunction.ts +4 -4
- package/src/useWindowSize.ts +1 -1
- package/src/utils/alphaNumericSort.ts +1 -1
- package/src/utils/bem.ts +15 -16
- package/src/utils/getNumberOfDigits.ts +1 -0
- package/src/utils/getRangeDefaultValue.ts +1 -1
- package/src/utils/nearest.ts +5 -2
- package/src/utils/parseCssLengthUnit.ts +5 -4
- package/src/utils/trigonometry.ts +1 -1
- package/dist/form/defaultGetSelectedOptionChildren.d.ts +0 -1
- package/dist/form/getSelectedOptionChildren.d.ts +0 -1
|
@@ -31,7 +31,7 @@ import { useEffect } from "react";
|
|
|
31
31
|
* @since 6.0.0
|
|
32
32
|
*/ export function useCSSVariables(variables, rootNode) {
|
|
33
33
|
useEffect(()=>{
|
|
34
|
-
if (
|
|
34
|
+
if (variables.length === 0) {
|
|
35
35
|
return;
|
|
36
36
|
}
|
|
37
37
|
// use an iife so that hoisting doesn't cause a possible "null" issue for
|
|
@@ -49,7 +49,7 @@ import { useEffect } from "react";
|
|
|
49
49
|
return;
|
|
50
50
|
}
|
|
51
51
|
// const root = document.documentElement;
|
|
52
|
-
|
|
52
|
+
for (const { name, value } of variables){
|
|
53
53
|
if (process.env.NODE_ENV !== "production" && root.style.getPropertyValue(name)) {
|
|
54
54
|
const currentValue = root.style.getPropertyValue(name);
|
|
55
55
|
const overwritten = currentValue !== value ? ` and will be overwritten to "${value}"` : "";
|
|
@@ -57,11 +57,11 @@ import { useEffect } from "react";
|
|
|
57
57
|
console.warn(`The "${name}" css variable has already been set to "${currentValue}" ` + `on the root element${overwritten}. There might be conflicting overrides.`);
|
|
58
58
|
}
|
|
59
59
|
root.style.setProperty(name, `${value}`);
|
|
60
|
-
}
|
|
60
|
+
}
|
|
61
61
|
return ()=>{
|
|
62
|
-
|
|
62
|
+
for (const { name } of variables){
|
|
63
63
|
root.style.removeProperty(name);
|
|
64
|
-
}
|
|
64
|
+
}
|
|
65
65
|
};
|
|
66
66
|
}, [
|
|
67
67
|
variables,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/theme/useCSSVariables.ts"],"sourcesContent":["\"use client\";\n\nimport { type RefObject, useEffect } from \"react\";\n\nimport { type CSSVariableName, type ReadonlyCSSVariableList } from \"./types.js\";\n\n/**\n * @example Applying Variables the root html element\n * ```ts\n * import { purple500 } from \"@react-md/core/theme/colors\";\n * import { useCSSVariables } from \"@react-md/core/theme/useCSSVariables\";\n * import { contrastColor } from \"@react-md/core/theme/utils\";\n * import { useMemo } from \"react\";\n *\n * function Example(): null {\n * // Note: You should use `useMemo` so that the custom variables are not\n * // added and removed during each render.\n * useCSSVariables(useMemo(() => {\n * return [\n * {\n * name: \"--rmd-primary-color\",\n * value: purple500,\n * },\n * {\n * name: \"--rmd-on-primary-color\",\n * value: contrastColor(purple500),\n * },\n * ];\n * }, []));\n *\n * return null;\n * }\n * ```\n *\n * @since 6.0.0\n */\nexport function useCSSVariables<Name extends CSSVariableName>(\n variables: ReadonlyCSSVariableList<Name>,\n rootNode?: RefObject<HTMLElement> | HTMLElement\n): void {\n useEffect(() => {\n if (
|
|
1
|
+
{"version":3,"sources":["../../src/theme/useCSSVariables.ts"],"sourcesContent":["\"use client\";\n\nimport { type RefObject, useEffect } from \"react\";\n\nimport { type CSSVariableName, type ReadonlyCSSVariableList } from \"./types.js\";\n\n/**\n * @example Applying Variables the root html element\n * ```ts\n * import { purple500 } from \"@react-md/core/theme/colors\";\n * import { useCSSVariables } from \"@react-md/core/theme/useCSSVariables\";\n * import { contrastColor } from \"@react-md/core/theme/utils\";\n * import { useMemo } from \"react\";\n *\n * function Example(): null {\n * // Note: You should use `useMemo` so that the custom variables are not\n * // added and removed during each render.\n * useCSSVariables(useMemo(() => {\n * return [\n * {\n * name: \"--rmd-primary-color\",\n * value: purple500,\n * },\n * {\n * name: \"--rmd-on-primary-color\",\n * value: contrastColor(purple500),\n * },\n * ];\n * }, []));\n *\n * return null;\n * }\n * ```\n *\n * @since 6.0.0\n */\nexport function useCSSVariables<Name extends CSSVariableName>(\n variables: ReadonlyCSSVariableList<Name>,\n rootNode?: RefObject<HTMLElement> | HTMLElement\n): void {\n useEffect(() => {\n if (variables.length === 0) {\n return;\n }\n\n // use an iife so that hoisting doesn't cause a possible \"null\" issue for\n // the root\n const root = (() => {\n if (!rootNode) {\n return document.documentElement;\n }\n\n if (\"current\" in rootNode) {\n return rootNode.current;\n }\n\n return rootNode;\n })();\n\n if (!root) {\n return;\n }\n\n // const root = document.documentElement;\n for (const { name, value } of variables) {\n if (\n process.env.NODE_ENV !== \"production\" &&\n root.style.getPropertyValue(name)\n ) {\n const currentValue = root.style.getPropertyValue(name);\n const overwritten =\n currentValue !== value\n ? ` and will be overwritten to \"${value}\"`\n : \"\";\n // eslint-disable-next-line no-console\n console.warn(\n `The \"${name}\" css variable has already been set to \"${currentValue}\" ` +\n `on the root element${overwritten}. There might be conflicting overrides.`\n );\n }\n\n root.style.setProperty(name, `${value}`);\n }\n return () => {\n for (const { name } of variables) {\n root.style.removeProperty(name);\n }\n };\n }, [variables, rootNode]);\n}\n"],"names":["useEffect","useCSSVariables","variables","rootNode","length","root","document","documentElement","current","name","value","process","env","NODE_ENV","style","getPropertyValue","currentValue","overwritten","console","warn","setProperty","removeProperty"],"mappings":"AAAA;AAEA,SAAyBA,SAAS,QAAQ,QAAQ;AAIlD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD,OAAO,SAASC,gBACdC,SAAwC,EACxCC,QAA+C;IAE/CH,UAAU;QACR,IAAIE,UAAUE,MAAM,KAAK,GAAG;YAC1B;QACF;QAEA,yEAAyE;QACzE,WAAW;QACX,MAAMC,OAAO,AAAC,CAAA;YACZ,IAAI,CAACF,UAAU;gBACb,OAAOG,SAASC,eAAe;YACjC;YAEA,IAAI,aAAaJ,UAAU;gBACzB,OAAOA,SAASK,OAAO;YACzB;YAEA,OAAOL;QACT,CAAA;QAEA,IAAI,CAACE,MAAM;YACT;QACF;QAEA,yCAAyC;QACzC,KAAK,MAAM,EAAEI,IAAI,EAAEC,KAAK,EAAE,IAAIR,UAAW;YACvC,IACES,QAAQC,GAAG,CAACC,QAAQ,KAAK,gBACzBR,KAAKS,KAAK,CAACC,gBAAgB,CAACN,OAC5B;gBACA,MAAMO,eAAeX,KAAKS,KAAK,CAACC,gBAAgB,CAACN;gBACjD,MAAMQ,cACJD,iBAAiBN,QACb,CAAC,6BAA6B,EAAEA,MAAM,CAAC,CAAC,GACxC;gBACN,sCAAsC;gBACtCQ,QAAQC,IAAI,CACV,CAAC,KAAK,EAAEV,KAAK,wCAAwC,EAAEO,aAAa,EAAE,CAAC,GACrE,CAAC,mBAAmB,EAAEC,YAAY,uCAAuC,CAAC;YAEhF;YAEAZ,KAAKS,KAAK,CAACM,WAAW,CAACX,MAAM,GAAGC,OAAO;QACzC;QACA,OAAO;YACL,KAAK,MAAM,EAAED,IAAI,EAAE,IAAIP,UAAW;gBAChCG,KAAKS,KAAK,CAACO,cAAc,CAACZ;YAC5B;QACF;IACF,GAAG;QAACP;QAAWC;KAAS;AAC1B"}
|
|
@@ -39,9 +39,9 @@ import { useEffect } from "react";
|
|
|
39
39
|
const meta = document.createElement("meta");
|
|
40
40
|
meta.name = "color-scheme";
|
|
41
41
|
meta.content = colorScheme;
|
|
42
|
-
document.head.
|
|
42
|
+
document.head.append(meta);
|
|
43
43
|
return ()=>{
|
|
44
|
-
|
|
44
|
+
meta.remove();
|
|
45
45
|
};
|
|
46
46
|
}, [
|
|
47
47
|
disabled,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/theme/useColorSchemeMetaTag.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect } from \"react\";\n\nimport { type LightDarkColorScheme } from \"./types.js\";\n\n/**\n * @since 6.0.0\n */\nexport interface ColorSchemeMetaTagOptions {\n /**\n * @defaultValue `\"false\"`\n */\n disabled?: boolean;\n colorScheme: LightDarkColorScheme;\n}\n\n/**\n * Adds a `<meta name=\"color-scheme\" content=\"light\">` or\n * `<meta name=\"color-scheme\" content=\"dark\">` into the head element. This\n * should not be used if you are using the `useColorSchemeProvider` since it is\n * already built in.\n *\n * @example\n * ```tsx\n * import { useColorScheme } from \"@react-md/core/theme/useColorScheme\";\n * import { useColorSchemeMetaTag } from \"@react-md/core/theme/useColorSchemeMetaTag\";\n *\n * function Example() {\n * const { currentColor } = useColorScheme();\n * useColorSchemeMetaTag({ colorScheme: currentColor });\n *\n * return null;\n * }\n * ```\n *\n * @since 6.0.0\n */\nexport function useColorSchemeMetaTag(\n options: ColorSchemeMetaTagOptions\n): void {\n const { disabled, colorScheme } = options;\n\n useEffect(() => {\n if (disabled || document.querySelector('meta[name=\"color-scheme\"]')) {\n return;\n }\n\n // Adding the meta tag allows the default browser styles for form inputs to\n // be updated as well.\n //\n // Chrome and Firefox:\n // - the input type=\"number\"'s spinner color will update from grey to white\n // - native `<select>` background color updates from grey/white to a dark color\n //\n // Chrome:\n // - the date/time/datetime icons will change from black to white\n // - the date/time/datetime pickers will use a darker theme instead of white\n const meta = document.createElement(\"meta\");\n meta.name = \"color-scheme\";\n meta.content = colorScheme;\n document.head.
|
|
1
|
+
{"version":3,"sources":["../../src/theme/useColorSchemeMetaTag.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect } from \"react\";\n\nimport { type LightDarkColorScheme } from \"./types.js\";\n\n/**\n * @since 6.0.0\n */\nexport interface ColorSchemeMetaTagOptions {\n /**\n * @defaultValue `\"false\"`\n */\n disabled?: boolean;\n colorScheme: LightDarkColorScheme;\n}\n\n/**\n * Adds a `<meta name=\"color-scheme\" content=\"light\">` or\n * `<meta name=\"color-scheme\" content=\"dark\">` into the head element. This\n * should not be used if you are using the `useColorSchemeProvider` since it is\n * already built in.\n *\n * @example\n * ```tsx\n * import { useColorScheme } from \"@react-md/core/theme/useColorScheme\";\n * import { useColorSchemeMetaTag } from \"@react-md/core/theme/useColorSchemeMetaTag\";\n *\n * function Example() {\n * const { currentColor } = useColorScheme();\n * useColorSchemeMetaTag({ colorScheme: currentColor });\n *\n * return null;\n * }\n * ```\n *\n * @since 6.0.0\n */\nexport function useColorSchemeMetaTag(\n options: ColorSchemeMetaTagOptions\n): void {\n const { disabled, colorScheme } = options;\n\n useEffect(() => {\n if (disabled || document.querySelector('meta[name=\"color-scheme\"]')) {\n return;\n }\n\n // Adding the meta tag allows the default browser styles for form inputs to\n // be updated as well.\n //\n // Chrome and Firefox:\n // - the input type=\"number\"'s spinner color will update from grey to white\n // - native `<select>` background color updates from grey/white to a dark color\n //\n // Chrome:\n // - the date/time/datetime icons will change from black to white\n // - the date/time/datetime pickers will use a darker theme instead of white\n const meta = document.createElement(\"meta\");\n meta.name = \"color-scheme\";\n meta.content = colorScheme;\n document.head.append(meta);\n\n return () => {\n meta.remove();\n };\n }, [disabled, colorScheme]);\n}\n"],"names":["useEffect","useColorSchemeMetaTag","options","disabled","colorScheme","document","querySelector","meta","createElement","name","content","head","append","remove"],"mappings":"AAAA;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAelC;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,SAASC,sBACdC,OAAkC;IAElC,MAAM,EAAEC,QAAQ,EAAEC,WAAW,EAAE,GAAGF;IAElCF,UAAU;QACR,IAAIG,YAAYE,SAASC,aAAa,CAAC,8BAA8B;YACnE;QACF;QAEA,2EAA2E;QAC3E,sBAAsB;QACtB,EAAE;QACF,sBAAsB;QACtB,2EAA2E;QAC3E,+EAA+E;QAC/E,EAAE;QACF,UAAU;QACV,iEAAiE;QACjE,4EAA4E;QAC5E,MAAMC,OAAOF,SAASG,aAAa,CAAC;QACpCD,KAAKE,IAAI,GAAG;QACZF,KAAKG,OAAO,GAAGN;QACfC,SAASM,IAAI,CAACC,MAAM,CAACL;QAErB,OAAO;YACLA,KAAKM,MAAM;QACb;IACF,GAAG;QAACV;QAAUC;KAAY;AAC5B"}
|
|
@@ -30,10 +30,11 @@ import { useMemo } from "react";
|
|
|
30
30
|
* @since 6.0.0
|
|
31
31
|
*/ export function useInlineCSSVariables(variables) {
|
|
32
32
|
return useMemo(()=>{
|
|
33
|
-
|
|
33
|
+
const style = {};
|
|
34
|
+
for (const { name, value } of variables){
|
|
34
35
|
style[name] = value;
|
|
35
|
-
|
|
36
|
-
|
|
36
|
+
}
|
|
37
|
+
return style;
|
|
37
38
|
}, [
|
|
38
39
|
variables
|
|
39
40
|
]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/theme/useInlineCSSVariables.ts"],"sourcesContent":["import { type CSSProperties, useMemo } from \"react\";\n\nimport {\n type CSSVariableName,\n type CSSVariablesProperties,\n type ReadonlyCSSVariableList,\n} from \"./types.js\";\n\n/**\n * @example Applying variables through inline styles\n * ```tsx\n * import { purple500 } from \"@react-md/core/theme/colors\";\n * import { type ReadonlyCSSVariableList } from \"@react-md/core/theme/types\";\n * import { useInlineCSSVariables } from \"@react-md/core/theme/useInlineCSSVariables\";\n * import { contrastColor } from \"@react-md/core/theme/utils\";\n * import { type ReactElement, type ReactNode, useMemo } from \"react\";\n *\n * function Example({ children }: { children: ReactNode }): ReactElement {\n * const customVariables = useMemo<ReadonlyCSSVariableList>(() => {\n * return [\n * {\n * name: \"--rmd-primary-color\",\n * value: purple500,\n * },\n * {\n * name: \"--rmd-on-primary-color\",\n * value: contrastColor(purple500),\n * },\n * ];\n * }, []);\n * const style = useInlineCSSVariables(customVariables);\n *\n * return <div style={style}>{children}</div>;\n * }\n * ```\n *\n * @since 6.0.0\n */\nexport function useInlineCSSVariables<Name extends CSSVariableName>(\n variables: ReadonlyCSSVariableList<Name>\n): CSSProperties {\n return useMemo(() => {\n
|
|
1
|
+
{"version":3,"sources":["../../src/theme/useInlineCSSVariables.ts"],"sourcesContent":["import { type CSSProperties, useMemo } from \"react\";\n\nimport {\n type CSSVariableName,\n type CSSVariablesProperties,\n type ReadonlyCSSVariableList,\n} from \"./types.js\";\n\n/**\n * @example Applying variables through inline styles\n * ```tsx\n * import { purple500 } from \"@react-md/core/theme/colors\";\n * import { type ReadonlyCSSVariableList } from \"@react-md/core/theme/types\";\n * import { useInlineCSSVariables } from \"@react-md/core/theme/useInlineCSSVariables\";\n * import { contrastColor } from \"@react-md/core/theme/utils\";\n * import { type ReactElement, type ReactNode, useMemo } from \"react\";\n *\n * function Example({ children }: { children: ReactNode }): ReactElement {\n * const customVariables = useMemo<ReadonlyCSSVariableList>(() => {\n * return [\n * {\n * name: \"--rmd-primary-color\",\n * value: purple500,\n * },\n * {\n * name: \"--rmd-on-primary-color\",\n * value: contrastColor(purple500),\n * },\n * ];\n * }, []);\n * const style = useInlineCSSVariables(customVariables);\n *\n * return <div style={style}>{children}</div>;\n * }\n * ```\n *\n * @since 6.0.0\n */\nexport function useInlineCSSVariables<Name extends CSSVariableName>(\n variables: ReadonlyCSSVariableList<Name>\n): CSSProperties {\n return useMemo(() => {\n const style: CSSVariablesProperties<Name> = {};\n for (const { name, value } of variables) {\n style[name] = value;\n }\n\n return style;\n }, [variables]);\n}\n"],"names":["useMemo","useInlineCSSVariables","variables","style","name","value"],"mappings":"AAAA,SAA6BA,OAAO,QAAQ,QAAQ;AAQpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD,OAAO,SAASC,sBACdC,SAAwC;IAExC,OAAOF,QAAQ;QACb,MAAMG,QAAsC,CAAC;QAC7C,KAAK,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAE,IAAIH,UAAW;YACvCC,KAAK,CAACC,KAAK,GAAGC;QAChB;QAEA,OAAOF;IACT,GAAG;QAACD;KAAU;AAChB"}
|
package/dist/theme/utils.js
CHANGED
|
@@ -14,9 +14,9 @@ const VERBOSE_REGEX = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
|
|
|
14
14
|
}
|
|
15
15
|
hex = hex.replace(SHORTHAND_REGEX, (_m, r, g, b)=>`${r}${r}${g}${g}${b}${b}`);
|
|
16
16
|
const result = hex.match(VERBOSE_REGEX) || [];
|
|
17
|
-
const r = parseInt(result[1] || "", 16) || 0;
|
|
18
|
-
const g = parseInt(result[2] || "", 16) || 0;
|
|
19
|
-
const b = parseInt(result[3] || "", 16) || 0;
|
|
17
|
+
const r = Number.parseInt(result[1] || "", 16) || 0;
|
|
18
|
+
const g = Number.parseInt(result[2] || "", 16) || 0;
|
|
19
|
+
const b = Number.parseInt(result[3] || "", 16) || 0;
|
|
20
20
|
return [
|
|
21
21
|
r,
|
|
22
22
|
g,
|
|
@@ -26,12 +26,12 @@ const VERBOSE_REGEX = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
|
|
|
26
26
|
export function getRGB(color) {
|
|
27
27
|
// chrome 102.0.50005.63 apparently has whitespace when calling `window.getComputedStyle(element)`
|
|
28
28
|
// remove whitespace to make it easy for supporting rgb or hex
|
|
29
|
-
color = color.
|
|
29
|
+
color = color.replaceAll(/\s/g, "");
|
|
30
30
|
const rgbMatches = color.match(RGB_REGEX);
|
|
31
31
|
if (rgbMatches) {
|
|
32
|
-
const r = parseInt(rgbMatches[1] || "", 16) || 0;
|
|
33
|
-
const g = parseInt(rgbMatches[2] || "", 16) || 0;
|
|
34
|
-
const b = parseInt(rgbMatches[3] || "", 16) || 0;
|
|
32
|
+
const r = Number.parseInt(rgbMatches[1] || "", 16) || 0;
|
|
33
|
+
const g = Number.parseInt(rgbMatches[2] || "", 16) || 0;
|
|
34
|
+
const b = Number.parseInt(rgbMatches[3] || "", 16) || 0;
|
|
35
35
|
return [
|
|
36
36
|
r,
|
|
37
37
|
g,
|
|
@@ -51,7 +51,7 @@ const BLUE_MULTIPLIER = 0.0722;
|
|
|
51
51
|
* @internal
|
|
52
52
|
*/ function get8BitColor(color) {
|
|
53
53
|
color /= 255;
|
|
54
|
-
if (color <= 0.
|
|
54
|
+
if (color <= 0.039_28) {
|
|
55
55
|
return color / 12.92;
|
|
56
56
|
}
|
|
57
57
|
return ((color + 0.055) / 1.055) ** 2.4;
|
package/dist/theme/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/theme/utils.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport { black, white } from \"./colors.js\";\n\nconst RGB_REGEX = /^rgb\\(((\\b([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\b),?){3}\\)$/;\nconst SHORTHAND_REGEX = /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i;\nconst VERBOSE_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i;\n\nexport type RGB = readonly [red: number, green: number, blue: number];\n\n/**\n * Converts a hex string into an rgb value. This is useful for detecting color\n * contrast ratios and other stuff.\n *\n * @param hex - The hex string to convert\n * @returns an object containing the r, g, b values for the color.\n */\nexport function hexToRGB(hex: string): RGB {\n if (\n process.env.NODE_ENV !== \"production\" &&\n !SHORTHAND_REGEX.test(hex) &&\n !VERBOSE_REGEX.test(hex)\n ) {\n throw new TypeError(\"Invalid color string.\");\n }\n\n hex = hex.replace(\n SHORTHAND_REGEX,\n (_m, r, g, b) => `${r}${r}${g}${g}${b}${b}`\n );\n\n const result = hex.match(VERBOSE_REGEX) || [];\n const r = parseInt(result[1] || \"\", 16) || 0;\n const g = parseInt(result[2] || \"\", 16) || 0;\n const b = parseInt(result[3] || \"\", 16) || 0;\n\n return [r, g, b];\n}\n\nexport function getRGB(color: string): RGB {\n // chrome 102.0.50005.63 apparently has whitespace when calling `window.getComputedStyle(element)`\n // remove whitespace to make it easy for supporting rgb or hex\n color = color.
|
|
1
|
+
{"version":3,"sources":["../../src/theme/utils.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport { black, white } from \"./colors.js\";\n\nconst RGB_REGEX = /^rgb\\(((\\b([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\b),?){3}\\)$/;\nconst SHORTHAND_REGEX = /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i;\nconst VERBOSE_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i;\n\nexport type RGB = readonly [red: number, green: number, blue: number];\n\n/**\n * Converts a hex string into an rgb value. This is useful for detecting color\n * contrast ratios and other stuff.\n *\n * @param hex - The hex string to convert\n * @returns an object containing the r, g, b values for the color.\n */\nexport function hexToRGB(hex: string): RGB {\n if (\n process.env.NODE_ENV !== \"production\" &&\n !SHORTHAND_REGEX.test(hex) &&\n !VERBOSE_REGEX.test(hex)\n ) {\n throw new TypeError(\"Invalid color string.\");\n }\n\n hex = hex.replace(\n SHORTHAND_REGEX,\n (_m, r, g, b) => `${r}${r}${g}${g}${b}${b}`\n );\n\n const result = hex.match(VERBOSE_REGEX) || [];\n const r = Number.parseInt(result[1] || \"\", 16) || 0;\n const g = Number.parseInt(result[2] || \"\", 16) || 0;\n const b = Number.parseInt(result[3] || \"\", 16) || 0;\n\n return [r, g, b];\n}\n\nexport function getRGB(color: string): RGB {\n // chrome 102.0.50005.63 apparently has whitespace when calling `window.getComputedStyle(element)`\n // remove whitespace to make it easy for supporting rgb or hex\n color = color.replaceAll(/\\s/g, \"\");\n const rgbMatches = color.match(RGB_REGEX);\n if (rgbMatches) {\n const r = Number.parseInt(rgbMatches[1] || \"\", 16) || 0;\n const g = Number.parseInt(rgbMatches[2] || \"\", 16) || 0;\n const b = Number.parseInt(rgbMatches[3] || \"\", 16) || 0;\n\n return [r, g, b];\n }\n\n return hexToRGB(color);\n}\n\nconst RED_MULTIPLIER = 0.2126;\nconst GREEN_MULTIPLIER = 0.7152;\nconst BLUE_MULTIPLIER = 0.0722;\n\n/**\n * I really couldn't figure out how to name these \"magic\" numbers since the\n * formula doesn't really describe it much:\n *\n * @see https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n * @internal\n */\nfunction get8BitColor(color: number): number {\n color /= 255;\n\n if (color <= 0.039_28) {\n return color / 12.92;\n }\n\n return ((color + 0.055) / 1.055) ** 2.4;\n}\n\n/**\n * A number closest to 0 should be closest to black while a number closest to 1\n * should be closest to white.\n *\n * @see https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n * @internal\n */\nexport function getLuminance(color: string): number {\n const [r, g, b] = getRGB(color);\n\n const red = get8BitColor(r) * RED_MULTIPLIER;\n const green = get8BitColor(g) * GREEN_MULTIPLIER;\n const blue = get8BitColor(b) * BLUE_MULTIPLIER;\n\n return red + green + blue;\n}\n\n/**\n * Gets the contrast ratio between a background color and a foreground color.\n *\n * @see https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n *\n * @param background - The background color\n * @param foreground - The foreground color. This is normally the `color` css\n * value.\n * @returns the contrast ratio between the background and foreground colors.\n */\nexport function getContrastRatio(\n background: string,\n foreground: string\n): number {\n const backgroundLuminance = getLuminance(background) + 0.05;\n const foregroundLuminance = getLuminance(foreground) + 0.05;\n\n return (\n Math.max(backgroundLuminance, foregroundLuminance) /\n Math.min(backgroundLuminance, foregroundLuminance)\n );\n}\n\n/**\n * The type of contrast ratio compliance to confirm to. The ratios in order are:\n * - 3:1 for large text (18pt normal or 14pt bold)\n * - 4.5:1 for normal text\n * - 7:1 for Level AAA requirements.\n *\n * @see https://www.w3.org/TR/WCAG20/#visual-audio-contrast\n * @see https://www.w3.org/TR/WCAG20/#larger-scaledef\n */\nexport type ContrastRatioCompliance = \"large\" | \"normal\" | \"AAA\";\n\n/**\n * The contrast ratio that can be used for large text where large text is\n * considered 18pt or 14pt bold.\n */\nexport const LARGE_TEXT_CONTRAST_RATIO = 3;\n\n/**\n * The contrast ratio that can be used for normal text.\n */\nexport const NORMAL_TEXT_CONTRAST_RATIO = 4.5;\n\n/**\n * The AAA contrast ratio for passing WGAC 2.0 color contrast ratios.\n */\nexport const AAA_CONTRAST_RATIO = 7;\n\n/**\n * Checks if there is an acceptable contrast ratio between the background and\n * foreground colors based on the provided compliance level.\n *\n * @param background - The background color to check against\n * @param foreground - The foreground color to check against\n * @param compliance - The compliance level to use or a custom number as a\n * ratio.\n * @returns true if there is enough contrast between the foreground and\n * background colors for the provided compliance level.\n */\nexport function isContrastCompliant(\n background: string,\n foreground: string,\n compliance: ContrastRatioCompliance | number = \"normal\"\n): boolean {\n let ratio: number;\n switch (compliance) {\n case \"large\":\n ratio = LARGE_TEXT_CONTRAST_RATIO;\n break;\n case \"normal\":\n ratio = NORMAL_TEXT_CONTRAST_RATIO;\n break;\n case \"AAA\":\n ratio = AAA_CONTRAST_RATIO;\n break;\n default:\n ratio = compliance;\n }\n\n return getContrastRatio(background, foreground) >= ratio;\n}\n\n/**\n * Returns the highest contrast color to the provided `backgroundColor`. This is\n * normally used to ensure that a new background color can use an accessible text\n * color of either `#000` or `#fff`.\n *\n * This is pretty much a javascript implementation as the `contrast-color` Sass\n * function.\n *\n * @since 6.0.0\n */\nexport function contrastColor(\n backgroundColor: string,\n lightColor = white,\n darkColor = black\n): string {\n const lightContrast = getContrastRatio(backgroundColor, lightColor);\n const darkContrast = getContrastRatio(backgroundColor, darkColor);\n\n return lightContrast > darkContrast ? lightColor : darkColor;\n}\n"],"names":["black","white","RGB_REGEX","SHORTHAND_REGEX","VERBOSE_REGEX","hexToRGB","hex","process","env","NODE_ENV","test","TypeError","replace","_m","r","g","b","result","match","Number","parseInt","getRGB","color","replaceAll","rgbMatches","RED_MULTIPLIER","GREEN_MULTIPLIER","BLUE_MULTIPLIER","get8BitColor","getLuminance","red","green","blue","getContrastRatio","background","foreground","backgroundLuminance","foregroundLuminance","Math","max","min","LARGE_TEXT_CONTRAST_RATIO","NORMAL_TEXT_CONTRAST_RATIO","AAA_CONTRAST_RATIO","isContrastCompliant","compliance","ratio","contrastColor","backgroundColor","lightColor","darkColor","lightContrast","darkContrast"],"mappings":"AAAA,oCAAoC,GACpC,SAASA,KAAK,EAAEC,KAAK,QAAQ,cAAc;AAE3C,MAAMC,YAAY;AAClB,MAAMC,kBAAkB;AACxB,MAAMC,gBAAgB;AAItB;;;;;;CAMC,GACD,OAAO,SAASC,SAASC,GAAW;IAClC,IACEC,QAAQC,GAAG,CAACC,QAAQ,KAAK,gBACzB,CAACN,gBAAgBO,IAAI,CAACJ,QACtB,CAACF,cAAcM,IAAI,CAACJ,MACpB;QACA,MAAM,IAAIK,UAAU;IACtB;IAEAL,MAAMA,IAAIM,OAAO,CACfT,iBACA,CAACU,IAAIC,GAAGC,GAAGC,IAAM,GAAGF,IAAIA,IAAIC,IAAIA,IAAIC,IAAIA,GAAG;IAG7C,MAAMC,SAASX,IAAIY,KAAK,CAACd,kBAAkB,EAAE;IAC7C,MAAMU,IAAIK,OAAOC,QAAQ,CAACH,MAAM,CAAC,EAAE,IAAI,IAAI,OAAO;IAClD,MAAMF,IAAII,OAAOC,QAAQ,CAACH,MAAM,CAAC,EAAE,IAAI,IAAI,OAAO;IAClD,MAAMD,IAAIG,OAAOC,QAAQ,CAACH,MAAM,CAAC,EAAE,IAAI,IAAI,OAAO;IAElD,OAAO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D,OAAO,MAAMI,4BAA4B,EAAE;AAE3C;;CAEC,GACD,OAAO,MAAMC,6BAA6B,IAAI;AAE9C;;CAEC,GACD,OAAO,MAAMC,qBAAqB,EAAE;AAEpC;;;;;;;;;;CAUC,GACD,OAAO,SAASC,oBACdV,UAAkB,EAClBC,UAAkB,EAClBU,aAA+C,QAAQ;IAEvD,IAAIC;IACJ,OAAQD;QACN,KAAK;YACHC,QAAQL;YACR;QACF,KAAK;YACHK,QAAQJ;YACR;QACF,KAAK;YACHI,QAAQH;YACR;QACF;YACEG,QAAQD;IACZ;IAEA,OAAOZ,iBAAiBC,YAAYC,eAAeW;AACrD;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASC,cACdC,eAAuB,EACvBC,aAAahD,KAAK,EAClBiD,YAAYlD,KAAK;IAEjB,MAAMmD,gBAAgBlB,iBAAiBe,iBAAiBC;IACxD,MAAMG,eAAenB,iBAAiBe,iBAAiBE;IAEvD,OAAOC,gBAAgBC,eAAeH,aAAaC;AACrD"}
|
|
@@ -136,7 +136,7 @@ const noop = ()=>{
|
|
|
136
136
|
let tooltipSpacing = dense ? denseSpacing : spacing;
|
|
137
137
|
const tooltip = tooltipRef.current;
|
|
138
138
|
if (!disableAutoSpacing && tooltip) {
|
|
139
|
-
tooltipSpacing =
|
|
139
|
+
tooltipSpacing = globalThis.getComputedStyle(tooltip).getPropertyValue(TOOLTIP_SPACING_VAR) || spacing;
|
|
140
140
|
}
|
|
141
141
|
const currentSpacing = parseCssLengthUnit({
|
|
142
142
|
value: tooltipSpacing
|
|
@@ -184,13 +184,13 @@ const noop = ()=>{
|
|
|
184
184
|
hideTooltip();
|
|
185
185
|
}
|
|
186
186
|
};
|
|
187
|
-
|
|
187
|
+
globalThis.addEventListener("keydown", handleKeyDown);
|
|
188
188
|
window.addEventListener("scroll", hideTooltip, true);
|
|
189
|
-
|
|
189
|
+
globalThis.addEventListener("touchend", hideTooltip, true);
|
|
190
190
|
return ()=>{
|
|
191
|
-
|
|
191
|
+
globalThis.removeEventListener("keydown", handleKeyDown);
|
|
192
192
|
window.removeEventListener("scroll", hideTooltip, true);
|
|
193
|
-
|
|
193
|
+
globalThis.removeEventListener("touchend", hideTooltip, true);
|
|
194
194
|
};
|
|
195
195
|
}, [
|
|
196
196
|
hideTooltip,
|
|
@@ -203,7 +203,7 @@ const noop = ()=>{
|
|
|
203
203
|
onDisabledCleanup: hideTooltip,
|
|
204
204
|
onChange (active) {
|
|
205
205
|
if (active) {
|
|
206
|
-
refocusFrame.current =
|
|
206
|
+
refocusFrame.current = globalThis.requestAnimationFrame(()=>{
|
|
207
207
|
pageInactive.current = false;
|
|
208
208
|
});
|
|
209
209
|
return;
|
|
@@ -304,7 +304,7 @@ const noop = ()=>{
|
|
|
304
304
|
return;
|
|
305
305
|
}
|
|
306
306
|
event.preventDefault();
|
|
307
|
-
const selection =
|
|
307
|
+
const selection = globalThis.getSelection();
|
|
308
308
|
const node = selection?.anchorNode?.parentElement;
|
|
309
309
|
if (node && event.currentTarget.contains(node)) {
|
|
310
310
|
selection.empty();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/tooltip/useTooltip.ts"],"sourcesContent":["\"use client\";\n\nimport { cnb } from \"cnbuilder\";\nimport {\n type CSSProperties,\n type FocusEvent,\n type MouseEvent,\n type MutableRefObject,\n type Ref,\n type RefObject,\n type TouchEvent,\n useCallback,\n useEffect,\n useId,\n useRef,\n} from \"react\";\n\nimport {\n type ControlledHoverModeImplementation,\n useHoverMode,\n} from \"../hoverMode/useHoverMode.js\";\nimport {\n type UserInteractionMode,\n useUserInteractionMode,\n} from \"../interaction/UserInteractionModeProvider.js\";\nimport { type SimplePosition } from \"../positioning/types.js\";\nimport {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n type FixedPositioningOptions,\n type FixedPositioningTransitionCallbacks,\n useFixedPositioning,\n} from \"../positioning/useFixedPositioning.js\";\nimport { type UseStateSetter } from \"../types.js\";\nimport { usePageInactive } from \"../usePageInactive.js\";\nimport { parseCssLengthUnit } from \"../utils/parseCssLengthUnit.js\";\nimport { useTooltipHoverMode } from \"./TooltipHoverModeProvider.js\";\nimport {\n DEFAULT_TOOLTIP_DENSE_SPACING,\n DEFAULT_TOOLTIP_MARGIN,\n DEFAULT_TOOLTIP_POSITION,\n DEFAULT_TOOLTIP_SPACING,\n DEFAULT_TOOLTIP_THRESHOLD,\n TOOLTIP_SPACING_VAR,\n} from \"./constants.js\";\nimport {\n type TooltipPositionHookOptions,\n useTooltipPosition,\n} from \"./useTooltipPosition.js\";\nimport { getAnchor } from \"./utils.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/** @since 2.8.0 */\nexport interface TooltipPositioningOptions {\n style?: CSSProperties;\n\n /**\n * @see {@link FixedPositioningOptions.vwMargin}\n * @defaultValue `16`\n */\n vwMargin?: number;\n\n /**\n * @see {@link FixedPositioningOptions.vhMargin}\n * @defaultValue `16`\n */\n vhMargin?: number;\n\n /**\n * Set this to `true` to reduce the font size and padding on the tooltip and\n * the amount of spacing between the tooltipped element and the tooltip.\n *\n * @defaultValue `false`\n */\n dense?: boolean;\n\n /**\n * The amount of spacing to use between the tooltipped element and the tooltip\n * when {@link disableAutoSpacing} is `false`.\n *\n * @defaultValue `\"1.5rem`\n */\n spacing?: number | string;\n\n /**\n * The amount of spacing to use between the tooltipped element and the tooltip\n * when {@link disableAutoSpacing} is `false` and {@link dense} is `true`.\n *\n * @defaultValue `\"0.875rem`\n */\n denseSpacing?: number | string;\n\n /**\n * Set this to `true` to prevent the {@link defaultPosition} to swap to the\n * other side of the tooltipped element when it is too close to the viewport\n * edge. This will always be `true` if a {@link position} is provided.\n *\n * @defaultValue `false`\n */\n disableSwapping?: boolean;\n\n /**\n * @defaultValue `false`\n */\n disableAutoSpacing?: boolean;\n}\n\n/**\n * @since 2.8.0\n * @since 6.0.0 Removed the `TooltipTouchEventHandlers` and\n * `TooltipKeyboardEventHandlers` types, removed the need for the `onKeyDown`\n * event.\n */\nexport interface TooltippedElementEventHandlers<\n E extends HTMLElement = HTMLButtonElement,\n> {\n onBlur?: (event: FocusEvent<E>) => void;\n onFocus?: (event: FocusEvent<E>) => void;\n onMouseEnter?: (event: MouseEvent<E>) => void;\n onMouseLeave?: (event: MouseEvent<E>) => void;\n onTouchStart?: (event: TouchEvent<E>) => void;\n onTouchEnd?: (event: TouchEvent<E>) => void;\n onContextMenu?: (event: MouseEvent<E>) => void;\n}\n\n/**\n * @since 2.8.0\n * @since 6.0.0 Renamed from `TooltipHookProvidedElementProps`\n */\nexport interface ProvidedTooltippedElementProps<\n E extends HTMLElement,\n> extends Required<TooltippedElementEventHandlers<E>> {\n \"aria-describedby\": string | undefined;\n id: string;\n}\n\n/**\n * @since 2.8.0\n * @since 6.0.0 A major API change for the hover mode behavior and no longer\n * requires a `baseId`/`id` for the tooltip. Also renamed from\n * `TooltipHookOptions` to `TooltipOptions` to match other hook naming\n * conventions.\n */\nexport interface TooltipOptions<\n TooltippedElement extends HTMLElement = HTMLButtonElement,\n>\n extends\n FixedPositioningTransitionCallbacks,\n TooltippedElementEventHandlers<TooltippedElement>,\n TooltipPositioningOptions,\n TooltipPositionHookOptions {\n /**\n * @defaultValue `\"tooltip-\" + useId()`\n */\n id?: string;\n\n /**\n * An optional override for the `aria-describedby`\n */\n describedBy?: string;\n\n /**\n * Any styles to be merged with the fixed positioning styles for the tooltip.\n */\n style?: CSSProperties;\n\n /**\n * Boolean if the event handlers should no longer attempt to show a tooltip. This\n * should be set to `true` when your component might not have a tooltip associated\n * with it.\n *\n * @example Real World Example\n * ```tsx\n * // This is _almost_ the source code for the `TooltippedButton` provided by react-md\n * import { Button } from \"@react-md/core/button/Button\";\n * import { Tooltip } from \"@react-md/core/tooltip/Tooltip\";\n * import { useTooltip } from \"@react-md/core/tooltip/useTooltip\";\n * import { type ReactElement, type ReactNode } from \"react\";\n *\n * export interface TooltippedButtonProps extends ButtonProps {\n * tooltip?: ReactNode;\n * }\n *\n * export function TooltippedButton({\n * id,\n * tooltip,\n * children,\n * onBlur,\n * onFocus,\n * onMouseEnter,\n * onMouseLeave,\n * onTouchStart,\n * onTouchEnd,\n * onContextMenu,\n * ...props\n * }: TooltippedButtonProps): ReactElement {\n * const { elementProps, tooltipProps } = useTooltip({\n * id,\n * disabled: !tooltip,\n * onBlur,\n * onFocus,\n * onMouseEnter,\n * onMouseLeave,\n * onTouchStart,\n * onTouchEnd,\n * onContextMenu,\n * });\n *\n * return (\n * <>\n * <Button {...props} {...elementProps}>\n * {children}\n * </Button>\n * <Tooltip {...tooltipProps}>{tooltip}</Tooltip>\n * </>\n * );\n * }\n * ```\n *\n * @defaultValue `false`\n * @since 5.1.0\n */\n disabled?: boolean;\n\n /**\n * The amount of time (in ms) to hover an element before the tooltip becomes\n * visible.\n *\n * The default value is really the current hover timeout from the\n * `TooltipHoverModeProvider`.\n *\n * @defaultValue `1000`\n */\n hoverTimeout?: number;\n\n /**\n * The amount of time to wait before triggering the exit animation for the\n * tooltip.\n *\n * The default value is really the current leaveTimeout timeout from the\n * `TooltipHoverModeProvider`.\n *\n * @defaultValue `0`\n */\n leaveTimeout?: number;\n\n /**\n * Set this to `true` to only allow the tooltip to become visible when the\n * `event .currentTarget` or `overflowRef` has text overflow.\n *\n * @defaultValue `false`\n * @since 6.0.0\n */\n overflowOnly?: boolean;\n\n /**\n * @see {@link FixedPositioningOptions.disabled}\n * @defaultValue `false`\n */\n disableFixedPositioning?: boolean;\n}\n\n/**\n * @since 2.8.0\n * @since 6.0.0 This was renamed from `TooltipHookProvidedTooltipProps`\n */\nexport interface ProvidedTooltipProps<\n E extends HTMLElement = HTMLSpanElement,\n> extends Required<FixedPositioningTransitionCallbacks> {\n id: string;\n ref: Ref<E>;\n dense: boolean;\n style: CSSProperties | undefined;\n visible: boolean;\n position: SimplePosition;\n}\n\n/**\n * @since 2.8.0\n * @since 6.0.0 No longer returns any properties from the hover mode provider\n * because of the major API change to hover mode.. Also renamed from\n * `TooltipHookReturnValue` to `TooltipImplementation` to match other hook\n * naming conventions.\n */\nexport interface TooltipImplementation<\n TooltippedElement extends HTMLElement = HTMLButtonElement,\n TooltipElement extends HTMLElement = HTMLSpanElement,\n> extends ControlledHoverModeImplementation {\n visible: boolean;\n setVisible: UseStateSetter<boolean>;\n animatedOnce: boolean;\n initiatedBy: MutableRefObject<UserInteractionMode | null>;\n elementProps: ProvidedTooltippedElementProps<TooltippedElement>;\n tooltipProps: ProvidedTooltipProps<TooltipElement>;\n\n /**\n * This is a wrapper around the {@link setVisible} behavior that will also\n * clear any pending timeouts.\n */\n hideTooltip: () => void;\n\n /**\n * @since 6.0.0\n */\n overflowRef: RefObject<HTMLElement>;\n}\n\n/**\n * @example Simple Usage\n * ```tsx\n * import { Button } from \"@react-md/core/button/Button\";\n * import { Tooltip } from \"@react-md/core/tooltip/Tooltip\";\n * import { useTooltip } from \"@react-md/core/tooltip/useTooltip\";\n *\n * function Example() {\n * const { elementProps, tooltipProps } = useTooltip();\n *\n * return (\n * <>\n * <Button {...elementProps}>Button</Button>\n * <Tooltip {...tooltipProps}>\n * Tooltip Content\n * </Tooltip>\n * </>\n * );\n * }\n * ```\n *\n * @example Overflow-only Tooltips\n * ```tsx\n * import { cssUtils } from \"@react-md/core/cssUtils\";\n * import { Link, type LinkProps } from \"@react-md/core/link/Link\";\n * import { Tooltip } from \"@react-md/core/tooltip/Tooltip\";\n * import { useTooltip } from \"@react-md/core/tooltip/useTooltip\";\n * import { type ReactElement } from \"react\";\n *\n * function NavigationLink(props: LinkProps): ReactElement {\n * const { children, ...remaining } = props;\n *\n * // using the `overflowRef` is optional and will default to the\n * // `event.currentTarget` when `null`\n * const { overflowRef, elementProps, tooltipProps } = useOverflowTooltip({\n * // just to pass any event handlers\n * ...remaining,\n * overflowOnly: true,\n * });\n *\n * return (\n * <Link {...remaining} {...elementProps} style={{ width: \"100%\" }}>\n * <span ref={overflowRef} className={cssUtils({ textOverflow: \"ellipsis\" })}>\n * {children}\n * </span>\n * <Tooltip {...tooltipProps}>\n * {children}\n * </Tooltip>\n * </Link>\n * );\n * }\n *\n * function Example(): ReactElement {\n * return (\n * <div style={{ width: \"10rem\", overflow: \"auto\" }}>\n * <NavigationLink href=\"/\">Home</NavigationLink>\n * <NavigationLink href=\"/some-path\">\n * Super long text that will be truncated with ellipsis and\n * have a tooltip appear\n * </NavigationLink>\n * </div>\n * );\n * }\n * ```\n *\n * ## Inspecting Tooltip Styles\n *\n * Since tooltips will disappear on blur, mouseleave, etc, it is a bit hard to\n * inspect the tooltip styles. In dev mode, you can manually set the visibility\n * to `true` through the dev tools.\n * - find your tooltip implementation\n * - expand the Tooltip hook\n * - expand the HoverMode hook\n * - set the first boolean state to `true`\n *\n * The tooltip will now remain visible allowing you to find it within the\n * \"Inspector\" tab in the dev tools.\n *\n * @see {@link https://react-md.dev/components/tooltip | Tooltip Demos}\n * @since 2.8.0\n * @since 6.0.0 Uses a separate `TooltipHoverModeProvider`.\n *\n * TODO: I need to fix the tooltip for click events and history changes since\n * the mouseleave event will not be correctly bubbled if hovering a child\n * element when the click or history update happens. this causes the tooltip to\n * stay visible\n */\nexport function useTooltip<\n TooltippedElement extends HTMLElement = HTMLButtonElement,\n TooltipElement extends HTMLElement = HTMLSpanElement,\n>(\n options: TooltipOptions<TooltippedElement> = {}\n): TooltipImplementation<TooltippedElement, TooltipElement> {\n const {\n id: propId,\n style: propStyle,\n disabled = false,\n describedBy,\n dense = false,\n hoverTimeout,\n leaveTimeout,\n vwMargin = DEFAULT_TOOLTIP_MARGIN,\n vhMargin = DEFAULT_TOOLTIP_MARGIN,\n spacing = DEFAULT_TOOLTIP_SPACING,\n denseSpacing = DEFAULT_TOOLTIP_DENSE_SPACING,\n disableSwapping,\n disableAutoSpacing,\n position: determinedPosition,\n defaultPosition = DEFAULT_TOOLTIP_POSITION,\n threshold = DEFAULT_TOOLTIP_THRESHOLD,\n onBlur = noop,\n onFocus = noop,\n onMouseEnter = noop,\n onMouseLeave = noop,\n onTouchStart = noop,\n onTouchEnd = noop,\n onContextMenu = noop,\n onEnter = noop,\n onEntering,\n onEntered = noop,\n onExited,\n overflowOnly,\n disableFixedPositioning,\n } = options;\n\n const fallbackId = useId();\n const id = propId || fallbackId;\n const tooltipId = `${id}-tooltip`;\n const {\n animatedOnceRef,\n hoverTimeoutRef,\n leaveTimeoutRef,\n enableHoverMode,\n disableHoverMode,\n startDisableTimer,\n clearDisableTimer,\n } = useTooltipHoverMode();\n const {\n visible,\n setVisible,\n startShowFlow,\n startHideFlow,\n clearVisibilityTimeout,\n } = useHoverMode({\n hoverTimeout,\n hoverTimeoutRef,\n leaveTimeout,\n leaveTimeoutRef,\n enableHoverMode,\n disableHoverMode,\n startDisableTimer,\n clearDisableTimer,\n });\n const [position, updatePosition] = useTooltipPosition({\n position: determinedPosition,\n defaultPosition,\n threshold,\n });\n\n const mode = useUserInteractionMode();\n const elementRef = useRef<HTMLElement | null>(null);\n const tooltipRef = useRef<TooltipElement>(null);\n const overflowRef = useRef<HTMLElement>(null);\n const initiatedBy = useRef<UserInteractionMode | null>(null);\n const { ref, style, callbacks } = useFixedPositioning({\n nodeRef: tooltipRef,\n style: propStyle,\n fixedTo: elementRef,\n anchor: getAnchor(position),\n disableSwapping: disableSwapping ?? !!determinedPosition,\n disabled: disableFixedPositioning,\n getFixedPositionOptions() {\n let tooltipSpacing = dense ? denseSpacing : spacing;\n const tooltip = tooltipRef.current;\n if (!disableAutoSpacing && tooltip) {\n tooltipSpacing =\n window\n .getComputedStyle(tooltip)\n .getPropertyValue(TOOLTIP_SPACING_VAR) || spacing;\n }\n\n const currentSpacing = parseCssLengthUnit({\n value: tooltipSpacing,\n });\n const horizontal = position === \"left\" || position === \"right\";\n\n return {\n vwMargin,\n vhMargin,\n xMargin: horizontal ? currentSpacing : undefined,\n yMargin: horizontal ? undefined : currentSpacing,\n };\n },\n onEnter(appearing) {\n onEnter(appearing);\n\n // This allows you to inspect the tooltip styles through the element\n // inspector without first hovering or focusing the tooltipped element\n // beforehand by setting the `HoverMode` hook to `true`\n if (process.env.NODE_ENV !== \"production\" && !elementRef.current) {\n elementRef.current = document.getElementById(id);\n }\n },\n onEntering,\n onEntered(appearing) {\n onEntered(appearing);\n\n animatedOnceRef.current = true;\n },\n onExited,\n });\n\n const hideTooltip = useCallback(() => {\n initiatedBy.current = null;\n disableHoverMode();\n clearVisibilityTimeout();\n setVisible(false);\n }, [clearVisibilityTimeout, disableHoverMode, setVisible]);\n\n useEffect(() => {\n if (!visible) {\n return;\n }\n\n const handleKeyDown = (event: KeyboardEvent): void => {\n if (event.key === \"Escape\") {\n hideTooltip();\n }\n };\n\n window.addEventListener(\"keydown\", handleKeyDown);\n window.addEventListener(\"scroll\", hideTooltip, true);\n window.addEventListener(\"touchend\", hideTooltip, true);\n return () => {\n window.removeEventListener(\"keydown\", handleKeyDown);\n window.removeEventListener(\"scroll\", hideTooltip, true);\n window.removeEventListener(\"touchend\", hideTooltip, true);\n };\n }, [hideTooltip, visible]);\n\n const refocusFrame = useRef(0);\n const pageInactive = useRef(false);\n usePageInactive({\n disabled,\n onDisabledCleanup: hideTooltip,\n onChange(active) {\n if (active) {\n refocusFrame.current = window.requestAnimationFrame(() => {\n pageInactive.current = false;\n });\n return;\n }\n\n pageInactive.current = true;\n hideTooltip();\n },\n });\n\n const isNotOverflown = (currentTarget: HTMLElement): boolean => {\n if (!overflowOnly) {\n return false;\n }\n\n const element = overflowRef.current || currentTarget;\n return !element || element.offsetWidth >= element.scrollWidth;\n };\n\n return {\n visible,\n setVisible,\n hideTooltip,\n animatedOnce: animatedOnceRef.current,\n initiatedBy,\n overflowRef,\n startShowFlow,\n startHideFlow,\n clearVisibilityTimeout,\n tooltipProps: {\n id: tooltipId,\n ref,\n dense,\n style,\n visible,\n position,\n ...callbacks,\n },\n elementProps: {\n \"aria-describedby\": cnb(visible && tooltipId, describedBy) || undefined,\n id,\n onMouseEnter(event) {\n onMouseEnter(event);\n if (\n disabled ||\n mode === \"touch\" ||\n initiatedBy.current !== null ||\n isNotOverflown(event.currentTarget)\n ) {\n return;\n }\n\n initiatedBy.current = \"mouse\";\n elementRef.current = event.currentTarget;\n updatePosition(event.currentTarget);\n startShowFlow(id);\n },\n onMouseLeave(event) {\n onMouseLeave(event);\n if (disabled || initiatedBy.current !== \"mouse\") {\n return;\n }\n\n startHideFlow();\n initiatedBy.current = null;\n },\n onBlur(event) {\n onBlur(event);\n if (disabled) {\n return;\n }\n\n initiatedBy.current = null;\n startHideFlow();\n },\n onFocus(event) {\n onFocus(event);\n // skip the focus events when the browser is re-focused if the user\n // pressed alt-tab, minimized the browser, etc\n if (\n disabled ||\n mode !== \"keyboard\" ||\n initiatedBy.current !== null ||\n pageInactive.current ||\n isNotOverflown(event.currentTarget)\n ) {\n pageInactive.current = false;\n return;\n }\n\n initiatedBy.current = \"keyboard\";\n elementRef.current = event.currentTarget;\n updatePosition(event.currentTarget);\n startShowFlow(id);\n },\n onTouchStart(event) {\n onTouchStart(event);\n if (\n disabled ||\n initiatedBy.current !== null ||\n isNotOverflown(event.currentTarget)\n ) {\n return;\n }\n\n initiatedBy.current = \"touch\";\n elementRef.current = event.currentTarget;\n updatePosition(event.currentTarget);\n startShowFlow(id);\n },\n onTouchEnd(event) {\n onTouchEnd(event);\n if (disabled) {\n return;\n }\n\n initiatedBy.current = null;\n startHideFlow();\n },\n onContextMenu(event) {\n onContextMenu(event);\n if (\n disabled ||\n initiatedBy.current !== \"touch\" ||\n isNotOverflown(event.currentTarget)\n ) {\n return;\n }\n\n event.preventDefault();\n const selection = window.getSelection();\n const node = selection?.anchorNode?.parentElement;\n if (node && event.currentTarget.contains(node)) {\n selection.empty();\n }\n },\n },\n };\n}\n"],"names":["cnb","useCallback","useEffect","useId","useRef","useHoverMode","useUserInteractionMode","useFixedPositioning","usePageInactive","parseCssLengthUnit","useTooltipHoverMode","DEFAULT_TOOLTIP_DENSE_SPACING","DEFAULT_TOOLTIP_MARGIN","DEFAULT_TOOLTIP_POSITION","DEFAULT_TOOLTIP_SPACING","DEFAULT_TOOLTIP_THRESHOLD","TOOLTIP_SPACING_VAR","useTooltipPosition","getAnchor","noop","useTooltip","options","id","propId","style","propStyle","disabled","describedBy","dense","hoverTimeout","leaveTimeout","vwMargin","vhMargin","spacing","denseSpacing","disableSwapping","disableAutoSpacing","position","determinedPosition","defaultPosition","threshold","onBlur","onFocus","onMouseEnter","onMouseLeave","onTouchStart","onTouchEnd","onContextMenu","onEnter","onEntering","onEntered","onExited","overflowOnly","disableFixedPositioning","fallbackId","tooltipId","animatedOnceRef","hoverTimeoutRef","leaveTimeoutRef","enableHoverMode","disableHoverMode","startDisableTimer","clearDisableTimer","visible","setVisible","startShowFlow","startHideFlow","clearVisibilityTimeout","updatePosition","mode","elementRef","tooltipRef","overflowRef","initiatedBy","ref","callbacks","nodeRef","fixedTo","anchor","getFixedPositionOptions","tooltipSpacing","tooltip","current","window","getComputedStyle","getPropertyValue","currentSpacing","value","horizontal","xMargin","undefined","yMargin","appearing","process","env","NODE_ENV","document","getElementById","hideTooltip","handleKeyDown","event","key","addEventListener","removeEventListener","refocusFrame","pageInactive","onDisabledCleanup","onChange","active","requestAnimationFrame","isNotOverflown","currentTarget","element","offsetWidth","scrollWidth","animatedOnce","tooltipProps","elementProps","preventDefault","selection","getSelection","node","anchorNode","parentElement","contains","empty"],"mappings":"AAAA;AAEA,SAASA,GAAG,QAAQ,YAAY;AAChC,SAQEC,WAAW,EACXC,SAAS,EACTC,KAAK,EACLC,MAAM,QACD,QAAQ;AAEf,SAEEC,YAAY,QACP,+BAA+B;AACtC,SAEEC,sBAAsB,QACjB,gDAAgD;AAEvD,SAIEC,mBAAmB,QACd,wCAAwC;AAE/C,SAASC,eAAe,QAAQ,wBAAwB;AACxD,SAASC,kBAAkB,QAAQ,iCAAiC;AACpE,SAASC,mBAAmB,QAAQ,gCAAgC;AACpE,SACEC,6BAA6B,EAC7BC,sBAAsB,EACtBC,wBAAwB,EACxBC,uBAAuB,EACvBC,yBAAyB,EACzBC,mBAAmB,QACd,iBAAiB;AACxB,SAEEC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E1E,YACA+C,YAAYS,OAAO,KAAK,WACxB4B,eAAeV,MAAMW,aAAa,GAClC;oBACA;gBACF;gBAEAX,MAAMkB,cAAc;gBACpB,MAAMC,YAAYpC,OAAOqC,YAAY;gBACrC,MAAMC,OAAOF,WAAWG,YAAYC;gBACpC,IAAIF,QAAQrB,MAAMW,aAAa,CAACa,QAAQ,CAACH,OAAO;oBAC9CF,UAAUM,KAAK;gBACjB;YACF;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/tooltip/useTooltip.ts"],"sourcesContent":["\"use client\";\n\nimport { cnb } from \"cnbuilder\";\nimport {\n type CSSProperties,\n type FocusEvent,\n type MouseEvent,\n type MutableRefObject,\n type Ref,\n type RefObject,\n type TouchEvent,\n useCallback,\n useEffect,\n useId,\n useRef,\n} from \"react\";\n\nimport {\n type ControlledHoverModeImplementation,\n useHoverMode,\n} from \"../hoverMode/useHoverMode.js\";\nimport {\n type UserInteractionMode,\n useUserInteractionMode,\n} from \"../interaction/UserInteractionModeProvider.js\";\nimport { type SimplePosition } from \"../positioning/types.js\";\nimport {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n type FixedPositioningOptions,\n type FixedPositioningTransitionCallbacks,\n useFixedPositioning,\n} from \"../positioning/useFixedPositioning.js\";\nimport { type UseStateSetter } from \"../types.js\";\nimport { usePageInactive } from \"../usePageInactive.js\";\nimport { parseCssLengthUnit } from \"../utils/parseCssLengthUnit.js\";\nimport { useTooltipHoverMode } from \"./TooltipHoverModeProvider.js\";\nimport {\n DEFAULT_TOOLTIP_DENSE_SPACING,\n DEFAULT_TOOLTIP_MARGIN,\n DEFAULT_TOOLTIP_POSITION,\n DEFAULT_TOOLTIP_SPACING,\n DEFAULT_TOOLTIP_THRESHOLD,\n TOOLTIP_SPACING_VAR,\n} from \"./constants.js\";\nimport {\n type TooltipPositionHookOptions,\n useTooltipPosition,\n} from \"./useTooltipPosition.js\";\nimport { getAnchor } from \"./utils.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/** @since 2.8.0 */\nexport interface TooltipPositioningOptions {\n style?: CSSProperties;\n\n /**\n * @see {@link FixedPositioningOptions.vwMargin}\n * @defaultValue `16`\n */\n vwMargin?: number;\n\n /**\n * @see {@link FixedPositioningOptions.vhMargin}\n * @defaultValue `16`\n */\n vhMargin?: number;\n\n /**\n * Set this to `true` to reduce the font size and padding on the tooltip and\n * the amount of spacing between the tooltipped element and the tooltip.\n *\n * @defaultValue `false`\n */\n dense?: boolean;\n\n /**\n * The amount of spacing to use between the tooltipped element and the tooltip\n * when {@link disableAutoSpacing} is `false`.\n *\n * @defaultValue `\"1.5rem`\n */\n spacing?: number | string;\n\n /**\n * The amount of spacing to use between the tooltipped element and the tooltip\n * when {@link disableAutoSpacing} is `false` and {@link dense} is `true`.\n *\n * @defaultValue `\"0.875rem`\n */\n denseSpacing?: number | string;\n\n /**\n * Set this to `true` to prevent the {@link defaultPosition} to swap to the\n * other side of the tooltipped element when it is too close to the viewport\n * edge. This will always be `true` if a {@link position} is provided.\n *\n * @defaultValue `false`\n */\n disableSwapping?: boolean;\n\n /**\n * @defaultValue `false`\n */\n disableAutoSpacing?: boolean;\n}\n\n/**\n * @since 2.8.0\n * @since 6.0.0 Removed the `TooltipTouchEventHandlers` and\n * `TooltipKeyboardEventHandlers` types, removed the need for the `onKeyDown`\n * event.\n */\nexport interface TooltippedElementEventHandlers<\n E extends HTMLElement = HTMLButtonElement,\n> {\n onBlur?: (event: FocusEvent<E>) => void;\n onFocus?: (event: FocusEvent<E>) => void;\n onMouseEnter?: (event: MouseEvent<E>) => void;\n onMouseLeave?: (event: MouseEvent<E>) => void;\n onTouchStart?: (event: TouchEvent<E>) => void;\n onTouchEnd?: (event: TouchEvent<E>) => void;\n onContextMenu?: (event: MouseEvent<E>) => void;\n}\n\n/**\n * @since 2.8.0\n * @since 6.0.0 Renamed from `TooltipHookProvidedElementProps`\n */\nexport interface ProvidedTooltippedElementProps<\n E extends HTMLElement,\n> extends Required<TooltippedElementEventHandlers<E>> {\n \"aria-describedby\": string | undefined;\n id: string;\n}\n\n/**\n * @since 2.8.0\n * @since 6.0.0 A major API change for the hover mode behavior and no longer\n * requires a `baseId`/`id` for the tooltip. Also renamed from\n * `TooltipHookOptions` to `TooltipOptions` to match other hook naming\n * conventions.\n */\nexport interface TooltipOptions<\n TooltippedElement extends HTMLElement = HTMLButtonElement,\n>\n extends\n FixedPositioningTransitionCallbacks,\n TooltippedElementEventHandlers<TooltippedElement>,\n TooltipPositioningOptions,\n TooltipPositionHookOptions {\n /**\n * @defaultValue `\"tooltip-\" + useId()`\n */\n id?: string;\n\n /**\n * An optional override for the `aria-describedby`\n */\n describedBy?: string;\n\n /**\n * Any styles to be merged with the fixed positioning styles for the tooltip.\n */\n style?: CSSProperties;\n\n /**\n * Boolean if the event handlers should no longer attempt to show a tooltip. This\n * should be set to `true` when your component might not have a tooltip associated\n * with it.\n *\n * @example Real World Example\n * ```tsx\n * // This is _almost_ the source code for the `TooltippedButton` provided by react-md\n * import { Button } from \"@react-md/core/button/Button\";\n * import { Tooltip } from \"@react-md/core/tooltip/Tooltip\";\n * import { useTooltip } from \"@react-md/core/tooltip/useTooltip\";\n * import { type ReactElement, type ReactNode } from \"react\";\n *\n * export interface TooltippedButtonProps extends ButtonProps {\n * tooltip?: ReactNode;\n * }\n *\n * export function TooltippedButton({\n * id,\n * tooltip,\n * children,\n * onBlur,\n * onFocus,\n * onMouseEnter,\n * onMouseLeave,\n * onTouchStart,\n * onTouchEnd,\n * onContextMenu,\n * ...props\n * }: TooltippedButtonProps): ReactElement {\n * const { elementProps, tooltipProps } = useTooltip({\n * id,\n * disabled: !tooltip,\n * onBlur,\n * onFocus,\n * onMouseEnter,\n * onMouseLeave,\n * onTouchStart,\n * onTouchEnd,\n * onContextMenu,\n * });\n *\n * return (\n * <>\n * <Button {...props} {...elementProps}>\n * {children}\n * </Button>\n * <Tooltip {...tooltipProps}>{tooltip}</Tooltip>\n * </>\n * );\n * }\n * ```\n *\n * @defaultValue `false`\n * @since 5.1.0\n */\n disabled?: boolean;\n\n /**\n * The amount of time (in ms) to hover an element before the tooltip becomes\n * visible.\n *\n * The default value is really the current hover timeout from the\n * `TooltipHoverModeProvider`.\n *\n * @defaultValue `1000`\n */\n hoverTimeout?: number;\n\n /**\n * The amount of time to wait before triggering the exit animation for the\n * tooltip.\n *\n * The default value is really the current leaveTimeout timeout from the\n * `TooltipHoverModeProvider`.\n *\n * @defaultValue `0`\n */\n leaveTimeout?: number;\n\n /**\n * Set this to `true` to only allow the tooltip to become visible when the\n * `event .currentTarget` or `overflowRef` has text overflow.\n *\n * @defaultValue `false`\n * @since 6.0.0\n */\n overflowOnly?: boolean;\n\n /**\n * @see {@link FixedPositioningOptions.disabled}\n * @defaultValue `false`\n */\n disableFixedPositioning?: boolean;\n}\n\n/**\n * @since 2.8.0\n * @since 6.0.0 This was renamed from `TooltipHookProvidedTooltipProps`\n */\nexport interface ProvidedTooltipProps<\n E extends HTMLElement = HTMLSpanElement,\n> extends Required<FixedPositioningTransitionCallbacks> {\n id: string;\n ref: Ref<E>;\n dense: boolean;\n style: CSSProperties | undefined;\n visible: boolean;\n position: SimplePosition;\n}\n\n/**\n * @since 2.8.0\n * @since 6.0.0 No longer returns any properties from the hover mode provider\n * because of the major API change to hover mode.. Also renamed from\n * `TooltipHookReturnValue` to `TooltipImplementation` to match other hook\n * naming conventions.\n */\nexport interface TooltipImplementation<\n TooltippedElement extends HTMLElement = HTMLButtonElement,\n TooltipElement extends HTMLElement = HTMLSpanElement,\n> extends ControlledHoverModeImplementation {\n visible: boolean;\n setVisible: UseStateSetter<boolean>;\n animatedOnce: boolean;\n initiatedBy: MutableRefObject<UserInteractionMode | null>;\n elementProps: ProvidedTooltippedElementProps<TooltippedElement>;\n tooltipProps: ProvidedTooltipProps<TooltipElement>;\n\n /**\n * This is a wrapper around the {@link setVisible} behavior that will also\n * clear any pending timeouts.\n */\n hideTooltip: () => void;\n\n /**\n * @since 6.0.0\n */\n overflowRef: RefObject<HTMLElement>;\n}\n\n/**\n * @example Simple Usage\n * ```tsx\n * import { Button } from \"@react-md/core/button/Button\";\n * import { Tooltip } from \"@react-md/core/tooltip/Tooltip\";\n * import { useTooltip } from \"@react-md/core/tooltip/useTooltip\";\n *\n * function Example() {\n * const { elementProps, tooltipProps } = useTooltip();\n *\n * return (\n * <>\n * <Button {...elementProps}>Button</Button>\n * <Tooltip {...tooltipProps}>\n * Tooltip Content\n * </Tooltip>\n * </>\n * );\n * }\n * ```\n *\n * @example Overflow-only Tooltips\n * ```tsx\n * import { cssUtils } from \"@react-md/core/cssUtils\";\n * import { Link, type LinkProps } from \"@react-md/core/link/Link\";\n * import { Tooltip } from \"@react-md/core/tooltip/Tooltip\";\n * import { useTooltip } from \"@react-md/core/tooltip/useTooltip\";\n * import { type ReactElement } from \"react\";\n *\n * function NavigationLink(props: LinkProps): ReactElement {\n * const { children, ...remaining } = props;\n *\n * // using the `overflowRef` is optional and will default to the\n * // `event.currentTarget` when `null`\n * const { overflowRef, elementProps, tooltipProps } = useOverflowTooltip({\n * // just to pass any event handlers\n * ...remaining,\n * overflowOnly: true,\n * });\n *\n * return (\n * <Link {...remaining} {...elementProps} style={{ width: \"100%\" }}>\n * <span ref={overflowRef} className={cssUtils({ textOverflow: \"ellipsis\" })}>\n * {children}\n * </span>\n * <Tooltip {...tooltipProps}>\n * {children}\n * </Tooltip>\n * </Link>\n * );\n * }\n *\n * function Example(): ReactElement {\n * return (\n * <div style={{ width: \"10rem\", overflow: \"auto\" }}>\n * <NavigationLink href=\"/\">Home</NavigationLink>\n * <NavigationLink href=\"/some-path\">\n * Super long text that will be truncated with ellipsis and\n * have a tooltip appear\n * </NavigationLink>\n * </div>\n * );\n * }\n * ```\n *\n * ## Inspecting Tooltip Styles\n *\n * Since tooltips will disappear on blur, mouseleave, etc, it is a bit hard to\n * inspect the tooltip styles. In dev mode, you can manually set the visibility\n * to `true` through the dev tools.\n * - find your tooltip implementation\n * - expand the Tooltip hook\n * - expand the HoverMode hook\n * - set the first boolean state to `true`\n *\n * The tooltip will now remain visible allowing you to find it within the\n * \"Inspector\" tab in the dev tools.\n *\n * @see {@link https://react-md.dev/components/tooltip | Tooltip Demos}\n * @since 2.8.0\n * @since 6.0.0 Uses a separate `TooltipHoverModeProvider`.\n *\n * TODO: I need to fix the tooltip for click events and history changes since\n * the mouseleave event will not be correctly bubbled if hovering a child\n * element when the click or history update happens. this causes the tooltip to\n * stay visible\n */\nexport function useTooltip<\n TooltippedElement extends HTMLElement = HTMLButtonElement,\n TooltipElement extends HTMLElement = HTMLSpanElement,\n>(\n options: TooltipOptions<TooltippedElement> = {}\n): TooltipImplementation<TooltippedElement, TooltipElement> {\n const {\n id: propId,\n style: propStyle,\n disabled = false,\n describedBy,\n dense = false,\n hoverTimeout,\n leaveTimeout,\n vwMargin = DEFAULT_TOOLTIP_MARGIN,\n vhMargin = DEFAULT_TOOLTIP_MARGIN,\n spacing = DEFAULT_TOOLTIP_SPACING,\n denseSpacing = DEFAULT_TOOLTIP_DENSE_SPACING,\n disableSwapping,\n disableAutoSpacing,\n position: determinedPosition,\n defaultPosition = DEFAULT_TOOLTIP_POSITION,\n threshold = DEFAULT_TOOLTIP_THRESHOLD,\n onBlur = noop,\n onFocus = noop,\n onMouseEnter = noop,\n onMouseLeave = noop,\n onTouchStart = noop,\n onTouchEnd = noop,\n onContextMenu = noop,\n onEnter = noop,\n onEntering,\n onEntered = noop,\n onExited,\n overflowOnly,\n disableFixedPositioning,\n } = options;\n\n const fallbackId = useId();\n const id = propId || fallbackId;\n const tooltipId = `${id}-tooltip`;\n const {\n animatedOnceRef,\n hoverTimeoutRef,\n leaveTimeoutRef,\n enableHoverMode,\n disableHoverMode,\n startDisableTimer,\n clearDisableTimer,\n } = useTooltipHoverMode();\n const {\n visible,\n setVisible,\n startShowFlow,\n startHideFlow,\n clearVisibilityTimeout,\n } = useHoverMode({\n hoverTimeout,\n hoverTimeoutRef,\n leaveTimeout,\n leaveTimeoutRef,\n enableHoverMode,\n disableHoverMode,\n startDisableTimer,\n clearDisableTimer,\n });\n const [position, updatePosition] = useTooltipPosition({\n position: determinedPosition,\n defaultPosition,\n threshold,\n });\n\n const mode = useUserInteractionMode();\n const elementRef = useRef<HTMLElement | null>(null);\n const tooltipRef = useRef<TooltipElement>(null);\n const overflowRef = useRef<HTMLElement>(null);\n const initiatedBy = useRef<UserInteractionMode | null>(null);\n const { ref, style, callbacks } = useFixedPositioning({\n nodeRef: tooltipRef,\n style: propStyle,\n fixedTo: elementRef,\n anchor: getAnchor(position),\n disableSwapping: disableSwapping ?? !!determinedPosition,\n disabled: disableFixedPositioning,\n getFixedPositionOptions() {\n let tooltipSpacing = dense ? denseSpacing : spacing;\n const tooltip = tooltipRef.current;\n if (!disableAutoSpacing && tooltip) {\n tooltipSpacing =\n globalThis\n .getComputedStyle(tooltip)\n .getPropertyValue(TOOLTIP_SPACING_VAR) || spacing;\n }\n\n const currentSpacing = parseCssLengthUnit({\n value: tooltipSpacing,\n });\n const horizontal = position === \"left\" || position === \"right\";\n\n return {\n vwMargin,\n vhMargin,\n xMargin: horizontal ? currentSpacing : undefined,\n yMargin: horizontal ? undefined : currentSpacing,\n };\n },\n onEnter(appearing) {\n onEnter(appearing);\n\n // This allows you to inspect the tooltip styles through the element\n // inspector without first hovering or focusing the tooltipped element\n // beforehand by setting the `HoverMode` hook to `true`\n if (process.env.NODE_ENV !== \"production\" && !elementRef.current) {\n elementRef.current = document.getElementById(id);\n }\n },\n onEntering,\n onEntered(appearing) {\n onEntered(appearing);\n\n animatedOnceRef.current = true;\n },\n onExited,\n });\n\n const hideTooltip = useCallback(() => {\n initiatedBy.current = null;\n disableHoverMode();\n clearVisibilityTimeout();\n setVisible(false);\n }, [clearVisibilityTimeout, disableHoverMode, setVisible]);\n\n useEffect(() => {\n if (!visible) {\n return;\n }\n\n const handleKeyDown = (event: KeyboardEvent): void => {\n if (event.key === \"Escape\") {\n hideTooltip();\n }\n };\n\n globalThis.addEventListener(\"keydown\", handleKeyDown);\n window.addEventListener(\"scroll\", hideTooltip, true);\n globalThis.addEventListener(\"touchend\", hideTooltip, true);\n return () => {\n globalThis.removeEventListener(\"keydown\", handleKeyDown);\n window.removeEventListener(\"scroll\", hideTooltip, true);\n globalThis.removeEventListener(\"touchend\", hideTooltip, true);\n };\n }, [hideTooltip, visible]);\n\n const refocusFrame = useRef(0);\n const pageInactive = useRef(false);\n usePageInactive({\n disabled,\n onDisabledCleanup: hideTooltip,\n onChange(active) {\n if (active) {\n refocusFrame.current = globalThis.requestAnimationFrame(() => {\n pageInactive.current = false;\n });\n return;\n }\n\n pageInactive.current = true;\n hideTooltip();\n },\n });\n\n const isNotOverflown = (currentTarget: HTMLElement): boolean => {\n if (!overflowOnly) {\n return false;\n }\n\n const element = overflowRef.current || currentTarget;\n return !element || element.offsetWidth >= element.scrollWidth;\n };\n\n return {\n visible,\n setVisible,\n hideTooltip,\n animatedOnce: animatedOnceRef.current,\n initiatedBy,\n overflowRef,\n startShowFlow,\n startHideFlow,\n clearVisibilityTimeout,\n tooltipProps: {\n id: tooltipId,\n ref,\n dense,\n style,\n visible,\n position,\n ...callbacks,\n },\n elementProps: {\n \"aria-describedby\": cnb(visible && tooltipId, describedBy) || undefined,\n id,\n onMouseEnter(event) {\n onMouseEnter(event);\n if (\n disabled ||\n mode === \"touch\" ||\n initiatedBy.current !== null ||\n isNotOverflown(event.currentTarget)\n ) {\n return;\n }\n\n initiatedBy.current = \"mouse\";\n elementRef.current = event.currentTarget;\n updatePosition(event.currentTarget);\n startShowFlow(id);\n },\n onMouseLeave(event) {\n onMouseLeave(event);\n if (disabled || initiatedBy.current !== \"mouse\") {\n return;\n }\n\n startHideFlow();\n initiatedBy.current = null;\n },\n onBlur(event) {\n onBlur(event);\n if (disabled) {\n return;\n }\n\n initiatedBy.current = null;\n startHideFlow();\n },\n onFocus(event) {\n onFocus(event);\n // skip the focus events when the browser is re-focused if the user\n // pressed alt-tab, minimized the browser, etc\n if (\n disabled ||\n mode !== \"keyboard\" ||\n initiatedBy.current !== null ||\n pageInactive.current ||\n isNotOverflown(event.currentTarget)\n ) {\n pageInactive.current = false;\n return;\n }\n\n initiatedBy.current = \"keyboard\";\n elementRef.current = event.currentTarget;\n updatePosition(event.currentTarget);\n startShowFlow(id);\n },\n onTouchStart(event) {\n onTouchStart(event);\n if (\n disabled ||\n initiatedBy.current !== null ||\n isNotOverflown(event.currentTarget)\n ) {\n return;\n }\n\n initiatedBy.current = \"touch\";\n elementRef.current = event.currentTarget;\n updatePosition(event.currentTarget);\n startShowFlow(id);\n },\n onTouchEnd(event) {\n onTouchEnd(event);\n if (disabled) {\n return;\n }\n\n initiatedBy.current = null;\n startHideFlow();\n },\n onContextMenu(event) {\n onContextMenu(event);\n if (\n disabled ||\n initiatedBy.current !== \"touch\" ||\n isNotOverflown(event.currentTarget)\n ) {\n return;\n }\n\n event.preventDefault();\n const selection = globalThis.getSelection();\n const node = selection?.anchorNode?.parentElement;\n if (node && event.currentTarget.contains(node)) {\n selection.empty();\n }\n },\n },\n };\n}\n"],"names":["cnb","useCallback","useEffect","useId","useRef","useHoverMode","useUserInteractionMode","useFixedPositioning","usePageInactive","parseCssLengthUnit","useTooltipHoverMode","DEFAULT_TOOLTIP_DENSE_SPACING","DEFAULT_TOOLTIP_MARGIN","DEFAULT_TOOLTIP_POSITION","DEFAULT_TOOLTIP_SPACING","DEFAULT_TOOLTIP_THRESHOLD","TOOLTIP_SPACING_VAR","useTooltipPosition","getAnchor","noop","useTooltip","options","id","propId","style","propStyle","disabled","describedBy","dense","hoverTimeout","leaveTimeout","vwMargin","vhMargin","spacing","denseSpacing","disableSwapping","disableAutoSpacing","position","determinedPosition","defaultPosition","threshold","onBlur","onFocus","onMouseEnter","onMouseLeave","onTouchStart","onTouchEnd","onContextMenu","onEnter","onEntering","onEntered","onExited","overflowOnly","disableFixedPositioning","fallbackId","tooltipId","animatedOnceRef","hoverTimeoutRef","leaveTimeoutRef","enableHoverMode","disableHoverMode","startDisableTimer","clearDisableTimer","visible","setVisible","startShowFlow","startHideFlow","clearVisibilityTimeout","updatePosition","mode","elementRef","tooltipRef","overflowRef","initiatedBy","ref","callbacks","nodeRef","fixedTo","anchor","getFixedPositionOptions","tooltipSpacing","tooltip","current","globalThis","getComputedStyle","getPropertyValue","currentSpacing","value","horizontal","xMargin","undefined","yMargin","appearing","process","env","NODE_ENV","document","getElementById","hideTooltip","handleKeyDown","event","key","addEventListener","window","removeEventListener","refocusFrame","pageInactive","onDisabledCleanup","onChange","active","requestAnimationFrame","isNotOverflown","currentTarget","element","offsetWidth","scrollWidth","animatedOnce","tooltipProps","elementProps","preventDefault","selection","getSelection","node","anchorNode","parentElement","contains","empty"],"mappings":"AAAA;AAEA,SAASA,GAAG,QAAQ,YAAY;AAChC,SAQEC,WAAW,EACXC,SAAS,EACTC,KAAK,EACLC,MAAM,QACD,QAAQ;AAEf,SAEEC,YAAY,QACP,+BAA+B;AACtC,SAEEC,sBAAsB,QACjB,gDAAgD;AAEvD,SAIEC,mBAAmB,QACd,wCAAwC;AAE/C,SAASC,eAAe,QAAQ,wBAAwB;AACxD,SAASC,kBAAkB,QAAQ,iCAAiC;AACpE,SAASC,mBAAmB,QAAQ,gCAAgC;AACpE,SACEC,6BAA6B,EAC7BC,sBAAsB,EACtBC,wBAAwB,EACxBC,uBAAuB,EACvBC,yBAAyB,EACzBC,mBAAmB,QACd,iBAAiB;AACxB,SAEEC,kBAAkB,QACb,0BAA0B;AACjC,SAASC,SAAS,QAAQ,aAAa;AAEvC,MAAMC,OAAO;AACX,aAAa;AACf;AAiQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsFC,GACD,OAAO,SAASC,WAIdC,UAA6C,CAAC,CAAC;IAE/C,MAAM,EACJC,IAAIC,MAAM,EACVC,OAAOC,SAAS,EAChBC,WAAW,KAAK,EAChBC,WAAW,EACXC,QAAQ,KAAK,EAC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Position.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useState } from \"react\";\n\nimport type { SimplePosition } from \"../positioning/types.js\";\nimport {\n DEFAULT_TOOLTIP_POSITION,\n DEFAULT_TOOLTIP_THRESHOLD,\n} from \"./constants.js\";\nimport { getPosition } from \"./utils.js\";\n\n/** @internal */\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n * @since 2.8.0\n */\nexport interface TooltipPositionHookOptions {\n /**\n * An optional controlled position to use that will disable the functionality\n * to determine the \"best\" position to render the tooltip within the viewport.\n */\n position?: SimplePosition;\n\n /**\n * An optional position to use before the positioning calculation has\n * occurred. This is also used to determine if the position should be\n * horizontal vs vertical.\n *\n * Vertical - `\"below\"` or `\"above\"`\n * Horizontal - `\"left\"` or `\"right\"`\n *\n * @defaultValue `\"below\"`\n */\n defaultPosition?: SimplePosition;\n\n /**\n * This value should be between 0 and 1 and will be multiplied by either the\n * viewport height or viewport width to determine the best position to render\n * the tooltip based on available space within the viewport.\n *\n * You _probably_ won't ever really need to update this value.\n *\n * @defaultValue `0.75`\n */\n threshold?: number;\n}\n\n/**\n * @internal\n * @since 2.8.0\n */\nexport type UpdateTooltipPosition = (container: HTMLElement) => void;\n\n/**\n * @internal\n * @since 2.8.0\n */\nexport type TooltipPositionHookReturnValue = [\n SimplePosition,\n UpdateTooltipPosition,\n];\n\n/**\n * A hook that's used to determine the \"best\" position to render the tooltip\n * within the viewport.\n *\n * @internal\n * @since 2.8.0\n */\nexport function useTooltipPosition(\n options: TooltipPositionHookOptions\n): TooltipPositionHookReturnValue {\n const {\n position: determinedPosition,\n threshold = DEFAULT_TOOLTIP_THRESHOLD,\n defaultPosition = DEFAULT_TOOLTIP_POSITION,\n } = options;\n\n const [position, setPosition] = useState(defaultPosition);\n const updatePosition = useCallback<UpdateTooltipPosition>(\n (container) => {\n setPosition(\n getPosition({\n container,\n threshold,\n defaultPosition,\n })\n );\n },\n [defaultPosition, threshold]\n );\n\n if (
|
|
1
|
+
{"version":3,"sources":["../../src/tooltip/useTooltipPosition.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useState } from \"react\";\n\nimport type { SimplePosition } from \"../positioning/types.js\";\nimport {\n DEFAULT_TOOLTIP_POSITION,\n DEFAULT_TOOLTIP_THRESHOLD,\n} from \"./constants.js\";\nimport { getPosition } from \"./utils.js\";\n\n/** @internal */\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n * @since 2.8.0\n */\nexport interface TooltipPositionHookOptions {\n /**\n * An optional controlled position to use that will disable the functionality\n * to determine the \"best\" position to render the tooltip within the viewport.\n */\n position?: SimplePosition;\n\n /**\n * An optional position to use before the positioning calculation has\n * occurred. This is also used to determine if the position should be\n * horizontal vs vertical.\n *\n * Vertical - `\"below\"` or `\"above\"`\n * Horizontal - `\"left\"` or `\"right\"`\n *\n * @defaultValue `\"below\"`\n */\n defaultPosition?: SimplePosition;\n\n /**\n * This value should be between 0 and 1 and will be multiplied by either the\n * viewport height or viewport width to determine the best position to render\n * the tooltip based on available space within the viewport.\n *\n * You _probably_ won't ever really need to update this value.\n *\n * @defaultValue `0.75`\n */\n threshold?: number;\n}\n\n/**\n * @internal\n * @since 2.8.0\n */\nexport type UpdateTooltipPosition = (container: HTMLElement) => void;\n\n/**\n * @internal\n * @since 2.8.0\n */\nexport type TooltipPositionHookReturnValue = [\n SimplePosition,\n UpdateTooltipPosition,\n];\n\n/**\n * A hook that's used to determine the \"best\" position to render the tooltip\n * within the viewport.\n *\n * @internal\n * @since 2.8.0\n */\nexport function useTooltipPosition(\n options: TooltipPositionHookOptions\n): TooltipPositionHookReturnValue {\n const {\n position: determinedPosition,\n threshold = DEFAULT_TOOLTIP_THRESHOLD,\n defaultPosition = DEFAULT_TOOLTIP_POSITION,\n } = options;\n\n const [position, setPosition] = useState(defaultPosition);\n const updatePosition = useCallback<UpdateTooltipPosition>(\n (container) => {\n setPosition(\n getPosition({\n container,\n threshold,\n defaultPosition,\n })\n );\n },\n [defaultPosition, threshold]\n );\n\n if (determinedPosition !== undefined) {\n return [determinedPosition, noop];\n }\n\n return [position, updatePosition];\n}\n"],"names":["useCallback","useState","DEFAULT_TOOLTIP_POSITION","DEFAULT_TOOLTIP_THRESHOLD","getPosition","noop","useTooltipPosition","options","position","determinedPosition","threshold","defaultPosition","setPosition","updatePosition","container","undefined"],"mappings":"AAAA;AAEA,SAASA,WAAW,EAAEC,QAAQ,QAAQ,QAAQ;AAG9C,SACEC,wBAAwB,EACxBC,yBAAyB,QACpB,iBAAiB;AACxB,SAASC,WAAW,QAAQ,aAAa;AAEzC,cAAc,GACd,MAAMC,OAAO;AACX,aAAa;AACf;AAmDA;;;;;;CAMC,GACD,OAAO,SAASC,mBACdC,OAAmC;IAEnC,MAAM,EACJC,UAAUC,kBAAkB,EAC5BC,YAAYP,yBAAyB,EACrCQ,kBAAkBT,wBAAwB,EAC3C,GAAGK;IAEJ,MAAM,CAACC,UAAUI,YAAY,GAAGX,SAASU;IACzC,MAAME,iBAAiBb,YACrB,CAACc;QACCF,YACER,YAAY;YACVU;YACAJ;YACAC;QACF;IAEJ,GACA;QAACA;QAAiBD;KAAU;IAG9B,IAAID,uBAAuBM,WAAW;QACpC,OAAO;YAACN;YAAoBJ;SAAK;IACnC;IAEA,OAAO;QAACG;QAAUK;KAAe;AACnC"}
|
|
@@ -138,7 +138,7 @@ import { loop } from "../utils/loop.js";
|
|
|
138
138
|
if (paused) {
|
|
139
139
|
return;
|
|
140
140
|
}
|
|
141
|
-
const timeout =
|
|
141
|
+
const timeout = globalThis.setTimeout(()=>{
|
|
142
142
|
const nextActiveIndex = loop({
|
|
143
143
|
min: 0,
|
|
144
144
|
max: total,
|
|
@@ -151,7 +151,7 @@ import { loop } from "../utils/loop.js";
|
|
|
151
151
|
});
|
|
152
152
|
}, duration);
|
|
153
153
|
return ()=>{
|
|
154
|
-
|
|
154
|
+
globalThis.clearTimeout(timeout);
|
|
155
155
|
};
|
|
156
156
|
}, [
|
|
157
157
|
paused,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/transition/useCarousel.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\n\nimport { type UseStateSetter } from \"../types.js\";\nimport { useToggle } from \"../useToggle.js\";\nimport { loop } from \"../utils/loop.js\";\nimport { type SlideDirection } from \"./SlideContainer.js\";\n\n/** @since 6.0.0 */\nexport interface CarouselSlideState {\n direction: SlideDirection;\n activeIndex: number;\n}\n\n/** @since 6.0.0 */\nexport interface CarouselState extends CarouselSlideState {\n paused: boolean;\n}\n\n/** @since 6.0.0 */\nexport interface CarouselImplementation extends CarouselState {\n /**\n * Increments the carousel slide active index by 1 ensuring it does not\n * advance past the {@link CarouselOptions.totalSlides} index.\n */\n increment: () => void;\n\n /**\n * Decrements the carousel slide active index by 1 and prevents decrementing\n * past 0.\n */\n decrement: () => void;\n\n /**\n * This can be used to manually control the {@link paused} state.\n */\n setPaused: UseStateSetter<boolean>;\n\n /**\n * Toggles the {@link paused} state.\n */\n togglePaused: () => void;\n\n /**\n * A convenience wrapper for the {@link setCarouselSlideState} that will\n * ensure the {@link CarouselSlideState.direction} is correct based on the\n * current active index and next active index.\n */\n setActiveIndex: UseStateSetter<number>;\n\n /**\n * This can be used if the provided carousel actions do not solve your use\n * case.\n */\n setCarouselSlideState: UseStateSetter<CarouselSlideState>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface CarouselOptions {\n /**\n * The amount of time in milliseconds each slide should be visible before\n * advancing to the next slide.\n *\n * @defaultValue `8000`\n */\n duration?: number;\n\n /**\n * The total number of slides within your carousel so that you can safely loop\n * through all slides.\n */\n totalSlides: number;\n}\n\n/**\n * @example Accessible Carousel Example\n * ```tsx\n * import { Button } from \"@react-md/core/button/Button\";\n * import { Slide } from \"@react-md/core/transition/Slide\";\n * import { SlideContainer } from \"@react-md/core/transition/SlideContainer\";\n * import { useCarousel } from \"@react-md/core/transition/useCarousel\";\n * import ChevronLeftIcon from \"@react-md/material-icons/ChevronLeftIcon\";\n * import ChevronRightIcon from \"@react-md/material-icons/ChevronRightIcon\";\n * import PauseIcon from \"@react-md/material-icons/PauseIcon\";\n * import PlayArrowIcon from \"@react-md/material-icons/PlayArrowIcon\";\n * import type { ReactElement } from \"react\";\n *\n * const slides = [\n * { title: \"Slide 1\" },\n * { title: \"Slide 2\" },\n * { title: \"Slide 3\" },\n * ] as const;\n *\n * function Example(): ReactElement {\n * const {\n * paused,\n * direction,\n * activeIndex,\n * togglePaused,\n * setActiveIndex,\n * increment,\n * decrement,\n * } = useCarousel({\n * duration: 5000,\n * totalSlides: slides.length,\n * });\n *\n * const slideId = useId();\n *\n * return (\n * <div\n * aria-roledescription=\"carousel\"\n * aria-label=\"Carousel\"\n * id={useId()}\n * role=\"region\"\n * >\n * <SlideContainer aria-live=\"off\" direction={direction}>\n * {slides.map(({ title }, index) => (\n * <Slide\n * key={title}\n * aria-label={`Slide ${index + 1} of ${slides.length - 1}`}\n * aria-roledescription=\"slide\"\n * id={`${slideId}-${index}`}\n * role=\"group\"\n * active={activeIndex === index}\n * >\n * {title}\n * </Slide>\n * ))}\n * </SlideContainer>\n * <Button\n * aria-label=\"Pause\"\n * aria-pressed={paused}\n * button=\"icon\"\n * onClick={togglePaused}\n * >\n * {paused ? <PlayArrowIcon /> : <PauseIcon />}\n * </Button>\n * {slides.map(({ title }, index) => (\n * <Button\n * key={title}\n * aria-label={`Slide ${index + 1}`}\n * aria-selected={activeIndex === index}\n * aria-controls={`${slideId}-${index}`}\n * role=\"tab\"\n * onClick={() => setActiveIndex(index))}\n * />\n * ))}\n * <Button\n * aria-label=\"Previous Slide\"\n * onClick={decrement}\n * disabled={activeIndex === 0}\n * buttonType=\"icon\"\n * >\n * <ChevronLeftIcon />\n * </Button>\n * <Button\n * aria-label=\"Next Slide\"\n * onClick={increment}\n * disabled={activeIndex === slides.length - 1}\n * buttonType=\"icon\"\n * >\n * <ChevronRightIcon />\n * </Button>\n * </div>\n * );\n * }\n * ```\n *\n * @see {@link https://react-md.dev/components/carousel | Carousel Demos}\n * @see {@link https://www.w3.org/WAI/ARIA/apg/patterns/carousel/}\n * @see {@link https://www.w3.org/WAI/ARIA/apg/example-index/carousel/carousel-2-tablist.html}\n * @since 6.0.0\n */\nexport function useCarousel(options: CarouselOptions): CarouselImplementation {\n const { duration = 8000, totalSlides } = options;\n const total = totalSlides - 1;\n\n const [state, setCarouselSlideState] = useState<CarouselSlideState>({\n direction: \"forward\",\n activeIndex: 0,\n });\n const {\n toggled: paused,\n toggle: togglePaused,\n setToggled: setPaused,\n } = useToggle(false);\n const setActiveIndex = useCallback<UseStateSetter<number>>(\n (activeIndexOrGetter) => {\n setCarouselSlideState((prevState) => {\n const prevActiveIndex = prevState.activeIndex;\n const nextActiveIndex =\n typeof activeIndexOrGetter === \"function\"\n ? activeIndexOrGetter(prevActiveIndex)\n : activeIndexOrGetter;\n\n return {\n direction: prevActiveIndex < nextActiveIndex ? \"forward\" : \"backward\",\n activeIndex: nextActiveIndex,\n };\n });\n },\n []\n );\n const increment = useCallback(() => {\n setCarouselSlideState((prevState) => ({\n direction: \"forward\",\n activeIndex: Math.min(total, prevState.activeIndex + 1),\n }));\n }, [total]);\n const decrement = useCallback(() => {\n setCarouselSlideState((prevState) => ({\n direction: \"backward\",\n activeIndex: Math.max(0, prevState.activeIndex - 1),\n }));\n }, []);\n\n const { activeIndex } = state;\n useEffect(() => {\n if (paused) {\n return;\n }\n\n const timeout =
|
|
1
|
+
{"version":3,"sources":["../../src/transition/useCarousel.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\n\nimport { type UseStateSetter } from \"../types.js\";\nimport { useToggle } from \"../useToggle.js\";\nimport { loop } from \"../utils/loop.js\";\nimport { type SlideDirection } from \"./SlideContainer.js\";\n\n/** @since 6.0.0 */\nexport interface CarouselSlideState {\n direction: SlideDirection;\n activeIndex: number;\n}\n\n/** @since 6.0.0 */\nexport interface CarouselState extends CarouselSlideState {\n paused: boolean;\n}\n\n/** @since 6.0.0 */\nexport interface CarouselImplementation extends CarouselState {\n /**\n * Increments the carousel slide active index by 1 ensuring it does not\n * advance past the {@link CarouselOptions.totalSlides} index.\n */\n increment: () => void;\n\n /**\n * Decrements the carousel slide active index by 1 and prevents decrementing\n * past 0.\n */\n decrement: () => void;\n\n /**\n * This can be used to manually control the {@link paused} state.\n */\n setPaused: UseStateSetter<boolean>;\n\n /**\n * Toggles the {@link paused} state.\n */\n togglePaused: () => void;\n\n /**\n * A convenience wrapper for the {@link setCarouselSlideState} that will\n * ensure the {@link CarouselSlideState.direction} is correct based on the\n * current active index and next active index.\n */\n setActiveIndex: UseStateSetter<number>;\n\n /**\n * This can be used if the provided carousel actions do not solve your use\n * case.\n */\n setCarouselSlideState: UseStateSetter<CarouselSlideState>;\n}\n\n/**\n * @since 6.0.0\n */\nexport interface CarouselOptions {\n /**\n * The amount of time in milliseconds each slide should be visible before\n * advancing to the next slide.\n *\n * @defaultValue `8000`\n */\n duration?: number;\n\n /**\n * The total number of slides within your carousel so that you can safely loop\n * through all slides.\n */\n totalSlides: number;\n}\n\n/**\n * @example Accessible Carousel Example\n * ```tsx\n * import { Button } from \"@react-md/core/button/Button\";\n * import { Slide } from \"@react-md/core/transition/Slide\";\n * import { SlideContainer } from \"@react-md/core/transition/SlideContainer\";\n * import { useCarousel } from \"@react-md/core/transition/useCarousel\";\n * import ChevronLeftIcon from \"@react-md/material-icons/ChevronLeftIcon\";\n * import ChevronRightIcon from \"@react-md/material-icons/ChevronRightIcon\";\n * import PauseIcon from \"@react-md/material-icons/PauseIcon\";\n * import PlayArrowIcon from \"@react-md/material-icons/PlayArrowIcon\";\n * import type { ReactElement } from \"react\";\n *\n * const slides = [\n * { title: \"Slide 1\" },\n * { title: \"Slide 2\" },\n * { title: \"Slide 3\" },\n * ] as const;\n *\n * function Example(): ReactElement {\n * const {\n * paused,\n * direction,\n * activeIndex,\n * togglePaused,\n * setActiveIndex,\n * increment,\n * decrement,\n * } = useCarousel({\n * duration: 5000,\n * totalSlides: slides.length,\n * });\n *\n * const slideId = useId();\n *\n * return (\n * <div\n * aria-roledescription=\"carousel\"\n * aria-label=\"Carousel\"\n * id={useId()}\n * role=\"region\"\n * >\n * <SlideContainer aria-live=\"off\" direction={direction}>\n * {slides.map(({ title }, index) => (\n * <Slide\n * key={title}\n * aria-label={`Slide ${index + 1} of ${slides.length - 1}`}\n * aria-roledescription=\"slide\"\n * id={`${slideId}-${index}`}\n * role=\"group\"\n * active={activeIndex === index}\n * >\n * {title}\n * </Slide>\n * ))}\n * </SlideContainer>\n * <Button\n * aria-label=\"Pause\"\n * aria-pressed={paused}\n * button=\"icon\"\n * onClick={togglePaused}\n * >\n * {paused ? <PlayArrowIcon /> : <PauseIcon />}\n * </Button>\n * {slides.map(({ title }, index) => (\n * <Button\n * key={title}\n * aria-label={`Slide ${index + 1}`}\n * aria-selected={activeIndex === index}\n * aria-controls={`${slideId}-${index}`}\n * role=\"tab\"\n * onClick={() => setActiveIndex(index))}\n * />\n * ))}\n * <Button\n * aria-label=\"Previous Slide\"\n * onClick={decrement}\n * disabled={activeIndex === 0}\n * buttonType=\"icon\"\n * >\n * <ChevronLeftIcon />\n * </Button>\n * <Button\n * aria-label=\"Next Slide\"\n * onClick={increment}\n * disabled={activeIndex === slides.length - 1}\n * buttonType=\"icon\"\n * >\n * <ChevronRightIcon />\n * </Button>\n * </div>\n * );\n * }\n * ```\n *\n * @see {@link https://react-md.dev/components/carousel | Carousel Demos}\n * @see {@link https://www.w3.org/WAI/ARIA/apg/patterns/carousel/}\n * @see {@link https://www.w3.org/WAI/ARIA/apg/example-index/carousel/carousel-2-tablist.html}\n * @since 6.0.0\n */\nexport function useCarousel(options: CarouselOptions): CarouselImplementation {\n const { duration = 8000, totalSlides } = options;\n const total = totalSlides - 1;\n\n const [state, setCarouselSlideState] = useState<CarouselSlideState>({\n direction: \"forward\",\n activeIndex: 0,\n });\n const {\n toggled: paused,\n toggle: togglePaused,\n setToggled: setPaused,\n } = useToggle(false);\n const setActiveIndex = useCallback<UseStateSetter<number>>(\n (activeIndexOrGetter) => {\n setCarouselSlideState((prevState) => {\n const prevActiveIndex = prevState.activeIndex;\n const nextActiveIndex =\n typeof activeIndexOrGetter === \"function\"\n ? activeIndexOrGetter(prevActiveIndex)\n : activeIndexOrGetter;\n\n return {\n direction: prevActiveIndex < nextActiveIndex ? \"forward\" : \"backward\",\n activeIndex: nextActiveIndex,\n };\n });\n },\n []\n );\n const increment = useCallback(() => {\n setCarouselSlideState((prevState) => ({\n direction: \"forward\",\n activeIndex: Math.min(total, prevState.activeIndex + 1),\n }));\n }, [total]);\n const decrement = useCallback(() => {\n setCarouselSlideState((prevState) => ({\n direction: \"backward\",\n activeIndex: Math.max(0, prevState.activeIndex - 1),\n }));\n }, []);\n\n const { activeIndex } = state;\n useEffect(() => {\n if (paused) {\n return;\n }\n\n const timeout = globalThis.setTimeout(() => {\n const nextActiveIndex = loop({\n min: 0,\n max: total,\n value: activeIndex,\n increment: true,\n });\n setCarouselSlideState({\n direction: activeIndex < nextActiveIndex ? \"forward\" : \"backward\",\n activeIndex: nextActiveIndex,\n });\n }, duration);\n\n return () => {\n globalThis.clearTimeout(timeout);\n };\n }, [paused, duration, activeIndex, total]);\n\n return {\n ...state,\n increment,\n decrement,\n paused,\n setPaused,\n togglePaused,\n setActiveIndex,\n setCarouselSlideState,\n };\n}\n"],"names":["useCallback","useEffect","useState","useToggle","loop","useCarousel","options","duration","totalSlides","total","state","setCarouselSlideState","direction","activeIndex","toggled","paused","toggle","togglePaused","setToggled","setPaused","setActiveIndex","activeIndexOrGetter","prevState","prevActiveIndex","nextActiveIndex","increment","Math","min","decrement","max","timeout","globalThis","setTimeout","value","clearTimeout"],"mappings":"AAAA;AAEA,SAASA,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAQ;AAGzD,SAASC,SAAS,QAAQ,kBAAkB;AAC5C,SAASC,IAAI,QAAQ,mBAAmB;AAuExC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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Y;gBACvDX,aAAaW;YACf;QACF,GAAGjB;QAEH,OAAO;YACLwB,WAAWG,YAAY,CAACJ;QAC1B;IACF,GAAG;QAACf;QAAQR;QAAUM;QAAaJ;KAAM;IAEzC,OAAO;QACL,GAAGC,KAAK;QACRe;QACAG;QACAb;QACAI;QACAF;QACAG;QACAT;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/transition/useCollapseTransition.ts"],"sourcesContent":["\"use client\";\n\nimport { cnb } from \"cnbuilder\";\nimport { type CSSProperties, useState } from \"react\";\n\nimport { useEnsuredRef } from \"../useEnsuredRef.js\";\nimport { DISPLAY_NONE_CLASS } from \"../utils/isElementVisible.js\";\nimport { collapse } from \"./collapseStyles.js\";\nimport {\n type CSSTransitionElementProps,\n type CSSTransitionHookReturnValue,\n type PreconfiguredCSSTransitionOptions,\n type TransitionTimeout,\n} from \"./types.js\";\nimport { useTransition } from \"./useTransition.js\";\nimport { getElementSizing, getTransitionTimeout } from \"./utils.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n * @since 2.0.0\n */\nexport const DEFAULT_COLLAPSE_TIMEOUT = {\n enter: 250,\n exit: 200,\n} as const satisfies TransitionTimeout;\n\n/**\n * @since 4.0.0\n */\nexport interface CollapseConfigurationStyle {\n /**\n * The minimum height that the collapsed element can be which defaults to `0`.\n * This can either be a number of pixels or a string CSS height value.\n *\n * Setting this value to any non-zero value will allow for the element to\n * shrink to the defined min-height, and then expand to the full height once\n * no longer collapsed.\n *\n * Note: If the `minHeight`, `minPaddingTop`, and `minPaddingBottom` options\n * are all set to `0` (default), the child will be removed from the DOM while\n * collapsed.\n *\n * @defaultValue `0`\n */\n minHeight?: number | string;\n\n /**\n * The minimum padding-top that the collapsed element can be which defaults to\n * `0`. This can either be a number of pixels or a string CSS `padding-top`\n * value.\n *\n * Note: If the `minHeight`, `minPaddingTop`, and `minPaddingBottom` options\n * are all set to `0` (default), the child will be removed from the DOM while\n * collapsed.\n *\n * @defaultValue `0`\n */\n minPaddingTop?: number | string;\n\n /**\n * The minimum padding-bottom that the collapsed element can be which defaults\n * to `0`. This can either be a number of pixels or a string CSS\n * `padding-bottom` value.\n *\n * Note: If the `minHeight`, `minPaddingTop`, and `minPaddingBottom` options\n * are all set to `0` (default), the child will be removed from the DOM while\n * collapsed.\n *\n * @defaultValue `0`\n */\n minPaddingBottom?: number | string;\n}\n\n/**\n * @since 4.0.0\n */\nexport interface CollapseStyle extends CollapseConfigurationStyle {\n /**\n * This will only be set when the {@link TransitionStage} is `\"entering\"` or\n * `\"exiting\"` as `\"${timeout}ms\"`.\n */\n transitionDuration?: string;\n}\n\n/**\n * These props (and `ref`) **must** be passed to a DOM element for the collapse\n * transition to work.\n *\n * @typeParam E - An HTMLElement type used for the ref required for the\n * transition.\n * @since 4.0.0\n */\nexport interface CollapseElementProps<\n E extends HTMLElement,\n> extends CSSTransitionElementProps<E> {\n /**\n * A merged styled object required for the collapse transition to work.\n *\n * @see {@link CollapseStyle}\n * @see {@link CollapseTransitionHookOptions.style}\n */\n style: CSSProperties;\n}\n\n/**\n * @typeParam E - An HTMLElement type used for the ref required for the\n * transition.\n * @since 4.0.0\n */\nexport interface CollapseTransitionHookOptions<E extends HTMLElement>\n extends\n Omit<PreconfiguredCSSTransitionOptions<E>, \"exitedHidden\">,\n CollapseConfigurationStyle {\n /**\n * An optional style to merge with the required collapse transition styles.\n *\n * If any keys from the {@link CollapseStyle} are included in this object,\n * these styles will override and possibly break the collapse transition.\n */\n style?: CSSProperties;\n\n /**\n *\n * @see {@link DEFAULT_COLLAPSE_TIMEOUT}\n * @defaultValue `DEFAULT_COLLAPSE_TIMEOUT`\n */\n timeout?: TransitionTimeout;\n\n /**\n *\n * @defaultValue `minHeight === 0 && minPaddingTop === 0 && minPaddingBottom === 0`\n */\n temporary?: boolean;\n}\n\n/**\n * @typeParam E - An HTMLElement type used for the ref required for the\n * transition.\n * @since 4.0.0\n */\nexport interface CollapseTransitionHookReturnValue<E extends HTMLElement>\n extends CSSTransitionHookReturnValue<E>, CollapseElementProps<E> {\n /**\n * This is just a convenience object so that you don't need to destructure as\n * many variables to pass to an element.\n *\n * @example Simple Usage\n * ```tsx\n * const { elementProps, rendered } = useCollapseTransition({\n * // ...options\n * transitionIn,\n * });\n *\n * if (!rendered) {\n * return null\n * }\n *\n * return <div {...elementProps}>{children}</div>;\n *\n * // This is the long-hand version\n * const { ref, style, className, hidden, rendered } = useCollapseTransition({\n * // ...options\n * transitionIn,\n * });\n *\n * if (!rendered) {\n * return null\n * }\n *\n * return (\n * <div\n * ref={ref}\n * style={style}\n * className={className}\n * hidden={hidden}\n * >\n * {children}\n * </div>\n * );\n * ```\n */\n elementProps: Readonly<CollapseElementProps<E>>;\n}\n\n/**\n * This hook is used to create a transition to collapse and expand an element\n * **inline** with other content like an accordion by animating the\n * `max-height`, `padding-top`, and `padding-bottom` CSS properties. The default\n * behavior is to hide the element completely while collapsed, but providing the\n * `minHeight`, `minPaddingTop`, and `minPaddingBottom` options can make this\n * work like a \"See More\"/\"Preview\" type of element\n *\n * @example Simple Example\n * ```tsx\n * import { Button } from \"@react-md/core/button/Button\";\n * import { useCollapseTransition } from \"@react-md/core/transition/useCollapseTransition\";\n * import { Typography } from \"@react-md/core/typography/Typography\";\n * import { type ReactElement, useState } from \"react\";\n *\n * function Example(): ReactElement {\n * const [collapsed, setCollapsed] = useState(true);\n * const { elementProps, rendered } =\n * useCollapseTransition({\n * transitionIn: !collapsed,\n * // If the collapsible element should maintain state by not unmounting\n * // while collapsed, uncomment this next line\n * // temporary: false,\n * });\n *\n * return (\n * <>\n * <Button onClick={() => setCollapsed(!collapsed)}>\n * Toggle\n * </Button>\n * {rendered && (\n * <div {...elementProps}>\n * <Typography>Stuff that should be collapsed</Typography>\n * <div>Whatever content...</div>\n * </div>\n * )}\n * </>\n * );\n * }\n * ```\n *\n * @example See More Example\n * ```tsx\n * import { Button } from \"@react-md/core/button/Button\";\n * import { IconRotator } from \"@react-md/core/icon/IconRotator\";\n * import KeyboardArrowDownIcon from \"@react-md/material-icons/KeyboardArrowDownIcon\"\n * import { useCollapseTransition } from \"@react-md/core/transition/useCollapseTransition\";\n * import { Typography } from \"@react-md/core/typography/Typography\";\n * import { type ReactElement, useState } from \"react\";\n *\n * import styles from \"./Example.module.scss\";\n * // pretend styles:\n * //\n * // .container {\n * // padding: 1rem;\n * // position: relative;\n * // }\n * //\n * // .button {\n * // position: absolute;\n * // right: 0;\n * // top: 0;\n * // }\n *\n *\n * function Example(): ReactElement {\n * const [collapsed, setCollapsed] = useState(true);\n * const { elementProps } =\n * useCollapseTransition({\n * transitionIn: !collapsed,\n * minHeight: 120,\n * minPaddingTop: 16,\n * className: styles.container,\n * });\n *\n * return (\n * <div {...elementProps}>\n * <Button\n * aria-expanded={!collapsed}\n * aria-label=\"Expand\"\n * onClick={() => setCollapsed(!collapsed)}\n * buttonType=\"icon\"\n * className={styles.button}\n * >\n * <IconRotator rotated={!collapsed}>\n * <KeyboardArrowDownIcon />\n * </IconRotator>\n * </Button>\n * <SomeComponentWithALotOfContent />\n * </div>\n * );\n * }\n * ```\n *\n * @see {@link https://react-md.dev/hooks/use-collapse-transition | useCollapseTransition Demos}\n * @see {@link https://react-md.dev/components/collapse | Collapse Demos}\n * @typeParam E - An HTMLElement type used for the ref required for the\n * transition.\n * @since 4.0.0\n */\nexport function useCollapseTransition<E extends HTMLElement>(\n options: CollapseTransitionHookOptions<E>\n): CollapseTransitionHookReturnValue<E> {\n const {\n nodeRef: propNodeRef,\n style: propStyle,\n className,\n transitionIn,\n timeout = DEFAULT_COLLAPSE_TIMEOUT,\n minHeight = 0,\n minPaddingTop = 0,\n minPaddingBottom = 0,\n temporary = minHeight === 0 &&\n minPaddingTop === 0 &&\n minPaddingBottom === 0,\n appear = false,\n enter = true,\n exit = true,\n onEnter = noop,\n onEntering = noop,\n onEntered = noop,\n onExit = noop,\n onExiting = noop,\n onExited = noop,\n } = options;\n\n const [nodeRef, refCallback] = useEnsuredRef(propNodeRef);\n const [style, setStyle] = useState<CSSProperties | undefined>(() => {\n if (transitionIn) {\n return undefined;\n }\n\n return {\n maxHeight: minHeight,\n paddingTop: minPaddingTop,\n paddingBottom: minPaddingBottom,\n };\n });\n\n const transitionTimeout = getTransitionTimeout({\n timeout,\n appear,\n enter,\n exit,\n });\n\n const { appearing, rendered, ref, stage, transitionTo, disablePortal } =\n useTransition({\n nodeRef: refCallback,\n timeout,\n transitionIn,\n reflow: true,\n appear,\n enter,\n exit,\n temporary,\n onEnter(appearing) {\n onEnter(appearing);\n setStyle({\n maxHeight: minHeight,\n paddingTop: minPaddingTop,\n paddingBottom: minPaddingBottom,\n });\n },\n onEntering(appearing) {\n onEntering(appearing);\n const { maxHeight, paddingTop, paddingBottom } = getElementSizing(\n nodeRef.current\n );\n\n const duration = appearing\n ? transitionTimeout.appear\n : transitionTimeout.enter;\n\n setStyle({\n maxHeight,\n paddingTop,\n paddingBottom,\n transitionDuration: `${duration}ms`,\n });\n },\n onEntered(appearing) {\n onEntered(appearing);\n setStyle(undefined);\n },\n onExit() {\n onExit();\n const { maxHeight, paddingTop, paddingBottom } = getElementSizing(\n nodeRef.current\n );\n\n setStyle({\n maxHeight,\n paddingTop,\n paddingBottom,\n transitionDuration: `${transitionTimeout.exit}ms`,\n });\n },\n onExiting() {\n onExiting();\n setStyle({\n maxHeight: minHeight,\n paddingTop: minPaddingTop,\n paddingBottom: minPaddingBottom,\n transitionDuration: `${transitionTimeout.exit}ms`,\n });\n },\n onExited() {\n onExited();\n setStyle({\n maxHeight: minHeight,\n paddingTop: minPaddingTop,\n paddingBottom: minPaddingBottom,\n });\n },\n });\n const entering = stage === \"enter\" || stage === \"entering\";\n const exiting = stage === \"exit\" || stage === \"exiting\";\n const collapsible =\n transitionTimeout.enter !== 0 || transitionTimeout.exit !== 0;\n\n const elementProps: CollapseElementProps<E> = {\n ref,\n style: { ...style, ...propStyle },\n className:\n cnb(\n className,\n collapsible &&\n collapse({\n enter: entering,\n leave: exiting,\n disableOverflow: !transitionIn || !!style,\n }),\n stage === \"exited\" &&\n minHeight === 0 &&\n minPaddingTop === 0 &&\n minPaddingBottom === 0 &&\n DISPLAY_NONE_CLASS\n ) || undefined,\n };\n\n return {\n ...elementProps,\n stage,\n rendered,\n appearing,\n elementProps,\n transitionTo,\n disablePortal,\n };\n}\n"],"names":["cnb","useState","useEnsuredRef","DISPLAY_NONE_CLASS","collapse","useTransition","getElementSizing","getTransitionTimeout","noop","DEFAULT_COLLAPSE_TIMEOUT","enter","exit","useCollapseTransition","options","nodeRef","propNodeRef","style","propStyle","className","transitionIn","timeout","minHeight","minPaddingTop","minPaddingBottom","temporary","appear","onEnter","onEntering","onEntered","onExit","onExiting","onExited","refCallback","setStyle","undefined","maxHeight","paddingTop","paddingBottom","transitionTimeout","appearing","rendered","ref","stage","transitionTo","disablePortal","reflow","current","duration","transitionDuration","entering","exiting","collapsible","elementProps","leave","disableOverflow"],"mappings":"AAAA;AAEA,SAASA,GAAG,QAAQ,YAAY;AAChC,SAA6BC,QAAQ,QAAQ,QAAQ;AAErD,SAASC,aAAa,QAAQ,sBAAsB;AACpD,SAASC,kBAAkB,QAAQ,+BAA+B;AAClE,SAASC,QAAQ,QAAQ,sBAAsB;AAO/C,SAASC,aAAa,QAAQ,qBAAqB;AACnD,SAASC,gBAAgB,EAAEC,oBAAoB,QAAQ,aAAa;AAEpE,MAAMC,OAAO;AACX,aAAa;AACf;AAEA;;CAEC,GACD,OAAO,MAAMC,2BAA2B;IACtCC,OAAO;IACPC,MAAM;AACR,EAAuC;AAgKvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmGC,GACD,OAAO,SAASC,sBACdC,OAAyC;IAEzC,MAAM,EACJC,SAASC,WAAW,EACpBC,OAAOC,SAAS,EAChBC,SAAS,EACTC,YAAY,EACZC,UAAUX,wBAAwB,EAClCY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AAU,EAAEC,aAAa,EAAE,GAAG/B,iBAC/CQ,QAAQgC,OAAO;YAGjBb,SAAS;gBACPE;gBACAC;gBACAC;gBACAW,oBAAoB,GAAGV,kBAAkB3B,IAAI,CAAC,EAAE,CAAC;YACnD;QACF;QACAmB;YACEA;YACAG,SAAS;gBACPE,WAAWd;gBACXe,YAAYd;gBACZe,eAAed;gBACfyB,oBAAoB,GAAGV,kBAAkB3B,IAAI,CAAC,EAAE,CAAC;YACnD;QACF;QACAoB;YACEA;YACAE,SAAS;gBACPE,WAAWd;gBACXe,YAAYd;gBACZe,eAAed;YACjB;QACF;IACF;IACF,MAAM0B,WAAWP,UAAU,WAAWA,UAAU;IAChD,MAAMQ,UAAUR,UAAU,UAAUA,UAAU;IAC9C,MAAMS,cACJb,kBAAkB5B,KAAK,KAAK,KAAK4B,kBAAkB3B,IAAI,KAAK;IAE9D,MAAMyC,eAAwC;QAC5CX;QACAzB,OAAO;YAAE,GAAGA,KAAK;YAAE,GAAGC,SAAS;QAAC;QAChCC,WACElB,IACEkB,WACAiC,eACE/C,SAAS;YACPM,OAAOuC;YACPI,OAAOH;YACPI,iBAAiB,CAACnC,gBAAgB,CAAC,CAACH;QACtC,IACF0B,UAAU,YACRrB,cAAc,KACdC,kBAAkB,KAClBC,qBAAqB,KACrBpB,uBACC+B;IACT;IAEA,OAAO;QACL,GAAGkB,YAAY;QACfV;QACAF;QACAD;QACAa;QACAT;QACAC;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/transition/useCollapseTransition.ts"],"sourcesContent":["\"use client\";\n\nimport { cnb } from \"cnbuilder\";\nimport { type CSSProperties, useState } from \"react\";\n\nimport { useEnsuredRef } from \"../useEnsuredRef.js\";\nimport { DISPLAY_NONE_CLASS } from \"../utils/isElementVisible.js\";\nimport { collapse } from \"./collapseStyles.js\";\nimport {\n type CSSTransitionElementProps,\n type CSSTransitionHookReturnValue,\n type PreconfiguredCSSTransitionOptions,\n type TransitionTimeout,\n} from \"./types.js\";\nimport { useTransition } from \"./useTransition.js\";\nimport { getElementSizing, getTransitionTimeout } from \"./utils.js\";\n\nconst noop = (): void => {\n // do nothing\n};\n\n/**\n * @since 2.0.0\n */\nexport const DEFAULT_COLLAPSE_TIMEOUT = {\n enter: 250,\n exit: 200,\n} as const satisfies TransitionTimeout;\n\n/**\n * @since 4.0.0\n */\nexport interface CollapseConfigurationStyle {\n /**\n * The minimum height that the collapsed element can be which defaults to `0`.\n * This can either be a number of pixels or a string CSS height value.\n *\n * Setting this value to any non-zero value will allow for the element to\n * shrink to the defined min-height, and then expand to the full height once\n * no longer collapsed.\n *\n * Note: If the `minHeight`, `minPaddingTop`, and `minPaddingBottom` options\n * are all set to `0` (default), the child will be removed from the DOM while\n * collapsed.\n *\n * @defaultValue `0`\n */\n minHeight?: number | string;\n\n /**\n * The minimum padding-top that the collapsed element can be which defaults to\n * `0`. This can either be a number of pixels or a string CSS `padding-top`\n * value.\n *\n * Note: If the `minHeight`, `minPaddingTop`, and `minPaddingBottom` options\n * are all set to `0` (default), the child will be removed from the DOM while\n * collapsed.\n *\n * @defaultValue `0`\n */\n minPaddingTop?: number | string;\n\n /**\n * The minimum padding-bottom that the collapsed element can be which defaults\n * to `0`. This can either be a number of pixels or a string CSS\n * `padding-bottom` value.\n *\n * Note: If the `minHeight`, `minPaddingTop`, and `minPaddingBottom` options\n * are all set to `0` (default), the child will be removed from the DOM while\n * collapsed.\n *\n * @defaultValue `0`\n */\n minPaddingBottom?: number | string;\n}\n\n/**\n * @since 4.0.0\n */\nexport interface CollapseStyle extends CollapseConfigurationStyle {\n /**\n * This will only be set when the {@link TransitionStage} is `\"entering\"` or\n * `\"exiting\"` as `\"${timeout}ms\"`.\n */\n transitionDuration?: string;\n}\n\n/**\n * These props (and `ref`) **must** be passed to a DOM element for the collapse\n * transition to work.\n *\n * @typeParam E - An HTMLElement type used for the ref required for the\n * transition.\n * @since 4.0.0\n */\nexport interface CollapseElementProps<\n E extends HTMLElement,\n> extends CSSTransitionElementProps<E> {\n /**\n * A merged styled object required for the collapse transition to work.\n *\n * @see {@link CollapseStyle}\n * @see {@link CollapseTransitionHookOptions.style}\n */\n style: CSSProperties;\n}\n\n/**\n * @typeParam E - An HTMLElement type used for the ref required for the\n * transition.\n * @since 4.0.0\n */\nexport interface CollapseTransitionHookOptions<E extends HTMLElement>\n extends\n Omit<PreconfiguredCSSTransitionOptions<E>, \"exitedHidden\">,\n CollapseConfigurationStyle {\n /**\n * An optional style to merge with the required collapse transition styles.\n *\n * If any keys from the {@link CollapseStyle} are included in this object,\n * these styles will override and possibly break the collapse transition.\n */\n style?: CSSProperties;\n\n /**\n *\n * @see {@link DEFAULT_COLLAPSE_TIMEOUT}\n * @defaultValue `DEFAULT_COLLAPSE_TIMEOUT`\n */\n timeout?: TransitionTimeout;\n\n /**\n *\n * @defaultValue `minHeight === 0 && minPaddingTop === 0 && minPaddingBottom === 0`\n */\n temporary?: boolean;\n}\n\n/**\n * @typeParam E - An HTMLElement type used for the ref required for the\n * transition.\n * @since 4.0.0\n */\nexport interface CollapseTransitionHookReturnValue<E extends HTMLElement>\n extends CSSTransitionHookReturnValue<E>, CollapseElementProps<E> {\n /**\n * This is just a convenience object so that you don't need to destructure as\n * many variables to pass to an element.\n *\n * @example Simple Usage\n * ```tsx\n * const { elementProps, rendered } = useCollapseTransition({\n * // ...options\n * transitionIn,\n * });\n *\n * if (!rendered) {\n * return null\n * }\n *\n * return <div {...elementProps}>{children}</div>;\n *\n * // This is the long-hand version\n * const { ref, style, className, hidden, rendered } = useCollapseTransition({\n * // ...options\n * transitionIn,\n * });\n *\n * if (!rendered) {\n * return null\n * }\n *\n * return (\n * <div\n * ref={ref}\n * style={style}\n * className={className}\n * hidden={hidden}\n * >\n * {children}\n * </div>\n * );\n * ```\n */\n elementProps: Readonly<CollapseElementProps<E>>;\n}\n\n/**\n * This hook is used to create a transition to collapse and expand an element\n * **inline** with other content like an accordion by animating the\n * `max-height`, `padding-top`, and `padding-bottom` CSS properties. The default\n * behavior is to hide the element completely while collapsed, but providing the\n * `minHeight`, `minPaddingTop`, and `minPaddingBottom` options can make this\n * work like a \"See More\"/\"Preview\" type of element\n *\n * @example Simple Example\n * ```tsx\n * import { Button } from \"@react-md/core/button/Button\";\n * import { useCollapseTransition } from \"@react-md/core/transition/useCollapseTransition\";\n * import { Typography } from \"@react-md/core/typography/Typography\";\n * import { type ReactElement, useState } from \"react\";\n *\n * function Example(): ReactElement {\n * const [collapsed, setCollapsed] = useState(true);\n * const { elementProps, rendered } =\n * useCollapseTransition({\n * transitionIn: !collapsed,\n * // If the collapsible element should maintain state by not unmounting\n * // while collapsed, uncomment this next line\n * // temporary: false,\n * });\n *\n * return (\n * <>\n * <Button onClick={() => setCollapsed(!collapsed)}>\n * Toggle\n * </Button>\n * {rendered && (\n * <div {...elementProps}>\n * <Typography>Stuff that should be collapsed</Typography>\n * <div>Whatever content...</div>\n * </div>\n * )}\n * </>\n * );\n * }\n * ```\n *\n * @example See More Example\n * ```tsx\n * import { Button } from \"@react-md/core/button/Button\";\n * import { IconRotator } from \"@react-md/core/icon/IconRotator\";\n * import KeyboardArrowDownIcon from \"@react-md/material-icons/KeyboardArrowDownIcon\"\n * import { useCollapseTransition } from \"@react-md/core/transition/useCollapseTransition\";\n * import { Typography } from \"@react-md/core/typography/Typography\";\n * import { type ReactElement, useState } from \"react\";\n *\n * import styles from \"./Example.module.scss\";\n * // pretend styles:\n * //\n * // .container {\n * // padding: 1rem;\n * // position: relative;\n * // }\n * //\n * // .button {\n * // position: absolute;\n * // right: 0;\n * // top: 0;\n * // }\n *\n *\n * function Example(): ReactElement {\n * const [collapsed, setCollapsed] = useState(true);\n * const { elementProps } =\n * useCollapseTransition({\n * transitionIn: !collapsed,\n * minHeight: 120,\n * minPaddingTop: 16,\n * className: styles.container,\n * });\n *\n * return (\n * <div {...elementProps}>\n * <Button\n * aria-expanded={!collapsed}\n * aria-label=\"Expand\"\n * onClick={() => setCollapsed(!collapsed)}\n * buttonType=\"icon\"\n * className={styles.button}\n * >\n * <IconRotator rotated={!collapsed}>\n * <KeyboardArrowDownIcon />\n * </IconRotator>\n * </Button>\n * <SomeComponentWithALotOfContent />\n * </div>\n * );\n * }\n * ```\n *\n * @see {@link https://react-md.dev/hooks/use-collapse-transition | useCollapseTransition Demos}\n * @see {@link https://react-md.dev/components/collapse | Collapse Demos}\n * @typeParam E - An HTMLElement type used for the ref required for the\n * transition.\n * @since 4.0.0\n */\nexport function useCollapseTransition<E extends HTMLElement>(\n options: CollapseTransitionHookOptions<E>\n): CollapseTransitionHookReturnValue<E> {\n const {\n nodeRef: propNodeRef,\n style: propStyle,\n className,\n transitionIn,\n timeout = DEFAULT_COLLAPSE_TIMEOUT,\n minHeight = 0,\n minPaddingTop = 0,\n minPaddingBottom = 0,\n temporary = minHeight === 0 &&\n minPaddingTop === 0 &&\n minPaddingBottom === 0,\n appear = false,\n enter = true,\n exit = true,\n onEnter = noop,\n onEntering = noop,\n onEntered = noop,\n onExit = noop,\n onExiting = noop,\n onExited = noop,\n } = options;\n\n const [nodeRef, refCallback] = useEnsuredRef(propNodeRef);\n const [style, setStyle] = useState<CSSProperties | undefined>(() => {\n if (transitionIn) {\n return;\n }\n\n return {\n maxHeight: minHeight,\n paddingTop: minPaddingTop,\n paddingBottom: minPaddingBottom,\n };\n });\n\n const transitionTimeout = getTransitionTimeout({\n timeout,\n appear,\n enter,\n exit,\n });\n\n const { appearing, rendered, ref, stage, transitionTo, disablePortal } =\n useTransition({\n nodeRef: refCallback,\n timeout,\n transitionIn,\n reflow: true,\n appear,\n enter,\n exit,\n temporary,\n onEnter(appearing) {\n onEnter(appearing);\n setStyle({\n maxHeight: minHeight,\n paddingTop: minPaddingTop,\n paddingBottom: minPaddingBottom,\n });\n },\n onEntering(appearing) {\n onEntering(appearing);\n const { maxHeight, paddingTop, paddingBottom } = getElementSizing(\n nodeRef.current\n );\n\n const duration = appearing\n ? transitionTimeout.appear\n : transitionTimeout.enter;\n\n setStyle({\n maxHeight,\n paddingTop,\n paddingBottom,\n transitionDuration: `${duration}ms`,\n });\n },\n onEntered(appearing) {\n onEntered(appearing);\n setStyle(undefined);\n },\n onExit() {\n onExit();\n const { maxHeight, paddingTop, paddingBottom } = getElementSizing(\n nodeRef.current\n );\n\n setStyle({\n maxHeight,\n paddingTop,\n paddingBottom,\n transitionDuration: `${transitionTimeout.exit}ms`,\n });\n },\n onExiting() {\n onExiting();\n setStyle({\n maxHeight: minHeight,\n paddingTop: minPaddingTop,\n paddingBottom: minPaddingBottom,\n transitionDuration: `${transitionTimeout.exit}ms`,\n });\n },\n onExited() {\n onExited();\n setStyle({\n maxHeight: minHeight,\n paddingTop: minPaddingTop,\n paddingBottom: minPaddingBottom,\n });\n },\n });\n const entering = stage === \"enter\" || stage === \"entering\";\n const exiting = stage === \"exit\" || stage === \"exiting\";\n const collapsible =\n transitionTimeout.enter !== 0 || transitionTimeout.exit !== 0;\n\n const elementProps: CollapseElementProps<E> = {\n ref,\n style: { ...style, ...propStyle },\n className:\n cnb(\n className,\n collapsible &&\n collapse({\n enter: entering,\n leave: exiting,\n disableOverflow: !transitionIn || !!style,\n }),\n stage === \"exited\" &&\n minHeight === 0 &&\n minPaddingTop === 0 &&\n minPaddingBottom === 0 &&\n DISPLAY_NONE_CLASS\n ) || undefined,\n };\n\n return {\n ...elementProps,\n stage,\n rendered,\n appearing,\n elementProps,\n transitionTo,\n disablePortal,\n };\n}\n"],"names":["cnb","useState","useEnsuredRef","DISPLAY_NONE_CLASS","collapse","useTransition","getElementSizing","getTransitionTimeout","noop","DEFAULT_COLLAPSE_TIMEOUT","enter","exit","useCollapseTransition","options","nodeRef","propNodeRef","style","propStyle","className","transitionIn","timeout","minHeight","minPaddingTop","minPaddingBottom","temporary","appear","onEnter","onEntering","onEntered","onExit","onExiting","onExited","refCallback","setStyle","maxHeight","paddingTop","paddingBottom","transitionTimeout","appearing","rendered","ref","stage","transitionTo","disablePortal","reflow","current","duration","transitionDuration","undefined","entering","exiting","collapsible","elementProps","leave","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