mirror of
https://github.com/supabase/supabase.git
synced 2026-12-06 08:29:01 +00:00
Part 3 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 ← this PR** | **`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 | Migrates all `apps/studio/components/layouts/**` files and the studio tab router integration off `next/router`. **Added:** - `useTabRouter()` in `apps/studio/state/tabs.tsx` so tab state actions navigate via TanStack's `useNavigate` + `navigateToUrl` instead of taking a `NextRouter` instance **Changed:** - Replaced `useRouter` across all layout directories (`AccountLayout`, `AdvisorsLayout`, `AppLayout`, `AuthLayout`, `BranchLayout`, `ComputeLayout`, `DatabaseLayout`, `DefaultLayout`, `EdgeFunctionsLayout`, `ExplorerLayout`, `LogsLayout`, `Navigation/*`, `ObservabilityLayout`, `OrganizationLayout`, `ProjectLayout`, `ProjectNeedsSecuring`, `ProjectSettingsLayout`, `RealtimeLayout`, `SQLEditorLayout`, `SignInLayout`, and `Tabs`) with TanStack Router hooks (`useNavigate`, `useLocation`, `useRoutePattern`) and `useParams` from `common` - Updated `ProjectDropdown.utils.ts` and `ProjectDropdown.test.ts` to work with TanStack `$param` route templates - Updated layout component tests (`AccountLayout.selfhosted.test.tsx`, `AdvisorsNavigationShortcuts.test.tsx`, `BranchLink.test.tsx`, `ExplorerLayout.test.tsx`, `ExplorerNavChats.test.tsx`, `ObservabilityMenu.utils.test.tsx`, `MobileIssuesNavigation.platform.test.tsx`, `ProjectLayout/index.test.tsx`, `ProjectNeedsSecuring.test.tsx`, `ProjectDropdown.test.tsx`) **Simplified:** - `OrganizationLayout` and `SettingsLayout` match against `useRoutePattern()` instead of the real pathname. An org slug ending in a settings segment (e.g. `acmeapps`) no longer gets the settings title. - `ProjectSettings.Commands` opens the Connect sheet through nuqs, the same way `Connect.Commands` does - `OrgMenuContent`, `OrganizationSettingsMenu` and `useTabRouter` read `orgSlug`/`schema` from `useParams` instead of casting `location.search` - Removed the dead `getPathnameWithoutQuery` helpers and their tests - `usePreservedQueryParams` builds its string in the `useLocation` selector (no `useMemo`), and `UnhealthyState` only navigates when `ref` is set - Moved `MobileIssuesNavigation.platform.test.tsx` onto a TanStack test router. It now covers the active-route logic again. - Tests use the shared `createTestRouter` and `customRender` router Addresses [FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks) ## To test - [ ] Switching projects, organizations, and branches from the top header dropdowns preserves the current sub-route where supported - [ ] Opening, switching, and closing Table Editor / SQL Editor tabs updates the URL and active tab cleanly - [ ] Active sidebar item highlighting works across Database, Auth, Edge Functions, Observability, Logs, Realtime, Explorer, and Project Settings layouts - [ ] Mobile navigation menu and floating toolbar sheets open and navigate properly --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
368 lines
13 KiB
TypeScript
368 lines
13 KiB
TypeScript
import {
|
|
DndContext,
|
|
DragEndEvent,
|
|
DragOverlay,
|
|
PointerSensor,
|
|
useSensor,
|
|
useSensors,
|
|
} from '@dnd-kit/core'
|
|
import { horizontalListSortingStrategy, SortableContext } from '@dnd-kit/sortable'
|
|
import { useLocation } from '@tanstack/react-router'
|
|
import { useParams } from 'common'
|
|
import { PlusIcon, XIcon } from 'lucide-react'
|
|
import { AnimatePresence, motion } from 'motion/react'
|
|
import { ReactNode, useState } from 'react'
|
|
import {
|
|
Checkbox,
|
|
cn,
|
|
ContextMenu,
|
|
ContextMenuContent,
|
|
ContextMenuItem,
|
|
ContextMenuTrigger,
|
|
Tabs,
|
|
TabsList,
|
|
TabsTrigger,
|
|
} from 'ui'
|
|
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
|
|
|
|
import { useEditorType } from '../editors/EditorsLayout.hooks'
|
|
import { CollapseButton } from './CollapseButton'
|
|
import { SortableTab } from './SortableTab'
|
|
import { TabPreview } from './TabPreview'
|
|
import { useTabsScroll } from './Tabs.utils'
|
|
import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'
|
|
import { useDashboardHistory } from '@/hooks/misc/useDashboardHistory'
|
|
import { useTrack } from '@/lib/telemetry/track'
|
|
import {
|
|
editorEntityTypes,
|
|
useTabRouter,
|
|
useTabsStateSnapshot,
|
|
type Tab,
|
|
type TabCloseConfirmation,
|
|
} from '@/state/tabs'
|
|
|
|
interface EditorTabsProps {
|
|
customTabs?: ReactNode
|
|
newTabButton?: ReactNode
|
|
isCollapseButtonHidden?: boolean
|
|
onTabChange?: (id: string) => void
|
|
}
|
|
|
|
// [Joshen] Will be adjusting this component to support Explorer
|
|
// Will require quite a bit of cleaning up once Explorer supersedes SQL Editor
|
|
export const EditorTabs = ({
|
|
customTabs,
|
|
newTabButton,
|
|
isCollapseButtonHidden,
|
|
onTabChange,
|
|
}: EditorTabsProps) => {
|
|
const { ref } = useParams()
|
|
const router = useTabRouter()
|
|
const hasNewTab = useLocation({ select: (location) => location.href.includes('/new') })
|
|
const { setLastVisitedSnippet, setLastVisitedTable, setLastVisitedExplorerTab } =
|
|
useDashboardHistory()
|
|
|
|
const editor = useEditorType()
|
|
const track = useTrack()
|
|
const tabs = useTabsStateSnapshot()
|
|
const [pendingClose, setPendingClose] = useState<(() => void) | null>(null)
|
|
const [pendingConfirmation, setPendingConfirmation] = useState<TabCloseConfirmation | null>(null)
|
|
const [isOptOutChecked, setIsOptOutChecked] = useState(false)
|
|
const sensors = useSensors(
|
|
useSensor(PointerSensor, {
|
|
activationConstraint: {
|
|
distance: 1, // Start with a very small distance
|
|
},
|
|
})
|
|
)
|
|
|
|
const openTabs = tabs.openTabs
|
|
.map((id) => tabs.tabsMap[id])
|
|
.filter((tab) => tab !== undefined) as Tab[]
|
|
|
|
// Filter by editor type - only show SQL tabs for SQL editor and table tabs for table editor
|
|
const editorTabs = !!editor
|
|
? openTabs.filter((tab) => editorEntityTypes[editor]?.includes(tab.type))
|
|
: []
|
|
const editorTabIds = editorTabs.map((tab) => tab.id)
|
|
|
|
const handleDragEnd = (event: DragEndEvent) => {
|
|
const { active, over } = event
|
|
if (!over || active.id === over.id) return
|
|
|
|
const oldIndex = tabs.openTabs.indexOf(active.id.toString())
|
|
const newIndex = tabs.openTabs.indexOf(over.id.toString())
|
|
|
|
if (oldIndex !== newIndex) {
|
|
tabs.handleTabDragEnd(oldIndex, newIndex, active.id.toString(), router)
|
|
}
|
|
}
|
|
|
|
const onClearDashboardHistory = () => {
|
|
if (editor === 'table') {
|
|
setLastVisitedTable(undefined)
|
|
}
|
|
if (editor === 'sql') {
|
|
setLastVisitedSnippet(undefined)
|
|
}
|
|
if (editor === 'explorer') {
|
|
setLastVisitedExplorerTab(undefined)
|
|
}
|
|
}
|
|
|
|
// Runs `performClose` immediately unless one of the tabs' registered close
|
|
// handlers asks to confirm first (e.g. a SQL snippet with unsaved edits), in
|
|
// which case a confirmation dialog is shown and `performClose` only runs if
|
|
// the user confirms. The layout stays agnostic of per-type close semantics.
|
|
const closeWithConfirmation = (tabIdsToClose: string[], performClose: () => void) => {
|
|
const confirmation = tabs.getCloseConfirmation(tabIdsToClose)
|
|
if (confirmation) {
|
|
setPendingConfirmation(confirmation)
|
|
setPendingClose(() => performClose)
|
|
} else {
|
|
performClose()
|
|
}
|
|
}
|
|
|
|
const resetPendingClose = () => {
|
|
setPendingClose(null)
|
|
setPendingConfirmation(null)
|
|
setIsOptOutChecked(false)
|
|
}
|
|
|
|
const trackTabClosed = (closeType: 'single' | 'others' | 'right' | 'all') => {
|
|
if (editor) track('editor_tab_closed', { closeType, editor })
|
|
}
|
|
|
|
const handleClose = (tabId: string) => {
|
|
closeWithConfirmation([tabId], () => {
|
|
trackTabClosed('single')
|
|
tabs.handleTabClose({ id: tabId, router, editor, onClearDashboardHistory })
|
|
})
|
|
}
|
|
|
|
const handleCloseAll = () => {
|
|
if (editor) {
|
|
const tabsToClose = editorTabIds
|
|
|
|
closeWithConfirmation(tabsToClose, () => {
|
|
trackTabClosed('all')
|
|
tabs.closeTabs(tabsToClose)
|
|
onClearDashboardHistory()
|
|
const editorPath = editor === 'table' ? 'editor' : editor
|
|
router.push(`/project/${ref}/${editorPath}`)
|
|
})
|
|
}
|
|
}
|
|
|
|
const handleCloseOthers = (tabId: string) => {
|
|
if (editor) {
|
|
const tabsToClose = editorTabIds.filter((id) => id !== tabId)
|
|
|
|
closeWithConfirmation(tabsToClose, () => {
|
|
if (tabsToClose.length > 0) trackTabClosed('others')
|
|
tabs.closeTabs(tabsToClose)
|
|
onClearDashboardHistory()
|
|
|
|
if (tabs.activeTab !== tabId) tabs.handleTabNavigation(tabId, router)
|
|
})
|
|
}
|
|
}
|
|
|
|
const handleCloseRight = (tabId: string) => {
|
|
if (editor) {
|
|
const openedTabs = editorTabIds
|
|
const tabIdx = openedTabs.indexOf(tabId)
|
|
const activeTabIdx = openedTabs.indexOf(tabs.activeTab!)
|
|
const tabsToClose = openedTabs.slice(tabIdx + 1)
|
|
|
|
closeWithConfirmation(tabsToClose, () => {
|
|
if (tabsToClose.length > 0) trackTabClosed('right')
|
|
tabs.closeTabs(tabsToClose)
|
|
|
|
const isActiveTabClosed = tabIdx < activeTabIdx
|
|
if (isActiveTabClosed) {
|
|
tabs.handleTabNavigation(tabId, router)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
const handleTabChange = (id: string) => {
|
|
onTabChange?.(id)
|
|
tabs.handleTabNavigation(id, router)
|
|
}
|
|
|
|
const { tabsListRef } = useTabsScroll({ activeTab: tabs.activeTab, tabCount: editorTabs.length })
|
|
|
|
return (
|
|
<>
|
|
<DndContext sensors={sensors} onDragEnd={handleDragEnd}>
|
|
<Tabs
|
|
className="w-full flex"
|
|
value={hasNewTab ? 'new' : (tabs.activeTab ?? undefined)}
|
|
onValueChange={handleTabChange}
|
|
>
|
|
{!isCollapseButtonHidden && <CollapseButton hideTabs={false} />}
|
|
|
|
<TabsList
|
|
className={cn(
|
|
'rounded-b-none gap-0 min-h-(--header-height) flex items-center w-full z-1',
|
|
'bg-surface-200 dark:bg-alternative border-none text-clip'
|
|
)}
|
|
>
|
|
{/* Pinned outside the scrollable segment below, so it never scrolls out of view. */}
|
|
{customTabs}
|
|
|
|
<div
|
|
ref={tabsListRef}
|
|
className="flex items-center min-w-0 flex-1 h-full overflow-x-auto"
|
|
>
|
|
<SortableContext
|
|
items={editorTabs.map((tab) => tab.id)}
|
|
strategy={horizontalListSortingStrategy}
|
|
>
|
|
{editorTabs.map((tab, index) => (
|
|
<ContextMenu key={tab.id}>
|
|
<ContextMenuTrigger>
|
|
<SortableTab
|
|
key={tab.id}
|
|
tab={tab}
|
|
index={index}
|
|
openTabs={openTabs}
|
|
onClose={() => handleClose(tab.id)}
|
|
/>
|
|
</ContextMenuTrigger>
|
|
<ContextMenuContent>
|
|
<ContextMenuItem onClick={() => handleClose(tab.id)}>Close</ContextMenuItem>
|
|
<ContextMenuItem onClick={() => handleCloseOthers(tab.id)}>
|
|
Close Others
|
|
</ContextMenuItem>
|
|
<ContextMenuItem onClick={() => handleCloseRight(tab.id)}>
|
|
Close to the Right
|
|
</ContextMenuItem>
|
|
<ContextMenuItem onClick={handleCloseAll}>Close All</ContextMenuItem>
|
|
</ContextMenuContent>
|
|
</ContextMenu>
|
|
))}
|
|
</SortableContext>
|
|
|
|
{/* Non-draggable new tab */}
|
|
{hasNewTab && (
|
|
<div className="group/new-tab relative flex h-full items-center">
|
|
<TabsTrigger
|
|
value="new"
|
|
onKeyDown={(e) => {
|
|
if (e.key !== 'Delete' && e.key !== 'Backspace') return
|
|
e.preventDefault()
|
|
e.stopPropagation()
|
|
handleClose('new')
|
|
}}
|
|
className={cn(
|
|
'flex items-center gap-2 px-3 text-xs',
|
|
'bg-dash-sidebar/50 dark:bg-surface-100/50',
|
|
'data-[state=active]:bg-dash-sidebar dark:data-[state=active]:bg-surface-100',
|
|
'relative group h-full border-t-2 border-b-0!',
|
|
'hover:bg-surface-300 dark:hover:bg-surface-100'
|
|
)}
|
|
>
|
|
<PlusIcon size={16} strokeWidth={1.5} className={'text-foreground-lighter'} />
|
|
<div className="flex items-center gap-0">
|
|
<span>New</span>
|
|
</div>
|
|
{/* Reserve close-icon width; close is a sibling overlay. */}
|
|
<span className="ml-1 inline-flex size-3 shrink-0" aria-hidden />
|
|
<div className="absolute w-full -bottom-px left-0 right-0 h-px bg-dash-sidebar dark:bg-surface-100 opacity-0 group-data-[state=active]:opacity-100" />
|
|
</TabsTrigger>
|
|
<button
|
|
type="button"
|
|
tabIndex={0}
|
|
aria-label="Close new tab"
|
|
onClick={(e) => {
|
|
e.preventDefault()
|
|
e.stopPropagation()
|
|
handleClose('new')
|
|
}}
|
|
onMouseDown={(e) => {
|
|
e.preventDefault()
|
|
e.stopPropagation()
|
|
}}
|
|
onPointerDown={(e) => {
|
|
e.preventDefault()
|
|
e.stopPropagation()
|
|
}}
|
|
className={cn(
|
|
'absolute top-1/2 right-3 z-10 flex -translate-y-1/2 items-center justify-center rounded-xs',
|
|
'opacity-0 group-hover/new-tab:opacity-100 group-focus-within/new-tab:opacity-100 focus-visible:opacity-100',
|
|
'hover:bg-200 focus-ring',
|
|
'cursor-pointer'
|
|
)}
|
|
>
|
|
<XIcon size={12} className="text-foreground-light" />
|
|
</button>
|
|
</div>
|
|
)}
|
|
|
|
<AnimatePresence initial={false}>
|
|
{!hasNewTab &&
|
|
(newTabButton ?? (
|
|
<motion.button
|
|
className="flex items-center justify-center w-10 min-h-(--header-height) hover:bg-surface-100 shrink-0 border-b"
|
|
onClick={() =>
|
|
router.push(
|
|
`/project/${router.query.ref}/${editor === 'table' ? 'editor' : 'sql'}/new?skip=true`
|
|
)
|
|
}
|
|
initial={{ opacity: 0, scale: 0.8, x: -10 }}
|
|
animate={{ opacity: 1, scale: 1, x: 0 }}
|
|
transition={{ duration: 0.2 }}
|
|
>
|
|
<PlusIcon
|
|
size={16}
|
|
strokeWidth={1.5}
|
|
className="text-foreground-lighter hover:text-foreground-light"
|
|
/>
|
|
</motion.button>
|
|
))}
|
|
</AnimatePresence>
|
|
<div className="grow h-full border-b pr-6" />
|
|
</div>
|
|
</TabsList>
|
|
</Tabs>
|
|
|
|
<DragOverlay dropAnimation={null}>
|
|
{tabs.activeTab ? <TabPreview tab={tabs.activeTab} /> : null}
|
|
</DragOverlay>
|
|
</DndContext>
|
|
|
|
<DiscardChangesConfirmationDialog
|
|
visible={pendingClose !== null}
|
|
onClose={() => {
|
|
if (isOptOutChecked) pendingConfirmation?.optOut?.onOptOut()
|
|
pendingClose?.()
|
|
resetPendingClose()
|
|
}}
|
|
onCancel={resetPendingClose}
|
|
title={pendingConfirmation?.title ?? 'Unsaved changes'}
|
|
description={pendingConfirmation?.description}
|
|
>
|
|
{pendingConfirmation?.optOut && (
|
|
<FormItemLayout
|
|
isReactForm={false}
|
|
layout="flex"
|
|
name="optOutOfCloseConfirmation"
|
|
label={pendingConfirmation.optOut.label}
|
|
className="[&>div:first-child>button]:translate-y-0.5"
|
|
>
|
|
<Checkbox
|
|
id="optOutOfCloseConfirmation"
|
|
checked={isOptOutChecked}
|
|
onCheckedChange={(value) => setIsOptOutChecked(!!value)}
|
|
/>
|
|
</FormItemLayout>
|
|
)}
|
|
</DiscardChangesConfirmationDialog>
|
|
</>
|
|
)
|
|
}
|