Files
supabase/apps/studio/components/layouts/ProjectLayout/OrganizationSettingsLayout.tsx
Alaister YoungandAlaister Young d98f706b7c [FE-5109] (part 1) refactor(studio): migrate core hooks, lib, and prefetchers off next/router (#54053)
Part 1 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 ← this PR** | **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 | Remaining `components/interfaces/**` and
`QueryInsightsTable` router events |
| 6 | #54058 | Remove `next/router` & `next/compat/router` shims,
`_router-events.ts`, Vite aliases, and test mocks |

Introduces the shared TanStack navigation helpers needed across the
stack and migrates `hooks/**`, `lib/**`, and `data/prefetchers/**` off
`next/router`.

**Added:**

- `navigateToUrl` in `apps/studio/lib/navigation.ts` (plus unit tests in
`lib/navigation.test.ts`): shared helper for navigating to internal
string URLs via TanStack's `useNavigate` (splitting pathname, search
params, and hash via `splitInternalUrl`, and handling
external/protocol-relative URLs)
- `useRoutePattern` in `apps/studio/hooks/misc/useRoutePattern.ts` (plus
`useRoutePattern.test.tsx`): returns the active matched TanStack route
template (e.g. `/project/$ref/editor/$id`) as the replacement for Next's
`router.pathname`

**Changed:**

- Migrated `hooks/misc/*` (`useHydratedQuery`,
`useStudioCommandMenuTelemetry`, `useTableEditorFiltersSort`,
`withAuth`) and `hooks/use-check-latest-deploy.tsx` to TanStack's
`useLocation`, `useNavigate`, `useRoutePattern`, and `useParams` from
`common`
- Migrated `lib/profile.tsx` and `lib/telemetry/track.ts` off
`next/router`
- Migrated `data/prefetchers/project.$ref.tsx`,
`project.$ref.editor.tsx`, and `project.$ref.editor.$id.tsx` to
`useRouter().preloadRoute`
- Wrapped `ReactQueryTestConfig` in `apps/studio/tests/helpers.tsx` with
`RouterContextProvider` and updated hook/navigation tests
(`useTableEditorFiltersSort*.test.*`,
`useFilterLifeCycle.navigation.test.tsx`,
`useTableFilter.navigation.test.tsx`, `useInboundBranding.test.ts`,
`state/tabs.test.ts`)

**Simplified:**

- `navigateToUrl` passes `replace` straight through and documents that
`url` must be an app-relative path or an external URL.
`StudioFrameworkProvider`'s `push` now reuses it.
- `useRoutePattern` reads matches and location in a single
`useRouterState` subscription
- `useTrack` and `useStudioCommandMenuTelemetry` take the pathname from
`useFramework()`, the same source as pageviews, so custom events and
pageviews always send the same pattern (e.g. `/project/[ref]/sql/[id]`).
New tests pin the strings sent, and `toRoutePattern` now has its own
unit tests.
- Removed `useCurrentPath` (a one-line wrapper with one consumer):
`OrganizationSettingsLayout` calls `useLocation` directly
- Dropped the no-op `.catch(() => {})` on `preloadRoute` in the
prefetchers (`preloadRoute` never rejects)
- `useTableEditorFiltersSort` builds the next search with a spread
instead of a delete loop
- Added `createTestRouter()` to `tests/lib/custom-render.tsx`, and
`customRender`/`customRenderHook` now return the `router`. The rest of
the stack uses these instead of hand-copied `createRouter` setups.

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

## To test

- [ ] Auth redirect flow (`withAuth`) still preserves `returnTo` query
parameters when redirecting unauthenticated users to `/sign-in`
- [ ] Table Editor sort and filter URL sync
(`useTableEditorFiltersSort`) persists and clears `?sort=` / `?filter=`
across table switches
- [ ] Hovering project and table editor links still triggers route/data
prefetching without console errors
- [ ] Page view and command menu telemetry still records route patterns
and paths accurately

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-27 09:37:49 +00:00

283 lines
7.3 KiB
TypeScript

import { useLocation } from '@tanstack/react-router'
import { useFlag, useParams } from 'common'
import { PropsWithChildren, useMemo } from 'react'
import { useIsPlatformWebhooksEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import type { SidebarSection } from '@/components/layouts/AccountLayout/AccountLayout.types'
import { toSubMenuSections } from '@/components/layouts/AccountLayout/AccountLayout.utils'
import { WithSidebar } from '@/components/layouts/AccountLayout/WithSidebar'
import { ProductMenuShortcuts } from '@/components/ui/ProductMenu/ProductMenuShortcuts'
import { convertSectionsToProductMenu } from '@/components/ui/ProductMenu/SubMenu.utils'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
interface OrganizationSettingsMenuItemsProps {
slug?: string
showSecuritySettings?: boolean
showSsoSettings?: boolean
showLegalDocuments?: boolean
showPlatformWebhooks?: boolean
showPrivateApps?: boolean
showAuditLogDrains?: boolean
}
interface OrganizationSettingsSectionsProps extends OrganizationSettingsMenuItemsProps {
currentPath: string
}
export const normalizeOrganizationSettingsPath = (path: string) => path.split('#')[0]
export const generateOrganizationSettingsMenuItems = ({
slug,
showSecuritySettings = true,
showSsoSettings = true,
showLegalDocuments = true,
showPlatformWebhooks = true,
showPrivateApps: _showPrivateApps = false,
showAuditLogDrains = false,
}: OrganizationSettingsMenuItemsProps) => [
{
key: 'general',
label: 'General',
href: `/org/${slug}/general`,
},
...(showSecuritySettings
? [
{
key: 'security',
label: 'Security',
href: `/org/${slug}/security`,
},
]
: []),
{
key: 'apps',
label: 'OAuth Apps',
href: `/org/${slug}/apps`,
},
...(showSsoSettings
? [
{
key: 'sso',
label: 'SSO',
href: `/org/${slug}/sso`,
},
]
: []),
...(showPlatformWebhooks
? [
{
key: 'webhooks',
label: 'Webhooks',
href: `/org/${slug}/webhooks`,
},
]
: []),
{
key: 'audit',
label: 'Audit Logs',
href: `/org/${slug}/audit`,
},
...(showAuditLogDrains
? [
{
key: 'audit-log-drains',
label: 'Audit Log Drains',
href: `/org/${slug}/audit-log-drains`,
},
]
: []),
...(showLegalDocuments
? [
{
key: 'documents',
label: 'Legal Documents',
href: `/org/${slug}/documents`,
},
]
: []),
]
export const generateOrganizationSettingsSections = ({
currentPath,
slug,
showSecuritySettings = true,
showSsoSettings = true,
showLegalDocuments = true,
showPlatformWebhooks = true,
showPrivateApps = false,
showAuditLogDrains = false,
}: OrganizationSettingsSectionsProps): SidebarSection[] => {
const isLinkActive = (key: string, href: string) =>
key === 'webhooks'
? currentPath === href || currentPath.startsWith(`${href}/`)
: currentPath === href
const configurationLinks = [
{
key: 'general',
label: 'General',
href: `/org/${slug}/general`,
shortcutId: SHORTCUT_IDS.NAV_ORG_SETTINGS_GENERAL,
},
...(showSecuritySettings
? [
{
key: 'security',
label: 'Security',
href: `/org/${slug}/security`,
shortcutId: SHORTCUT_IDS.NAV_ORG_SETTINGS_SECURITY,
},
]
: []),
...(showSsoSettings
? [
{
key: 'sso',
label: 'SSO',
href: `/org/${slug}/sso`,
shortcutId: SHORTCUT_IDS.NAV_ORG_SETTINGS_SSO,
},
]
: []),
]
const connectionsLinks = [
{
key: 'apps',
label: 'OAuth Apps',
href: `/org/${slug}/apps`,
shortcutId: SHORTCUT_IDS.NAV_ORG_SETTINGS_APPS,
},
...(showPrivateApps
? [
{
key: 'private-apps',
label: 'Private Apps',
href: `/org/${slug}/private-apps`,
shortcutId: SHORTCUT_IDS.NAV_ORG_SETTINGS_PRIVATE_APPS,
},
]
: []),
...(showPlatformWebhooks
? [
{
key: 'webhooks',
label: 'Webhooks',
href: `/org/${slug}/webhooks`,
shortcutId: SHORTCUT_IDS.NAV_ORG_SETTINGS_WEBHOOKS,
},
]
: []),
]
const complianceLinks = [
{
key: 'audit',
label: 'Audit Logs',
href: `/org/${slug}/audit`,
shortcutId: SHORTCUT_IDS.NAV_ORG_SETTINGS_AUDIT,
},
...(showAuditLogDrains
? [
{
key: 'audit-log-drains',
label: 'Audit Log Drains',
href: `/org/${slug}/audit-log-drains`,
shortcutId: SHORTCUT_IDS.NAV_ORG_SETTINGS_AUDIT_LOG_DRAINS,
},
]
: []),
...(showLegalDocuments
? [
{
key: 'documents',
label: 'Legal Documents',
href: `/org/${slug}/documents`,
shortcutId: SHORTCUT_IDS.NAV_ORG_SETTINGS_DOCUMENTS,
},
]
: []),
]
return [
{
key: 'configuration',
heading: 'Configuration',
links: configurationLinks.map((item) => ({
...item,
isActive: isLinkActive(item.key, item.href),
})),
},
{
key: 'connections',
heading: 'Connections',
links: connectionsLinks.map((item) => ({
...item,
isActive: isLinkActive(item.key, item.href),
})),
},
{
key: 'compliance',
heading: 'Compliance',
links: complianceLinks.map((item) => ({
...item,
isActive: isLinkActive(item.key, item.href),
})),
},
]
}
export function OrganizationSettingsLayout({ children }: PropsWithChildren) {
const { slug } = useParams()
const showPlatformWebhooks = useIsPlatformWebhooksEnabled()
const showPrivateApps = useFlag('privateApps')
const showAuditLogDrains = useFlag('auditLogsLogDrain')
const fullCurrentPath = useLocation({ select: (location) => location.pathname })
const currentPath = normalizeOrganizationSettingsPath(fullCurrentPath)
const {
organizationShowSsoSettings: showSsoSettings,
organizationShowSecuritySettings: showSecuritySettings,
organizationShowLegalDocuments: showLegalDocuments,
} = useIsFeatureEnabled([
'organization:show_sso_settings',
'organization:show_security_settings',
'organization:show_legal_documents',
])
const sections = generateOrganizationSettingsSections({
currentPath,
slug,
showSecuritySettings,
showSsoSettings,
showLegalDocuments,
showPlatformWebhooks,
showPrivateApps,
showAuditLogDrains,
})
const orgSettingsMenu = useMemo(
() => convertSectionsToProductMenu(toSubMenuSections(sections)),
[sections]
)
// Browser titles for org settings routes are set by OrganizationLayout.
return (
<>
<ProductMenuShortcuts menu={orgSettingsMenu} />
<WithSidebar
title="Organization Settings"
sections={sections}
header={
<div className="border-default flex min-h-(--header-height) items-center border-b px-6">
<h4 className="text-lg">Settings</h4>
</div>
}
>
{children}
</WithSidebar>
</>
)
}