Files
supabase/apps/studio/components/interfaces/App/CommandMenu/FeaturePreviews.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

161 lines
6.1 KiB
TypeScript

import { useLocation, useNavigate } from '@tanstack/react-router'
import { useParams } from 'common'
import { CheckIcon, ExternalLinkIcon, FlaskConicalIcon, SquareIcon } from 'lucide-react'
import { useMemo } from 'react'
import { useLatest } from 'react-use'
import { toast } from 'sonner'
import { Badge } from 'ui'
import {
PageType,
useRegisterCommands,
useRegisterPage,
useSetCommandMenuOpen,
useSetPage,
} from 'ui-patterns/CommandMenu'
import { COMMAND_MENU_SECTIONS } from './CommandMenu.utils'
import {
useFeaturePreviewContext,
useFeaturePreviewModal,
} from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import {
FeaturePreview,
useVisibleFeaturePreviewsByCategory,
} from '@/components/interfaces/App/FeaturePreview/useFeaturePreviews'
import { useBannerStack } from '@/components/ui/BannerStack/BannerStackProvider'
import { navigateToUrl } from '@/lib/navigation'
const FEATURE_PREVIEWS_PAGE_NAME = 'Feature previews'
export function useFeaturePreviewCommands() {
const navigate = useNavigate()
const pathname = useLocation({ select: (location) => location.pathname })
const { ref } = useParams()
const { dismissBanner } = useBannerStack()
const setPage = useSetPage()
const setIsOpen = useSetCommandMenuOpen()
const { flags, onUpdateFlag } = useFeaturePreviewContext()
const { selectFeaturePreview, toggleFeaturePreviewModal } = useFeaturePreviewModal()
const openFeaturePreviewDetails = (key: string) => {
selectFeaturePreview(key)
toggleFeaturePreviewModal(true)
setIsOpen(false)
}
// Registering this page tears it down and re-adds it (popping it off the
// page stack if it's currently open) whenever `deps` changes identity, so
// `flags` is read through a ref instead of being a dep — toggling a preview
// must not kick the user back to the root menu. Same reasoning applies to
// `ref`/`pathname`: the command's `action` closure is only recreated when
// `previewsByCategory` changes identity, so without reading these through a
// ref too, navigating between projects (or to/from the org view) after that
// page was first registered would keep routing to whatever project was
// current back then.
const flagsRef = useLatest(flags)
const routeContextRef = useLatest({ ref, pathname })
// Mirrors FeaturePreviewModal's toggleFeature: if the preview has a route to
// try it out in, enabling it takes the user there instead of just flipping
// the flag silently.
const toggleFeaturePreview = (preview: FeaturePreview) => {
if (preview.isForced) return
const isEnabling = !flagsRef.current[preview.key]
onUpdateFlag(preview.key, isEnabling)
if (!isEnabling) {
toast(`${preview.name} disabled`)
return
}
// Only route into a project when actually on a project-scoped page —
// `ref` alone isn't enough, since it can retain a stale value after
// client-side navigating to a route without a `ref` segment (e.g. the org
// view).
const { ref: currentRef, pathname: currentPathname } = routeContextRef.current
const isProjectScopedRoute = currentPathname.startsWith('/project/')
const route = isProjectScopedRoute ? preview.getRoute?.(currentRef) : undefined
if (route !== undefined && currentRef !== undefined) {
setIsOpen(false)
navigateToUrl(navigate, route)
toast.success(`${preview.name} enabled`, {
description: "We've taken you to where you can try it out.",
})
if (preview.bannerId) dismissBanner(preview.bannerId)
} else {
toast.success(`${preview.name} enabled`, {
description: "It's now active across the dashboard.",
})
}
}
// Grouped identically to the feature preview modal's category accordion —
// shared hook, so the two can never list a different set of previews.
const previewsByCategory = useVisibleFeaturePreviewsByCategory()
const visiblePreviews = useMemo(
() => previewsByCategory.flatMap(({ previews }) => previews),
[previewsByCategory]
)
useRegisterPage(
FEATURE_PREVIEWS_PAGE_NAME,
{
type: PageType.Commands,
sections: previewsByCategory
.filter(({ previews }) => previews.length > 0)
.map(({ category, previews }) => ({
id: `feature-previews-${category ?? 'others'}`,
name: category ?? 'Others',
commands: previews.flatMap((preview) => [
{
id: `feature-preview-${preview.key}`,
name: preview.name,
value: preview.isForced
? `${preview.name}, Feature preview, now the default, can't be turned off`
: `${preview.name}, Feature preview, Toggle ${preview.name}`,
action: () => toggleFeaturePreview(preview),
icon: () => (flagsRef.current[preview.key] ? <CheckIcon /> : <SquareIcon />),
badge: preview.isForced
? () => (
<Badge
variant="default"
title="This feature is now the default and can no longer be turned off"
>
Default
</Badge>
)
: preview.isNew
? () => <Badge variant="success">New</Badge>
: undefined,
},
{
id: `feature-preview-${preview.key}-details`,
name: `${preview.name}: View details`,
value: `${preview.name}, About, Learn more, Description, Feedback, Discussion`,
action: () => openFeaturePreviewDetails(preview.key),
icon: () => <ExternalLinkIcon />,
defaultHidden: true,
},
]),
})),
},
{ deps: [previewsByCategory], enabled: visiblePreviews.length > 0 }
)
useRegisterCommands(
COMMAND_MENU_SECTIONS.ACTIONS,
[
{
id: 'feature-previews',
name: 'Feature previews...',
value: 'Feature previews, Try new features, Early access, Opt in, Opt out, Beta features',
action: () => setPage(FEATURE_PREVIEWS_PAGE_NAME),
icon: () => <FlaskConicalIcon />,
},
],
{ enabled: visiblePreviews.length > 0 }
)
}