import clsx from 'clsx'
import { useRouter, NextRouter } from 'next/router'
import { ReactNode, useState } from 'react'
import { track } from '@amplitude/analytics-browser'
type Tab = {
title: string
tabIcon?: ReactNode
content: ReactNode
// If set, show a badge with this content
badge?: string
}
type TabProps = {
tabs: Tab[]
labelClassName?: string
onClick?: (tabTitle: string, index: number) => void
className?: string
currentPageForAnalytics?: string
}
export function ControlledTabs(props: TabProps & { activeIndex: number }) {
const {
tabs,
activeIndex,
labelClassName,
onClick,
className,
currentPageForAnalytics,
} = props
return (
<>
{tabs.map((tab, i) => (
{tab.content}
))}
>
)
}
export function UncontrolledTabs(props: TabProps & { defaultIndex?: number }) {
const { defaultIndex, onClick, ...rest } = props
const [activeIndex, setActiveIndex] = useState(defaultIndex ?? 0)
return (
{
setActiveIndex(i)
onClick?.(title, i)
}}
/>
)
}
const isTabSelected = (router: NextRouter, queryParam: string, tab: Tab) => {
const selected = router.query[queryParam]
if (typeof selected === 'string') {
return tab.title.toLowerCase() === selected
} else {
return false
}
}
export function QueryUncontrolledTabs(
props: TabProps & { defaultIndex?: number }
) {
const { tabs, defaultIndex, onClick, ...rest } = props
const router = useRouter()
const selectedIdx = tabs.findIndex((t) => isTabSelected(router, 'tab', t))
const activeIndex = selectedIdx !== -1 ? selectedIdx : defaultIndex ?? 0
return (
{
router.replace(
{ query: { ...router.query, tab: title.toLowerCase() } },
undefined,
{ shallow: true }
)
onClick?.(title, i)
}}
/>
)
}
// legacy code that didn't know about any other kind of tabs imports this
export const Tabs = UncontrolledTabs