import { createRootRoute, createRoute, RouterContextProvider } from '@tanstack/react-router' import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { LOCAL_STORAGE_KEYS } from 'common' import { useState, type ReactNode } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MobileSheetProvider, useMobileSheet } from '../Navigation/NavigationBar/MobileSheetContext' import { ProjectLayout } from './index' import type { MobileMenuContentProps } from './LayoutHeader/MobileMenuContent' import { STUDIO_PAGE_TITLE_SEPARATOR } from '@/lib/page-title' import { createTestRouter } from '@/tests/lib/custom-render' const { mockRoute, mockSetSelectedDatabaseId, mockSetMobileMenuOpen, mockViewport, mockMainScrollContainer, } = vi.hoisted(() => ({ mockRoute: { url: '/project/default/observability/query-performance' }, mockSetSelectedDatabaseId: vi.fn(), mockSetMobileMenuOpen: vi.fn(), mockViewport: { isMobile: false }, mockMainScrollContainer: { current: null as { scrollTo: ReturnType } | null }, })) const { mockAddBanner, mockDismissBanner, mockProjectState, mockOrgPlanState, mockBannerDismissedState, mockUseLocalStorageQuery, } = vi.hoisted(() => ({ mockAddBanner: vi.fn(), mockDismissBanner: vi.fn(), mockProjectState: { current: { ref: 'default', name: 'Project 1', status: 'ACTIVE_HEALTHY', postgrestStatus: 'ONLINE', infra_compute_size: undefined as string | undefined, integration_source: null as string | null, }, }, mockOrgPlanState: { current: { id: 'pro', name: 'Pro' } as { id: string; name: string } | undefined, }, mockBannerDismissedState: { current: false }, mockUseLocalStorageQuery: vi.fn(), })) vi.mock('common', () => ({ useParams: () => ({ ref: 'default' }), mergeRefs: (..._refs: any[]) => (_value: unknown) => {}, IS_PLATFORM: false, LOCAL_STORAGE_KEYS: { FREE_MICRO_UPGRADE_BANNER_DISMISSED_AT: (ref: string) => `free-micro-upgrade-banner-dismissed-at-${ref}`, PROJECT_INTEGRATION_BANNER_DISMISSED: (ref: string, integrationSource: string) => `project-integration-banner-dismissed-${ref}-${integrationSource}`, }, isFeatureEnabled: () => false, useFlag: () => false, })) vi.mock('motion/react', () => ({ AnimatePresence: ({ children }: { children: ReactNode }) => <>{children}, motion: { div: ({ children, ...props }: any) =>
{children}
, create: (Component: any) => Component, }, })) vi.mock('ui', async () => ({ ...(await import('ui/src/components/shadcn/ui/resizable')), cn: (...classes: Array) => classes.filter(Boolean).join(' '), Alert: ({ children, ...props }: any) =>
{children}
, AlertDescription: ({ children, ...props }: any) =>
{children}
, AlertTitle: ({ children, ...props }: any) =>
{children}
, CommandInput: { displayName: 'CommandInput' }, Command: { displayName: 'Command' }, CommandGroup: { displayName: 'CommandGroup' }, CommandItem: { displayName: 'CommandItem' }, CommandList: { displayName: 'CommandList' }, LogoLoader: () =>
, Sidebar: ({ children, ...props }: any) =>
{children}
, SidebarContent: ({ children, ...props }: any) =>
{children}
, SidebarFooter: ({ children, ...props }: any) =>
{children}
, SidebarGroup: ({ children, ...props }: any) =>
{children}
, SidebarMenu: ({ children, ...props }: any) =>
{children}
, SidebarMenuButton: (props: any) =>
, SidebarMenuItem: (props: any) =>
, useIsMobile: () => mockViewport.isMobile, useSidebar: () => ({ setOpen: vi.fn() }), })) vi.mock('ui-patterns/MobileSheetNav/MobileSheetNav', () => ({ default: ({ children }: { children: ReactNode }) => <>{children}, })) vi.mock('../editors/EditorsLayout.hooks', () => ({ useEditorType: () => undefined, })) vi.mock('../MainScrollContainerContext', () => ({ useMainScrollContainer: () => mockMainScrollContainer.current, useSetMainScrollContainer: () => () => {}, })) vi.mock('./BuildingState', () => ({ default: () => null })) vi.mock('./ConnectingState', () => ({ default: () => null })) vi.mock('./LoadingState', () => ({ LoadingState: () => null })) vi.mock('./PausedState/ProjectPausedState', () => ({ ProjectPausedState: () =>
Project paused
, })) vi.mock('./PauseFailedState', () => ({ PauseFailedState: () => null })) vi.mock('./PausingState', () => ({ PausingState: () => null })) vi.mock('./ProductMenuBar', () => ({ ProductMenuBar: ({ children }: { children: ReactNode }) => <>{children}, })) vi.mock('./ResizingState', () => ({ ResizingState: () => null })) vi.mock('./RestartingState', () => ({ default: () => null })) vi.mock('./RestoreFailedState', () => ({ RestoreFailedState: () => null })) vi.mock('./RestoringState', () => ({ RestoringState: () => null })) vi.mock('./UpgradingState', () => ({ UpgradingState: () => null })) vi.mock('@/components/interfaces/BranchManagement/CreateBranchModal', () => ({ CreateBranchModal: () => null, })) vi.mock('@/components/interfaces/ProjectAPIDocs/ProjectAPIDocs', () => ({ ProjectAPIDocs: () => null, })) vi.mock('@/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner', () => ({ ResourceExhaustionWarningBanner: () => null, })) vi.mock('@/components/ui/ButtonTooltip', () => ({ ButtonTooltip: ({ children, ...props }: any) => ( ), })) vi.mock('@/components/ui/PartnerIcon', () => ({ default: () =>
, })) vi.mock('@/hooks/custom-content/useCustomContent', () => ({ useCustomContent: () => ({ appTitle: 'Supabase' }), })) vi.mock('@/hooks/misc/useLocalStorage', () => ({ useLocalStorageQuery: (...args: unknown[]) => mockUseLocalStorageQuery(...args), })) vi.mock('@/components/ui/BannerStack/BannerStackProvider', () => ({ BANNER_ID: { FREE_MICRO_UPGRADE: 'free-micro-upgrade-banner', }, useBannerStack: () => ({ addBanner: mockAddBanner, dismissBanner: mockDismissBanner, banners: [], }), })) vi.mock('@/components/ui/BannerStack/Banners/BannerFreeMicroUpgrade', () => ({ BannerFreeMicroUpgrade: () => null, })) vi.mock('@/data/usage/resource-warnings-query', () => ({})) vi.mock('@/hooks/misc/useSelectedOrganization', () => ({ useSelectedOrganizationQuery: () => ({ data: { name: 'Organization 1', slug: 'org-1', plan: mockOrgPlanState.current }, }), })) vi.mock('@/hooks/misc/useSelectedProject', () => ({ useSelectedProjectQuery: () => ({ data: mockProjectState.current }), })) vi.mock('@/hooks/misc/withAuth', () => ({ withAuth: (Component: any) => Component, })) vi.mock('@/hooks/ui/useFlag', () => ({ usePHFlag: () => undefined, })) vi.mock('@/state/app-state', () => ({ useAppStateSnapshot: () => ({ mobileMenuOpen: false, showSidebar: false, setMobileMenuOpen: mockSetMobileMenuOpen, }), })) vi.mock('@/state/database-selector', () => ({ useDatabaseSelectorStateSnapshot: () => ({ setSelectedDatabaseId: mockSetSelectedDatabaseId, }), })) vi.mock('./LayoutHeader/MobileMenuContent', async (importOriginal) => { const actual = await importOriginal() return { ...actual, MobileMenuContent: ({ currentProductMenuHeader, currentProductMenu, }: MobileMenuContentProps) => (
{currentProductMenuHeader} {currentProductMenu}
), } }) vi.mock('../Navigation/ProductMenuBar', () => ({ ProductMenuBar: ({ children }: { children: ReactNode }) => <>{children}, })) const MobileSheetHarness = () => { const { content, openMenu, setContent } = useMobileSheet() return ( <>
{content}
) } const ResourceMenuHarness = () => { const [section, setSection] = useState('Explorer') return ( <> {section} header} productMenu={ } >
) } const createProjectRouter = async () => { const rootRoute = createRootRoute() const routes = [ '/project/$ref', '/project/$ref/branches', '/project/$ref/observability/query-performance', ].map((path) => createRoute({ getParentRoute: () => rootRoute, path })) const router = createTestRouter(mockRoute.url, rootRoute.addChildren(routes)) await router.load() return router } const renderWithRouter = async (ui: ReactNode) => { const router = await createProjectRouter() return render({ui}) } const renderLayout = () => renderWithRouter(
) describe('ProjectLayout title', () => { beforeEach(() => { mockViewport.isMobile = false mockMainScrollContainer.current = null mockRoute.url = '/project/default/observability/query-performance' document.title = '' mockProjectState.current = { ref: 'default', name: 'Project 1', status: 'ACTIVE_HEALTHY', postgrestStatus: 'ONLINE', infra_compute_size: undefined, integration_source: null, } mockBannerDismissedState.current = false mockUseLocalStorageQuery.mockImplementation(() => [ mockBannerDismissedState.current ? new Date().toISOString() : null, vi.fn(), { isSuccess: true }, ]) }) afterEach(() => { document.title = '' }) it('updates the open mobile menu when resource navigation changes without replacing other sheets', async () => { mockViewport.isMobile = true await renderWithRouter( ) expect(screen.getByTestId('mobile-sheet')).toBeEmptyDOMElement() fireEvent.click(screen.getByRole('button', { name: 'Open menu' })) expect(screen.getByText('Explorer header')).toBeInTheDocument() fireEvent.click(screen.getByRole('button', { name: 'Open notebooks' })) expect(screen.getByText('Notebooks header')).toBeInTheDocument() fireEvent.click(screen.getByRole('button', { name: 'Return to Explorer' })) expect(screen.getByText('Explorer header')).toBeInTheDocument() fireEvent.click(screen.getByRole('button', { name: 'Open other sheet' })) fireEvent.click(screen.getByRole('button', { name: 'Change section' })) expect(screen.getByTestId('mobile-sheet')).toHaveTextContent('Other sheet') }) it.each([false, true])( 'keeps sidebar navigation enabled with resizableSidebar=%s and preserves handle availability', async (resizableSidebar) => { await renderWithRouter( Tables} >
Page Content
) const link = screen.getByRole('link', { name: 'Tables' }) expect(link.closest('[aria-disabled="true"]')).toBeNull() link.focus() expect(link).toHaveFocus() const handle = screen.getByRole('separator') if (resizableSidebar) { expect(handle).not.toHaveAttribute('aria-disabled') expect(handle).toHaveAttribute('tabindex', '0') } else { expect(handle).toHaveAttribute('aria-disabled', 'true') expect(handle).not.toHaveAttribute('tabindex') } } ) it('sets a composed document title and deduplicates identical section/surface labels', async () => { await renderWithRouter(
Page Content
) await waitFor(() => { expect(document.title).toBe( ['Settings', 'Project 1', 'Organization 1', 'Supabase'].join(STUDIO_PAGE_TITLE_SEPARATOR) ) }) }) it('prefers entity-first browserTitle metadata when provided', async () => { await renderWithRouter(
Page Content
) await waitFor(() => { expect(document.title).toBe( ['users', 'Tables', 'Database', 'Project 1', 'Organization 1', 'Supabase'].join( STUDIO_PAGE_TITLE_SEPARATOR ) ) }) }) it('renders the Stripe project banner with a project-specific dismiss key when the selected project is Stripe-connected', async () => { mockProjectState.current = { ...mockProjectState.current, integration_source: 'stripe_projects', } await renderLayout() expect(screen.getByText('This project is connected to Stripe')).toBeInTheDocument() expect( screen.getByText('Changes made here may affect your connected Stripe project.') ).toBeInTheDocument() expect(screen.getByTestId('partner-icon')).toBeInTheDocument() expect(mockUseLocalStorageQuery).toHaveBeenCalledWith( LOCAL_STORAGE_KEYS.PROJECT_INTEGRATION_BANNER_DISMISSED('default', 'stripe_projects'), false ) }) it('renders the paused state for a paused project', async () => { mockProjectState.current = { ...mockProjectState.current, status: 'INACTIVE' } await renderLayout() expect(screen.getByText('Project paused')).toBeInTheDocument() }) it('renders the branches page instead of the paused state for a paused project', async () => { mockProjectState.current = { ...mockProjectState.current, status: 'INACTIVE' } mockRoute.url = '/project/default/branches' await renderLayout() expect(screen.queryByText('Project paused')).not.toBeInTheDocument() }) describe('main scroll reset', () => { const scrollTo = vi.fn() beforeEach(() => { scrollTo.mockClear() mockMainScrollContainer.current = { scrollTo } }) afterEach(() => { window.history.replaceState(null, '', window.location.pathname) document.getElementById('sms-mfa')?.remove() }) it('scrolls to the top on navigation', async () => { await renderLayout() expect(scrollTo).toHaveBeenCalledWith({ top: 0, left: 0 }) }) it('leaves the position to HashScrollController when the hash target is on the page', async () => { window.history.replaceState(null, '', '#sms-mfa') document.body.append(Object.assign(document.createElement('section'), { id: 'sms-mfa' })) await renderLayout() expect(scrollTo).not.toHaveBeenCalled() }) it('still scrolls to the top when nothing on the page matches the hash', async () => { window.history.replaceState(null, '', '#sms-mfa') await renderLayout() expect(scrollTo).toHaveBeenCalledWith({ top: 0, left: 0 }) }) }) }) describe('FREE_MICRO_UPGRADE banner', () => { beforeEach(() => { mockRoute.url = '/project/default' mockProjectState.current = { ref: 'default', name: 'Project 1', status: 'ACTIVE_HEALTHY', postgrestStatus: 'ONLINE', infra_compute_size: 'nano', integration_source: null, } mockBannerDismissedState.current = false }) afterEach(() => { mockRoute.url = '/project/default/observability/query-performance' mockProjectState.current = { ref: 'default', name: 'Project 1', status: 'ACTIVE_HEALTHY', postgrestStatus: 'ONLINE', infra_compute_size: undefined, integration_source: null, } mockOrgPlanState.current = { id: 'pro', name: 'Pro' } mockBannerDismissedState.current = false }) it('calls addBanner when a paid-plan project is nano', async () => { await renderLayout() await waitFor(() => { expect(mockAddBanner).toHaveBeenCalledWith( expect.objectContaining({ id: 'free-micro-upgrade-banner' }) ) }) }) it.each([ [ 'the banner was previously dismissed', () => { mockBannerDismissedState.current = true }, ], [ 'the project is not nano compute', () => { mockProjectState.current = { ...mockProjectState.current, infra_compute_size: 'micro' } }, ], [ 'the organization is on the free plan', () => { mockOrgPlanState.current = { id: 'free', name: 'Free' } }, ], [ 'the organization plan is not loaded yet', () => { mockOrgPlanState.current = undefined }, ], ])('calls dismissBanner instead of addBanner when %s', async (_, arrange) => { arrange() await renderLayout() await waitFor(() => { expect(mockDismissBanner).toHaveBeenCalledWith('free-micro-upgrade-banner') }) expect(mockAddBanner).not.toHaveBeenCalledWith( expect.objectContaining({ id: 'free-micro-upgrade-banner' }) ) }) })