import * as React from 'react'; import { QuickNav } from '../quick-nav'; import { TabContent, TabContentTitle, TabTitleRow, TabViewStyled, } from './TabView.styled'; export type TabViewProps = { children: React.ReactNode[]; initialTab?: number; masthead?: React.ReactNode; }; type TabProps = { title: string; children: () => React.ReactNode; }; export const TabView = (props: TabViewProps) => { const tabNames = React.Children.map(props.children, (child) => { if (!React.isValidElement(child)) { return '(Oops)'; } return child.props.title; }) as string[]; if (tabNames.length === 0) { return null; } const [currentTab, setCurrentTab] = React.useState(props.initialTab ?? 0); const tabRefs = tabNames.reduce<{ [name: string]: React.RefObject }>( (acc, name) => ({ ...acc, [name]: React.createRef() }), {} ); return ( {props.masthead && props.masthead} { setCurrentTab(tabNames.findIndex((name) => newTabName === name)); tabRefs[newTabName].current?.scrollIntoView({ behavior: 'smooth', }); }} /> {React.Children.map(props.children, (child) => { if (!React.isValidElement(child)) { return null; } return (
{child.props.title} {child}
); })}
); }; export const Tab = (props: TabProps) =>
{props.children()}
;