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

View File

@@ -17,7 +17,7 @@ import {
import { useIsMobile } from "@/hooks/use-mobile"; import { useIsMobile } from "@/hooks/use-mobile";
import { cn } from "@/lib/utils"; 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_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = "16rem"; const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "18rem"; const SIDEBAR_WIDTH_MOBILE = "18rem";