fix: eliminate sidebar jitter on collapse/expand

Root cause: class switching (px-2↔px-3, justify-center↔gap-2.5,
conditional DOM rendering) caused instant layout jumps during the
200ms width transition.

Fix: internal layout is now 100% static — same padding, same gap,
same DOM structure in both states. Only opacity transitions on text
labels (via Label component). The sidebar overflow:hidden + width
transition handles the visual collapse. Collapse icon rotates 180deg
instead of swapping between two icons.
This commit is contained in:
Usman Baig
2026-03-18 16:45:39 +01:00
parent 5807a50092
commit 5c8f334017

View File

@@ -22,6 +22,8 @@ import {
} from '@ciphera-net/ui' } from '@ciphera-net/ui'
const SIDEBAR_KEY = 'pulse_sidebar_collapsed' const SIDEBAR_KEY = 'pulse_sidebar_collapsed'
const EXPANDED = 256
const COLLAPSED = 56
type IconWeight = 'thin' | 'light' | 'regular' | 'bold' | 'fill' | 'duotone' type IconWeight = 'thin' | 'light' | 'regular' | 'bold' | 'fill' | 'duotone'
@@ -32,10 +34,7 @@ interface NavItem {
matchPrefix?: boolean matchPrefix?: boolean
} }
interface NavGroup { interface NavGroup { label: string; items: NavItem[] }
label: string
items: NavItem[]
}
const NAV_GROUPS: NavGroup[] = [ const NAV_GROUPS: NavGroup[] = [
{ {
@@ -58,23 +57,24 @@ const NAV_GROUPS: NavGroup[] = [
] ]
const SETTINGS_ITEM: NavItem = { const SETTINGS_ITEM: NavItem = {
label: 'Settings', label: 'Settings', href: (id) => `/sites/${id}/settings`, icon: SettingsIcon, matchPrefix: true,
href: (id) => `/sites/${id}/settings`, }
icon: SettingsIcon,
matchPrefix: true, // Label that fades with the sidebar — always in the DOM, never removed
function Label({ children, collapsed }: { children: React.ReactNode; collapsed: boolean }) {
return (
<span
className="whitespace-nowrap overflow-hidden transition-opacity duration-150"
style={{ opacity: collapsed ? 0 : 1 }}
>
{children}
</span>
)
} }
// ─── Site Picker ──────────────────────────────────────────── // ─── Site Picker ────────────────────────────────────────────
function SitePicker({ function SitePicker({ sites, siteId, collapsed }: { sites: Site[]; siteId: string; collapsed: boolean }) {
sites,
siteId,
collapsed,
}: {
sites: Site[]
siteId: string
collapsed: boolean
}) {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [search, setSearch] = useState('') const [search, setSearch] = useState('')
const ref = useRef<HTMLDivElement>(null) const ref = useRef<HTMLDivElement>(null)
@@ -85,10 +85,7 @@ function SitePicker({
useEffect(() => { useEffect(() => {
const handler = (e: MouseEvent) => { const handler = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) { if (ref.current && !ref.current.contains(e.target as Node)) { setOpen(false); setSearch('') }
setOpen(false)
setSearch('')
}
} }
document.addEventListener('mousedown', handler) document.addEventListener('mousedown', handler)
return () => document.removeEventListener('mousedown', handler) return () => document.removeEventListener('mousedown', handler)
@@ -96,38 +93,33 @@ function SitePicker({
const switchSite = (id: string) => { const switchSite = (id: string) => {
router.push(`/sites/${id}${pathname.replace(/^\/sites\/[^/]+/, '')}`) router.push(`/sites/${id}${pathname.replace(/^\/sites\/[^/]+/, '')}`)
setOpen(false) setOpen(false); setSearch('')
setSearch('')
} }
const filtered = sites.filter( const filtered = sites.filter(
(s) => (s) => s.name.toLowerCase().includes(search.toLowerCase()) || s.domain.toLowerCase().includes(search.toLowerCase())
s.name.toLowerCase().includes(search.toLowerCase()) ||
s.domain.toLowerCase().includes(search.toLowerCase())
) )
return ( return (
<div className={`relative mb-4 ${collapsed ? 'px-2' : 'px-3'}`} ref={ref}> <div className="relative mb-4 px-3" ref={ref}>
<button <button
onClick={() => setOpen(!open)} onClick={() => setOpen(!open)}
className={`w-full flex items-center rounded-lg py-2 text-sm font-medium text-neutral-700 dark:text-neutral-200 hover:bg-neutral-100 dark:hover:bg-neutral-800 ${ className="w-full flex items-center gap-2.5 rounded-lg px-2 py-2 text-sm font-medium text-neutral-700 dark:text-neutral-200 hover:bg-neutral-100 dark:hover:bg-neutral-800 overflow-hidden"
collapsed ? 'justify-center px-0' : 'gap-2.5 px-2'
}`}
title={collapsed ? currentSite?.name || 'Select site' : undefined} title={collapsed ? currentSite?.name || 'Select site' : undefined}
> >
<span className="w-7 h-7 rounded-md bg-brand-orange/10 text-brand-orange flex items-center justify-center text-xs font-bold shrink-0"> <span className="w-7 h-7 rounded-md bg-brand-orange/10 text-brand-orange flex items-center justify-center text-xs font-bold shrink-0">
{initial} {initial}
</span> </span>
{!collapsed && ( <Label collapsed={collapsed}>
<> <span className="flex items-center gap-1">
<span className="truncate flex-1 text-left">{currentSite?.name || 'Select site'}</span> <span className="truncate">{currentSite?.name || 'Select site'}</span>
<ChevronUpDownIcon className="w-4 h-4 text-neutral-400 shrink-0" /> <ChevronUpDownIcon className="w-4 h-4 text-neutral-400 shrink-0" />
</> </span>
)} </Label>
</button> </button>
{open && ( {open && (
<div className={`absolute top-full mt-1 z-50 bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-700 rounded-xl shadow-xl overflow-hidden min-w-[220px] ${collapsed ? 'left-1 right-auto' : 'left-3 right-3'}`}> <div className="absolute left-3 top-full mt-1 z-50 w-[240px] bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-700 rounded-xl shadow-xl overflow-hidden">
<div className="p-2"> <div className="p-2">
<input <input
type="text" type="text"
@@ -158,16 +150,10 @@ function SitePicker({
</span> </span>
</button> </button>
))} ))}
{filtered.length === 0 && ( {filtered.length === 0 && <p className="px-4 py-3 text-sm text-neutral-400">No sites found</p>}
<p className="px-4 py-3 text-sm text-neutral-400">No sites found</p>
)}
</div> </div>
<div className="border-t border-neutral-200 dark:border-neutral-700 p-2"> <div className="border-t border-neutral-200 dark:border-neutral-700 p-2">
<Link <Link href="/sites/new" onClick={() => setOpen(false)} className="flex items-center gap-2 px-3 py-1.5 text-sm text-brand-orange hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg">
href="/sites/new"
onClick={() => setOpen(false)}
className="flex items-center gap-2 px-3 py-1.5 text-sm text-brand-orange hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg"
>
<PlusIcon className="w-4 h-4" /> <PlusIcon className="w-4 h-4" />
Add new site Add new site
</Link> </Link>
@@ -181,52 +167,30 @@ function SitePicker({
// ─── Nav Item ─────────────────────────────────────────────── // ─── Nav Item ───────────────────────────────────────────────
function NavLink({ function NavLink({
item, item, siteId, collapsed, onClick, pendingHref, onNavigate,
siteId,
collapsed,
onClick,
pendingHref,
onNavigate,
}: { }: {
item: NavItem item: NavItem; siteId: string; collapsed: boolean; onClick?: () => void
siteId: string pendingHref: string | null; onNavigate: (href: string) => void
collapsed: boolean
onClick?: () => void
pendingHref: string | null
onNavigate: (href: string) => void
}) { }) {
const pathname = usePathname() const pathname = usePathname()
const href = item.href(siteId) const href = item.href(siteId)
// Active if pathname matches OR if this link was just clicked (optimistic)
const matchesPathname = item.matchPrefix ? pathname.startsWith(href) : pathname === href const matchesPathname = item.matchPrefix ? pathname.startsWith(href) : pathname === href
const matchesPending = pendingHref !== null && (item.matchPrefix ? pendingHref.startsWith(href) : pendingHref === href) const matchesPending = pendingHref !== null && (item.matchPrefix ? pendingHref.startsWith(href) : pendingHref === href)
const active = matchesPathname || matchesPending const active = matchesPathname || matchesPending
const handleClick = () => {
onNavigate(href)
onClick?.()
}
return ( return (
<Link <Link
href={href} href={href}
onClick={handleClick} onClick={() => { onNavigate(href); onClick?.() }}
title={collapsed ? item.label : undefined} title={collapsed ? item.label : undefined}
className={`flex items-center rounded-lg py-2 text-sm font-medium ${ className={`flex items-center gap-2.5 rounded-lg px-2.5 py-2 text-sm font-medium overflow-hidden ${
collapsed ? 'justify-center px-0' : 'gap-2.5 px-2.5'
} ${
active active
? 'bg-brand-orange/10 text-brand-orange' ? 'bg-brand-orange/10 text-brand-orange'
: 'text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white hover:bg-neutral-100 dark:hover:bg-neutral-800' : 'text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white hover:bg-neutral-100 dark:hover:bg-neutral-800'
}`} }`}
> >
<item.icon className="w-[18px] h-[18px] shrink-0" weight={active ? 'fill' : 'regular'} /> <item.icon className="w-[18px] h-[18px] shrink-0" weight={active ? 'fill' : 'regular'} />
{!collapsed && ( <Label collapsed={collapsed}>{item.label}</Label>
<span className="whitespace-nowrap overflow-hidden">
{item.label}
</span>
)}
</Link> </Link>
) )
} }
@@ -234,15 +198,9 @@ function NavLink({
// ─── Main Sidebar ─────────────────────────────────────────── // ─── Main Sidebar ───────────────────────────────────────────
export default function Sidebar({ export default function Sidebar({
siteId, siteId, mobileOpen, onMobileClose, onMobileOpen,
mobileOpen,
onMobileClose,
onMobileOpen,
}: { }: {
siteId: string siteId: string; mobileOpen: boolean; onMobileClose: () => void; onMobileOpen: () => void
mobileOpen: boolean
onMobileClose: () => void
onMobileOpen: () => void
}) { }) {
const { user } = useAuth() const { user } = useAuth()
const canEdit = user?.role === 'owner' || user?.role === 'admin' const canEdit = user?.role === 'owner' || user?.role === 'admin'
@@ -254,24 +212,15 @@ export default function Sidebar({
return localStorage.getItem(SIDEBAR_KEY) === 'true' return localStorage.getItem(SIDEBAR_KEY) === 'true'
}) })
useEffect(() => { useEffect(() => { listSites().then(setSites).catch(() => {}) }, [])
listSites().then(setSites).catch(() => {}) useEffect(() => { setPendingHref(null); onMobileClose() }, [pathname, onMobileClose])
}, [])
// Clear pending href once navigation completes
useEffect(() => {
setPendingHref(null)
onMobileClose()
}, [pathname, onMobileClose])
// Keyboard shortcut: [ to toggle
useEffect(() => { useEffect(() => {
const handler = (e: KeyboardEvent) => { const handler = (e: KeyboardEvent) => {
if (e.key === '[' && !e.metaKey && !e.ctrlKey && !e.altKey) { if (e.key === '[' && !e.metaKey && !e.ctrlKey && !e.altKey) {
const tag = (e.target as HTMLElement)?.tagName const tag = (e.target as HTMLElement)?.tagName
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return
e.preventDefault() e.preventDefault(); toggle()
toggle()
} }
} }
document.addEventListener('keydown', handler) document.addEventListener('keydown', handler)
@@ -279,66 +228,39 @@ export default function Sidebar({
}, [collapsed]) }, [collapsed])
const toggle = useCallback(() => { const toggle = useCallback(() => {
setCollapsed((prev) => { setCollapsed((prev) => { const next = !prev; localStorage.setItem(SIDEBAR_KEY, String(next)); return next })
const next = !prev
localStorage.setItem(SIDEBAR_KEY, String(next))
return next
})
}, []) }, [])
const handleNavigate = useCallback((href: string) => { const handleNavigate = useCallback((href: string) => { setPendingHref(href) }, [])
setPendingHref(href)
}, [])
const sidebarContent = (isMobile: boolean) => { const sidebarContent = (isMobile: boolean) => {
const isCollapsed = isMobile ? false : collapsed const c = isMobile ? false : collapsed
return ( return (
<div className="flex flex-col h-full overflow-x-hidden"> <div className="flex flex-col h-full overflow-hidden">
{/* Logo */} {/* Logo — fixed layout, text fades */}
<Link <Link href="/" className="flex items-center gap-3 px-4 py-5 shrink-0 group overflow-hidden">
href="/" <img src="/pulse_icon_no_margins.png" alt="Pulse" className="w-8 h-8 shrink-0 object-contain group-hover:scale-105 transition-transform duration-200" />
className={`flex items-center shrink-0 group py-5 ${ <span className={`text-lg font-bold text-neutral-900 dark:text-white tracking-tight group-hover:text-brand-orange whitespace-nowrap transition-opacity duration-150 ${c ? 'opacity-0' : 'opacity-100'}`}>
isCollapsed ? 'justify-center px-0' : 'gap-3 px-5' Pulse
}`} </span>
>
<img
src="/pulse_icon_no_margins.png"
alt="Pulse"
className="w-8 h-8 shrink-0 object-contain group-hover:scale-105 transition-transform duration-200"
/>
{!isCollapsed && (
<span className="text-lg font-bold text-neutral-900 dark:text-white tracking-tight group-hover:text-brand-orange transition-colors duration-150 whitespace-nowrap">
Pulse
</span>
)}
</Link> </Link>
{/* Site Picker */} {/* Site Picker */}
<SitePicker sites={sites} siteId={siteId} collapsed={isCollapsed} /> <SitePicker sites={sites} siteId={siteId} collapsed={c} />
{/* Nav Groups */} {/* Nav Groups */}
<nav className={`flex-1 overflow-y-auto overflow-x-hidden space-y-4 ${isCollapsed ? 'px-2' : 'px-3'}`}> <nav className="flex-1 overflow-y-auto overflow-x-hidden px-3 space-y-4">
{NAV_GROUPS.map((group) => ( {NAV_GROUPS.map((group) => (
<div key={group.label}> <div key={group.label}>
{isCollapsed ? ( <div className="h-5 flex items-center overflow-hidden">
<div className="h-2" /> <p className={`px-2.5 text-[11px] font-semibold text-neutral-400 dark:text-neutral-500 uppercase tracking-wider whitespace-nowrap transition-opacity duration-150 ${c ? 'opacity-0' : 'opacity-100'}`}>
) : (
<p className="px-2.5 mb-1 text-[11px] font-semibold text-neutral-400 dark:text-neutral-500 uppercase tracking-wider">
{group.label} {group.label}
</p> </p>
)} </div>
<div className="space-y-0.5"> <div className="space-y-0.5">
{group.items.map((item) => ( {group.items.map((item) => (
<NavLink <NavLink key={item.label} item={item} siteId={siteId} collapsed={c} onClick={isMobile ? onMobileClose : undefined} pendingHref={pendingHref} onNavigate={handleNavigate} />
key={item.label}
item={item}
siteId={siteId}
collapsed={isCollapsed}
onClick={isMobile ? onMobileClose : undefined}
pendingHref={pendingHref}
onNavigate={handleNavigate}
/>
))} ))}
</div> </div>
</div> </div>
@@ -346,33 +268,18 @@ export default function Sidebar({
</nav> </nav>
{/* Bottom */} {/* Bottom */}
<div className={`border-t border-neutral-200 dark:border-neutral-800 py-3 space-y-0.5 shrink-0 ${isCollapsed ? 'px-2' : 'px-3'}`}> <div className="border-t border-neutral-200 dark:border-neutral-800 px-3 py-3 space-y-0.5 shrink-0">
{canEdit && ( {canEdit && (
<NavLink <NavLink item={SETTINGS_ITEM} siteId={siteId} collapsed={c} onClick={isMobile ? onMobileClose : undefined} pendingHref={pendingHref} onNavigate={handleNavigate} />
item={SETTINGS_ITEM}
siteId={siteId}
collapsed={isCollapsed}
onClick={isMobile ? onMobileClose : undefined}
pendingHref={pendingHref}
onNavigate={handleNavigate}
/>
)} )}
{!isMobile && ( {!isMobile && (
<button <button
onClick={toggle} onClick={toggle}
className={`flex items-center rounded-lg py-2 text-sm font-medium text-neutral-400 dark:text-neutral-500 hover:text-neutral-600 dark:hover:text-neutral-300 hover:bg-neutral-100 dark:hover:bg-neutral-800 w-full ${ className="flex items-center gap-2.5 rounded-lg px-2.5 py-2 text-sm font-medium text-neutral-400 dark:text-neutral-500 hover:text-neutral-600 dark:hover:text-neutral-300 hover:bg-neutral-100 dark:hover:bg-neutral-800 w-full overflow-hidden"
isCollapsed ? 'justify-center px-0' : 'gap-2.5 px-2.5'
}`}
title={collapsed ? 'Expand sidebar (press [)' : 'Collapse sidebar (press [)'} title={collapsed ? 'Expand sidebar (press [)' : 'Collapse sidebar (press [)'}
> >
{collapsed ? ( <CollapseLeftIcon className={`w-[18px] h-[18px] shrink-0 transition-transform duration-200 ${c ? 'rotate-180' : ''}`} />
<CollapseRightIcon className="w-[18px] h-[18px] shrink-0" /> <Label collapsed={c}>Collapse</Label>
) : (
<>
<CollapseLeftIcon className="w-[18px] h-[18px] shrink-0" />
<span className="whitespace-nowrap overflow-hidden">Collapse</span>
</>
)}
</button> </button>
)} )}
</div> </div>
@@ -382,13 +289,10 @@ export default function Sidebar({
return ( return (
<> <>
{/* Desktop */} {/* Desktop — width transitions, internal layout never changes */}
<aside <aside
className="hidden md:flex flex-col shrink-0 border-r border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 overflow-hidden" className="hidden md:flex flex-col shrink-0 border-r border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 overflow-hidden"
style={{ style={{ width: collapsed ? COLLAPSED : EXPANDED, transition: 'width 200ms cubic-bezier(0.4, 0, 0.2, 1)' }}
width: collapsed ? 56 : 256,
transition: 'width 200ms cubic-bezier(0.4, 0, 0.2, 1)',
}}
> >
{sidebarContent(false)} {sidebarContent(false)}
</aside> </aside>
@@ -396,17 +300,11 @@ export default function Sidebar({
{/* Mobile overlay */} {/* Mobile overlay */}
{mobileOpen && ( {mobileOpen && (
<> <>
<div <div className="fixed inset-0 z-40 bg-black/30 md:hidden" onClick={onMobileClose} />
className="fixed inset-0 z-40 bg-black/30 md:hidden"
onClick={onMobileClose}
/>
<aside className="fixed inset-y-0 left-0 z-50 w-72 bg-white dark:bg-neutral-900 border-r border-neutral-200 dark:border-neutral-800 shadow-xl md:hidden animate-in slide-in-from-left duration-200"> <aside className="fixed inset-y-0 left-0 z-50 w-72 bg-white dark:bg-neutral-900 border-r border-neutral-200 dark:border-neutral-800 shadow-xl md:hidden animate-in slide-in-from-left duration-200">
<div className="flex items-center justify-between px-4 py-3 border-b border-neutral-200 dark:border-neutral-800"> <div className="flex items-center justify-between px-4 py-3 border-b border-neutral-200 dark:border-neutral-800">
<span className="text-sm font-semibold text-neutral-900 dark:text-white">Navigation</span> <span className="text-sm font-semibold text-neutral-900 dark:text-white">Navigation</span>
<button <button onClick={onMobileClose} className="p-1.5 text-neutral-400 hover:text-neutral-600 dark:hover:text-neutral-300">
onClick={onMobileClose}
className="p-1.5 text-neutral-400 hover:text-neutral-600 dark:hover:text-neutral-300"
>
<XIcon className="w-5 h-5" /> <XIcon className="w-5 h-5" />
</button> </button>
</div> </div>