"use client"; import { useCallback, useSyncExternalStore } from "react"; const STORAGE_KEY = "sidebar.collapsed"; const EVENT_NAME = "sidebar-collapsed-change"; /** * In-module cache so multiple hook instances share a single source of * truth without round-tripping through localStorage on every render. * `null` means "not yet hydrated"; the first read populates it. */ let cachedValue: boolean | null = null; function readFromStorage(): boolean { if (cachedValue !== null) return cachedValue; if (typeof window === "undefined") { cachedValue = false; return false; } try { cachedValue = window.localStorage.getItem(STORAGE_KEY) === "1"; } catch { cachedValue = false; } return cachedValue; } function subscribe(notify: () => void): () => void { if (typeof window === "undefined") return () => {}; const handler = (event: Event) => { const detail = (event as CustomEvent).detail; cachedValue = Boolean(detail); notify(); }; // Cross-tab sync: storage events fire only in OTHER tabs/windows. const onStorage = (event: StorageEvent) => { if (event.key !== STORAGE_KEY) return; cachedValue = event.newValue === "1"; notify(); }; window.addEventListener(EVENT_NAME, handler as EventListener); window.addEventListener("storage", onStorage); return () => { window.removeEventListener(EVENT_NAME, handler as EventListener); window.removeEventListener("storage", onStorage); }; } function getSnapshot(): boolean { return readFromStorage(); } // During SSR the sidebar starts expanded; React will reconcile to the // stored value during hydration via useSyncExternalStore. function getServerSnapshot(): boolean { return false; } /** * Persist sidebar collapsed state in localStorage and synchronise across * mounted instances using a custom window event. Built on * useSyncExternalStore so React 18 concurrent rendering and SSR hydration * both observe a stable, tearing-free value. */ export function useSidebarCollapsed() { const collapsed = useSyncExternalStore( subscribe, getSnapshot, getServerSnapshot, ); const setCollapsed = useCallback((next: boolean) => { cachedValue = next; try { window.localStorage.setItem(STORAGE_KEY, next ? "1" : "0"); } catch { // Ignore storage write errors (private mode, quota, etc.). } window.dispatchEvent(new CustomEvent(EVENT_NAME, { detail: next })); }, []); const toggle = useCallback(() => { setCollapsed(!readFromStorage()); }, [setCollapsed]); return { collapsed, setCollapsed, toggle }; }