feat: 完成代码编写
This commit is contained in:
@@ -26,6 +26,17 @@ const SIDEBAR_WIDTH_MOBILE = '14rem';
|
||||
const SIDEBAR_WIDTH_ICON = '2rem';
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = 'b';
|
||||
|
||||
// Define a safe default context so consumers won't crash without a Provider
|
||||
const SAFE_SIDEBAR_CONTEXT: SidebarContext = {
|
||||
state: 'collapsed',
|
||||
open: false,
|
||||
setOpen: () => {},
|
||||
openMobile: false,
|
||||
setOpenMobile: () => {},
|
||||
isMobile: false,
|
||||
toggleSidebar: () => {},
|
||||
};
|
||||
|
||||
type SidebarContext = {
|
||||
state: 'expanded' | 'collapsed';
|
||||
open: boolean;
|
||||
@@ -36,14 +47,14 @@ type SidebarContext = {
|
||||
toggleSidebar: () => void;
|
||||
};
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContext | null>(null);
|
||||
const SidebarContext = React.createContext<SidebarContext>(SAFE_SIDEBAR_CONTEXT);
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext);
|
||||
if (!context) {
|
||||
throw new Error('useSidebar must be used within a SidebarProvider.');
|
||||
// Optionally warn in development when using the safe fallback
|
||||
if (process.env.NODE_ENV !== 'production' && context === SAFE_SIDEBAR_CONTEXT) {
|
||||
// console.warn('useSidebar is used outside of a SidebarProvider. Falling back to no-op context.');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user