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(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 ( <> {!isCollapseButtonHidden && } {/* Pinned outside the scrollable segment below, so it never scrolls out of view. */} {customTabs}
tab.id)} strategy={horizontalListSortingStrategy} > {editorTabs.map((tab, index) => ( handleClose(tab.id)} /> handleClose(tab.id)}>Close handleCloseOthers(tab.id)}> Close Others handleCloseRight(tab.id)}> Close to the Right Close All ))} {/* Non-draggable new tab */} {hasNewTab && (
{ 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' )} >
New
{/* Reserve close-icon width; close is a sibling overlay. */}
)} {!hasNewTab && (newTabButton ?? ( 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 }} > ))}
{tabs.activeTab ? : null} { if (isOptOutChecked) pendingConfirmation?.optOut?.onOptOut() pendingClose?.() resetPendingClose() }} onCancel={resetPendingClose} title={pendingConfirmation?.title ?? 'Unsaved changes'} description={pendingConfirmation?.description} > {pendingConfirmation?.optOut && ( setIsOptOutChecked(!!value)} /> )} ) }