Files
supabase/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx
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

219 lines
7.3 KiB
TypeScript

import { type Hotkey } from '@tanstack/react-hotkeys'
import { useNavigate } from '@tanstack/react-router'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import {
AlignLeftIcon,
CheckIcon,
KeyboardIcon,
Loader2Icon,
MoreVerticalIcon,
SquareCodeIcon,
} from 'lucide-react'
import { useCallback, useContext, useEffect, useRef, useState } from 'react'
import {
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
KeyboardShortcut,
} from 'ui'
import { ExplorerToolbarAction } from './ExplorerToolbar'
import { QueryEditor, type ExplorerQueryModel, type QueryEditorHandle } from './QueryEditor'
import { SaveQueryDropdown } from './SaveQueryDropdown'
import { type QueryDisplay, type QueryResult } from './types'
import { toQuerySourceBinding } from '@/data/query-sources/query-source-registry'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { explorerQueryState, useExplorerQueryStateSnapshot } from '@/state/explorer-query'
import { useControlledRoleImpersonationState } from '@/state/role-impersonation-state'
import { hotkeyToKeys } from '@/state/shortcuts/formatShortcut'
import { SHORTCUT_DEFINITIONS, SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { createTabId, TabsStateContext } from '@/state/tabs'
/** Query-tab lifecycle adapter around the shared QueryEditor. */
export const ExplorerQueryTab = () => {
const navigate = useNavigate()
const { id, ref } = useParams()
const tabs = useContext(TabsStateContext)
const querySnap = useExplorerQueryStateSnapshot()
const [isIntellisenseEnabled, setIsIntellisenseEnabled] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE,
true
)
const queryEditorRef = useRef<QueryEditorHandle>(null)
const hotkeySequnece: Hotkey | undefined =
SHORTCUT_DEFINITIONS[SHORTCUT_IDS.SQL_EDITOR_FORMAT].sequence[0]
const formatKeys = hotkeySequnece ? hotkeyToKeys(hotkeySequnece) : undefined
const [restoredQueryKey, setRestoredQueryKey] = useState<string>()
const [showQuery, setShowQuery] = useState(true)
const stateDraft = id ? querySnap.drafts[id] : undefined
const draft = stateDraft?.projectRef === ref ? stateDraft : undefined
const result = draft && id ? querySnap.results[id] : undefined
const queryKey = id && ref ? `${ref}:${id}` : undefined
const isDraftReady = !!queryKey && restoredQueryKey === queryKey
const roleImpersonationState = useControlledRoleImpersonationState(
draft?._tag === 'database' ? draft.role : undefined,
useCallback(
(role) => {
if (id) explorerQueryState.setRole({ id, role })
},
[id]
)
)
useEffect(() => {
if (!id || !ref) return
setShowQuery(true)
explorerQueryState.restoreDraft({ id, projectRef: ref })
setRestoredQueryKey(`${ref}:${id}`)
}, [id, ref])
useEffect(() => {
if (!id || !isDraftReady || !draft?.pendingAutoRun) return
queryEditorRef.current?.run()
explorerQueryState.clearPendingAutoRun({ id })
}, [id, isDraftReady, draft?.pendingAutoRun])
if (!queryKey || restoredQueryKey !== queryKey) {
return (
<div
role="status"
aria-label="Loading query"
className="flex h-full items-center justify-center bg-surface-100"
>
<Loader2Icon className="animate-spin text-foreground-muted" size={18} />
</div>
)
}
if (!id || !draft) {
return (
<div className="flex h-full flex-col items-center justify-center gap-3 bg-surface-100">
<SquareCodeIcon className="text-foreground-muted" size={24} />
<div className="text-center">
<p className="text-sm font-medium">Query draft not found</p>
<p className="text-sm text-foreground-lighter">
This local draft may have been closed or cleared from this browser.
</p>
</div>
<Button
variant="primary"
onClick={() => {
if (ref) void navigate({ to: '/project/$ref/explorer', params: { ref } })
}}
>
Back to Explorer
</Button>
</div>
)
}
const display: QueryDisplay = {
view: draft.view,
chart: draft.chart ? { ...draft.chart, y_series: [...draft.chart.y_series] } : undefined,
}
const query: ExplorerQueryModel =
draft._tag === 'logs'
? { ...toQuerySourceBinding(draft), uncheckedSql: draft.uncheckedSql }
: {
...toQuerySourceBinding(draft),
uncheckedSql: draft.uncheckedSql,
rowLimit: draft.rowLimit,
}
const persistTab = () => tabs.makeTabPermanent(createTabId('query', { id }))
const handleResultChange = (nextResult: QueryResult) => {
explorerQueryState.setResult({
id,
result: { ...nextResult, executedAt: Date.now() },
})
}
return (
<QueryEditor
ref={queryEditorRef}
id={id}
location={{ surface: 'query_tab', queryId: id }}
variant="viewport"
title={draft.name}
query={query}
result={result}
display={display}
showQuery={showQuery}
onShowQueryChange={setShowQuery}
roleImpersonationState={roleImpersonationState}
onTitleChange={(value) => {
persistTab()
const name = value.trim() || 'Run SQL'
explorerQueryState.updateDraft({ id, name })
tabs.updateTab(createTabId('query', { id }), { label: name })
}}
onSqlChange={(sql) => {
persistTab()
explorerQueryState.updateDraft({ id, sql })
}}
onSourceChange={(source) => {
persistTab()
explorerQueryState.updateDraft({ id, source })
}}
onRowLimitChange={(rowLimit) => {
persistTab()
explorerQueryState.updateDraft({ id, rowLimit })
}}
onResultChange={handleResultChange}
onDisplayChange={(display) => {
persistTab()
explorerQueryState.setDisplay({ id, display })
}}
toolbarActions={
<>
<SaveQueryDropdown
query={{ title: draft.name, sql: draft.uncheckedSql }}
source={toQuerySourceBinding(draft)}
/>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<ExplorerToolbarAction icon={<MoreVerticalIcon size={16} strokeWidth={2} />} />
</DropdownMenuTrigger>
<DropdownMenuContent className="w-48" align="end">
<DropdownMenuItem
className="justify-between"
onClick={() => setIsIntellisenseEnabled(!isIntellisenseEnabled)}
>
<div className="flex items-center gap-x-2">
<KeyboardIcon size={14} />
<span>Intellisense enabled</span>
</div>
{isIntellisenseEnabled && <CheckIcon className="text-primary" size={16} />}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="justify-between"
onClick={() => queryEditorRef.current?.prettify()}
>
<span className="flex items-center gap-x-2">
<AlignLeftIcon size={14} />
Prettify SQL
</span>
{formatKeys && <KeyboardShortcut keys={formatKeys} />}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</>
}
/>
)
}