import React from 'react';
import { Item } from './Item';
import { TabsProps, TabsVariant } from './types';
import { SxProps } from '../../lib/styleDictionary';
import { Box } from '../Box';
import { ScrollView } from '../ScrollView';
import Content from './Content';
import useTheme from '../../context/theme/useTheme';
export function Tabs({
items,
activeKey,
onChange,
defaultActiveKey,
backgroundColors,
renderTabItem,
sx,
styles,
itemLabelColors,
itemBackgroundColors,
scrollable = false,
variant = 'solid',
labelProps = {},
size = 'middle',
...sxProps
}: TabsProps) {
const theme = useTheme();
const [internalValue, setInternalValue] = React.useState<
TabsProps['items'][0] | null
>(null);
const onInternalChange = (item: TabsProps['items'][0]) => {
setInternalValue(item);
onChange?.(item);
};
React.useEffect(() => {
setInternalValue((prev) => {
if (prev?.key !== activeKey) {
return items.find((item) => item.key === activeKey) || null;
}
return prev;
});
}, [activeKey, items]);
React.useEffect(() => {
typeof defaultActiveKey !== 'undefined' &&
setInternalValue((prev) => {
if (!prev) {
return items.find((item) => item.key === defaultActiveKey) || null;
}
return prev;
});
}, [defaultActiveKey, items]);
const variants = getVariantStyles({
backgroundColors
});
const isUnderline = variant === 'underlined';
return (
{variant === 'underlined' && (
)}
{items.map((item) => {
if (renderTabItem) {
return renderTabItem({
key: item.key,
label: item.label,
onPress: () => onInternalChange(item),
endAdornment: item?.endAdornment,
startAdornment: item?.startAdornment,
isActive: internalValue?.key === item.key
});
}
return (
- onInternalChange(item)}
labelColors={item?.labelColors || itemLabelColors}
backgroundColors={
item?.backgroundColors || itemBackgroundColors
}
style={styles?.item}
sx={{
flex: 1 / (items?.length || 0),
...sx?.item
}}
/>
);
})}
{internalValue?.children && (
{internalValue?.children}
)}
);
}
const getVariantStyles: (
props: Pick
) => Record = ({ backgroundColors }) => {
return {
solid: {
borderRadius: 1.2,
borderColor: backgroundColors?.borderColor || 'transparent',
backgroundColor: backgroundColors?.background || 'card'
},
underlined: {
borderTopColor: 'transparent',
borderLeftColor: 'transparent',
borderRightColor: 'transparent',
borderBottomColor: 'border'
},
bordered: {
borderRadius: 1.2,
borderColor: backgroundColors?.borderColor || 'border',
backgroundColor: backgroundColors?.background || 'background'
},
light: {
borderRadius: 1.2,
borderColor: backgroundColors?.borderColor || 'transparent',
backgroundColor: backgroundColors?.background || 'transparent'
}
};
};