Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat: shared tab state between matching tab groups

Greg Richardson1038b4143aa5
diff --git a/apps/docs/pages/_app.tsx b/apps/docs/pages/_app.tsx
index 1ddc56fd1fa..aeb409b0910 100644
--- a/apps/docs/pages/_app.tsx
+++ b/apps/docs/pages/_app.tsx
@@ -1,5 +1,5 @@
-import '../../../packages/ui/build/css/themes/light.css'
import '../../../packages/ui/build/css/themes/dark.css'
+import '../../../packages/ui/build/css/themes/light.css'
import 'config/code-hike.scss'
import '../styles/main.scss?v=1.0.0'
@@ -13,6 +13,7 @@ import { useRouter } from 'next/router'
import { useCallback, useEffect, useState } from 'react'
import { AppPropsWithLayout } from 'types'
import { CommandMenuProvider } from 'ui'
+import { TabsProvider } from 'ui/src/components/Tabs'
import Favicons from '~/components/Favicons'
import SiteLayout from '~/layouts/SiteLayout'
import { API_URL, IS_PLATFORM, LOCAL_SUPABASE } from '~/lib/constants'
@@ -150,9 +151,11 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) {
<AuthContainer>
<ThemeProvider>
<CommandMenuProvider site="docs">
- <SiteLayout>
- <Component {...pageProps} />
- </SiteLayout>
+ <TabsProvider>
+ <SiteLayout>
+ <Component {...pageProps} />
+ </SiteLayout>
+ </TabsProvider>
</CommandMenuProvider>
</ThemeProvider>
</AuthContainer>
diff --git a/packages/ui/src/components/Tabs/Tabs.tsx b/packages/ui/src/components/Tabs/Tabs.tsx
index aba66a6dfea..67d389baecd 100644
--- a/packages/ui/src/components/Tabs/Tabs.tsx
+++ b/packages/ui/src/components/Tabs/Tabs.tsx
@@ -1,13 +1,8 @@
-import * as React from 'react'
-import { TabsContext } from './TabsContext'
-
import * as TabsPrimitive from '@radix-ui/react-tabs'
import { useRouter } from 'next/router'
-
-// @ts-ignore
-// import TabsStyles from './Tabs.module.css'
-
+import * as React from 'react'
import styleHandler from '../../lib/theme/styleHandler'
+import { useTabGroup } from './TabsProvider'
interface TabsProps {
type?: 'pills' | 'underlined' | 'cards' | 'rounded-pills'
@@ -45,12 +40,9 @@ const Tabs: React.FC<TabsProps> & TabsSubComponents = ({
children,
}) => {
const [activeTab, setActiveTab] = React.useState(
- defaultActiveId
- ? defaultActiveId
- : // if no defaultActiveId is set use the first panel
- children && children[0].props
- ? children[0].props.id
- : ''
+ defaultActiveId ??
+ // if no defaultActiveId is set use the first panel
+ children?.[0]?.props?.id
)
const router = useRouter()
@@ -58,40 +50,39 @@ const Tabs: React.FC<TabsProps> & TabsSubComponents = ({
let __styles = styleHandler('tabs')
- // activeId state can be overriden externally with `active`
- // defaults to the first panelif we have one or url hash if not
- const active = activeId ? activeId : activeTab ? activeTab : hash
+ if (children && !Array.isArray(children)) {
+ children = [children]
+ }
+
+ const tabIds = children.map((tab) => tab.props.id)
+
+ const { groupActiveId, setGroupActiveId } = useTabGroup(tabIds)
+
+ const active = activeId ?? groupActiveId ?? activeTab ?? hash
function onTabClick(id: string) {
- const newTabSelected = id !== active
setActiveTab(id)
- if (onClick) onClick(id)
- if (onChange && newTabSelected) onChange(id)
- }
+ setGroupActiveId?.(id)
- // for styling the tabs for underline style
- const underlined = type === 'underlined'
- // for styling the tabs for cards style
+ onClick?.(id)
+ if (id !== active) {
+ onChange?.(id)
+ }
+ }
const listClasses = [__styles[type].list]
if (scrollable) listClasses.push(__styles.scrollable)
if (listClassNames) listClasses.push(listClassNames)
- // if only 1 react child, it needs to be converted to a list/array
- // this is so 1 tab can be displayed
- if (children && !Array.isArray(children)) {
- children = [children]
- }
-
return (
- <TabsPrimitive.Root defaultValue={defaultActiveId} value={active} className={__styles.base}>
+ <TabsPrimitive.Root value={active} className={__styles.base}>
<TabsPrimitive.List className={listClasses.join(' ')}>
{addOnBefore}
{children.map((tab) => {
- const activeMatch = active === tab.props.id
+ const isActive = active === tab.props.id
const triggerClasses = [__styles[type].base, __styles.size[size]]
- if (activeMatch) {
+ if (isActive) {
triggerClasses.push(__styles[type].active)
} else {
triggerClasses.push(__styles[type].inactive)
@@ -118,10 +109,9 @@ const Tabs: React.FC<TabsProps> & TabsSubComponents = ({
</TabsPrimitive.Trigger>
)
})}
- {/* </Space> */}
{addOnAfter}
</TabsPrimitive.List>
- <TabsContext.Provider value={{ activeId: active }}>{children}</TabsContext.Provider>
+ {children}
</TabsPrimitive.Root>
)
}
@@ -142,16 +132,9 @@ export const Panel: React.FC<PanelProps> = ({ children, id, className }) => {
let __styles = styleHandler('tabs')
return (
- <TabsContext.Consumer>
- {({ activeId }) => {
- const active = activeId === id
- return (
- <TabsPrimitive.Content value={id} className={[__styles.content, className].join(' ')}>
- {children}
- </TabsPrimitive.Content>
- )
- }}
- </TabsContext.Consumer>
+ <TabsPrimitive.Content value={id} className={[__styles.content, className].join(' ')}>
+ {children}
+ </TabsPrimitive.Content>
)
}
diff --git a/packages/ui/src/components/Tabs/TabsContext.tsx b/packages/ui/src/components/Tabs/TabsContext.tsx
deleted file mode 100644
index b4a3471f16b..00000000000
--- a/packages/ui/src/components/Tabs/TabsContext.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-import { createContext } from 'react'
-
-// Make sure the shape of the default value passed to
-// createContext matches the shape that the consumers expect!
-export const TabsContext = createContext({
- activeId: '',
-})
diff --git a/packages/ui/src/components/Tabs/TabsProvider.tsx b/packages/ui/src/components/Tabs/TabsProvider.tsx
new file mode 100644
index 00000000000..feb6a74941b
--- /dev/null
+++ b/packages/ui/src/components/Tabs/TabsProvider.tsx
@@ -0,0 +1,103 @@
+import { xor } from 'lodash'
+import {
+ Dispatch,
+ PropsWithChildren,
+ SetStateAction,
+ createContext,
+ useCallback,
+ useContext,
+ useMemo,
+ useState,
+} from 'react'
+
+export interface TabGroup {
+ tabIds: string[]
+ activeId: string
+}
+
+interface TabsContextValue {
+ tabGroups: TabGroup[]
+ setTabGroups: Dispatch<SetStateAction<TabGroup[]>>
+}
+
+const TabsContext = createContext<TabsContextValue>({
+ tabGroups: [],
+ setTabGroups: () => {},
+})
+
+/**
+ * Tracks active Tab IDs across the site so that tabs
+ * with the same ID stay in sync (eg. JS vs TS tabs).
+ */
+const TabsProvider = ({ children }: PropsWithChildren<{}>) => {
+ const [tabGroups, setTabGroups] = useState<TabGroup[]>([])
+
+ return <TabsContext.Provider value={{ tabGroups, setTabGroups }}>{children}</TabsContext.Provider>
+}
+
+export interface UseTabGroupValue {
+ /**
+ * The active tab ID for the tab group.
+ * This value is shared with all matching tab
+ * groups within the context.
+ */
+ groupActiveId?: string
+
+ /**
+ * Set the active tab ID for the tab group.
+ * Value will be shared with all matching tab
+ * groups within the context.
+ */
+ setGroupActiveId?(id: string): void
+}
+
+/**
+ * Hook to retrieve and set the active tab ID for
+ * the current tab group.
+ * The value will be shared with all matching tab
+ * groups within the context.
+ *
+ * Silently fails if no `TabsProvider` is set.
+ */
+export const useTabGroup = (tabIds: string[]): UseTabGroupValue => {
+ const tabsContext = useContext(TabsContext)
+
+ if (!tabsContext) {
+ return {}
+ }
+
+ const { tabGroups, setTabGroups } = tabsContext
+
+ const groupActiveId = useMemo(
+ () => tabGroups.find((group) => xor(group.tabIds, tabIds).length === 0)?.activeId,
+ [tabGroups]
+ )
+
+ const setGroupActiveId = useCallback((id: string) => {
+ setTabGroups((groups) => {
+ // Clone the array
+ const newGroups = groups.concat()
+
+ const existingGroupIndex = groups.findIndex((group) => xor(group.tabIds, tabIds).length === 0)
+
+ const tabGroup: TabGroup = {
+ tabIds,
+ activeId: id,
+ }
+
+ // If this group already exists, replace it
+ // Otherwise add to the end
+ if (existingGroupIndex !== -1) {
+ newGroups.splice(existingGroupIndex, 1, tabGroup)
+ } else {
+ newGroups.push(tabGroup)
+ }
+
+ return newGroups
+ })
+ }, [])
+
+ return { groupActiveId, setGroupActiveId }
+}
+
+export default TabsProvider
diff --git a/packages/ui/src/components/Tabs/index.tsx b/packages/ui/src/components/Tabs/index.tsx
index 91e13405f93..14400819be6 100644
--- a/packages/ui/src/components/Tabs/index.tsx
+++ b/packages/ui/src/components/Tabs/index.tsx
@@ -1 +1,2 @@
export { default as Tabs } from './Tabs'
+export { default as TabsProvider } from './TabsProvider'