({
children,
className = {},
controlledActive,
onActiveChange,
renderTab,
shouldFocusTabOnChange = false,
shouldMountInactive = false,
showBorder = true,
showHeader = true,
style,
shallow = false,
swipeable = false,
tabListProps = {},
tabTag,
extraHeaderContent,
}: TabContainerProps<T>)
| 69 | } |
| 70 | |
| 71 | export function TabContainer<T extends string = string>({ |
| 72 | children, |
| 73 | className = {}, |
| 74 | controlledActive, |
| 75 | onActiveChange, |
| 76 | renderTab, |
| 77 | shouldFocusTabOnChange = false, |
| 78 | shouldMountInactive = false, |
| 79 | showBorder = true, |
| 80 | showHeader = true, |
| 81 | style, |
| 82 | shallow = false, |
| 83 | swipeable = false, |
| 84 | tabListProps = {}, |
| 85 | tabTag, |
| 86 | extraHeaderContent, |
| 87 | }: TabContainerProps<T>): ReactElement { |
| 88 | const router = useRouter(); |
| 89 | const containerRef = useRef<HTMLDivElement>(null); |
| 90 | const tabs = useMemo(() => (children ?? []).filter(Boolean), [children]); |
| 91 | const currentPath = getRouterPathname(router.asPath || router.pathname); |
| 92 | |
| 93 | const [active, setActive] = useState(() => { |
| 94 | if (!tabs.length) { |
| 95 | return '' as T; |
| 96 | } |
| 97 | |
| 98 | const defaultLabel = tabs[0].props.label; |
| 99 | |
| 100 | if (tabs[0].props.url) { |
| 101 | const matchingChild = tabs.find((c) => c.props.url === currentPath); |
| 102 | return matchingChild ? matchingChild.props.label : defaultLabel; |
| 103 | } |
| 104 | |
| 105 | return defaultLabel; |
| 106 | }); |
| 107 | |
| 108 | const currentActive = controlledActive ?? active; |
| 109 | |
| 110 | const navigateToUrl = useCallback( |
| 111 | (url: string) => { |
| 112 | router.push(url, undefined, { shallow }); |
| 113 | }, |
| 114 | [router, shallow], |
| 115 | ); |
| 116 | |
| 117 | const onClick: TabListProps['onClick'] = (label, event) => { |
| 118 | const child = tabs.find((c) => c.props.label === label); |
| 119 | setActive(label as T); |
| 120 | const shouldChange = onActiveChange?.(label as T, event); |
| 121 | |
| 122 | // evaluate !== false due to backwards compatibility with implementations that return undefined |
| 123 | if (shouldChange !== false) { |
| 124 | setTimeout(() => { |
| 125 | if (shouldFocusTabOnChange && containerRef?.current) { |
| 126 | const [firstChild] = containerRef.current.children; |
| 127 | if (firstChild instanceof HTMLElement) { |
| 128 | firstChild.focus(); |
nothing calls this directly
no test coverage detected