fix(sidebar): 修复侧栏连点,统一布局与加载交互
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
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 };
|
||||
}
|
||||
Reference in New Issue
Block a user