UNPKG

2.68 kBJavaScriptView Raw
1'use client';
2
3import _extends from "@babel/runtime/helpers/esm/extends";
4import * as React from 'react';
5import { unstable_useId as useId, unstable_useForkRef as useForkRef } from '@mui/utils';
6import { useTabsContext } from '../Tabs';
7import { extractEventHandlers } from '../utils/extractEventHandlers';
8import { useCompoundItem } from '../useCompound';
9import { useListItem } from '../useList';
10import { useButton } from '../useButton';
11import { combineHooksSlotProps } from '../utils/combineHooksSlotProps';
12function tabValueGenerator(otherTabValues) {
13 return otherTabValues.size;
14}
15
16/**
17 *
18 * Demos:
19 *
20 * - [Tabs](https://mui.com/base-ui/react-tabs/#hooks)
21 *
22 * API:
23 *
24 * - [useTab API](https://mui.com/base-ui/react-tabs/hooks-api/#use-tab)
25 */
26function useTab(parameters) {
27 const {
28 value: valueParam,
29 rootRef: externalRef,
30 disabled = false,
31 id: idParam
32 } = parameters;
33 const tabRef = React.useRef(null);
34 const id = useId(idParam);
35 const {
36 value: selectedValue,
37 selectionFollowsFocus,
38 getTabPanelId
39 } = useTabsContext();
40 const tabMetadata = React.useMemo(() => ({
41 disabled,
42 ref: tabRef,
43 id
44 }), [disabled, tabRef, id]);
45 const {
46 id: value,
47 index,
48 totalItemCount: totalTabsCount
49 } = useCompoundItem(valueParam != null ? valueParam : tabValueGenerator, tabMetadata);
50 const {
51 getRootProps: getTabProps,
52 highlighted,
53 selected
54 } = useListItem({
55 item: value
56 });
57 const {
58 getRootProps: getButtonProps,
59 rootRef: buttonRefHandler,
60 active,
61 focusVisible,
62 setFocusVisible
63 } = useButton({
64 disabled,
65 focusableWhenDisabled: !selectionFollowsFocus,
66 type: 'button'
67 });
68 const handleRef = useForkRef(tabRef, externalRef, buttonRefHandler);
69 const tabPanelId = value !== undefined ? getTabPanelId(value) : undefined;
70 const getRootProps = (externalProps = {}) => {
71 const externalEventHandlers = extractEventHandlers(externalProps);
72 const getCombinedRootProps = combineHooksSlotProps(getTabProps, getButtonProps);
73 return _extends({}, externalProps, getCombinedRootProps(externalEventHandlers), {
74 role: 'tab',
75 'aria-controls': tabPanelId,
76 'aria-selected': selected,
77 id,
78 ref: handleRef
79 });
80 };
81 return {
82 getRootProps,
83 active,
84 focusVisible,
85 highlighted,
86 index,
87 rootRef: handleRef,
88 // the `selected` state isn't set on the server (it relies on effects to be calculated),
89 // so we fall back to checking the `value` prop with the selectedValue from the TabsContext
90 selected: selected || value === selectedValue,
91 setFocusVisible,
92 totalTabsCount
93 };
94}
95export { useTab };
\No newline at end of file