45 lines
1.2 KiB
JavaScript
45 lines
1.2 KiB
JavaScript
import { useCallback, useRef, useState } from 'react';
|
|
import { useSidebarToggleGuard } from './useSidebarToggleGuard';
|
|
|
|
function readGroups(storageKey) {
|
|
if (!storageKey) return [];
|
|
try {
|
|
const saved = JSON.parse(localStorage.getItem(storageKey));
|
|
return Array.isArray(saved) ? saved : [];
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
export function useSidebarGroups(storageKey) {
|
|
const [keys, setKeys] = useState(() => readGroups(storageKey));
|
|
const current = useRef(keys);
|
|
const canToggle = useSidebarToggleGuard();
|
|
|
|
const setGroup = useCallback(
|
|
(key, included, persist = false) => {
|
|
const previous = current.current;
|
|
if (!key || previous.includes(key) === included) return;
|
|
const next = included
|
|
? [...previous, key]
|
|
: previous.filter((item) => item !== key);
|
|
current.current = next;
|
|
setKeys(next);
|
|
if (persist && storageKey) {
|
|
try {
|
|
localStorage.setItem(storageKey, JSON.stringify(next));
|
|
} catch {
|
|
// Keep the in-memory preference if storage is unavailable.
|
|
}
|
|
}
|
|
},
|
|
[storageKey],
|
|
);
|
|
|
|
const toggle = (key) => {
|
|
if (canToggle(key)) setGroup(key, !current.current.includes(key), true);
|
|
};
|
|
|
|
return { keys, toggle, setGroup };
|
|
}
|