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

561 lines
18 KiB
TypeScript

import { createRootRoute, createRoute, RouterContextProvider } from '@tanstack/react-router'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { LOCAL_STORAGE_KEYS } from 'common'
import { useState, type ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { MobileSheetProvider, useMobileSheet } from '../Navigation/NavigationBar/MobileSheetContext'
import { ProjectLayout } from './index'
import type { MobileMenuContentProps } from './LayoutHeader/MobileMenuContent'
import { STUDIO_PAGE_TITLE_SEPARATOR } from '@/lib/page-title'
import { createTestRouter } from '@/tests/lib/custom-render'
const {
mockRoute,
mockSetSelectedDatabaseId,
mockSetMobileMenuOpen,
mockViewport,
mockMainScrollContainer,
} = vi.hoisted(() => ({
mockRoute: { url: '/project/default/observability/query-performance' },
mockSetSelectedDatabaseId: vi.fn(),
mockSetMobileMenuOpen: vi.fn(),
mockViewport: { isMobile: false },
mockMainScrollContainer: { current: null as { scrollTo: ReturnType<typeof vi.fn> } | null },
}))
const {
mockAddBanner,
mockDismissBanner,
mockProjectState,
mockOrgPlanState,
mockBannerDismissedState,
mockUseLocalStorageQuery,
} = vi.hoisted(() => ({
mockAddBanner: vi.fn(),
mockDismissBanner: vi.fn(),
mockProjectState: {
current: {
ref: 'default',
name: 'Project 1',
status: 'ACTIVE_HEALTHY',
postgrestStatus: 'ONLINE',
infra_compute_size: undefined as string | undefined,
integration_source: null as string | null,
},
},
mockOrgPlanState: {
current: { id: 'pro', name: 'Pro' } as { id: string; name: string } | undefined,
},
mockBannerDismissedState: { current: false },
mockUseLocalStorageQuery: vi.fn(),
}))
vi.mock('common', () => ({
useParams: () => ({ ref: 'default' }),
mergeRefs:
(..._refs: any[]) =>
(_value: unknown) => {},
IS_PLATFORM: false,
LOCAL_STORAGE_KEYS: {
FREE_MICRO_UPGRADE_BANNER_DISMISSED_AT: (ref: string) =>
`free-micro-upgrade-banner-dismissed-at-${ref}`,
PROJECT_INTEGRATION_BANNER_DISMISSED: (ref: string, integrationSource: string) =>
`project-integration-banner-dismissed-${ref}-${integrationSource}`,
},
isFeatureEnabled: () => false,
useFlag: () => false,
}))
vi.mock('motion/react', () => ({
AnimatePresence: ({ children }: { children: ReactNode }) => <>{children}</>,
motion: {
div: ({ children, ...props }: any) => <div {...props}>{children}</div>,
create: (Component: any) => Component,
},
}))
vi.mock('ui', async () => ({
...(await import('ui/src/components/shadcn/ui/resizable')),
cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
Alert: ({ children, ...props }: any) => <div {...props}>{children}</div>,
AlertDescription: ({ children, ...props }: any) => <div {...props}>{children}</div>,
AlertTitle: ({ children, ...props }: any) => <div {...props}>{children}</div>,
CommandInput: { displayName: 'CommandInput' },
Command: { displayName: 'Command' },
CommandGroup: { displayName: 'CommandGroup' },
CommandItem: { displayName: 'CommandItem' },
CommandList: { displayName: 'CommandList' },
LogoLoader: () => <div data-testid="logo-loader" />,
Sidebar: ({ children, ...props }: any) => <div {...props}>{children}</div>,
SidebarContent: ({ children, ...props }: any) => <div {...props}>{children}</div>,
SidebarFooter: ({ children, ...props }: any) => <div {...props}>{children}</div>,
SidebarGroup: ({ children, ...props }: any) => <div {...props}>{children}</div>,
SidebarMenu: ({ children, ...props }: any) => <div {...props}>{children}</div>,
SidebarMenuButton: (props: any) => <div {...props} />,
SidebarMenuItem: (props: any) => <div {...props} />,
useIsMobile: () => mockViewport.isMobile,
useSidebar: () => ({ setOpen: vi.fn() }),
}))
vi.mock('ui-patterns/MobileSheetNav/MobileSheetNav', () => ({
default: ({ children }: { children: ReactNode }) => <>{children}</>,
}))
vi.mock('../editors/EditorsLayout.hooks', () => ({
useEditorType: () => undefined,
}))
vi.mock('../MainScrollContainerContext', () => ({
useMainScrollContainer: () => mockMainScrollContainer.current,
useSetMainScrollContainer: () => () => {},
}))
vi.mock('./BuildingState', () => ({ default: () => null }))
vi.mock('./ConnectingState', () => ({ default: () => null }))
vi.mock('./LoadingState', () => ({ LoadingState: () => null }))
vi.mock('./PausedState/ProjectPausedState', () => ({
ProjectPausedState: () => <div>Project paused</div>,
}))
vi.mock('./PauseFailedState', () => ({ PauseFailedState: () => null }))
vi.mock('./PausingState', () => ({ PausingState: () => null }))
vi.mock('./ProductMenuBar', () => ({
ProductMenuBar: ({ children }: { children: ReactNode }) => <>{children}</>,
}))
vi.mock('./ResizingState', () => ({ ResizingState: () => null }))
vi.mock('./RestartingState', () => ({ default: () => null }))
vi.mock('./RestoreFailedState', () => ({ RestoreFailedState: () => null }))
vi.mock('./RestoringState', () => ({ RestoringState: () => null }))
vi.mock('./UpgradingState', () => ({ UpgradingState: () => null }))
vi.mock('@/components/interfaces/BranchManagement/CreateBranchModal', () => ({
CreateBranchModal: () => null,
}))
vi.mock('@/components/interfaces/ProjectAPIDocs/ProjectAPIDocs', () => ({
ProjectAPIDocs: () => null,
}))
vi.mock('@/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner', () => ({
ResourceExhaustionWarningBanner: () => null,
}))
vi.mock('@/components/ui/ButtonTooltip', () => ({
ButtonTooltip: ({ children, ...props }: any) => (
<button tabIndex={0} {...props}>
{children}
</button>
),
}))
vi.mock('@/components/ui/PartnerIcon', () => ({
default: () => <div data-testid="partner-icon" />,
}))
vi.mock('@/hooks/custom-content/useCustomContent', () => ({
useCustomContent: () => ({ appTitle: 'Supabase' }),
}))
vi.mock('@/hooks/misc/useLocalStorage', () => ({
useLocalStorageQuery: (...args: unknown[]) => mockUseLocalStorageQuery(...args),
}))
vi.mock('@/components/ui/BannerStack/BannerStackProvider', () => ({
BANNER_ID: {
FREE_MICRO_UPGRADE: 'free-micro-upgrade-banner',
},
useBannerStack: () => ({
addBanner: mockAddBanner,
dismissBanner: mockDismissBanner,
banners: [],
}),
}))
vi.mock('@/components/ui/BannerStack/Banners/BannerFreeMicroUpgrade', () => ({
BannerFreeMicroUpgrade: () => null,
}))
vi.mock('@/data/usage/resource-warnings-query', () => ({}))
vi.mock('@/hooks/misc/useSelectedOrganization', () => ({
useSelectedOrganizationQuery: () => ({
data: { name: 'Organization 1', slug: 'org-1', plan: mockOrgPlanState.current },
}),
}))
vi.mock('@/hooks/misc/useSelectedProject', () => ({
useSelectedProjectQuery: () => ({ data: mockProjectState.current }),
}))
vi.mock('@/hooks/misc/withAuth', () => ({
withAuth: (Component: any) => Component,
}))
vi.mock('@/hooks/ui/useFlag', () => ({
usePHFlag: () => undefined,
}))
vi.mock('@/state/app-state', () => ({
useAppStateSnapshot: () => ({
mobileMenuOpen: false,
showSidebar: false,
setMobileMenuOpen: mockSetMobileMenuOpen,
}),
}))
vi.mock('@/state/database-selector', () => ({
useDatabaseSelectorStateSnapshot: () => ({
setSelectedDatabaseId: mockSetSelectedDatabaseId,
}),
}))
vi.mock('./LayoutHeader/MobileMenuContent', async (importOriginal) => {
const actual = await importOriginal<typeof import('./LayoutHeader/MobileMenuContent')>()
return {
...actual,
MobileMenuContent: ({
currentProductMenuHeader,
currentProductMenu,
}: MobileMenuContentProps) => (
<div>
{currentProductMenuHeader}
{currentProductMenu}
</div>
),
}
})
vi.mock('../Navigation/ProductMenuBar', () => ({
ProductMenuBar: ({ children }: { children: ReactNode }) => <>{children}</>,
}))
const MobileSheetHarness = () => {
const { content, openMenu, setContent } = useMobileSheet()
return (
<>
<button tabIndex={0} onClick={openMenu}>
Open menu
</button>
<button tabIndex={0} onClick={() => setContent(<span>Other sheet</span>)}>
Open other sheet
</button>
<div data-testid="mobile-sheet">{content}</div>
</>
)
}
const ResourceMenuHarness = () => {
const [section, setSection] = useState('Explorer')
return (
<>
<button tabIndex={0} onClick={() => setSection('Chats')}>
Change section
</button>
<ProjectLayout
product="Explorer"
isBlocking={false}
productMenuHeader={<span>{section} header</span>}
productMenu={
<button
tabIndex={0}
onClick={() => setSection(section === 'Explorer' ? 'Notebooks' : 'Explorer')}
>
{section === 'Explorer' ? 'Open notebooks' : 'Return to Explorer'}
</button>
}
>
<div />
</ProjectLayout>
</>
)
}
const createProjectRouter = async () => {
const rootRoute = createRootRoute()
const routes = [
'/project/$ref',
'/project/$ref/branches',
'/project/$ref/observability/query-performance',
].map((path) => createRoute({ getParentRoute: () => rootRoute, path }))
const router = createTestRouter(mockRoute.url, rootRoute.addChildren(routes))
await router.load()
return router
}
const renderWithRouter = async (ui: ReactNode) => {
const router = await createProjectRouter()
return render(<RouterContextProvider router={router}>{ui}</RouterContextProvider>)
}
const renderLayout = () =>
renderWithRouter(
<MobileSheetProvider>
<ProjectLayout product="Database" isBlocking={false}>
<div />
</ProjectLayout>
</MobileSheetProvider>
)
describe('ProjectLayout title', () => {
beforeEach(() => {
mockViewport.isMobile = false
mockMainScrollContainer.current = null
mockRoute.url = '/project/default/observability/query-performance'
document.title = ''
mockProjectState.current = {
ref: 'default',
name: 'Project 1',
status: 'ACTIVE_HEALTHY',
postgrestStatus: 'ONLINE',
infra_compute_size: undefined,
integration_source: null,
}
mockBannerDismissedState.current = false
mockUseLocalStorageQuery.mockImplementation(() => [
mockBannerDismissedState.current ? new Date().toISOString() : null,
vi.fn(),
{ isSuccess: true },
])
})
afterEach(() => {
document.title = ''
})
it('updates the open mobile menu when resource navigation changes without replacing other sheets', async () => {
mockViewport.isMobile = true
await renderWithRouter(
<MobileSheetProvider>
<ResourceMenuHarness />
<MobileSheetHarness />
</MobileSheetProvider>
)
expect(screen.getByTestId('mobile-sheet')).toBeEmptyDOMElement()
fireEvent.click(screen.getByRole('button', { name: 'Open menu' }))
expect(screen.getByText('Explorer header')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Open notebooks' }))
expect(screen.getByText('Notebooks header')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Return to Explorer' }))
expect(screen.getByText('Explorer header')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Open other sheet' }))
fireEvent.click(screen.getByRole('button', { name: 'Change section' }))
expect(screen.getByTestId('mobile-sheet')).toHaveTextContent('Other sheet')
})
it.each([false, true])(
'keeps sidebar navigation enabled with resizableSidebar=%s and preserves handle availability',
async (resizableSidebar) => {
await renderWithRouter(
<MobileSheetProvider>
<ProjectLayout
product="Database"
isBlocking={false}
resizableSidebar={resizableSidebar}
productMenu={<a href="/project/default/database/tables">Tables</a>}
>
<div>Page Content</div>
</ProjectLayout>
</MobileSheetProvider>
)
const link = screen.getByRole('link', { name: 'Tables' })
expect(link.closest('[aria-disabled="true"]')).toBeNull()
link.focus()
expect(link).toHaveFocus()
const handle = screen.getByRole('separator')
if (resizableSidebar) {
expect(handle).not.toHaveAttribute('aria-disabled')
expect(handle).toHaveAttribute('tabindex', '0')
} else {
expect(handle).toHaveAttribute('aria-disabled', 'true')
expect(handle).not.toHaveAttribute('tabindex')
}
}
)
it('sets a composed document title and deduplicates identical section/surface labels', async () => {
await renderWithRouter(
<MobileSheetProvider>
<ProjectLayout browserTitle={{ section: 'Settings' }} product="Settings" isBlocking={false}>
<div>Page Content</div>
</ProjectLayout>
</MobileSheetProvider>
)
await waitFor(() => {
expect(document.title).toBe(
['Settings', 'Project 1', 'Organization 1', 'Supabase'].join(STUDIO_PAGE_TITLE_SEPARATOR)
)
})
})
it('prefers entity-first browserTitle metadata when provided', async () => {
await renderWithRouter(
<MobileSheetProvider>
<ProjectLayout
product="Database"
browserTitle={{ entity: 'users', section: 'Tables' }}
isBlocking={false}
>
<div>Page Content</div>
</ProjectLayout>
</MobileSheetProvider>
)
await waitFor(() => {
expect(document.title).toBe(
['users', 'Tables', 'Database', 'Project 1', 'Organization 1', 'Supabase'].join(
STUDIO_PAGE_TITLE_SEPARATOR
)
)
})
})
it('renders the Stripe project banner with a project-specific dismiss key when the selected project is Stripe-connected', async () => {
mockProjectState.current = {
...mockProjectState.current,
integration_source: 'stripe_projects',
}
await renderLayout()
expect(screen.getByText('This project is connected to Stripe')).toBeInTheDocument()
expect(
screen.getByText('Changes made here may affect your connected Stripe project.')
).toBeInTheDocument()
expect(screen.getByTestId('partner-icon')).toBeInTheDocument()
expect(mockUseLocalStorageQuery).toHaveBeenCalledWith(
LOCAL_STORAGE_KEYS.PROJECT_INTEGRATION_BANNER_DISMISSED('default', 'stripe_projects'),
false
)
})
it('renders the paused state for a paused project', async () => {
mockProjectState.current = { ...mockProjectState.current, status: 'INACTIVE' }
await renderLayout()
expect(screen.getByText('Project paused')).toBeInTheDocument()
})
it('renders the branches page instead of the paused state for a paused project', async () => {
mockProjectState.current = { ...mockProjectState.current, status: 'INACTIVE' }
mockRoute.url = '/project/default/branches'
await renderLayout()
expect(screen.queryByText('Project paused')).not.toBeInTheDocument()
})
describe('main scroll reset', () => {
const scrollTo = vi.fn()
beforeEach(() => {
scrollTo.mockClear()
mockMainScrollContainer.current = { scrollTo }
})
afterEach(() => {
window.history.replaceState(null, '', window.location.pathname)
document.getElementById('sms-mfa')?.remove()
})
it('scrolls to the top on navigation', async () => {
await renderLayout()
expect(scrollTo).toHaveBeenCalledWith({ top: 0, left: 0 })
})
it('leaves the position to HashScrollController when the hash target is on the page', async () => {
window.history.replaceState(null, '', '#sms-mfa')
document.body.append(Object.assign(document.createElement('section'), { id: 'sms-mfa' }))
await renderLayout()
expect(scrollTo).not.toHaveBeenCalled()
})
it('still scrolls to the top when nothing on the page matches the hash', async () => {
window.history.replaceState(null, '', '#sms-mfa')
await renderLayout()
expect(scrollTo).toHaveBeenCalledWith({ top: 0, left: 0 })
})
})
})
describe('FREE_MICRO_UPGRADE banner', () => {
beforeEach(() => {
mockRoute.url = '/project/default'
mockProjectState.current = {
ref: 'default',
name: 'Project 1',
status: 'ACTIVE_HEALTHY',
postgrestStatus: 'ONLINE',
infra_compute_size: 'nano',
integration_source: null,
}
mockBannerDismissedState.current = false
})
afterEach(() => {
mockRoute.url = '/project/default/observability/query-performance'
mockProjectState.current = {
ref: 'default',
name: 'Project 1',
status: 'ACTIVE_HEALTHY',
postgrestStatus: 'ONLINE',
infra_compute_size: undefined,
integration_source: null,
}
mockOrgPlanState.current = { id: 'pro', name: 'Pro' }
mockBannerDismissedState.current = false
})
it('calls addBanner when a paid-plan project is nano', async () => {
await renderLayout()
await waitFor(() => {
expect(mockAddBanner).toHaveBeenCalledWith(
expect.objectContaining({ id: 'free-micro-upgrade-banner' })
)
})
})
it.each([
[
'the banner was previously dismissed',
() => {
mockBannerDismissedState.current = true
},
],
[
'the project is not nano compute',
() => {
mockProjectState.current = { ...mockProjectState.current, infra_compute_size: 'micro' }
},
],
[
'the organization is on the free plan',
() => {
mockOrgPlanState.current = { id: 'free', name: 'Free' }
},
],
[
'the organization plan is not loaded yet',
() => {
mockOrgPlanState.current = undefined
},
],
])('calls dismissBanner instead of addBanner when %s', async (_, arrange) => {
arrange()
await renderLayout()
await waitFor(() => {
expect(mockDismissBanner).toHaveBeenCalledWith('free-micro-upgrade-banner')
})
expect(mockAddBanner).not.toHaveBeenCalledWith(
expect.objectContaining({ id: 'free-micro-upgrade-banner' })
)
})
})