refactor: add sidebar persistence

This commit is contained in:
Mauricio Siu 2025-01-19 01:44:42 -06:00
parent 5310a559b0
commit adb204ec1f
2 changed files with 23 additions and 2 deletions

View File

@ -1,5 +1,5 @@
"use client";
import { useState, useEffect } from "react";
import {
Activity,
AudioWaveform,
@ -46,6 +46,7 @@ import {
import { Separator } from "@/components/ui/separator";
import {
Sidebar,
SIDEBAR_COOKIE_NAME,
SidebarContent,
SidebarFooter,
SidebarGroup,
@ -369,6 +370,19 @@ function SidebarLogo() {
}
export default function Page({ children }: Props) {
const [defaultOpen, setDefaultOpen] = useState<boolean | undefined>(
undefined,
);
useEffect(() => {
const cookieValue = document.cookie
.split("; ")
.find((row) => row.startsWith(`${SIDEBAR_COOKIE_NAME}=`))
?.split("=")[1];
setDefaultOpen(cookieValue === undefined ? true : cookieValue === "true");
}, []);
const router = useRouter();
const pathname = usePathname();
const currentPath = router.pathname;
@ -445,6 +459,13 @@ export default function Page({ children }: Props) {
return (
<SidebarProvider
defaultOpen={defaultOpen}
open={defaultOpen}
onOpenChange={(open) => {
setDefaultOpen(open);
document.cookie = `${SIDEBAR_COOKIE_NAME}=${open}`;
}}
style={
{
"--sidebar-width": "19.5rem",

View File

@ -17,7 +17,7 @@ import {
import { useIsMobile } from "@/hooks/use-mobile";
import { cn } from "@/lib/utils";
const SIDEBAR_COOKIE_NAME = "sidebar:state";
export const SIDEBAR_COOKIE_NAME = "sidebar:state";
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "18rem";