Files
supabase/apps/studio/components/interfaces/ProjectHome/ProjectUsageSection.tsx
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

308 lines
10 KiB
TypeScript

import { useNavigate } from '@tanstack/react-router'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import dayjs from 'dayjs'
import Link from 'next/link'
import { useMemo } from 'react'
import { Card, CardContent, CardHeader, CardTitle, Loading, WarningIcon } from 'ui'
import { ChartEmptyState } from 'ui-patterns/Chart'
import { LogsBarChart } from 'ui-patterns/LogsBarChart'
import { Row } from 'ui-patterns/Row'
import { isChartIntervalKey, resolveChartInterval } from './ChartInterval.utils'
import { useUnifiedLogsPreview } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import {
buildUnifiedLogsUrl,
type UnifiedLogType,
} from '@/components/interfaces/UnifiedLogs/UnifiedLogs.utils'
import { NoDataPlaceholder } from '@/components/ui/Charts/NoDataPlaceholder'
import { ChartIntervalDropdown } from '@/components/ui/Logs/ChartIntervalDropdown'
import { CHART_INTERVALS } from '@/components/ui/Logs/logs.utils'
import { UsageApiCounts, useProjectLogStatsQuery } from '@/data/analytics/project-log-stats-query'
import { fillTimeseriesSorted } from '@/hooks/analytics/useFillTimeseriesSorted'
import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { navigateToUrl } from '@/lib/navigation'
import { useTrack } from '@/lib/telemetry/track'
type LogsBarChartDatum = {
timestamp: string
error_count: number
ok_count: number
warning_count: number
}
type ServiceKey = 'db' | 'auth' | 'storage' | 'realtime'
type ServiceEntry = {
key: ServiceKey
title: string
href?: string
route: string
logType: UnifiedLogType
enabled: boolean
}
type ServiceComputed = ServiceEntry & {
data: LogsBarChartDatum[]
total: number
isLoading: boolean
error: unknown | null
}
export const ProjectUsageSection = () => {
const navigate = useNavigate()
const { ref: projectRef } = useParams()
const { data: organization } = useSelectedOrganizationQuery()
const track = useTrack()
const { projectAuthAll: authEnabled, projectStorageAll: storageEnabled } = useIsFeatureEnabled([
'project_auth:all',
'project_storage:all',
])
const { getEntitlementMax } = useCheckEntitlements('log.retention_days')
const retentionDays = getEntitlementMax()
const { isEnabled: isUnifiedLogsEnabled } = useUnifiedLogsPreview()
const [storedInterval, setStoredInterval] = useLocalStorageQuery<string | undefined>(
LOCAL_STORAGE_KEYS.HOME_CHART_INTERVAL(projectRef ?? ''),
undefined
)
const interval = resolveChartInterval(storedInterval, retentionDays)
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])
// Use V1 data fetching
const {
data: filledCharts,
isPending: isLoading,
error,
} = useProjectLogStatsQuery(
{
projectRef,
interval,
},
{
select: (data) => {
// Calculate date range for gap filling
const startDateLocal = dayjs().subtract(
selectedInterval.startValue,
selectedInterval.startUnit as dayjs.ManipulateType
)
const endDateLocal = dayjs()
return fillTimeseriesSorted({
data: data.result,
timestampKey: 'timestamp',
valueKey: [
'total_auth_requests',
'total_rest_requests',
'total_storage_requests',
'total_realtime_requests',
],
defaultValue: 0,
startDate: startDateLocal.toISOString(),
endDate: endDateLocal.toISOString(),
minPointsToFill: 5,
})
},
refetchOnWindowFocus: false,
}
)
const serviceBase: ServiceEntry[] = useMemo(
() => [
{
key: 'db',
title: 'Database requests',
href: `/project/${projectRef}/editor`,
route: '/logs/postgres-logs',
logType: 'postgres',
enabled: true,
},
{
key: 'auth',
title: 'Auth requests',
href: `/project/${projectRef}/auth/users`,
route: '/logs/auth-logs',
logType: 'auth',
enabled: authEnabled,
},
{
key: 'storage',
title: 'Storage requests',
href: `/project/${projectRef}/storage/buckets`,
route: '/logs/storage-logs',
logType: 'storage',
enabled: storageEnabled,
},
{
key: 'realtime',
title: 'Realtime requests',
href: `/project/${projectRef}/realtime/inspector`,
route: '/logs/realtime-logs',
logType: 'realtime',
enabled: true,
},
],
[projectRef, authEnabled, storageEnabled]
)
const services: ServiceComputed[] = useMemo(
() =>
serviceBase.map((s) => {
// Map service keys to V1 data field names
const dataKeyMap: Record<ServiceKey, keyof UsageApiCounts> = {
db: 'total_rest_requests',
auth: 'total_auth_requests',
storage: 'total_storage_requests',
realtime: 'total_realtime_requests',
}
const dataKey = dataKeyMap[s.key]
// Transform V1 data to LogsBarChart format
// Since V1 doesn't have error/warning breakdown, we show everything as "ok"
const transformedData: LogsBarChartDatum[] = (filledCharts?.data || []).map((item) => ({
timestamp: item.timestamp,
error_count: 0,
warning_count: 0,
ok_count: Number(item[dataKey]) || 0,
}))
// Calculate total from filled data
const total = transformedData.reduce((sum, item) => sum + item.ok_count, 0)
return {
...s,
data: transformedData,
total,
isLoading,
error: error || filledCharts?.error || null,
}
}),
[serviceBase, filledCharts, isLoading, error]
)
const handleBarClick = (service: ServiceEntry) => (datum: LogsBarChartDatum) => {
if (!datum?.timestamp) return
const datumTimestamp = dayjs(datum.timestamp).toISOString()
const start = dayjs(datumTimestamp).subtract(1, 'minute').toISOString()
const end = dayjs(datumTimestamp).add(1, 'minute').toISOString()
if (isUnifiedLogsEnabled) {
navigateToUrl(
navigate,
buildUnifiedLogsUrl({ projectRef: projectRef!, logType: service.logType, start, end })
)
} else {
const queryParams = new URLSearchParams({
iso_timestamp_start: start,
iso_timestamp_end: end,
})
navigateToUrl(navigate, `/project/${projectRef}${service.route}?${queryParams.toString()}`)
}
track('home_project_usage_chart_clicked', {
service_type: service.key,
bar_timestamp: datum.timestamp,
})
}
const enabledServices = services.filter((s) => s.enabled)
const totalRequests = enabledServices.reduce((sum, s) => sum + (s.total || 0), 0)
return (
<div className="space-y-6">
<div className="flex flex-row justify-between items-center gap-x-2">
<div className="flex items-start gap-2 heading-section text-foreground-light">
<span className="text-foreground">{totalRequests.toLocaleString()}</span>
<span>Total Requests</span>
</div>
<ChartIntervalDropdown
value={interval}
onChange={(next) => {
if (isChartIntervalKey(next)) setStoredInterval(next)
}}
organizationSlug={organization?.slug}
dropdownAlign="end"
tooltipSide="left"
/>
</div>
<Row maxColumns={4} minWidth={280}>
{enabledServices.map((s) => (
<Card key={s.key} className="mb-0 md:mb-0 h-full flex flex-col h-64">
<CardHeader className="flex flex-row items-end justify-between gap-2 space-y-0 pb-0 border-b-0">
<div className="flex items-center gap-2">
<div className="flex flex-col">
<CardTitle className="text-xs font-mono uppercase text-foreground-light">
{s.href ? (
<Link
href={s.href}
onClick={() => {
track('home_project_usage_service_clicked', {
service_type: s.key,
total_requests: s.total || 0,
})
}}
>
{s.title}
</Link>
) : (
s.title
)}
</CardTitle>
<span className="text-foreground text-xl">{(s.total || 0).toLocaleString()}</span>
</div>
</div>
</CardHeader>
<CardContent className="p-card flex-1 h-full overflow-hidden">
<Loading isFullHeight active={isLoading}>
<LogsBarChart
isFullHeight
data={s.data}
error={s.error}
DateTimeFormat={datetimeFormat}
onBarClick={handleBarClick(s)}
hideZeroValues={true}
chartConfig={{
error_count: {
label: 'Errors',
},
warning_count: {
label: 'Warnings',
},
ok_count: {
label: 'Requests',
},
}}
ErrorState={
<ChartEmptyState
icon={<WarningIcon />}
title="Failed to load project usage"
description="Check our Status Page or try again later."
/>
}
EmptyState={
<NoDataPlaceholder
size="small"
message="No data for selected period"
isFullHeight
/>
}
/>
</Loading>
</CardContent>
</Card>
))}
</Row>
</div>
)
}