mirror of
https://github.com/vercel/commerce.git
synced 2025-07-22 12:24:18 +00:00
95 lines
3.2 KiB
TypeScript
95 lines
3.2 KiB
TypeScript
import React, { useRef, useEffect, Children, ReactElement, PropsWithChildren, useState, cloneElement } from "react"
|
|
import s from './AccountNavigation.module.scss'
|
|
|
|
import AccountNavigationItem from './components/AccountNavigationItem/AccountNavigationItem'
|
|
import {TabPaneProps} from '../../../common/TabCommon/components/TabPane/TabPane'
|
|
import { ACCOUNT_TAB, QUERY_KEY } from "src/utils/constanst.utils"
|
|
import { useRouter } from "next/router"
|
|
|
|
interface AccountNavigationProps {
|
|
defaultActiveIndex: number;
|
|
children: React.ReactNode
|
|
}
|
|
|
|
const getTabIndex = (tab?: string): number => {
|
|
switch (tab) {
|
|
case ACCOUNT_TAB.CUSTOMER_INFO:
|
|
return 0;
|
|
case ACCOUNT_TAB.ORDER:
|
|
return 1;
|
|
case ACCOUNT_TAB.FAVOURITE:
|
|
return 2;
|
|
default:
|
|
return 0
|
|
}
|
|
}
|
|
|
|
const AccountNavigation = ({ defaultActiveIndex, children } : AccountNavigationProps) => {
|
|
const router = useRouter()
|
|
|
|
const [active, setActive] = useState(defaultActiveIndex)
|
|
const sliderRef = useRef<HTMLDivElement>(null);
|
|
const headerRef = useRef<HTMLUListElement>(null)
|
|
|
|
useEffect(() => {
|
|
const query = router.query[QUERY_KEY.TAB] as string
|
|
const index = getTabIndex(query)
|
|
setActive(index)
|
|
}, [router.query[QUERY_KEY.TAB]])
|
|
|
|
const onTabClick = (index: number) => {
|
|
setActive(index)
|
|
}
|
|
|
|
function slide(index: number) {
|
|
const active = headerRef.current?.children.item(index)?.getBoundingClientRect()
|
|
const header = headerRef.current?.getBoundingClientRect()
|
|
const firstEl = headerRef.current?.children.item(0)?.getBoundingClientRect()
|
|
const current = sliderRef.current
|
|
|
|
if (current && active && header && firstEl) {
|
|
const firstElTop = firstEl.top
|
|
const top = active.top - firstElTop;
|
|
current.style.top = top.toString()+"px";
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
slide(active);
|
|
}, [active])
|
|
|
|
return (
|
|
<section className={s.accountNavigation}>
|
|
<ul className={s.tabList} ref={headerRef}>
|
|
{
|
|
Children.map(children, (tab, index) => {
|
|
let item = tab as ReactElement<PropsWithChildren<TabPaneProps>>
|
|
return (
|
|
<li key={item.props.tabName}>
|
|
<AccountNavigationItem
|
|
active={active === index}
|
|
onClick={onTabClick}
|
|
tabIndex={index}
|
|
>
|
|
{item.props.tabName}
|
|
</AccountNavigationItem>
|
|
</li>
|
|
)
|
|
})
|
|
}
|
|
<div ref={sliderRef} className={s.slider}></div>
|
|
</ul>
|
|
|
|
<div className={s.tabBody}>
|
|
{
|
|
Children.map(children, (tab, index) => {
|
|
let item = tab as ReactElement<PropsWithChildren<TabPaneProps>>
|
|
return cloneElement(item, { active: index === active });
|
|
})
|
|
}
|
|
</div>
|
|
</section>
|
|
)
|
|
}
|
|
|
|
export default AccountNavigation |