refactor(sidebar): simplify auto-collapse logic and improve sidebar toggle behavior

This commit is contained in:
tusharmagar 2026-04-09 20:58:59 +05:30
parent 79a21c715e
commit 1d29ca8886

View file

@ -81,33 +81,18 @@ function SidebarProvider({
[setOpenProp, open] [setOpenProp, open]
) )
// Auto-collapse sidebar when window is too narrow, re-expand when wide enough // Auto-collapse sidebar when window crosses below the threshold
const autoCollapsedRef = React.useRef(false)
React.useEffect(() => { React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${SIDEBAR_AUTO_COLLAPSE_WIDTH - 1}px)`) const mql = window.matchMedia(`(max-width: ${SIDEBAR_AUTO_COLLAPSE_WIDTH - 1}px)`)
const onChange = () => { const onChange = () => {
if (mql.matches && open) { if (mql.matches) setOpen(false)
// Window became narrow — auto-collapse
autoCollapsedRef.current = true
setOpen(false)
} else if (!mql.matches && !open && autoCollapsedRef.current) {
// Window became wide again — restore if we auto-collapsed it
autoCollapsedRef.current = false
setOpen(true)
}
}
// Check on mount
if (mql.matches && open) {
autoCollapsedRef.current = true
setOpen(false)
} }
mql.addEventListener("change", onChange) mql.addEventListener("change", onChange)
return () => mql.removeEventListener("change", onChange) return () => mql.removeEventListener("change", onChange)
}, [open, setOpen]) }, [setOpen])
// Helper to toggle the sidebar. // Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => { const toggleSidebar = React.useCallback(() => {
autoCollapsedRef.current = false // User manually toggled, don't auto-restore
return setOpen((open) => !open) return setOpen((open) => !open)
}, [setOpen]) }, [setOpen])