"use client"; import { useCallback, useSyncExternalStore } from "react"; /** * Mirror of {@link useSidebarCollapsed} for the *secondary* (detail-page) * sidebar. Same persistence + cross-instance + cross-tab sync pattern, with * a separate localStorage key so the two sidebars collapse independently. * * The reason for two hooks rather than one with a key parameter: each * useSyncExternalStore needs a stable subscribe / snapshot pair, and a * single subscribe shared between two state slots would notify all * consumers on every change. Splitting keeps the dependency graph clean * and avoids the "primary toggle re-renders every detail page" gotcha. */ const STORAGE_KEY = "detail-sidebar.collapsed"; const EVENT_NAME = "detail-sidebar-collapsed-change"; 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(); }; 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 detail sidebar starts expanded; hydration reconciles. function getServerSnapshot(): boolean { return false; } export function useDetailSidebarCollapsed() { const collapsed = useSyncExternalStore( subscribe, getSnapshot, getServerSnapshot, ); const setCollapsed = useCallback((next: boolean) => { cachedValue = next; try { window.localStorage.setItem(STORAGE_KEY, next ? "1" : "0"); } catch { // Ignore — private mode / quota / etc. } window.dispatchEvent(new CustomEvent(EVENT_NAME, { detail: next })); }, []); const toggle = useCallback(() => { setCollapsed(!readFromStorage()); }, [setCollapsed]); return { collapsed, setCollapsed, toggle }; }