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

226 lines
8.8 KiB
TypeScript

import { useLocation, useNavigate } from '@tanstack/react-router'
import { useParams } from 'common'
import { PlusIcon } from 'lucide-react'
import { parseAsBoolean, useQueryState } from 'nuqs'
import { useState } from 'react'
import { toast } from 'sonner'
import { Menu } from 'ui'
import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'
import { InnerSideBarEmptyPanel } from 'ui-patterns/InnerSideMenu'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import {
useGenerateCustomReportsMenu,
useGenerateObservabilityMenu,
} from './ObservabilityMenu.utils'
import { ObservabilityMenuItem } from './ObservabilityMenuItem'
import { CreateReportModal } from '@/components/interfaces/Reports/CreateReportModal'
import { UpdateCustomReportModal } from '@/components/interfaces/Reports/UpdateModal'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { ProductMenu } from '@/components/ui/ProductMenu'
import { ProductMenuShortcuts } from '@/components/ui/ProductMenu/ProductMenuShortcuts'
import { useContentDeleteMutation } from '@/data/content/content-delete-mutation'
import { ContentOfType } from '@/data/content/content-query'
import {
FGA_PERMISSIONS,
useAsyncCheckUserContentPermissions,
} from '@/hooks/misc/useCheckPermissionsV2'
import { IS_PLATFORM } from '@/lib/constants'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
export const ObservabilityMenu = () => {
const navigate = useNavigate()
const pathname = useLocation({ select: (location) => location.pathname })
const { ref, id } = useParams()
const pageKey = id || pathname.split('/')[4] || 'observability'
const menuItems = useGenerateObservabilityMenu()
const { data: customReportItems, isLoading } = useGenerateCustomReportsMenu()
const { can: canCreateCustomReport } = useAsyncCheckUserContentPermissions(
FGA_PERMISSIONS.PROJECT.SNIPPETS_WRITE,
{ mode: 'create', type: 'report' }
)
const { mutateAsync: deleteReport } = useContentDeleteMutation({
// Toasts are driven by toast.promise in onConfirmDeleteReport. This no-op keeps the hook
// from showing its own default error toast, while its optimistic rollback still runs.
onError: () => {},
})
const [deleteModalOpen, setDeleteModalOpen] = useState(false)
const [showNewReportModal, setShowNewReportModal] = useQueryState(
'newReport',
parseAsBoolean.withDefault(false).withOptions({ history: 'push', clearOnDefault: true })
)
const [selectedReportToDelete, setSelectedReportToDelete] = useState<ContentOfType<'report'>>()
const [selectedReportToUpdate, setSelectedReportToUpdate] = useState<ContentOfType<'report'>>()
const onConfirmDeleteReport = () => {
if (ref === undefined) return console.error('Project ref is required')
if (selectedReportToDelete?.id === undefined) return console.error('Report ID is required')
const reportId = selectedReportToDelete.id
const isViewingDeletedReport = id === reportId
setDeleteModalOpen(false)
const deletion = deleteReport({ projectRef: ref, ids: [reportId] })
toast.promise(deletion, {
loading: 'Deleting report...',
success: 'Report deleted',
error: (err) => `Failed to delete report: ${err?.message ?? 'Unknown error'}`,
})
// Only navigate away when the open report is the one deleted, and only after it
// succeeds so a failed delete (which rolls the cache back) doesn't strand the route.
deletion
.then(() => {
if (isViewingDeletedReport)
void navigate({ to: '/project/$ref/observability', params: { ref } })
})
.catch(() => {
// Error is already surfaced by toast.promise; keep the user on the current route.
})
}
useShortcut(
SHORTCUT_IDS.OBSERVABILITY_NEW_REPORT,
() => {
setShowNewReportModal(true)
},
{ enabled: IS_PLATFORM && canCreateCustomReport }
)
return (
<div>
<ProductMenuShortcuts menu={menuItems} />
{isLoading ? (
<div className="px-5 my-4 space-y-2">
<ShimmeringLoader />
<ShimmeringLoader className="w-3/4" />
<ShimmeringLoader className="w-1/2" />
</div>
) : (
<div className="flex flex-col">
<ProductMenu
page={pageKey}
menu={menuItems.map((item) => ({
...item,
items: item.items.map((subItem) => ({ ...subItem, items: [] })),
}))}
/>
{IS_PLATFORM && (
<>
<div className="h-px w-full bg-border-overlay" />
<div className="mx-2 my-4">
<Menu type="pills">
<Menu.Group
title={
<span className="flex w-full items-center justify-between relative h-6">
<span className="uppercase font-mono">Custom Reports</span>
{customReportItems.length > 0 && (
<ButtonTooltip
size="tiny"
icon={<PlusIcon />}
disabled={!canCreateCustomReport}
className="flex items-center justify-center h-6 w-6 absolute top-0 -right-1"
onClick={() => {
setShowNewReportModal(true)
}}
tooltip={{
content: {
side: 'bottom',
text: !canCreateCustomReport
? 'You need additional permissions to create custom reports'
: undefined,
},
}}
/>
)}
</span>
}
/>
{customReportItems.length > 0 &&
customReportItems.map((item) => (
<ObservabilityMenuItem
key={item.id}
item={item}
pageKey={pageKey}
onSelectEdit={() => {
setSelectedReportToUpdate(item.report)
}}
onSelectDelete={() => {
setSelectedReportToDelete(item.report)
setDeleteModalOpen(true)
}}
/>
))}
</Menu>
{customReportItems.length === 0 ? (
<div className="px-2">
<InnerSideBarEmptyPanel
title="No custom reports yet"
description="Create and save custom reports to track your project metrics"
actions={
<ButtonTooltip
icon={<PlusIcon />}
disabled={!canCreateCustomReport}
onClick={() => {
setShowNewReportModal(true)
}}
tooltip={{
content: {
side: 'bottom',
text: !canCreateCustomReport
? 'You need additional permissions to create custom reports'
: undefined,
},
}}
>
New custom report
</ButtonTooltip>
}
/>
</div>
) : null}
</div>
</>
)}
<UpdateCustomReportModal
onCancel={() => setSelectedReportToUpdate(undefined)}
selectedReport={selectedReportToUpdate}
initialValues={{
name: selectedReportToUpdate?.name || '',
description: selectedReportToUpdate?.description || '',
}}
/>
<ConfirmationModal
title="Delete custom report"
confirmLabel="Delete report"
size="medium"
loading={false}
visible={deleteModalOpen}
onCancel={() => setDeleteModalOpen(false)}
onConfirm={onConfirmDeleteReport}
>
<div className="text-sm text-foreground-light grid gap-4">
<div className="grid gap-1">
<p>Are you sure you want to delete '{selectedReportToDelete?.name}'?</p>
</div>
</div>
</ConfirmationModal>
<CreateReportModal
visible={showNewReportModal}
onCancel={() => setShowNewReportModal(false)}
afterSubmit={() => setShowNewReportModal(false)}
/>
</div>
)}
</div>
)
}