mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
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>
392 lines
15 KiB
TypeScript
392 lines
15 KiB
TypeScript
import { zodResolver } from '@hookform/resolvers/zod'
|
|
import { useNavigate } from '@tanstack/react-router'
|
|
import { IS_PLATFORM, useParams } from 'common'
|
|
import { CheckIcon, CodeIcon, PlusIcon } from 'lucide-react'
|
|
import { useEffect, useState } from 'react'
|
|
import { useForm } from 'react-hook-form'
|
|
import { toast } from 'sonner'
|
|
import {
|
|
Button,
|
|
Command,
|
|
CommandEmpty,
|
|
CommandGroup,
|
|
CommandInput,
|
|
CommandItem,
|
|
CommandList,
|
|
CommandSeparator,
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogSection,
|
|
DialogSectionSeparator,
|
|
DialogTitle,
|
|
Form,
|
|
FormControl,
|
|
FormField,
|
|
FormItem,
|
|
FormLabel,
|
|
FormMessage,
|
|
Input,
|
|
Label,
|
|
Popover,
|
|
PopoverContent,
|
|
PopoverTrigger,
|
|
ScrollArea,
|
|
} from 'ui'
|
|
import * as z from 'zod'
|
|
|
|
import { getSqlSnippetById } from '@/data/content/content-id-query'
|
|
import { useContentUpsertMutation } from '@/data/content/content-upsert-mutation'
|
|
import { useSQLSnippetFolderCreateMutation } from '@/data/content/sql-folder-create-mutation'
|
|
import { Snippet } from '@/data/content/sql-folders-query'
|
|
import type { SnippetWithContent } from '@/data/content/sql-folders-query'
|
|
import { navigateToUrl } from '@/lib/navigation'
|
|
import { useTrack } from '@/lib/telemetry/track'
|
|
import { useSnippetFolders, useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
|
|
import { createTabId, useTabsStateSnapshot } from '@/state/tabs'
|
|
|
|
interface MoveQueryModalProps {
|
|
visible: boolean
|
|
snippets?: Snippet[]
|
|
onClose: () => void
|
|
}
|
|
|
|
/**
|
|
* [Joshen] Just FYI react-accessible-tree-view doesn't support drag and drop for moving
|
|
* files out of the box and we'll need to figure out a way to support this ideal UX. Same
|
|
* thing for the Storage Explorer actually. So this is just a temporary UX till we can figure
|
|
* out drag and drop that works nicely with the tree view. React beautiful dnd unfortunately
|
|
* doesn't support drag drop into a folder kind of UX.
|
|
*/
|
|
|
|
export const MoveQueryModal = ({ visible, snippets = [], onClose }: MoveQueryModalProps) => {
|
|
const { ref } = useParams()
|
|
const snapV2 = useSqlEditorV2StateSnapshot()
|
|
const tabsSnap = useTabsStateSnapshot()
|
|
const navigate = useNavigate()
|
|
const track = useTrack()
|
|
|
|
const [open, setOpen] = useState(false)
|
|
const [selectedId, setSelectedId] = useState<string>()
|
|
|
|
const { mutateAsync: createFolder, isPending: isCreatingFolder } =
|
|
useSQLSnippetFolderCreateMutation({
|
|
onError: (error) => {
|
|
toast.error(`Failed to create new folder: ${error.message}`)
|
|
},
|
|
})
|
|
const { mutateAsync: moveSnippetAsync, isPending: isMovingSnippet } = useContentUpsertMutation({
|
|
onError: (error) => {
|
|
toast.error(`Failed to move query: ${error.message}`)
|
|
},
|
|
})
|
|
|
|
const getFormSchema = () => {
|
|
if (selectedId === 'new-folder') {
|
|
return z
|
|
.object({
|
|
name: z.string().min(1, 'Please provide a name for the folder'),
|
|
})
|
|
.refine((data) => !snapV2.allFolderNames.includes(data.name), {
|
|
message: 'This folder name already exists',
|
|
path: ['name'],
|
|
})
|
|
} else {
|
|
return z.object({})
|
|
}
|
|
}
|
|
|
|
const FormSchema = getFormSchema()
|
|
|
|
const form = useForm<z.infer<typeof FormSchema>>({
|
|
mode: 'onSubmit',
|
|
reValidateMode: 'onSubmit',
|
|
resolver: zodResolver(FormSchema),
|
|
defaultValues: { name: '' },
|
|
})
|
|
|
|
const folders = useSnippetFolders(ref as string)
|
|
const selectedFolder =
|
|
selectedId === 'root'
|
|
? 'Root of the editor'
|
|
: selectedId === 'new-folder'
|
|
? 'Create a new folder'
|
|
: folders.find((f) => f.id === selectedId)?.name
|
|
const isCurrentFolder =
|
|
snippets.length === 1 &&
|
|
((!snippets[0].folder_id && selectedId === 'root') || snippets[0].folder_id === selectedId)
|
|
const isMovingToSameFolder =
|
|
snippets.length === 1 &&
|
|
((!snippets[0].folder_id && selectedId === 'root') || snippets[0].folder_id === selectedId)
|
|
|
|
const onConfirmMove = async (values: z.infer<typeof FormSchema>) => {
|
|
if (!ref) return console.error('Project ref is required')
|
|
|
|
try {
|
|
let folderId = selectedId
|
|
|
|
if (selectedId === 'new-folder' && 'name' in values) {
|
|
const { id } = await createFolder({
|
|
projectRef: ref,
|
|
name: values.name,
|
|
})
|
|
folderId = id
|
|
}
|
|
|
|
// Computed before the moves run, so it reflects each snippet's original folder
|
|
const destinationFolderId = selectedId === 'root' ? null : folderId
|
|
const movedSnippetCount = snippets.filter(
|
|
(snippet) => (snippet.folder_id ?? null) !== destinationFolderId
|
|
).length
|
|
|
|
await Promise.all(
|
|
snippets.map(async (snippet) => {
|
|
let snippetContent = (snippet as SnippetWithContent)?.content
|
|
if (snippetContent === undefined) {
|
|
// Move only ever operates on database SQL snippets
|
|
const { content } = await getSqlSnippetById({ projectRef: ref, id: snippet.id })
|
|
snippetContent = content
|
|
}
|
|
|
|
if (snippetContent === undefined) {
|
|
return toast.error('Failed to save snippet: Unable to retrieve snippet contents')
|
|
} else {
|
|
const movedSnippet = await moveSnippetAsync({
|
|
projectRef: ref,
|
|
payload: {
|
|
id: snippet.id,
|
|
type: 'sql',
|
|
name: snippet.name,
|
|
description: snippet.description ?? undefined,
|
|
visibility: snippet.visibility,
|
|
project_id: snippet.project_id,
|
|
owner_id: snippet.owner_id,
|
|
folder_id: selectedId === 'root' ? null : folderId,
|
|
content: snippetContent,
|
|
},
|
|
})
|
|
if (IS_PLATFORM) {
|
|
snapV2.updateSnippet({
|
|
id: snippet.id,
|
|
snippet: { ...snippet, folder_id: selectedId === 'root' ? null : folderId },
|
|
skipSave: true,
|
|
})
|
|
} else if (movedSnippet) {
|
|
// On selfhosted, we need to update the state with the moved snippet because the snippet depends on the
|
|
// folder_id the moved snippet has a different id than the original snippet.
|
|
|
|
// remove the old snippet from the state without saving to API
|
|
snapV2.removeSnippet(snippet.id, true)
|
|
|
|
snapV2.addSnippet({ projectRef: ref, snippet: movedSnippet })
|
|
|
|
// remove the tab for the old snippet if the snippet was open. Moving can also happen when the tab is not open.
|
|
const tabId = createTabId('sql', { id: snippet.id })
|
|
if (tabsSnap.hasTab(tabId)) {
|
|
tabsSnap.removeTab(tabId)
|
|
await navigateToUrl(navigate, `/project/${ref}/sql/${movedSnippet.id}`)
|
|
}
|
|
}
|
|
}
|
|
})
|
|
)
|
|
|
|
if (movedSnippetCount > 0) {
|
|
track(
|
|
'sql_editor_snippet_folder_updated',
|
|
{ snippetCount: movedSnippetCount, toNewFolder: selectedId === 'new-folder' },
|
|
{ project: ref }
|
|
)
|
|
}
|
|
|
|
toast.success(
|
|
`Successfully moved ${snippets.length === 1 ? `"${snippets[0].name}"` : `${snippets.length} snippets`} to ${selectedId === 'root' ? 'the root of the editor' : selectedFolder}`
|
|
)
|
|
|
|
onClose()
|
|
} catch (error: any) {
|
|
// error will be handled by the mutation's onError callback
|
|
console.error('Error moving snippets:', error)
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (visible && snippets !== undefined) {
|
|
if (snippets.length === 1) {
|
|
setSelectedId(snippets[0].folder_id ?? 'root')
|
|
} else {
|
|
setSelectedId('root')
|
|
}
|
|
form.reset({ name: '' })
|
|
}
|
|
}, [visible, snippets])
|
|
|
|
return (
|
|
<Dialog open={visible} onOpenChange={() => onClose()}>
|
|
<DialogContent>
|
|
<Form {...form}>
|
|
<form id="move-snippet" onSubmit={form.handleSubmit(onConfirmMove)}>
|
|
<DialogHeader>
|
|
<DialogTitle>
|
|
Move{' '}
|
|
{snippets.length === 1 ? (
|
|
<span>{`"${snippets[0].name}"`}</span>
|
|
) : (
|
|
<span>{`${snippets.length}`}</span>
|
|
)}{' '}
|
|
<span>snippet</span>
|
|
{snippets.length > 1 ? <span>s</span> : ''} <span>to a folder</span>
|
|
</DialogTitle>
|
|
<DialogDescription>
|
|
Select which folder to move your quer
|
|
{snippets.length > 1 ? <span>ies</span> : <span>y</span>} <span>to</span>
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<DialogSectionSeparator />
|
|
|
|
<DialogSection className="py-5 flex flex-col gap-y-4">
|
|
<div className="flex flex-col gap-y-2">
|
|
<Label className="text-foreground-light">Select a folder</Label>
|
|
<Popover open={open} onOpenChange={setOpen} modal={false}>
|
|
<PopoverTrigger asChild>
|
|
<Button
|
|
block
|
|
size="small"
|
|
className="pr-2 justify-between"
|
|
iconRight={
|
|
<CodeIcon
|
|
className="text-foreground-light rotate-90"
|
|
strokeWidth={2}
|
|
size={12}
|
|
/>
|
|
}
|
|
>
|
|
<div className="flex items-center space-x-2">
|
|
{selectedFolder}
|
|
{isCurrentFolder && <span>{` (Current)`}</span>}
|
|
</div>
|
|
</Button>
|
|
</PopoverTrigger>
|
|
<PopoverContent className="p-0" side="bottom" align="start" sameWidthAsTrigger>
|
|
<Command>
|
|
<CommandInput placeholder="Find folder..." />
|
|
<CommandList>
|
|
<CommandEmpty>No folders found</CommandEmpty>
|
|
<CommandGroup>
|
|
<ScrollArea className={(folders || []).length > 6 ? 'h-[210px]' : ''}>
|
|
<CommandItem
|
|
key="root"
|
|
value="root"
|
|
className="cursor-pointer w-full justify-between"
|
|
onSelect={() => {
|
|
setOpen(false)
|
|
setSelectedId('root')
|
|
}}
|
|
onClick={() => {
|
|
setOpen(false)
|
|
setSelectedId('root')
|
|
}}
|
|
>
|
|
<span>
|
|
Root of the editor
|
|
{snippets.length === 1 && snippets[0].folder_id === null && (
|
|
<span>{` (Current)`}</span>
|
|
)}
|
|
</span>
|
|
{selectedId === 'root' && <CheckIcon size={14} />}
|
|
</CommandItem>
|
|
{folders?.map((folder) => (
|
|
<CommandItem
|
|
key={folder.id}
|
|
value={folder.name}
|
|
className="cursor-pointer w-full justify-between"
|
|
onSelect={() => {
|
|
setOpen(false)
|
|
setSelectedId(folder.id)
|
|
}}
|
|
onClick={() => {
|
|
setOpen(false)
|
|
setSelectedId(folder.id)
|
|
}}
|
|
>
|
|
<span>
|
|
{folder.name}
|
|
{snippets.length === 1 && snippets[0].folder_id === folder.id && (
|
|
<span>{` (Current)`}</span>
|
|
)}
|
|
</span>
|
|
{folder.id === selectedId && <CheckIcon size={14} />}
|
|
</CommandItem>
|
|
))}
|
|
</ScrollArea>
|
|
</CommandGroup>
|
|
<CommandSeparator />
|
|
<CommandGroup>
|
|
<CommandItem
|
|
className="cursor-pointer w-full justify-start gap-x-2"
|
|
onSelect={(_e) => {
|
|
setOpen(false)
|
|
setSelectedId('new-folder')
|
|
}}
|
|
onClick={() => {
|
|
setOpen(false)
|
|
setSelectedId('new-folder')
|
|
}}
|
|
>
|
|
<PlusIcon size={14} strokeWidth={1.5} />
|
|
<p>New folder</p>
|
|
</CommandItem>
|
|
</CommandGroup>
|
|
</CommandList>
|
|
</Command>
|
|
</PopoverContent>
|
|
</Popover>
|
|
</div>
|
|
|
|
{selectedId === 'new-folder' && (
|
|
<div className="flex flex-col gap-y-2">
|
|
<FormField
|
|
name="name"
|
|
control={form.control}
|
|
render={({ field }) => (
|
|
<FormItem className="flex flex-col gap-y-2">
|
|
<FormLabel>Provide a name for your new folder</FormLabel>
|
|
<FormControl>
|
|
<Input
|
|
autoFocus
|
|
{...field}
|
|
autoComplete="off"
|
|
disabled={isMovingSnippet || isCreatingFolder}
|
|
/>
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
</div>
|
|
)}
|
|
</DialogSection>
|
|
|
|
<DialogFooter>
|
|
<Button disabled={isMovingSnippet || isCreatingFolder} onClick={() => onClose()}>
|
|
Cancel
|
|
</Button>
|
|
<Button
|
|
variant="primary"
|
|
type="submit"
|
|
disabled={isMovingToSameFolder}
|
|
loading={isMovingSnippet || isCreatingFolder}
|
|
>
|
|
Move file
|
|
</Button>
|
|
</DialogFooter>
|
|
</form>
|
|
</Form>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|