From b363163683e5c7ea35431593bd854bbb98a888d3 Mon Sep 17 00:00:00 2001 From: rikhall1515 <30295873+rikhall1515@users.noreply.github.com> Date: Fri, 19 Apr 2024 21:07:08 +0200 Subject: [PATCH] feat: add sidebar context --- context/sidebar.tsx | 77 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 context/sidebar.tsx diff --git a/context/sidebar.tsx b/context/sidebar.tsx new file mode 100644 index 0000000..a53d7ba --- /dev/null +++ b/context/sidebar.tsx @@ -0,0 +1,77 @@ +"use client"; +import { disableBodyScroll, enableBodyScroll } from "body-scroll-lock"; +import { + type Dispatch, + type RefObject, + type SetStateAction, + createContext, + useContext, + useRef, + useState, +} from "react"; + +type SidebarStore = { + isExpanded: boolean; + setIsExpanded: Dispatch>; + isAtTop: boolean; + setIsAtTop: Dispatch>; + toggle: () => void; + mainMenuBtnRef: RefObject; + btnInSidebarRef: RefObject; + sidebarRef: RefObject; +}; + +export const SidebarContext = createContext( + undefined +); +export function useSidebarContext() { + const sidebarStore = useContext(SidebarContext); + + if (sidebarStore === undefined) { + throw new Error( + "useSidebarContext must be used with a SidebarContext provider" + ); + } + + return sidebarStore; +} + +export default function SidebarContextProvider({ + children, +}: { + children: React.ReactNode; +}) { + const [isExpanded, setIsExpanded] = useState(false); + const [isAtTop, setIsAtTop] = useState(true); + const mainMenuBtnRef = useRef(null); + const btnInSidebarRef = useRef(null); + const sidebarRef = useRef(null); + const toggle = () => { + setIsExpanded(!isExpanded); + if (sidebarRef.current) { + if (!isExpanded) { + disableBodyScroll(sidebarRef.current); + return; + } + enableBodyScroll(sidebarRef.current); + } + }; + return ( + <> + + {children} + + + ); +}