From dad16bbaf652589a3be0e535404e7f3388bb8ee6 Mon Sep 17 00:00:00 2001 From: Marc Seitz Date: Sat, 18 Jan 2025 13:05:40 +0100 Subject: [PATCH] feat: add persistent cookie sidebar --- components/ui/sidebar.tsx | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/components/ui/sidebar.tsx b/components/ui/sidebar.tsx index 5834dca93..a72ea6cc5 100644 --- a/components/ui/sidebar.tsx +++ b/components/ui/sidebar.tsx @@ -70,9 +70,22 @@ const SidebarProvider = React.forwardRef< const isMobile = useIsMobile(); const [openMobile, setOpenMobile] = React.useState(false); + // Read initial state from cookie + const initialState = React.useMemo(() => { + if (typeof window === "undefined") return defaultOpen; + const cookie = document.cookie + .split("; ") + .find((row) => row.startsWith(SIDEBAR_COOKIE_NAME)); + if (cookie) { + const value = cookie.split("=")[1]; + return value === "true"; + } + return defaultOpen; + }, [defaultOpen]); + // This is the internal state of the sidebar. // We use openProp and setOpenProp for control from outside the component. - const [_open, _setOpen] = React.useState(defaultOpen); + const [_open, _setOpen] = React.useState(initialState); const open = openProp ?? _open; const setOpen = React.useCallback( (value: boolean | ((value: boolean) => boolean)) => {