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

218 lines
7.3 KiB
TypeScript

import { useNavigate } from '@tanstack/react-router'
import { useParams } from 'common'
import { Loader2Icon } from 'lucide-react'
import { parseAsBoolean, parseAsString, useQueryState } from 'nuqs'
import { MouseEvent, useEffect, useMemo, useRef, useState } from 'react'
import type { DataGridHandle } from 'react-data-grid'
import { toast } from 'sonner'
import { LoadingLine } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { PageSection } from 'ui-patterns/PageSection'
import { ConstrainedIntegrationTabScaffold } from '../ConstrainedIntegrationTabScaffold'
import { useIntegrationDetail } from '../Landing/useIntegrationDetail'
import { formatCronJobColumns } from './CronJobs.utils'
import { CronJobRunDetailsOverflowNotice } from './CronJobsTab.CleanupNotice'
import { CronJobsTabDataGrid } from './CronJobsTab.DataGrid'
import { CronJobsTabHeader } from './CronJobsTab.Header'
import { useCronJobsData } from './CronJobsTab.useCronJobsData'
import { DeleteCronJob } from './DeleteCronJob'
import { CreateCronJobSheet } from '@/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet'
import { CronJob } from '@/data/database-cron-jobs/database-cron-jobs-infinite-query'
import { useInfiniteScroll } from '@/hooks/misc/useInfiniteScroll'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { cleanPointerEventsNoneOnBody } from '@/lib/helpers'
import { createNavigationHandler } from '@/lib/navigation'
import { useTrack } from '@/lib/telemetry/track'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
const EMPTY_CRON_JOB = { jobname: '', schedule: '', active: true, command: '' }
export const CronjobsTab = () => {
const navigate = useNavigate()
const { ref } = useParams()
const { data: project } = useSelectedProjectQuery()
const track = useTrack()
const { isInstalled } = useIntegrationDetail()
const [searchQuery, setSearchQuery] = useQueryState('search', parseAsString.withDefault(''))
const [search, setSearch] = useState(searchQuery)
const handleSearchSubmit = () => {
const trimmed = search.trim()
setSearchQuery(trimmed.length > 0 ? trimmed : null)
}
const handleClearSearch = () => {
setSearch('')
setSearchQuery(null)
}
const { grid, count } = useCronJobsData({
projectRef: project?.ref,
connectionString: project?.connectionString,
searchQuery,
enabled: isInstalled,
})
const [createCronJobSheetShown, setCreateCronJobSheetShown] = useQueryState(
'new',
parseAsBoolean.withDefault(false).withOptions({ clearOnDefault: true })
)
const [cronJobIdForEditing, setCronJobForEditing] = useQueryState('edit', parseAsString)
const cronJobForEditing = grid.rows.find((j) => j.jobid.toString() === cronJobIdForEditing)
const [, setCronJobForDeletion] = useQueryState('delete', parseAsString)
const columns = useMemo(
() =>
formatCronJobColumns({
onSelectEdit: (job: CronJob) => {
track('cron_job_update_clicked')
setCronJobForEditing(job.jobid.toString())
},
onSelectDelete: (job: CronJob) => {
track('cron_job_delete_clicked')
setCronJobForDeletion(job.jobid.toString())
},
}),
[track, setCronJobForEditing, setCronJobForDeletion]
)
const gridRef = useRef<DataGridHandle>(null)
const handleScroll = useInfiniteScroll({
isLoading: grid.isLoading,
isFetchingNextPage: grid.isFetchingNextPage,
isRefetching: grid.isRefetching,
isError: !!grid.error,
hasNextPage: grid.hasNextPage,
fetchNextPage: grid.fetchNextPage,
containerRef: gridRef,
rowCount: grid.rows.length,
})
const onOpenCreateJobSheet = () => {
track('cron_job_create_clicked')
setCreateCronJobSheetShown(true)
}
const searchInputRef = useRef<HTMLInputElement>(null)
useShortcut(
SHORTCUT_IDS.LIST_PAGE_FOCUS_SEARCH,
() => {
searchInputRef.current?.focus()
searchInputRef.current?.select()
},
{ label: 'Search cron jobs' }
)
useShortcut(SHORTCUT_IDS.LIST_PAGE_RESET_FILTERS, handleClearSearch)
useShortcut(SHORTCUT_IDS.LIST_PAGE_NEW_ITEM, onOpenCreateJobSheet, { label: 'Create cron job' })
// Row click handler
const handleRowClick = (row: CronJob, event: MouseEvent<HTMLDivElement>) => {
const { jobid, jobname } = row
const url = `/project/${ref}/integrations/cron/jobs/${jobid}?child-label=${encodeURIComponent(
jobname || `Job #${jobid}`
)}`
track('cron_job_history_clicked')
createNavigationHandler(url, navigate)(event)
}
const onClose = () => {
setCronJobForEditing(null)
setCreateCronJobSheetShown(false)
cleanPointerEventsNoneOnBody(500)
}
useEffect(() => {
if (grid.isSuccess && !!cronJobIdForEditing && !cronJobForEditing) {
toast('Cron job not found')
setCronJobForEditing(null)
}
}, [cronJobForEditing, cronJobIdForEditing, grid.isSuccess, setCronJobForEditing])
if (!isInstalled) {
return (
<div className="mx-auto w-full max-w-6xl px-6 xl:px-10">
<ConstrainedIntegrationTabScaffold>
<PageSection className="py-0">
<Admonition type="default" description="Cron is not installed." />
</PageSection>
</ConstrainedIntegrationTabScaffold>
</div>
)
}
return (
<>
<div className="h-full w-full space-y-4">
<div className="h-full w-full flex flex-col relative">
<CronJobsTabHeader
search={search}
isRefreshing={grid.isRefetching && !grid.isFetchingNextPage}
searchInputRef={searchInputRef}
onSearchChange={setSearch}
onSearchSubmit={handleSearchSubmit}
onClearSearch={handleClearSearch}
onRefresh={grid.refetch}
onCreateJob={onOpenCreateJobSheet}
/>
<LoadingLine loading={grid.isLoading || grid.isRefetching || grid.isFetchingNextPage} />
{grid.isMinimal && (
<CronJobRunDetailsOverflowNotice
queryCost={grid.queryCost}
refetchJobs={grid.refetch}
/>
)}
<CronJobsTabDataGrid
gridRef={gridRef}
columns={columns}
rows={grid.rows}
isLoading={grid.isLoading}
error={grid.error}
searchQuery={searchQuery}
onScroll={handleScroll}
onRowClick={handleRowClick}
/>
<CronJobsFooter count={count} />
</div>
</div>
<DeleteCronJob />
<CreateCronJobSheet
open={!!createCronJobSheetShown || !!cronJobForEditing}
selectedCronJob={cronJobForEditing ?? EMPTY_CRON_JOB}
onClose={onClose}
/>
</>
)
}
// Footer component for displaying job count
interface CronJobsFooterProps {
count: {
value: number | undefined
isEstimate: boolean
isLoading: boolean
}
}
const CronJobsFooter = ({ count }: CronJobsFooterProps) => (
<div className="flex justify-between min-h-9 h-9 overflow-hidden items-center px-6 w-full border-t text-xs text-foreground-light">
{count.isLoading ? (
<span className="flex items-center gap-2">
<Loader2Icon size={14} className="animate-spin" /> Loading...
</span>
) : (
`Total: ${count.value ?? 0} jobs${count.isEstimate ? ' (estimate)' : ''}`
)}
</div>
)