import 'swiper/css' import { useBreakpoint } from 'common' import { domAnimation, LazyMotion, m, useAnimation, useInView } from 'motion/react' import React, { useEffect, useRef, useState, type ReactNode } from 'react' import { Swiper, SwiperSlide } from 'swiper/react' import { cn } from 'ui' interface TabProps { label: string | React.ReactNode paragraph?: string | React.ReactNode isActive: boolean onClick: VoidFunction progress: number | undefined intervalDuration?: number } const Tab = ({ isActive, label, paragraph, onClick, progress, intervalDuration }: TabProps) => { const paragraphRef = useRef(null) const [height, setHeight] = useState('auto') useEffect(() => { if (!paragraphRef) return setHeight(isActive ? (paragraphRef.current?.clientHeight ?? 0) : 0) }, [isActive]) return ( ) } interface Tab { label: ReactNode paragraph?: ReactNode panel?: ReactNode code?: string } interface Props { tabs: Tab[] intervalDuration?: number updateFrequency?: number } const TimedAccordionSection = ({ tabs, intervalDuration = 25, updateFrequency = 10 }: Props) => { const ref = useRef(null) const isInView = useInView(ref, { margin: '-25%' }) const [activeTab, setActiveTab] = useState(0) const [progress, setProgress] = useState(0) const [apiSwiper, setApiSwiper] = useState(undefined) const controls = useAnimation() const isMobile = useBreakpoint() useEffect(() => { if (!apiSwiper) return // @ts-ignore apiSwiper.slideTo(activeTab) }, [activeTab]) const restartInterval = (tabIndex: number) => { setProgress(0) setActiveTab(tabIndex) } const animation = { width: '100%', transition: { duration: intervalDuration, ease: 'linear' }, } useEffect(() => { // pause timer when component is not in view if (!isInView) { controls.stop() setProgress(progress) return } const progressIncrement = (100 / intervalDuration) * (updateFrequency / 1000) controls.start(animation) const progressInterval = setInterval(() => { setProgress((prevProgress) => (prevProgress + progressIncrement) % 101) }, updateFrequency) return () => { clearInterval(progressInterval) setProgress(0) } }, [activeTab, controls, isInView]) useEffect(() => { if (progress >= 100.9) { setActiveTab((prevActiveTab) => (prevActiveTab === tabs.length - 1 ? 0 : prevActiveTab + 1)) } }, [progress]) const handleTabClick = (tabIndex: number) => { // Disable trigger if tab is already active if (tabIndex === activeTab) return restartInterval(tabIndex) } return (
{tabs.map((tab, index) => ( handleTabClick(index)} progress={index === activeTab ? progress : undefined} intervalDuration={intervalDuration} /> ))}
handleTabClick(s.activeIndex)} slidesPerView={1} speed={300} allowTouchMove={isMobile} > {tabs.map((tab, i) => ( {tab.panel} ))}
) } export default TimedAccordionSection