From 2d2153448daf175baa79c5efb82e367732f63569 Mon Sep 17 00:00:00 2001 From: codytseng Date: Thu, 3 Jul 2025 18:00:00 +0800 Subject: [PATCH] refactor: tabs --- src/components/Tabs/index.tsx | 52 ++++++++++------------------------- 1 file changed, 14 insertions(+), 38 deletions(-) diff --git a/src/components/Tabs/index.tsx b/src/components/Tabs/index.tsx index 821139ca..ba2a0f78 100644 --- a/src/components/Tabs/index.tsx +++ b/src/components/Tabs/index.tsx @@ -1,6 +1,6 @@ import { cn } from '@/lib/utils' import { useDeepBrowsing } from '@/providers/DeepBrowsingProvider' -import { useEffect, useRef, useState } from 'react' +import { useMemo } from 'react' import { useTranslation } from 'react-i18next' type TabDefinition = { @@ -21,62 +21,38 @@ export default function Tabs({ }) { const { t } = useTranslation() const { deepBrowsing, lastScrollTop } = useDeepBrowsing() - const tabRefs = useRef<(HTMLDivElement | null)[]>([]) - const [indicatorStyle, setIndicatorStyle] = useState({ width: 0, left: 0 }) - - useEffect(() => { - const handleResize = () => { - const activeIndex = tabs.findIndex((tab) => tab.value === value) - if (tabs.length === 4) { - console.log('notification tabs', activeIndex, value) - } - if (activeIndex >= 0 && tabRefs.current[activeIndex]) { - const activeTab = tabRefs.current[activeIndex] - const { offsetWidth, offsetLeft } = activeTab - const padding = 24 // 12px padding on each side - if (tabs.length === 4) { - console.log('notification tabs', offsetWidth, offsetLeft, padding) - } - setIndicatorStyle({ - width: offsetWidth - padding, - left: offsetLeft + padding / 2 - }) - } - } - window.addEventListener('resize', handleResize) - setTimeout(() => handleResize(), 20) // ensure tabs are rendered before calculating - return () => { - window.removeEventListener('resize', handleResize) - } - }, [value]) + const activeIndex = useMemo(() => tabs.findIndex((tab) => tab.value === value), [value, tabs]) return (
threshold ? '-translate-y-[calc(100%+12rem)]' : '' )} > - {tabs.map((tab, index) => ( + {tabs.map((tab) => (
(tabRefs.current[index] = el)} className={cn( - `text-center w-full py-2 font-semibold clickable cursor-pointer rounded-lg`, + `flex-1 text-center py-2 font-semibold clickable cursor-pointer rounded-lg`, value === tab.value ? '' : 'text-muted-foreground' )} - onClick={() => onTabChange?.(tab.value)} + onClick={() => { + onTabChange?.(tab.value) + }} > {t(tab.label)}
))}
= 0 ? activeIndex * (100 / tabs.length) : 0}%` }} - /> + > +
+
) }