Files
Alaister YoungandAlaister Young d8568215ad [FE-5109] (part 4) refactor(studio): migrate database, editor, storage, and functions interfaces off next/router (#54056)
Part 4 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 ← this PR** | **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 |

Migrates the database, branching, compute, functions, explorer, SQL
editor, storage, and table editor interfaces off `next/router` and
`next/compat/router`.

**Changed:**

- Migrated the sole `next/compat/router` consumer
(`components/interfaces/Database/Replication/Destinations.tsx`) to
`useNavigate`
- Replaced `useRouter` across `BranchManagement`, `Branching`,
`Compute`, `Database` (`Backups`, `Functions`, `Replication`, `Schemas`,
`Tables`, `Triggers`), `EdgeFunctions`, `Explorer`, `Functions`,
`SQLEditor`, `Storage` (`AnalyticsBuckets`, `FilesBuckets`,
`VectorBuckets`, `StorageMenuV2`, `Storage.utils`), and
`TableGridEditor` with TanStack Router hooks (`useNavigate`,
`useLocation`, `useRoutePattern`) and `useParams` from `common`
- Updated unit and component tests across `Database/Replication`,
`Explorer`, `Functions`, and
`Storage/FilesBuckets/DeleteBucketModal.test.tsx` to use TanStack Router

**Simplified:**

- `useSnippetEditor` and `useRedirectLegacyReadReplicaDestination` read
search values from `useParams` instead of casting `location.search`
- `resolveSourceSwitch` returns `replace: boolean` instead of a
`push`/`replace` method name
- `ExplorerQueryTab` and `EdgeFunctionDetails` guard on a defined ref
instead of navigating with `ref ?? ''`
- `useFunctionsDetailShortcuts` and `StorageMenuV2` use a local `goTo`
helper for their navigation shortcuts
- Tests use the shared `createTestRouter` and `customRender` router, use
`toMatchObject` for search assertions, and drop duplicate assertions

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

## To test

- [ ] SQL Editor: creating, renaming, moving, opening
templates/examples, and keyboard shortcuts navigate between snippets
cleanly
- [ ] Table Editor & Database: opening tables, schema table nodes,
triggers, functions, backups/PITR, and replication destination flows
navigate as expected
- [ ] Storage: switching between Files, Analytics, and Vector buckets
and deleting a bucket navigates cleanly
- [ ] Edge Functions & Explorer: opening function details/logs, explorer
chat/query tabs, and branch management actions navigate properly

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 14:44:59 +08:00

162 lines
4.4 KiB
TypeScript

import { useNavigate } from '@tanstack/react-router'
import { useParams } from 'common'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { ContentDiff, DiffType } from './SQLEditor.types'
import {
compareAsAddition,
compareAsModification,
compareAsNewSnippet,
createSqlSnippetSkeletonV2,
} from './SQLEditor.utils'
import {
FGA_PERMISSIONS,
useAsyncCheckUserContentPermissions,
} from '@/hooks/misc/useCheckPermissionsV2'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { navigateToUrl } from '@/lib/navigation'
import { useProfile } from '@/lib/profile'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
export const useNewQuery = () => {
const navigate = useNavigate()
const { ref } = useParams()
const { profile } = useProfile()
const { data: project } = useSelectedProjectQuery()
const snapV2 = useSqlEditorV2StateSnapshot()
const { can: canCreateSQLSnippet } = useAsyncCheckUserContentPermissions(
FGA_PERMISSIONS.PROJECT.SNIPPETS_WRITE,
{ mode: 'create', type: 'sql' }
)
const newQuery = async (sql: string, name: string, shouldRedirect: boolean = true) => {
if (!ref) return console.error('Project ref is required')
if (!project) return console.error('Project is required')
if (!profile) return console.error('Profile is required')
if (!canCreateSQLSnippet) {
toast('Your queries will not be saved as you do not have sufficient permissions')
return undefined
}
try {
const snippet = createSqlSnippetSkeletonV2({
name,
sql,
owner_id: profile?.id,
project_id: project?.id,
})
snapV2.addSnippet({ projectRef: ref, snippet })
snapV2.addNeedsSaving(snippet.id)
if (shouldRedirect) {
void navigateToUrl(navigate, `/project/${ref}/sql/${snippet.id}`)
return undefined
} else {
return snippet.id
}
} catch (error: any) {
toast.error(`Failed to create new query: ${error.message}`)
return undefined
}
}
return { newQuery }
}
export function useSqlEditorDiff() {
const [sourceSqlDiff, setSourceSqlDiff] = useState<ContentDiff>()
const [selectedDiffType, setSelectedDiffType] = useState<DiffType>()
const [isAcceptDiffLoading, setIsAcceptDiffLoading] = useState(false)
const isDiffOpen = !!sourceSqlDiff
const defaultSqlDiff = useMemo(() => {
if (!sourceSqlDiff) {
return { original: '', modified: '' }
}
switch (selectedDiffType) {
case DiffType.Modification:
return compareAsModification(sourceSqlDiff)
case DiffType.Addition:
return compareAsAddition(sourceSqlDiff)
case DiffType.NewSnippet:
return compareAsNewSnippet(sourceSqlDiff)
default:
return { original: '', modified: '' }
}
}, [selectedDiffType, sourceSqlDiff])
const closeDiff = useCallback(() => {
setSourceSqlDiff(undefined)
setSelectedDiffType(undefined)
}, [])
return useMemo(
() => ({
sourceSqlDiff,
setSourceSqlDiff,
selectedDiffType,
setSelectedDiffType,
isAcceptDiffLoading,
setIsAcceptDiffLoading,
isDiffOpen,
defaultSqlDiff,
closeDiff,
}),
[sourceSqlDiff, selectedDiffType, isAcceptDiffLoading, isDiffOpen, defaultSqlDiff, closeDiff]
)
}
interface PromptState {
isOpen: boolean
selection: string
beforeSelection: string
afterSelection: string
startLineNumber: number
endLineNumber: number
}
const initialPromptState: PromptState = {
isOpen: false,
selection: '',
beforeSelection: '',
afterSelection: '',
startLineNumber: 0,
endLineNumber: 0,
}
export function useSqlEditorPrompt() {
const [promptState, setPromptState] = useState<PromptState>(initialPromptState)
const [promptInput, setPromptInput] = useState('')
useEffect(() => {
if (!promptState.isOpen) {
setPromptInput('')
}
}, [promptState.isOpen])
const resetPrompt = useCallback(() => {
setPromptState(initialPromptState)
setPromptInput('')
}, [])
const openPrompt = useCallback((context: Omit<PromptState, 'isOpen'>) => {
setPromptState((prev) => ({ ...prev, isOpen: true, ...context }))
}, [])
return useMemo(
() => ({
promptState,
setPromptState,
promptInput,
setPromptInput,
resetPrompt,
openPrompt,
}),
[promptState, promptInput, resetPrompt, openPrompt]
)
}