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

349 lines
12 KiB
TypeScript

import { type AnyRouter, useNavigate } from '@tanstack/react-router'
import { useParams } from 'common'
import dayjs from 'dayjs'
import { RewindIcon } from 'lucide-react'
import { PropsWithChildren, useEffect, useRef, useState } from 'react'
import { Button } from 'ui'
import { LogsBarChart } from 'ui-patterns/LogsBarChart'
import {
LOG_ROUTES_WITH_REPLICA_SUPPORT,
LOGS_TABLES,
LogsTableName,
PREVIEWER_DATEPICKER_HELPERS,
} from './Logs.constants'
import { DatePickerValue } from './Logs.DatePickers'
import type { Filters, LogSearchCallback, LogTemplate, QueryType } from './Logs.types'
import { isStartOutsideRetention } from './Logs.utils'
import { calculateBarClickTimeRange } from './LogsBarChart.utils'
import { LogTable } from './LogTable'
import UpgradePrompt from './UpgradePrompt'
import { useLogsPreviewShortcuts } from './useLogsPreviewShortcuts'
import { PreviewFilterPanel } from '@/components/interfaces/Settings/Logs/PreviewFilterPanel'
import LoadingOpacity from '@/components/ui/LoadingOpacity'
import ShimmerLine from '@/components/ui/ShimmerLine'
import { ShortcutTooltip } from '@/components/ui/ShortcutTooltip'
import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'
import useLogsPreview from '@/hooks/analytics/useLogsPreview'
import { useLogsUrlState } from '@/hooks/analytics/useLogsUrlState'
import { useSelectedLog } from '@/hooks/analytics/useSelectedLog'
import useSingleLog from '@/hooks/analytics/useSingleLog'
import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
import { useRoutePattern } from '@/hooks/misc/useRoutePattern'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useUpgradePrompt } from '@/hooks/misc/useUpgradePrompt'
import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
/**
* Acts as a container component for the entire log display
*
* ## Query Params Syncing
* Query params are synced on query submission.
*
* params used are:
* - `s` for search query.
* - `te` for timestamp start value.
*/
interface LogsPreviewerProps {
projectRef: string
queryType: QueryType
filterOverride?: Filters
condensedLayout?: boolean
tableName?: LogsTableName
EmptyState?: React.ReactNode
filterPanelClassName?: string
}
export const LogsPreviewer = ({
projectRef,
queryType,
filterOverride,
condensedLayout = false,
tableName,
children,
EmptyState,
filterPanelClassName,
}: PropsWithChildren<LogsPreviewerProps>) => {
const navigate = useNavigate()
const routePattern = useRoutePattern()
const { db, iso_timestamp_start, iso_timestamp_end } = useParams()
const { data: organization } = useSelectedOrganizationQuery()
const state = useDatabaseSelectorStateSnapshot()
const searchInputRef = useRef<HTMLInputElement>(null)
const [showChart, setShowChart] = useState(true)
const [selectedDatePickerValue, setSelectedDatePickerValue] = useState<DatePickerValue>(
getDefaultDatePickerValue()
)
const { search, setSearch, timestampStart, timestampEnd, setTimeRange, filters, setFilters } =
useLogsUrlState()
useEffect(() => {
if (timestampStart && timestampEnd) {
setSelectedDatePickerValue({
to: timestampEnd,
from: timestampStart,
text: `${dayjs(timestampStart).format('DD MMM, HH:mm')} - ${dayjs(timestampEnd).format('DD MMM, HH:mm')}`,
isHelper: false,
})
}
}, [timestampStart, timestampEnd])
const [selectedLogId, setSelectedLogId] = useSelectedLog()
const { data: databases, isSuccess } = useReadReplicasQuery({ projectRef })
// TODO: Move this to useLogsUrlState to simplify LogsPreviewer. - Jordi
function getDefaultDatePickerValue() {
if (iso_timestamp_start && iso_timestamp_end) {
return {
to: iso_timestamp_end,
from: iso_timestamp_start,
text: `${dayjs(iso_timestamp_start).format('DD MMM, HH:mm')} - ${dayjs(iso_timestamp_end).format('DD MMM, HH:mm')}`,
isHelper: false,
}
}
const defaultDatePickerValue = PREVIEWER_DATEPICKER_HELPERS.find((x) => x.default)
return {
to: defaultDatePickerValue!.calcTo(),
from: defaultDatePickerValue!.calcFrom(),
text: defaultDatePickerValue!.text,
isHelper: true,
}
}
const table = !tableName ? LOGS_TABLES[queryType] : tableName
const {
error,
logData,
params,
newCount,
isLoading,
eventChartData,
isLoadingOlder,
loadOlder,
refresh,
} = useLogsPreview({ projectRef, table, filterOverride })
const {
data: selectedLog,
isLoading: isSelectedLogLoading,
error: selectedLogError,
} = useSingleLog({
projectRef,
id: selectedLogId ?? undefined,
queryType,
paramsToMerge: params,
})
const { showUpgradePrompt, setShowUpgradePrompt } = useUpgradePrompt(timestampStart)
const onSelectTemplate = (template: LogTemplate) => {
setFilters({ ...filters, search_query: template.searchString })
}
// [Joshen] For helper date picker values, reset the timestamp start to prevent data caching
// Since the helpers are "Last n minutes" -> hitting refresh, you'd expect to see the latest result
// Whereas if a specific range is selected, you'd not expect new data to show up
const handleRefresh = () => {
if (selectedDatePickerValue.isHelper) {
const helper = PREVIEWER_DATEPICKER_HELPERS.find(
(x) => x.text === selectedDatePickerValue.text
)
if (helper) {
const newTimestampStart = helper.calcFrom()
setTimeRange(newTimestampStart, timestampEnd)
}
}
setSelectedLogId(null)
refresh()
}
const { getEntitlementNumericValue } = useCheckEntitlements('log.retention_days')
const entitledToAuditLogDays = getEntitlementNumericValue()
const handleSearch: LogSearchCallback = async (event, { query, to, from }) => {
if (event === 'search-input-change') {
setSearch(query || '')
setSelectedLogId(null)
} else if (event === 'event-chart-bar-click') {
setSelectedLogId(null)
setTimeRange(from || '', to || '')
} else if (event === 'datepicker-change') {
const shouldShowUpgradePrompt = isStartOutsideRetention(from || '', entitledToAuditLogDays)
if (shouldShowUpgradePrompt) {
setShowUpgradePrompt(!showUpgradePrompt)
} else {
setSelectedLogId(null)
setTimeRange(from || '', to || '')
}
}
}
// Show the prompt on page load based on query params
useEffect(() => {
if (timestampStart) {
const shouldShowUpgradePrompt = isStartOutsideRetention(
timestampStart,
entitledToAuditLogDays
)
if (shouldShowUpgradePrompt) {
setShowUpgradePrompt(!showUpgradePrompt)
}
}
}, [timestampStart, organization])
useEffect(() => {
if (db !== undefined) {
const database = databases?.find((d) => d.identifier === db)
if (database !== undefined) state.setSelectedDatabaseId(db)
} else if (state.selectedDatabaseId !== undefined && state.selectedDatabaseId !== projectRef) {
if (LOG_ROUTES_WITH_REPLICA_SUPPORT.includes(routePattern)) {
navigate<AnyRouter, string>({
to: '.',
search: (prev: Record<string, unknown>) => ({
...prev,
db: state.selectedDatabaseId,
}),
})
} else {
state.setSelectedDatabaseId(projectRef)
}
}
}, [db, isSuccess])
// Common props shared between both filter panel components to avoid duplication
const filterPanelProps = {
className: filterPanelClassName,
csvData: logData,
isLoading,
newCount,
onRefresh: handleRefresh,
onSearch: handleSearch,
defaultSearchValue: search,
defaultToValue: timestampEnd,
defaultFromValue: timestampStart,
queryUrl: `/project/${projectRef}/logs/explorer?q=${encodeURIComponent(
params.sql || ''
)}&its=${encodeURIComponent(timestampStart)}&ite=${encodeURIComponent(timestampEnd)}`,
onSelectTemplate,
filters,
onFiltersChange: setFilters,
table,
condensedLayout,
isShowingEventChart: showChart,
onToggleEventChart: () => setShowChart(!showChart),
onSelectedDatabaseChange: (id: string) => {
setFilters({ ...filters, database: id !== projectRef ? id : undefined })
navigate<AnyRouter, string>({
to: '.',
search: (prev: Record<string, unknown>) => {
const { db: _db, ...params } = prev
return id !== projectRef ? { ...params, db: id } : params
},
})
},
selectedDatePickerValue,
setSelectedDatePickerValue,
searchInputRef,
}
useLogsPreviewShortcuts({
searchInputRef,
hasSearch: search.length > 0,
onResetSearch: () => {
setSearch('')
setSelectedLogId(null)
},
onRefresh: handleRefresh,
onToggleChart: () => setShowChart((prev) => !prev),
onLoadOlder: loadOlder,
canLoadOlder: !error && logData.length > 0 && !isLoadingOlder,
})
return (
<div className="flex-1 flex flex-col h-full">
<PreviewFilterPanel {...filterPanelProps} />
{children}
<div
className={
'transition-all duration-500 ' +
(showChart && logData.length > 0 ? 'mb-2 mt-1 opacity-100' : 'h-0 opacity-0')
}
>
<div className={condensedLayout ? 'px-3' : ''}>
{showChart && (
<LogsBarChart
data={eventChartData}
onBarClick={(datum) => {
if (!datum?.timestamp) return
const { start, end } = calculateBarClickTimeRange(
timestampStart,
timestampEnd,
datum.timestamp
)
handleSearch('event-chart-bar-click', {
query: filters.search_query?.toString(),
to: end,
from: start,
})
}}
EmptyState={
<div className="flex flex-col items-center justify-center h-[67px]">
<p className="text-foreground-light text-xs">No data</p>
<p className="text-foreground-lighter text-xs">
It may take up to 24 hours for data to refresh
</p>
</div>
}
/>
)}
</div>
</div>
<div className="relative flex flex-col grow flex-1 overflow-auto">
<ShimmerLine active={isLoading} />
<LoadingOpacity active={isLoading}>
<LogTable
projectRef={projectRef}
isLoading={isLoading}
data={logData}
queryType={queryType}
isHistogramShowing={showChart}
onHistogramToggle={() => setShowChart(!showChart)}
error={error}
EmptyState={EmptyState}
onSelectedLogChange={(log) => setSelectedLogId(log?.id ?? null)}
selectedLog={selectedLog}
isSelectedLogLoading={isSelectedLogLoading}
selectedLogError={selectedLogError ?? undefined}
/>
</LoadingOpacity>
</div>
{!error && logData.length > 0 && (
<div className="border-t flex flex-row items-center gap-3 p-2">
<ShortcutTooltip shortcutId={SHORTCUT_IDS.LOGS_PREVIEW_LOAD_OLDER} side="top">
<Button
onClick={loadOlder}
icon={<RewindIcon />}
loading={isLoadingOlder}
disabled={isLoadingOlder}
>
Load older
</Button>
</ShortcutTooltip>
<div className="text-sm text-foreground-lighter">
Showing <span className="font-mono">{logData.length}</span> results
</div>
<div className="flex flex-row justify-end mt-2">
<UpgradePrompt show={showUpgradePrompt} setShowUpgradePrompt={setShowUpgradePrompt} />
</div>
</div>
)}
</div>
)
}