import React, { CSSProperties, MouseEvent, useEffect, useMemo, useRef, useState } from 'react' import useTheme from '../use-theme' import { TabsHeaderItem, TabsConfig, TabsContext } from './tabs-context' import useScale, { withScale } from '../use-scale' import Highlight from '../shared/highlight' import { useRect } from '../utils/layouts' import { isHuiElement } from '../utils/collections' import useClasses from '../use-classes' interface Props { initialValue?: string value?: string hideDivider?: boolean hideBorder?: boolean highlight?: boolean onChange?: (val: string) => void className?: string leftSpace?: CSSProperties['marginLeft'] hoverHeightRatio?: number hoverWidthRatio?: number align?: CSSProperties['justifyContent'] activeClassName?: string activeStyle?: CSSProperties } const defaultProps = { className: '', hideDivider: false, highlight: true, leftSpace: '0px' as CSSProperties['marginLeft'], hoverHeightRatio: 0.7, hoverWidthRatio: 1.15, activeClassName: '', activeStyle: {}, align: 'left' } type NativeAttrs = Omit, keyof Props> export type TabsProps = Props & NativeAttrs const TabsComponent: React.FC> = ({ initialValue: userCustomInitialValue, value, hideDivider, hideBorder, children, onChange, className, leftSpace, highlight, hoverHeightRatio, hoverWidthRatio, activeClassName, activeStyle, align, ...props }: React.PropsWithChildren) => { const theme = useTheme() const { SCALES } = useScale() const [tabs, setTabs] = useState>([]) const [selfValue, setSelfValue] = useState(userCustomInitialValue) const ref = useRef(null) const [displayHighlight, setDisplayHighlight] = useState(false) const { rect, setRect } = useRect() const register = (next: TabsHeaderItem) => { setTabs((last) => { const hasItem = last.find((item) => item.value === next.value) if (!hasItem) return [...last, next] return last.map((item) => { if (item.value !== next.value) return item return { ...item, ...next } }) }) } const initialValue = useMemo( () => ({ register, currentValue: selfValue, inGroup: true, leftSpace }), [selfValue, leftSpace] ) useEffect(() => { if (typeof value === 'undefined') return setSelfValue(value) }, [value]) const clickHandler = (value: string) => { setSelfValue(value) onChange && onChange(value) } const tabItemMouseOverHandler = (event: MouseEvent) => { if (!isHuiElement(event.target as HTMLDivElement)) return setRect(event, () => ref.current) if (highlight) { setDisplayHighlight(true) } } return (
setDisplayHighlight(false)}>
{tabs.map(({ cell: Cell, value }) => ( ))}
{children}
) } TabsComponent.defaultProps = defaultProps TabsComponent.displayName = 'HuiTabs' const Tabs = withScale(TabsComponent) export default Tabs