Files
Alaister YoungandAlaister Young 57d40e4705 [FE-5109] (part 3) refactor(studio): migrate layout components off next/router (#54055)
Part 3 of a 6-PR stack migrating all `next/router` and
`next/compat/router` imports in `apps/studio` onto TanStack Router hooks
and removing the router shims.

| Part | PR | Scope |
| --- | --- | --- |
| 1 | #54053 | Core navigation helpers, `hooks/**`, `lib/**`,
`data/prefetchers/**` |
| 2 | #54054 | `components/ui/**` |
| **3** | **#54055 ← this PR** | **`components/layouts/**` and
`state/tabs.tsx`** |
| 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer,
SQL Editor, Storage, Table Editor |
| 5 | #54057 | Remaining `components/interfaces/**` and
`QueryInsightsTable` router events |
| 6 | #54058 | Remove `next/router` & `next/compat/router` shims,
`_router-events.ts`, Vite aliases, and test mocks |

Migrates all `apps/studio/components/layouts/**` files and the studio
tab router integration off `next/router`.

**Added:**

- `useTabRouter()` in `apps/studio/state/tabs.tsx` so tab state actions
navigate via TanStack's `useNavigate` + `navigateToUrl` instead of
taking a `NextRouter` instance

**Changed:**

- Replaced `useRouter` across all layout directories (`AccountLayout`,
`AdvisorsLayout`, `AppLayout`, `AuthLayout`, `BranchLayout`,
`ComputeLayout`, `DatabaseLayout`, `DefaultLayout`,
`EdgeFunctionsLayout`, `ExplorerLayout`, `LogsLayout`, `Navigation/*`,
`ObservabilityLayout`, `OrganizationLayout`, `ProjectLayout`,
`ProjectNeedsSecuring`, `ProjectSettingsLayout`, `RealtimeLayout`,
`SQLEditorLayout`, `SignInLayout`, and `Tabs`) with TanStack Router
hooks (`useNavigate`, `useLocation`, `useRoutePattern`) and `useParams`
from `common`
- Updated `ProjectDropdown.utils.ts` and `ProjectDropdown.test.ts` to
work with TanStack `$param` route templates
- Updated layout component tests (`AccountLayout.selfhosted.test.tsx`,
`AdvisorsNavigationShortcuts.test.tsx`, `BranchLink.test.tsx`,
`ExplorerLayout.test.tsx`, `ExplorerNavChats.test.tsx`,
`ObservabilityMenu.utils.test.tsx`,
`MobileIssuesNavigation.platform.test.tsx`,
`ProjectLayout/index.test.tsx`, `ProjectNeedsSecuring.test.tsx`,
`ProjectDropdown.test.tsx`)

**Simplified:**

- `OrganizationLayout` and `SettingsLayout` match against
`useRoutePattern()` instead of the real pathname. An org slug ending in
a settings segment (e.g. `acmeapps`) no longer gets the settings title.
- `ProjectSettings.Commands` opens the Connect sheet through nuqs, the
same way `Connect.Commands` does
- `OrgMenuContent`, `OrganizationSettingsMenu` and `useTabRouter` read
`orgSlug`/`schema` from `useParams` instead of casting `location.search`
- Removed the dead `getPathnameWithoutQuery` helpers and their tests
- `usePreservedQueryParams` builds its string in the `useLocation`
selector (no `useMemo`), and `UnhealthyState` only navigates when `ref`
is set
- Moved `MobileIssuesNavigation.platform.test.tsx` onto a TanStack test
router. It now covers the active-route logic again.
- Tests use the shared `createTestRouter` and `customRender` router

Addresses
[FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks)

## To test

- [ ] Switching projects, organizations, and branches from the top
header dropdowns preserves the current sub-route where supported
- [ ] Opening, switching, and closing Table Editor / SQL Editor tabs
updates the URL and active tab cleanly
- [ ] Active sidebar item highlighting works across Database, Auth, Edge
Functions, Observability, Logs, Realtime, Explorer, and Project Settings
layouts
- [ ] Mobile navigation menu and floating toolbar sheets open and
navigate properly

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 14:30:25 +08:00

548 lines
19 KiB
TypeScript

import { useLocation, useNavigate } from '@tanstack/react-router'
import { LOCAL_STORAGE_KEYS, mergeRefs, useFlag, useParams } from 'common'
import { XIcon } from 'lucide-react'
import { AnimatePresence, motion } from 'motion/react'
import {
forwardRef,
Fragment,
isValidElement,
useEffect,
useLayoutEffect,
useRef,
type PropsWithChildren,
type ReactNode,
} from 'react'
import {
Alert,
AlertDescription,
AlertTitle,
cn,
LogoLoader,
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
useIsMobile,
usePanelRef,
} from 'ui'
import { useEditorType } from '../editors/EditorsLayout.hooks'
import { useMainScrollContainer, useSetMainScrollContainer } from '../MainScrollContainerContext'
import { useMobileSheet } from '../Navigation/NavigationBar/MobileSheetContext'
import { ProductMenuBar } from '../Navigation/ProductMenuBar'
import BuildingState from './BuildingState'
import ConnectingState from './ConnectingState'
import { getSectionKeyFromPathname, MobileMenuContent } from './LayoutHeader/MobileMenuContent'
import { ProjectPausedState } from './PausedState/ProjectPausedState'
import { PauseFailedState } from './PauseFailedState'
import { PausingState } from './PausingState'
import { ResizingState } from './ResizingState'
import RestartingState from './RestartingState'
import { RestoreFailedState } from './RestoreFailedState'
import { RestoringState } from './RestoringState'
import { UnhealthyState } from './UnhealthyState'
import { UpgradingState } from './UpgradingState'
import { CreateBranchModal } from '@/components/interfaces/BranchManagement/CreateBranchModal'
import { ProjectAPIDocs } from '@/components/interfaces/ProjectAPIDocs/ProjectAPIDocs'
import { isEligibleForFreeMicroUpgrade } from '@/components/interfaces/Support/FreeMicroUpgradeSuggestion.utils'
import { BannerExplorer } from '@/components/ui/BannerStack/Banners/BannerExplorer'
import { BannerFreeMicroUpgrade } from '@/components/ui/BannerStack/Banners/BannerFreeMicroUpgrade'
import { isFreeMicroUpgradeBannerSnoozed } from '@/components/ui/BannerStack/Banners/BannerFreeMicroUpgrade.utils'
import { BANNER_ID, useBannerStack } from '@/components/ui/BannerStack/BannerStackProvider'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import PartnerIcon from '@/components/ui/PartnerIcon'
import { ResourceExhaustionWarningBanner } from '@/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner'
import { useCustomContent } from '@/hooks/custom-content/useCustomContent'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { useRoutePattern } from '@/hooks/misc/useRoutePattern'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { withAuth } from '@/hooks/misc/withAuth'
import { PROJECT_STATUS } from '@/lib/constants'
import { MANAGED_BY } from '@/lib/constants/infrastructure'
import { buildStudioPageTitle } from '@/lib/page-title'
import { useAppStateSnapshot } from '@/state/app-state'
import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
// [Joshen] This is temporary while we unblock users from managing their project
// if their project is not responding well for any reason. Eventually needs a bit of an overhaul
const routesToIgnoreProjectDetailsRequest = [
'/project/$ref/settings/infrastructure',
'/project/$ref/settings/addons',
'/project/$ref/settings/general',
'/project/$ref/database/settings',
'/project/$ref/storage/settings',
]
const routesToIgnoreDBConnection = [
'/project/$ref/branches',
'/project/$ref/database/backups',
'/project/$ref/settings',
'/project/$ref/functions',
'/project/$ref/logs',
]
const routesToIgnorePostgrestConnection = [
'/project/$ref/settings/general',
'/project/$ref/settings/infrastructure',
'/project/$ref/settings/addons',
'/project/$ref/database/settings',
'/project/$ref/reports',
]
const DEFAULT_PROJECT_INTEGRATION_BANNER_DISMISS_KEY =
LOCAL_STORAGE_KEYS.PROJECT_INTEGRATION_BANNER_DISMISSED('unknown', 'unknown')
function getProjectIntegrationBannerDismissKey({
projectRef,
integrationSource,
}: {
projectRef?: string
integrationSource?: string | null
}) {
if (!projectRef || !integrationSource) return DEFAULT_PROJECT_INTEGRATION_BANNER_DISMISS_KEY
return LOCAL_STORAGE_KEYS.PROJECT_INTEGRATION_BANNER_DISMISSED(projectRef, integrationSource)
}
export interface ProjectLayoutProps {
isLoading?: boolean
isBlocking?: boolean
product?: string
productMenuBadge?: ReactNode
productMenuHeader?: ReactNode
productMenu?: ReactNode
browserTitle?: {
entity?: string
section?: string
override?: string
}
// Deprecated: use browserTitle.entity instead. Kept for backwards compatibility.
selectedTable?: string
resizableSidebar?: boolean
/** Starting width of the product menu in pixels, for menus that list more than links */
productMenuDefaultSize?: number
productMenuClassName?: string
}
export const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayoutProps>>(
(
{
isLoading = false,
isBlocking = true,
product = '',
productMenuBadge,
productMenuHeader,
productMenu,
browserTitle,
children,
selectedTable,
resizableSidebar = false,
productMenuDefaultSize = 256,
productMenuClassName,
},
ref
) => {
const pathname = useLocation({ select: (location) => location.pathname })
const routePattern = useRoutePattern()
const { data: selectedOrganization } = useSelectedOrganizationQuery()
const { data: selectedProject } = useSelectedProjectQuery()
const { addBanner, dismissBanner } = useBannerStack()
const showUpgradeBanner =
selectedProject?.status === 'ACTIVE_HEALTHY' &&
isEligibleForFreeMicroUpgrade({
planId: selectedOrganization?.plan?.id,
computeSize: selectedProject?.infra_compute_size,
})
const isExplorerEnabled = useFlag('explorer')
const [freeMicroUpgradeBannerDismissedAt] = useLocalStorageQuery<string | null>(
LOCAL_STORAGE_KEYS.FREE_MICRO_UPGRADE_BANNER_DISMISSED_AT(selectedProject?.ref ?? ''),
null
)
const isFreeMicroUpgradeBannerDismissed = isFreeMicroUpgradeBannerSnoozed(
freeMicroUpgradeBannerDismissedAt
)
const [isProjectIntegrationBannerDismissed, setIsProjectIntegrationBannerDismissed] =
useLocalStorageQuery(
getProjectIntegrationBannerDismissKey({
projectRef: selectedProject?.ref,
integrationSource: selectedProject?.integration_source,
}),
false
)
const [isExplorerBannerDismissed, , { isSuccess: isLocalStorageReady }] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.EXPLORER_BANNER_DISMISSED,
false
)
const { showSidebar } = useAppStateSnapshot()
const {
content: mobileSheetContent,
setContent: setMobileSheetContent,
registerOpenMenu,
} = useMobileSheet()
const isIssuesInboxEnabled = useFlag('issuesInbox')
const sectionKey = getSectionKeyFromPathname(pathname)
const currentSectionKey =
sectionKey === 'advisors' && isIssuesInboxEnabled ? 'issues' : sectionKey
const mainScrollContainer = useMainScrollContainer()
const setMainScrollContainer = useSetMainScrollContainer()
const combinedRef = mergeRefs(ref, setMainScrollContainer)
const { appTitle } = useCustomContent(['app:title'])
const brandTitle = appTitle || 'Supabase'
const isMobile = useIsMobile()
const editor = useEditorType()
const forceShowProductMenu = editor === undefined
const sideBarIsOpen = (forceShowProductMenu || showSidebar) && !isMobile
const panelRef = usePanelRef()
const projectName = selectedProject?.name
const organizationName = selectedOrganization?.name
const pageTitle =
browserTitle?.override ||
buildStudioPageTitle({
entity: browserTitle?.entity ?? selectedTable,
section: browserTitle?.section,
surface: product,
project: projectName,
org: organizationName,
brand: brandTitle,
}) ||
brandTitle
const isPaused = selectedProject?.status === PROJECT_STATUS.INACTIVE
const ignorePausedState =
routePattern === '/project/$ref' ||
routePattern.includes('/project/$ref/branches') ||
routePattern.includes('/project/$ref/settings') ||
routePattern.includes('/project/$ref/functions') ||
routePattern.includes('/project/$ref/logs')
const showPausedState = isPaused && !ignorePausedState
const showStripeProjectBanner =
selectedProject?.integration_source === 'stripe_projects' &&
!isProjectIntegrationBannerDismissed
useEffect(() => {
if (!selectedProject?.ref) return
const isProjectHomepage = routePattern === '/project/$ref'
if (isProjectHomepage && showUpgradeBanner && !isFreeMicroUpgradeBannerDismissed) {
addBanner({
id: BANNER_ID.FREE_MICRO_UPGRADE,
isDismissed: false,
content: <BannerFreeMicroUpgrade />,
priority: 2,
})
} else {
dismissBanner(BANNER_ID.FREE_MICRO_UPGRADE)
}
}, [
routePattern,
selectedProject?.ref,
showUpgradeBanner,
isFreeMicroUpgradeBannerDismissed,
addBanner,
dismissBanner,
])
useEffect(() => {
if (!isExplorerEnabled || !isLocalStorageReady || isExplorerBannerDismissed) return
addBanner({
id: 'explorer-banner',
priority: 2,
isDismissed: false,
content: <BannerExplorer />,
})
}, [addBanner, isExplorerEnabled, isExplorerBannerDismissed, isLocalStorageReady])
const mobileSheetContentRef = useRef(mobileSheetContent)
useLayoutEffect(() => {
mobileSheetContentRef.current = mobileSheetContent
}, [mobileSheetContent])
useLayoutEffect(() => {
const menu = (
<MobileMenuContent
currentProductMenu={productMenu ?? null}
currentProductMenuHeader={productMenuHeader}
currentProduct={product}
currentSectionKey={currentSectionKey}
onCloseSheet={() => setMobileSheetContent(null)}
/>
)
const unregister = registerOpenMenu(() => setMobileSheetContent(menu))
// Keep resource navigation in an already open sheet in sync with the layout.
const currentContent = mobileSheetContentRef.current
if (isValidElement(currentContent) && currentContent.type === MobileMenuContent) {
setMobileSheetContent(menu)
}
return unregister
}, [
registerOpenMenu,
productMenu,
productMenuHeader,
product,
currentSectionKey,
setMobileSheetContent,
])
useLayoutEffect(() => {
// `HashScrollController` scrolls to a `#section` that's on the page; don't undo it
const hash = window.location.hash.slice(1)
if (hash && document.getElementById(hash)) return
mainScrollContainer?.scrollTo({ top: 0, left: 0 })
}, [pathname, mainScrollContainer])
return (
<>
<title>{pageTitle}</title>
<meta name="description" content="Supabase Studio" />
<div className="flex flex-row h-full w-full">
<ResizablePanelGroup orientation="horizontal">
{productMenu && sideBarIsOpen && (
<ResizablePanel
panelRef={panelRef}
minSize="256px"
maxSize={resizableSidebar ? '512px' : '256px'}
defaultSize={`${productMenuDefaultSize}px`}
groupResizeBehavior="preserve-pixel-size"
id="panel-left"
>
<AnimatePresence initial={false}>
<motion.div
initial={{ width: 0, opacity: 0, height: '100%' }}
animate={{ width: 'auto', opacity: 1, height: '100%' }}
exit={{ width: 0, opacity: 0, height: '100%' }}
className="h-full"
transition={{ duration: 0.12 }}
>
<MenuBarWrapper
isLoading={isLoading}
isBlocking={isBlocking}
productMenu={productMenu}
>
<ProductMenuBar
title={product}
titleBadge={productMenuBadge}
header={productMenuHeader}
className={productMenuClassName}
>
{productMenu}
</ProductMenuBar>
</MenuBarWrapper>
</motion.div>
</AnimatePresence>
</ResizablePanel>
)}
{productMenu && sideBarIsOpen && (
<ResizableHandle
withHandle
disabled={resizableSidebar ? false : true}
className="hidden md:flex"
/>
)}
<ResizablePanel
className={cn('h-full flex flex-col w-full xl:min-w-[600px] bg-dash-sidebar')}
id="panel-project-content"
>
<main
className="h-full flex flex-col flex-1 w-full overflow-y-auto overflow-x-hidden @container"
ref={combinedRef}
>
{showStripeProjectBanner && (
<Alert
variant="default"
className="flex items-center gap-4 border-t-0 border-x-0 rounded-none"
>
<PartnerIcon
organization={{ managed_by: MANAGED_BY.STRIPE_PROJECTS }}
showTooltip={false}
size="medium"
/>
<div className="flex-1">
<AlertTitle>This project is connected to Stripe</AlertTitle>
<AlertDescription>
Changes made here may affect your connected Stripe project.
</AlertDescription>
</div>
<ButtonTooltip
variant="text"
icon={<XIcon size={14} />}
className="h-7 w-7 p-0"
onClick={() => setIsProjectIntegrationBannerDismissed(true)}
aria-label="Dismiss project integration banner"
tooltip={{ content: { text: 'Dismiss' } }}
/>
</Alert>
)}
{showPausedState ? (
<div className="mx-auto my-16 w-full h-full max-w-7xl flex items-center px-4">
<div className="w-full">
<ProjectPausedState product={product} />
</div>
</div>
) : (
<ContentWrapper>
<ResourceExhaustionWarningBanner />
{children}
</ContentWrapper>
)}
</main>
</ResizablePanel>
</ResizablePanelGroup>
</div>
<CreateBranchModal />
<ProjectAPIDocs />
</>
)
}
)
ProjectLayout.displayName = 'ProjectLayout'
export const ProjectLayoutWithAuth = withAuth(ProjectLayout)
interface MenuBarWrapperProps {
isLoading: boolean
isBlocking?: boolean
productMenu?: ReactNode
children: ReactNode
}
const MenuBarWrapper = ({
isLoading,
isBlocking = true,
productMenu,
children,
}: MenuBarWrapperProps) => {
const routePattern = useRoutePattern()
const { data: selectedProject } = useSelectedProjectQuery()
const requiresProjectDetails = !routesToIgnoreProjectDetailsRequest.includes(routePattern)
if (!isBlocking) {
return children
}
const showMenuBar =
!requiresProjectDetails || (requiresProjectDetails && selectedProject !== undefined)
return !isLoading && productMenu && showMenuBar ? children : null
}
interface ContentWrapperProps {
children: ReactNode
}
/**
* Check project.status to show building state or error state
*
* [Joshen] As of 210422: Current testing connection by pinging postgres
* Ideally we'd have a more specific monitoring of the project such as during restarts
* But that will come later: https://supabase.slack.com/archives/C01D6TWFFFW/p1650427619665549
*
* Just note that this logic does not differentiate between a "restarting" state and
* a "something is wrong and can't connect to project" state.
*
* [TODO] Next iteration should scrape long polling and just listen to the project's status
*/
const ContentWrapper = ({ children }: ContentWrapperProps) => {
const navigate = useNavigate()
const routePattern = useRoutePattern()
const { ref } = useParams()
const state = useDatabaseSelectorStateSnapshot()
const { data: selectedProject } = useSelectedProjectQuery()
const isBackupsPage = routePattern.includes('/project/$ref/database/backups')
const isHomePage = routePattern === '/project/$ref'
const requiresDbConnection = !routesToIgnoreDBConnection.some((x) => routePattern.includes(x))
const requiresPostgrestConnection = !routesToIgnorePostgrestConnection.includes(routePattern)
const isRestarting = selectedProject?.status === PROJECT_STATUS.RESTARTING
const isResizing = selectedProject?.status === PROJECT_STATUS.RESIZING
const isProjectUpgrading = selectedProject?.status === PROJECT_STATUS.UPGRADING
const isProjectRestoring = selectedProject?.status === PROJECT_STATUS.RESTORING
const isProjectRestoreFailed = selectedProject?.status === PROJECT_STATUS.RESTORE_FAILED
const isProjectBuilding =
selectedProject?.status === PROJECT_STATUS.COMING_UP ||
selectedProject?.status === PROJECT_STATUS.UNKNOWN
const isProjectPausing = selectedProject?.status === PROJECT_STATUS.PAUSING
const isProjectPauseFailed = selectedProject?.status === PROJECT_STATUS.PAUSE_FAILED
const isProjectUnhealthy = selectedProject?.status === PROJECT_STATUS.ACTIVE_UNHEALTHY
const isProjectOffline = selectedProject?.postgrestStatus === 'OFFLINE'
const ignoreUnhealthyState =
isHomePage ||
routePattern.includes('/project/$ref/settings') ||
routePattern.includes('/project/$ref/logs')
const shouldRedirectToHomeForBuilding = isProjectBuilding && requiresDbConnection && !isHomePage
// Don't show building state on the home page — it handles building state inline
const shouldShowBuildingState = isProjectBuilding && requiresDbConnection && !isHomePage
useEffect(() => {
if (shouldRedirectToHomeForBuilding && ref) {
void navigate({ to: '/project/$ref', params: { ref }, replace: true })
}
}, [shouldRedirectToHomeForBuilding, ref, navigate])
useEffect(() => {
if (ref) state.setSelectedDatabaseId(ref)
}, [ref])
if (isRestarting && !isBackupsPage) {
return <RestartingState />
}
if (isResizing && !isBackupsPage) {
return <ResizingState />
}
if (isProjectUpgrading && !isBackupsPage) {
return <UpgradingState />
}
if (isProjectPausing) {
return <PausingState project={selectedProject} />
}
if (isProjectPauseFailed) {
return <PauseFailedState />
}
if (isProjectUnhealthy && !ignoreUnhealthyState) {
return <UnhealthyState />
}
if (requiresPostgrestConnection && isProjectOffline) {
return <ConnectingState project={selectedProject} />
}
if (requiresDbConnection && isProjectRestoring) {
return <RestoringState />
}
if (requiresDbConnection && isProjectRestoreFailed) {
return <RestoreFailedState />
}
if (shouldRedirectToHomeForBuilding) {
return <LogoLoader />
}
if (shouldShowBuildingState) {
return <BuildingState />
}
return <Fragment key={selectedProject?.ref}>{children}</Fragment>
}