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

167 lines
5.1 KiB
TypeScript

import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import { parseAsString, useQueryState } from 'nuqs'
import { lazy, Suspense, useEffect, useEffectEvent, useRef, type PropsWithChildren } from 'react'
import { getSupportLinkQueryParams } from '@/components/ui/HelpPanel/HelpPanel.utils'
import { useLatest } from '@/hooks/misc/useLatest'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useTrack } from '@/lib/telemetry/track'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
import {
sidebarManagerState,
useRegisterSidebar,
useSidebarManagerSnapshot,
} from '@/state/sidebar-manager-state'
const AdvisorPanel = lazy(() =>
import('@/components/ui/AdvisorPanel/AdvisorPanel').then((m) => ({ default: m.AdvisorPanel }))
)
const AIAssistant = lazy(() =>
import('@/components/ui/AIAssistantPanel/AIAssistant').then((m) => ({ default: m.AIAssistant }))
)
const EditorPanel = lazy(() =>
import('@/components/ui/EditorPanel/EditorPanel').then((m) => ({ default: m.EditorPanel }))
)
const HelpPanel = lazy(() =>
import('@/components/ui/HelpPanel/HelpPanel').then((m) => ({ default: m.HelpPanel }))
)
export const SIDEBAR_KEYS = {
AI_ASSISTANT: 'ai-assistant',
EDITOR_PANEL: 'editor-panel',
ADVISOR_PANEL: 'advisor-panel',
HELP_PANEL: 'help-panel',
} as const
export type TYPEOF_SIDEBAR_KEYS = (typeof SIDEBAR_KEYS)[keyof typeof SIDEBAR_KEYS]
export const LayoutSidebarProvider = ({ children }: PropsWithChildren) => {
const { ref } = useParams()
const { data: project } = useSelectedProjectQuery()
const { data: org } = useSelectedOrganizationQuery()
const track = useTrack()
const { openSidebar, closeSidebar, activeSidebar } = useSidebarManagerSnapshot()
const [sidebarURLParam, setSidebarUrlParam] = useQueryState('sidebar', parseAsString)
const [sidebarLocalStorage, setSidebarLocalStorage, { isSuccess: isLoadedLocalStorage }] =
useLocalStorageQuery(LOCAL_STORAGE_KEYS.LAST_OPENED_SIDE_BAR(project?.ref ?? ''), '')
const supportLinkQueryParams = getSupportLinkQueryParams(project, org, ref)
const sidebarLocalStorageRef = useLatest(sidebarLocalStorage)
useRegisterSidebar(
SIDEBAR_KEYS.AI_ASSISTANT,
() => (
<Suspense fallback={null}>
<AIAssistant />
</Suspense>
),
{},
!!project
)
useRegisterSidebar(
SIDEBAR_KEYS.EDITOR_PANEL,
() => (
<Suspense fallback={null}>
<EditorPanel />
</Suspense>
),
{},
!!project
)
useRegisterSidebar(
SIDEBAR_KEYS.ADVISOR_PANEL,
() => (
<Suspense fallback={null}>
<AdvisorPanel />
</Suspense>
),
{},
true
)
useRegisterSidebar(
SIDEBAR_KEYS.HELP_PANEL,
() => (
<Suspense fallback={null}>
<HelpPanel
onClose={() => closeSidebar(SIDEBAR_KEYS.HELP_PANEL)}
projectRef={project?.ref}
supportLinkQueryParams={supportLinkQueryParams}
/>
</Suspense>
),
{},
true
)
useShortcut(SHORTCUT_IDS.AI_ASSISTANT_TOGGLE, () =>
sidebarManagerState.toggleSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
)
useShortcut(SHORTCUT_IDS.INLINE_EDITOR_TOGGLE, () =>
sidebarManagerState.toggleSidebar(SIDEBAR_KEYS.EDITOR_PANEL)
)
const onSidebarChanged = useEffectEvent(
(sidebarId: (typeof SIDEBAR_KEYS)[keyof typeof SIDEBAR_KEYS]) => {
track('sidebar_opened', { sidebar: sidebarId })
}
)
const previousSidebarIdRef = useRef<string | undefined>(undefined)
useEffect(() => {
const previousSidebarId = previousSidebarIdRef.current
previousSidebarIdRef.current = activeSidebar?.id
// unregistering (e.g. project switch) isn't a user close
const isClosedByUser =
!activeSidebar &&
previousSidebarId !== undefined &&
previousSidebarId in sidebarManagerState.sidebars
if (isClosedByUser) {
setSidebarUrlParam(null)
}
if (!project) {
return
}
if (activeSidebar) {
onSidebarChanged(activeSidebar.id as (typeof SIDEBAR_KEYS)[keyof typeof SIDEBAR_KEYS])
setSidebarLocalStorage(activeSidebar.id)
return
}
setSidebarLocalStorage('')
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeSidebar])
// Prioritize URL params first, then local storage
useEffect(() => {
if (isLoadedLocalStorage) {
if (
typeof sidebarURLParam === 'string' &&
Object.values(SIDEBAR_KEYS).includes(
sidebarURLParam as (typeof SIDEBAR_KEYS)[keyof typeof SIDEBAR_KEYS]
)
) {
openSidebar(sidebarURLParam)
} else if (
!!sidebarLocalStorageRef.current &&
Object.values(SIDEBAR_KEYS).includes(
sidebarLocalStorageRef.current as (typeof SIDEBAR_KEYS)[keyof typeof SIDEBAR_KEYS]
)
) {
openSidebar(sidebarLocalStorageRef.current)
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isLoadedLocalStorage, sidebarURLParam])
return <>{children}</>
}