Files
Alaister YoungandAlaister Young 0f14ef4d67 [FE-5109] (part 5) refactor(studio): migrate remaining interfaces and router events off next/router (#54057)
Part 5 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 | `components/layouts/**` and `state/tabs.tsx` |
| 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer,
SQL Editor, Storage, Table Editor |
| **5** | **#54057 ← this PR** | **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 remaining `apps/studio/components/interfaces/**`
directories off `next/router`, including the last production
`router.events` consumer (`QueryInsightsTable`) and the only default
`next/router` import (`DiscordCTACard`). After this PR, zero files under
`apps/studio/components/**` import `next/router` or
`next/compat/router`.

**Added:**

-
`apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.test.tsx`:
verifies that pathname changes clear selected query state without
mutating destination or history search params, while same-pathname
search updates preserve selection

**Changed:**

- Replaced the sole production `router.events.on('routeChangeStart',
...)` consumer in `QueryInsightsTable.tsx` with a `pathname` effect that
clears `onCurrentSelectQuery` on pathname changes, and derived
`searchQuery` directly from `nuqs` (`urlSearch`) instead of mirroring it
in local state. Drops the legacy `setQueryStates({ search: null })` call
on leave, which ran after `history.push` on TanStack Router (targeting
the destination URL rather than the previous history entry, while
browser Back is expected to restore previous search params).
- Removed the `router: NextRouter` prop from `ReportWidgetRendererProps`
in `Reports/ReportWidget.tsx` and updated its callers (`ChartBlock`,
`ReportHeader`, `CreateReportModal`)
- Updated `LOG_ROUTES_WITH_REPLICA_SUPPORT` in
`Settings/Logs/Logs.constants.ts` from `[ref]` to `$ref` for TanStack
route patterns
- Replaced the default `import router from 'next/router'` in
`Support/DiscordCTACard.tsx` with `useNavigate`
- Replaced `useRouter` across `Account`, `Advisors`, `App`, `Auth`,
`ErrorHandling`, `Home`, `HomePageActions`, `Integrations`, `Linter`,
`LocalDropdown`, `Observability`, `Organization`, `OrganizationInvite`,
`Platform/Webhooks`, `Project`, `ProjectCreation`, `ProjectHome`,
`QueryPerformance`, `RedeemCredits`, `Settings`, `Sidebar`, `SignIn`,
`Support`, `UnifiedLogs`, and `UserDropdown`
- Updated affected tests (`Auth/Users/UserPanel`, `Home/ProjectList`,
`LocalDropdown`, `Organization/*`, `OrganizationInvite`,
`RedeemCredits`, `Settings/General/*`, `SignIn/SignInRecoveryCodeForm`,
`UnifiedLogs/*`)

**Simplified:**

- `LocalDropdown`, `UserDropdown` and `RedeemCredits` build the current
route from `location.href`, so the hash keeps its leading `#`
- `NewOrgForm` navigates to the `returnTo` path instead of an absolute
URL, which was being treated as external. It also uses a typed
`/new/$slug` navigate.
- Read search params from `useParams()` instead of `location.search`
casts (`CronJobPage`, `QueuePage`, `LogsPreviewer`,
`LinkSupportTicketPage`, `MarketplaceSidebar`, `PlanCards`,
`SignUpForm`)
- Dropped the dead `isReady`/`isRouterReady` constants and the
`navigate<AnyRouter, string>` casts where typed routes work
(`ForgotPasswordWizard`, `SignInPartner`, `ReportWidget`,
`ProjectUpgradeAlert`)
- Linter, `ReportHeader` and `LogsPreviewer` use `to: '.'` instead of a
separate pathname subscription. `CreateReportModal` builds the preserved
query params in `onSuccess` instead of a `useMemo`.
- Tests use the shared `createTestRouter` and `customRender` router.
`LocalDropdown` now tests that the hash is kept.

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

## To test

- [x] Query Insights: select a query and confirm search/filter updates
keep selection while switching projects/routes clears it; navigating to
Logs keeps Logs' query params intact and pressing Back restores Query
Insights' `?search=` param cleanly
- [x] Auth / Sign-in flows: sign in, sign up, MFA, recovery code,
forgot/reset password, and partner sign-in preserve `returnTo` and
redirect as expected
- [x] Organization & Project flows: creating an org/project, accepting
an org invite, claiming a project, redeeming credits, and
deleting/pausing/restarting a project or branch navigate cleanly
- [ ] Logs & Reports: replica selector appears on supported log routes
(`LOG_ROUTES_WITH_REPLICA_SUPPORT`), saved log queries open, and custom
reports create/navigate properly
- [ ] Sidebar, LocalDropdown, UserDropdown, Integrations
(Cron/Queues/Marketplace), Advisors/Linter, and Unified Logs navigate
cleanly

---------

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

251 lines
9.3 KiB
TypeScript

import { useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { useParams } from 'common'
import dayjs from 'dayjs'
import { RefreshCwIcon } from 'lucide-react'
import { useCallback, useMemo, useState } from 'react'
import { Badge, Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import { useUnifiedLogsPreview } from '../App/FeaturePreview/FeaturePreviewContext'
import { DatabaseInfrastructureSection } from './DatabaseInfrastructureSection'
import { OBSERVABILITY_DOCS_HREFS } from './Observability.constants'
import { useObservabilityOverviewData } from './ObservabilityOverview.utils'
import { ObservabilityOverviewFooter } from './ObservabilityOverviewFooter'
import { ServiceHealthTable } from './ServiceHealthTable'
import { useSlowQueriesCount } from './useSlowQueriesCount'
import { ReportHeader } from '@/components/interfaces/Reports/ReportHeader'
import { ReportPadding } from '@/components/interfaces/Reports/ReportPadding'
import {
buildUnifiedLogsUrl,
type UnifiedLogType,
} from '@/components/interfaces/UnifiedLogs/UnifiedLogs.utils'
import { DocsButton } from '@/components/ui/DocsButton'
import { ChartIntervalDropdown } from '@/components/ui/Logs/ChartIntervalDropdown'
import { CHART_INTERVALS } from '@/components/ui/Logs/logs.utils'
import { ShortcutTooltip } from '@/components/ui/ShortcutTooltip'
import { useIsDataApiEnabled } from '@/hooks/misc/useIsDataApiEnabled'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { navigateToUrl } from '@/lib/navigation'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
const REPORT_TITLE = 'Overview'
type ChartIntervalKey = '1hr' | '1day' | '7day'
export const ObservabilityOverview = () => {
const navigate = useNavigate()
const { ref: projectRef } = useParams()
const { data: organization } = useSelectedOrganizationQuery()
const queryClient = useQueryClient()
const { isEnabled: isUnifiedLogsEnabled } = useUnifiedLogsPreview()
const { projectStorageAll: storageSupported } = useIsFeatureEnabled(['project_storage:all'])
const { isEnabled: isDataApiEnabled } = useIsDataApiEnabled({ projectRef })
const DEFAULT_INTERVAL: ChartIntervalKey = '1day'
const [interval, setInterval] = useState<ChartIntervalKey>(DEFAULT_INTERVAL)
const [refreshKey, setRefreshKey] = useState(0)
const [showIntervalDropdown, setShowIntervalDropdown] = useState(false)
const selectedInterval = CHART_INTERVALS.find((i) => i.key === interval) || CHART_INTERVALS[1]
const { datetimeFormat } = useMemo(() => {
const format = selectedInterval.format || 'MMM D, ha'
return { datetimeFormat: format }
}, [selectedInterval])
const overviewData = useObservabilityOverviewData(projectRef!, interval, refreshKey)
const { slowQueriesCount, isLoading: slowQueriesLoading } = useSlowQueriesCount(
projectRef,
refreshKey
)
const handleRefresh = useCallback(() => {
setRefreshKey((prev) => prev + 1)
queryClient.invalidateQueries({ queryKey: ['projects', projectRef, 'service-health'] })
queryClient.invalidateQueries({ queryKey: ['project-metrics'] })
queryClient.invalidateQueries({ queryKey: ['infra-monitoring'] })
queryClient.invalidateQueries({ queryKey: ['max-connections'] })
}, [queryClient, projectRef])
useShortcut(SHORTCUT_IDS.OBSERVABILITY_REFRESH, handleRefresh)
useShortcut(SHORTCUT_IDS.OBSERVABILITY_TOGGLE_DATE_PICKER, () => {
setShowIntervalDropdown((open) => !open)
})
const getLogsUrl = useCallback(
(logType: UnifiedLogType, legacyLogsUrl: string) =>
isUnifiedLogsEnabled
? buildUnifiedLogsUrl({ projectRef: projectRef!, logType })
: `/project/${projectRef}${legacyLogsUrl}`,
[projectRef, isUnifiedLogsEnabled]
)
const serviceBase = useMemo(
() => [
{
key: 'data_api' as const,
name: 'API Gateway',
reportUrl: undefined,
logType: 'edge' as const,
logsUrl: getLogsUrl('edge', '/logs/edge-logs'),
enabled: isDataApiEnabled,
hasReport: false,
},
{
key: 'db' as const,
name: 'Database',
reportUrl: `/project/${projectRef}/observability/database`,
logType: 'postgres' as const,
logsUrl: getLogsUrl('postgres', '/logs/postgres-logs'),
enabled: true,
hasReport: true,
},
{
key: 'postgrest' as const,
name: 'PostgREST',
reportUrl: `/project/${projectRef}/observability/postgrest`,
logType: 'postgrest' as const,
logsUrl: getLogsUrl('postgrest', '/logs/postgrest-logs'),
enabled: true,
hasReport: true,
},
{
key: 'auth' as const,
name: 'Auth',
reportUrl: `/project/${projectRef}/observability/auth`,
logType: 'auth' as const,
logsUrl: getLogsUrl('auth', '/logs/auth-logs'),
enabled: true,
hasReport: true,
},
{
key: 'functions' as const,
name: 'Edge Functions',
reportUrl: `/project/${projectRef}/observability/edge-functions`,
logType: 'edge function' as const,
logsUrl: getLogsUrl('edge function', '/logs/edge-functions-logs'),
enabled: true,
hasReport: true,
},
{
key: 'storage' as const,
name: 'Storage',
reportUrl: `/project/${projectRef}/observability/storage`,
logType: 'storage' as const,
logsUrl: getLogsUrl('storage', '/logs/storage-logs'),
enabled: storageSupported,
hasReport: true,
},
{
key: 'realtime' as const,
name: 'Realtime',
reportUrl: `/project/${projectRef}/observability/realtime`,
logType: 'realtime' as const,
logsUrl: getLogsUrl('realtime', '/logs/realtime-logs'),
enabled: true,
hasReport: true,
},
],
[projectRef, storageSupported, isDataApiEnabled, getLogsUrl]
)
const enabledServices = serviceBase.filter((s) => s.enabled)
const dbServiceData = overviewData.services.db
// Navigate to the log view scoped to the clicked bar's bucket window
const handleBarClick = useCallback(
(service: { logType: UnifiedLogType; logsUrl: string }) => (datum: any) => {
if (!datum?.timestamp) return
// datum.timestamp is already the UTC-truncated bucket boundary from timestamp_trunc(),
// so use it directly to avoid local-timezone startOf() misalignment (e.g. UTC+5:30).
const unit = interval === '1hr' ? 'minute' : 'hour'
const start = datum.timestamp
const end = dayjs.utc(datum.timestamp).add(1, unit).toISOString()
if (isUnifiedLogsEnabled) {
navigateToUrl(
navigate,
buildUnifiedLogsUrl({ projectRef: projectRef!, logType: service.logType, start, end })
)
} else {
const queryParams = new URLSearchParams({ its: start, ite: end })
const separator = service.logsUrl.includes('?') ? '&' : '?'
navigateToUrl(navigate, `${service.logsUrl}${separator}${queryParams.toString()}`)
}
},
[navigate, interval, isUnifiedLogsEnabled, projectRef]
)
return (
<ReportPadding>
<div className="flex flex-row justify-between items-center">
<div className="flex items-center gap-3">
<ReportHeader title={REPORT_TITLE} />
<Tooltip>
<TooltipTrigger asChild>
<Badge variant="warning">Beta</Badge>
</TooltipTrigger>
<TooltipContent>
<p>This page is subject to change</p>
</TooltipContent>
</Tooltip>
</div>
<div className="flex items-center gap-2">
<DocsButton href={OBSERVABILITY_DOCS_HREFS.overview} topic={REPORT_TITLE} />
<ShortcutTooltip
shortcutId={SHORTCUT_IDS.OBSERVABILITY_REFRESH}
label="Refresh report"
side="bottom"
>
<Button variant="outline" icon={<RefreshCwIcon size={14} />} onClick={handleRefresh}>
Refresh
</Button>
</ShortcutTooltip>
<ChartIntervalDropdown
value={interval}
onChange={(interval) => setInterval(interval as ChartIntervalKey)}
organizationSlug={organization?.slug}
dropdownAlign="end"
tooltipSide="left"
open={showIntervalDropdown}
onOpenChange={setShowIntervalDropdown}
/>
</div>
</div>
<div className="space-y-12 mt-8">
<DatabaseInfrastructureSection
interval={interval}
refreshKey={refreshKey}
dbErrorRate={dbServiceData.errorRate}
isLoading={dbServiceData.isLoading}
slowQueriesCount={slowQueriesCount}
slowQueriesLoading={slowQueriesLoading}
/>
<ServiceHealthTable
services={enabledServices.map((service) => ({
key: service.key,
name: service.name,
description: '',
reportUrl: service.hasReport ? service.reportUrl : undefined,
logType: service.logType,
logsUrl: service.logsUrl,
}))}
serviceData={overviewData.services}
onBarClick={handleBarClick}
datetimeFormat={datetimeFormat}
/>
</div>
<ObservabilityOverviewFooter />
</ReportPadding>
)
}