Files
supabase/apps/studio/components/interfaces/Sidebar.tsx
anthony lio a66aa7417a fix(studio): sidebar collapsible (#53425)
## Problem

- in "Expanded" mode the nav icons sit 2px right of the logo center
- on page reload the sidebar starts collapsed and then plays the open
animation when previously opened

## Solution

- removes the extra padding kept for "Expanded" mode so the icons stay
on the logo center
- changes the sidebar to read the stored mode on the first render, so it
opens with no animation or layout jump
- fixes a sidebar that stays open after the user picks "Expand on hover"
in the account preferences

| before | after |
|
---------------------------------------------------------------------------
|
--------------------------------------------------------------------------
|
| <video
src="https://github.com/user-attachments/assets/36100073-6265-41b0-ab9a-1189d298b3bc"
/> | <video
src="https://github.com/user-attachments/assets/0d0a1f5f-fbd7-4bca-baae-3ac511f028c5"
/> |

## Preview links

| Site | Live | Preview | Search for |
| ------ |
------------------------------------------------------------------ |
--------------------------------------------------------------------------------------------------------------------
| ---------------- |
| Studio |
[/dashboard/project/\_](https://supabase.com/dashboard/project/_) |
[/dashboard/project/\_](https://studio-git-antlio-fix-studio-sidebar-shift-supabase.vercel.app/dashboard/project/_)
| Expand on hover |
| Studio |
[/dashboard/account/me](https://supabase.com/dashboard/account/me) |
[/dashboard/account/me](https://studio-git-antlio-fix-studio-sidebar-shift-supabase.vercel.app/dashboard/account/me)
| Sidebar behavior |

## Review instructions

1. open
[/dashboard/project/\_](https://studio-git-antlio-fix-studio-sidebar-shift-supabase.vercel.app/dashboard/project/_)
and select a project
2. open the sidebar control at the bottom of the sidebar and select
"Collapsed"
3. select "Expanded" in the sidebar control, and make sure that the
icons do not move to the side
4. reload the page, and make sure that the sidebar shows open at once
with no animation

## Checklist

Check all before review:

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
2026-11-16 13:11:51 +02:00

495 lines
15 KiB
TypeScript

import { LOCAL_STORAGE_KEYS, useFlag, useIsMFAEnabled, useMountEffect, useParams } from 'common'
import { Home } from 'icons'
import { isUndefined } from 'lodash'
import {
BlocksIcon,
BoxesIcon,
ChartAreaIcon,
PanelLeftDashedIcon,
ReceiptIcon,
SettingsIcon,
UsersIcon,
} from 'lucide-react'
import { AnimatePresence, motion, MotionProps } from 'motion/react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { ComponentProps, ComponentPropsWithoutRef, FC, ReactNode, useEffect } from 'react'
import {
Badge,
Button,
cn,
DropdownMenu,
DropdownMenuContent,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
Separator,
SidebarContent as SidebarContentPrimitive,
SidebarFooter,
SidebarGroup,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
Sidebar as SidebarPrimitive,
useSidebar,
} from 'ui'
import { Shortcut } from '../ui/Shortcut'
import { Route } from '../ui/ui.types'
import {
generateProductRoutes,
generateSettingsRoutes,
useGenerateOtherRoutes,
useGenerateToolRoutes,
} from '@/components/layouts/Navigation/NavigationBar/NavigationBar.utils'
import { ORG_SETTINGS_ROUTES } from '@/components/layouts/OrganizationLayout/OrganizationLayout.utils'
import { ProjectIndexPageLink } from '@/data/prefetchers/project.$ref'
import { useHideSidebar } from '@/hooks/misc/useHideSidebar'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { useLints } from '@/hooks/misc/useLints'
import { useLocalStorage, useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useTrack } from '@/lib/telemetry/track'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
export const ICON_SIZE = 32
export const ICON_STROKE_WIDTH = 1.5
export type SidebarBehaviourType = 'expandable' | 'open' | 'closed'
export const DEFAULT_SIDEBAR_BEHAVIOR = 'expandable'
const SidebarMotion = motion.create(SidebarPrimitive) as FC<
ComponentProps<typeof SidebarPrimitive> & {
transition?: MotionProps['transition']
}
>
export interface SidebarProps extends ComponentPropsWithoutRef<typeof SidebarPrimitive> {}
export const Sidebar = ({ className, ...props }: SidebarProps) => {
const { setOpen } = useSidebar()
const hideSideBar = useHideSidebar()
// useLocalStorageQuery returns data after the first render, so seed it with the stored value
const [storedBehavior] = useLocalStorage(
LOCAL_STORAGE_KEYS.SIDEBAR_BEHAVIOR,
DEFAULT_SIDEBAR_BEHAVIOR
)
const [sidebarBehaviour, setSidebarBehaviour] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.SIDEBAR_BEHAVIOR,
storedBehavior
)
// account pages keep the provider but not this component, so a hover-expand choice made there must close it here
useMountEffect(() => {
if (sidebarBehaviour === 'expandable') setOpen(false)
})
useEffect(() => {
// logic to toggle sidebar open based on sidebarBehaviour state
if (sidebarBehaviour === 'open') setOpen(true)
if (sidebarBehaviour === 'closed') setOpen(false)
}, [sidebarBehaviour, setOpen])
return (
<AnimatePresence>
{!hideSideBar && (
<SidebarMotion
{...props}
className={cn('z-50', className)}
transition={{ delay: 0.4, duration: 0.4 }}
overflowing={sidebarBehaviour === 'expandable'}
collapsible="icon"
variant="sidebar"
onMouseEnter={() => {
if (sidebarBehaviour === 'expandable') setOpen(true)
}}
onMouseLeave={() => {
if (sidebarBehaviour === 'expandable') setOpen(false)
}}
>
<SidebarContent
footer={
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="text"
className="w-min px-1.5 mx-0.5"
icon={<PanelLeftDashedIcon size={ICON_SIZE} strokeWidth={ICON_STROKE_WIDTH} />}
aria-label="Sidebar control"
/>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start" className="w-40">
<DropdownMenuRadioGroup
value={sidebarBehaviour}
onValueChange={(value) => setSidebarBehaviour(value as SidebarBehaviourType)}
>
<DropdownMenuLabel>Sidebar control</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuRadioItem value="open">Expanded</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="closed">Collapsed</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="expandable">
Expand on hover
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
}
/>
</SidebarMotion>
)}
</AnimatePresence>
)
}
export const SidebarContent = ({ footer }: { footer?: ReactNode }) => {
const { ref: projectRef } = useParams()
return (
<>
<AnimatePresence mode="wait">
<SidebarContentPrimitive>
{projectRef ? (
<motion.nav key="project-links">
<ProjectLinks />
</motion.nav>
) : (
<motion.nav
key="org-links"
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.2, ease: 'easeOut' }}
>
<OrganizationLinks />
</motion.nav>
)}
</SidebarContentPrimitive>
</AnimatePresence>
<SidebarFooter>
<SidebarGroup className="p-0">{footer}</SidebarGroup>
</SidebarFooter>
</>
)
}
export function SideBarNavLink({
route,
active,
onClick,
isLoading,
...props
}: {
route: Route
active?: boolean
onClick?: () => void
} & ComponentPropsWithoutRef<typeof SidebarMenuButton>) {
const router = useRouter()
const { state: sidebarState } = useSidebar()
const isActiveLink = !!(route.link && !route.disabled)
const hasShortcut = !!(route.shortcutId && isActiveLink)
// Collapsed: show immediately (replaces the old label-only tooltip
// that used to surface the name of an icon-only item). Expanded:
// slight delay so the tooltip doesn't flash while skimming the nav.
const shortcutPopoverDelay = sidebarState === 'collapsed' ? 0 : 1000
const buttonProps = {
disabled: route.disabled,
isActive: active,
isLoading,
className: 'text-sm',
size: 'default' as const,
onClick: onClick,
}
const content = props.children ? (
props.children
) : (
<>
{route.icon}
<span>{route.label}</span>
{route.isNew && (
<Badge
variant="success"
className="ml-auto shrink-0 px-1.5 py-0.5 text-[9px] uppercase tracking-wider"
>
New
</Badge>
)}
</>
)
const button = isActiveLink ? (
<SidebarMenuButton {...buttonProps} asChild>
<Link href={route.link!}>{content}</Link>
</SidebarMenuButton>
) : (
<SidebarMenuButton {...buttonProps}>{content}</SidebarMenuButton>
)
return (
<SidebarMenuItem>
{hasShortcut ? (
<Shortcut
label={
route.shortcutId === SHORTCUT_IDS.NAV_ADVISORS || route.key === 'explorer'
? `Go to ${route.label}`
: undefined
}
id={route.shortcutId!}
onTrigger={() => router.push(route.link!)}
side="right"
delayDuration={shortcutPopoverDelay}
>
{button}
</Shortcut>
) : (
button
)}
</SidebarMenuItem>
)
}
const ActiveDot = ({ hasErrors, hasWarnings }: { hasErrors: boolean; hasWarnings: boolean }) => {
return (
<div
className={cn(
'absolute pointer-events-none flex h-2 w-2 top-2 left-4.5 z-10 rounded-full',
hasErrors ? 'bg-destructive-600' : hasWarnings ? 'bg-warning-600' : 'bg-transparent'
)}
/>
)
}
const ProjectLinks = () => {
const router = useRouter()
const track = useTrack()
const { ref } = useParams()
const { data: project, isPending: isProjectPending } = useSelectedProjectQuery()
const { securityLints, errorLints } = useLints()
const activeRoute = router.pathname.split('/')[3]
const {
projectAuthAll: authEnabled,
projectEdgeFunctionAll: edgeFunctionsEnabled,
projectStorageAll: storageEnabled,
realtimeAll: realtimeEnabled,
} = useIsFeatureEnabled([
'project_auth:all',
'project_edge_function:all',
'project_storage:all',
'realtime:all',
])
const authOverviewPageEnabled = useFlag('authOverviewPage')
const computeEnabled = useFlag('compute')
const toolRoutes = useGenerateToolRoutes()
const productRoutes = generateProductRoutes(ref, project, {
auth: authEnabled,
edgeFunctions: edgeFunctionsEnabled,
storage: storageEnabled,
realtime: realtimeEnabled,
authOverviewPage: authOverviewPageEnabled,
compute: computeEnabled,
})
const otherRoutes = useGenerateOtherRoutes()
const settingsRoutes = generateSettingsRoutes(ref)
return (
<>
<SidebarGroup className="gap-0.5">
<SidebarMenu>
<SideBarNavLink
key="home"
active={isUndefined(activeRoute) && !isUndefined(router.query.ref)}
route={{
key: 'HOME',
label: 'Project Overview',
icon: <Home size={ICON_SIZE} strokeWidth={ICON_STROKE_WIDTH} />,
link: `/project/${ref}`,
linkElement: <ProjectIndexPageLink projectRef={ref} />,
shortcutId: SHORTCUT_IDS.NAV_HOME,
}}
/>
{toolRoutes.map((route, i) => (
<SideBarNavLink
key={`tools-routes-${i}`}
route={route}
active={activeRoute === route.key}
isLoading={isProjectPending}
onClick={
route.key === 'explorer' && activeRoute === 'sql'
? () => track('sql_editor_back_explorer_clicked')
: undefined
}
/>
))}
</SidebarMenu>
</SidebarGroup>
<Separator className="w-[calc(100%-1rem)] mx-auto" />
<SidebarGroup className="gap-0.5">
<SidebarMenu>
{productRoutes.map((route, i) => (
<SideBarNavLink
key={`product-routes-${i}`}
route={route}
active={activeRoute === route.key}
isLoading={isProjectPending}
/>
))}
</SidebarMenu>
</SidebarGroup>
<Separator className="w-[calc(100%-1rem)] mx-auto" />
<SidebarGroup className="gap-0.5">
<SidebarMenu>
{otherRoutes.map((route) => {
if (route.key === 'issues' || route.key === 'advisors') {
return (
<SideBarNavLink
key={route.key}
route={route}
active={
activeRoute === route.key ||
(route.key === 'issues' && activeRoute === 'advisors')
}
isLoading={isProjectPending}
>
{route.icon}
<span>{route.label}</span>
{!route.disabled && (
<ActiveDot
hasErrors={errorLints.length > 0}
hasWarnings={securityLints.length > 0}
/>
)}
</SideBarNavLink>
)
} else {
return (
<SideBarNavLink
key={route.key}
route={route}
active={activeRoute === route.key}
isLoading={isProjectPending}
/>
)
}
})}
</SidebarMenu>
</SidebarGroup>
<Separator className="w-[calc(100%-1rem)] mx-auto" />
{/* Settings routes to be added in with project/org nav */}
<SidebarGroup className="gap-0.5">
<SidebarMenu>
{settingsRoutes.map((route, i) => (
<SideBarNavLink
key={`settings-routes-${i}`}
route={route}
active={activeRoute === route.key}
isLoading={isProjectPending}
/>
))}
</SidebarMenu>
</SidebarGroup>
</>
)
}
const OrganizationLinks = () => {
const router = useRouter()
const { slug } = useParams()
const organizationSlug: string = slug ?? (router.query.orgSlug as string) ?? ''
const { data: org } = useSelectedOrganizationQuery()
const isUserMFAEnabled = useIsMFAEnabled()
const disableAccessMfa = org?.organization_requires_mfa && !isUserMFAEnabled
const showBilling = useIsFeatureEnabled('billing:all')
const activeRoute = router.pathname.split('/')[3]
const navMenuItems = [
{
label: 'Projects',
href: `/org/${organizationSlug}`,
key: 'projects',
icon: <BoxesIcon size={ICON_SIZE} strokeWidth={ICON_STROKE_WIDTH} />,
shortcutId: SHORTCUT_IDS.NAV_ORG_PROJECTS,
},
{
label: 'Team',
href: `/org/${organizationSlug}/team`,
key: 'team',
icon: <UsersIcon size={ICON_SIZE} strokeWidth={ICON_STROKE_WIDTH} />,
shortcutId: SHORTCUT_IDS.NAV_ORG_TEAM,
},
{
label: 'Integrations',
href: `/org/${organizationSlug}/integrations`,
key: 'integrations',
icon: <BlocksIcon size={ICON_SIZE} strokeWidth={ICON_STROKE_WIDTH} />,
shortcutId: SHORTCUT_IDS.NAV_ORG_INTEGRATIONS,
},
{
label: 'Usage',
href: `/org/${organizationSlug}/usage`,
key: 'usage',
icon: <ChartAreaIcon size={ICON_SIZE} strokeWidth={ICON_STROKE_WIDTH} />,
shortcutId: SHORTCUT_IDS.NAV_ORG_USAGE,
},
...(showBilling
? [
{
label: 'Billing',
href: `/org/${organizationSlug}/billing`,
key: 'billing',
icon: <ReceiptIcon size={ICON_SIZE} strokeWidth={ICON_STROKE_WIDTH} />,
shortcutId: SHORTCUT_IDS.NAV_ORG_BILLING,
},
]
: []),
{
label: 'Organization Settings',
href: `/org/${organizationSlug}/general`,
key: 'settings',
icon: <SettingsIcon size={ICON_SIZE} strokeWidth={ICON_STROKE_WIDTH} />,
shortcutId: SHORTCUT_IDS.NAV_ORG_SETTINGS,
},
]
if (!organizationSlug) return null
return (
<SidebarGroup className="gap-0.5">
<SidebarMenu className="flex flex-col gap-1">
{navMenuItems.map((item, i) => (
<SideBarNavLink
key={item.key}
active={
i === 0
? activeRoute === undefined
: item.key === 'settings'
? ORG_SETTINGS_ROUTES.includes(activeRoute ?? '')
: activeRoute === item.key
}
route={{
label: item.label,
link: item.href,
key: item.label,
icon: item.icon,
disabled: disableAccessMfa,
shortcutId: item.shortcutId,
}}
/>
))}
</SidebarMenu>
</SidebarGroup>
)
}