Files
supabase/apps/studio/components/layouts/DefaultLayout.tsx
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

162 lines
6.7 KiB
TypeScript

import { useLocation } from '@tanstack/react-router'
import { LOCAL_STORAGE_KEYS, useBreakpoint, useFlag, useParams } from 'common'
import { PropsWithChildren, useEffect, useState } from 'react'
import { ResizablePanel, ResizablePanelGroup, SidebarProvider, usePanelRef } from 'ui'
import { SkipToContent } from 'ui-patterns/SkipToContent'
import { BannerStack } from '../ui/BannerStack/BannerStack'
import { LayoutHeader } from './Navigation/LayoutHeader/LayoutHeader'
import { MobileNavigationBar } from './Navigation/NavigationBar/MobileNavigationBar'
import { MobileSheetProvider } from './Navigation/NavigationBar/MobileSheetContext'
import { StudioMobileSheetNav } from './Navigation/NavigationBar/StudioMobileSheetNav'
import { LayoutSidebar } from './ProjectLayout/LayoutSidebar'
import {
LayoutSidebarProvider,
SIDEBAR_KEYS,
} from './ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import { ProjectContextProvider } from './ProjectLayout/ProjectContext'
import { AppBannerWrapper } from '@/components/interfaces/App/AppBannerWrapper'
import { GitHubConfigDriftBanner } from '@/components/interfaces/App/GitHubConfigDriftBanner'
import { OnboardingSurveyFollowUpCard } from '@/components/interfaces/OnboardingSurvey/OnboardingSurveyFollowUpCard'
import { DEFAULT_SIDEBAR_BEHAVIOR, Sidebar } from '@/components/interfaces/Sidebar'
import { useLastVisitedOrganization } from '@/hooks/misc/useLastVisitedOrganization'
import { useLocalStorage } from '@/hooks/misc/useLocalStorage'
import { useCheckLatestDeploy } from '@/hooks/use-check-latest-deploy'
import { IS_PLATFORM } from '@/lib/constants'
import { getPathSegment } from '@/lib/pathname.utils'
import { useAppStateSnapshot } from '@/state/app-state'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
export interface DefaultLayoutProps {
headerTitle?: string
hideMobileMenu?: boolean
}
/**
* Base layout for all project pages in the dashboard, rendered as the first child on all page files within a project.
*
* A second layout as the child to this is required, and the layout depends on which section of the dashboard the page is on. (e.g Auth - AuthLayout)
*
* The base layout handles rendering the following UI components:
* - App banner (e.g for notices or incidents)
* - Mobile navigation bar
* - First level side navigation bar (e.g For navigating to Table Editor, SQL Editor, Database page, etc)
*/
export const DefaultLayout = ({
children,
headerTitle,
hideMobileMenu,
}: PropsWithChildren<DefaultLayoutProps>) => {
useCheckLatestDeploy()
const { ref } = useParams()
const pathname = useLocation({ select: (location) => location.pathname })
const panelRef = usePanelRef()
const isMobile = useBreakpoint('md')
const isSidebarOverlay = useBreakpoint('xl')
const appSnap = useAppStateSnapshot()
const { isMaximised, activeSidebar } = useSidebarManagerSnapshot()
const { lastVisitedOrganization } = useLastVisitedOrganization()
const showConfigDrift = useFlag('ConfigDrift') && IS_PLATFORM
const [isMounted, setIsMounted] = useState(false)
const [sidebarBehavior] = useLocalStorage(
LOCAL_STORAGE_KEYS.SIDEBAR_BEHAVIOR,
DEFAULT_SIDEBAR_BEHAVIOR
)
const backToDashboardURL = pathname.startsWith('/account')
? appSnap.lastRouteBeforeVisitingAccountPage.length > 0
? appSnap.lastRouteBeforeVisitingAccountPage
: IS_PLATFORM && !!lastVisitedOrganization
? `/org/${lastVisitedOrganization}`
: IS_PLATFORM
? '/organizations'
: '/project/default'
: undefined
const contentMinSizePercentage = 50
const contentMaxSizePercentage = 70
useEffect(() => {
setIsMounted(true)
}, [])
useEffect(() => {
if (!isMounted || !panelRef.current || !activeSidebar || isMobile || isSidebarOverlay) return
if (isMaximised) {
panelRef.current.collapse()
} else {
panelRef.current.resize(`${contentMaxSizePercentage}%`)
}
}, [isMounted, isMaximised, panelRef, activeSidebar, isMobile, isSidebarOverlay])
// This is required to prevent layout shift when rendering resizable panels (they initially render at 50%, then shift
// to whatever is specified).
if (!isMounted) {
return null
}
return (
<SidebarProvider defaultOpen={sidebarBehavior === 'open'}>
<LayoutSidebarProvider>
<ProjectContextProvider projectRef={ref}>
<MobileSheetProvider>
<div className="flex flex-col h-screen w-screen">
<SkipToContent href="#main" />
{/* Top Banner */}
<AppBannerWrapper />
<div className="shrink-0">
{isMobile && (
<MobileNavigationBar
hideMobileMenu={hideMobileMenu}
backToDashboardURL={backToDashboardURL}
/>
)}
<LayoutHeader headerTitle={headerTitle} backToDashboardURL={backToDashboardURL} />
{showConfigDrift && ref && <GitHubConfigDriftBanner />}
</div>
{/* Main Content Area */}
<div className="flex flex-1 w-full overflow-y-hidden">
{/* Sidebar - Only show for project pages, not account pages */}
{!pathname.startsWith('/account') && <Sidebar />}
{/* Main Content with Layout Sidebar */}
<ResizablePanelGroup
orientation="horizontal"
className="h-full w-full overflow-x-hidden flex-1 flex flex-row gap-0"
autoSaveId="default-layout-content"
>
<ResizablePanel
id="panel-content"
className="w-full"
panelRef={panelRef}
collapsible={activeSidebar?.id === SIDEBAR_KEYS.AI_ASSISTANT}
minSize={`${contentMinSizePercentage}`}
maxSize={`${contentMaxSizePercentage}`}
defaultSize={`${contentMaxSizePercentage}`}
>
<main id="main" tabIndex={-1} className="h-full overflow-y-auto outline-hidden">
{children}
</main>
</ResizablePanel>
<LayoutSidebar
minSize={`${100 - contentMaxSizePercentage}`}
maxSize="100"
defaultSize={`${100 - contentMaxSizePercentage}`}
/>
</ResizablePanelGroup>
</div>
</div>
<BannerStack />
{IS_PLATFORM && <OnboardingSurveyFollowUpCard />}
<StudioMobileSheetNav
shouldCloseOnQueryChange={getPathSegment(pathname, 3) !== 'issues'}
/>
</MobileSheetProvider>
</ProjectContextProvider>
</LayoutSidebarProvider>
</SidebarProvider>
)
}