UNPKG

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