amati/apps/frontend/src/components/AppNavbar.tsx
2024-09-12 15:10:30 +07:00

88 lines
2.3 KiB
TypeScript

import { useQuery } from "@tanstack/react-query";
import client from "../honoClient";
import MenuItem from "./NavbarMenuItem";
import { useState, useEffect } from "react";
import { useLocation } from "@tanstack/react-router";
import { ScrollArea } from "@/shadcn/components/ui/scroll-area";
import AppHeader from "./AppHeader";
// import MenuItem from "./SidebarMenuItem";
// import { useAuth } from "@/modules/auth/contexts/AuthContext";
/**
* `AppNavbar` is a React functional component that renders the application's navigation bar.
* It utilizes data from `allMenu` to create a list of menu items displayed in a scrollable area.
*
* @returns A React element representing the application's navigation bar.
*/
export default function AppNavbar() {
// const {user} = useAuth();
const { pathname } = useLocation();
const [isSidebarOpen, setSidebarOpen] = useState(true);
const toggleSidebar = () => {
setSidebarOpen(!isSidebarOpen);
};
const { data } = useQuery({
queryKey: ["sidebarData"],
queryFn: async () => {
const res = await client.dashboard.getSidebarItems.$get();
if (res.ok) {
const data = await res.json();
return data;
}
console.error("Error:", res.status, res.statusText);
throw new Error("Error fetching sidebar data");
},
});
useEffect(() => {
const handleResize = () => {
if (window.innerWidth < 768) { // Ganti 768 dengan breakpoint mobile Anda
setSidebarOpen(false);
} else {
setSidebarOpen(true);
}
};
window.addEventListener('resize', handleResize);
handleResize(); // Initial check
return () => window.removeEventListener('resize', handleResize);
}, []);
const handleMenuItemClick = () => {
if (window.innerWidth < 768) {
setSidebarOpen(false);
}
};
return (
<>
<div>
{/* Header */}
<AppHeader toggle={toggleSidebar} openNavbar={isSidebarOpen} />
{/* Sidebar */}
<div
className={`fixed lg:relative w-64 bg-white top-16 left-0 h-full z-40 px-3 py-4 transition-transform border-x
${isSidebarOpen ? 'translate-x-0' : '-translate-x-full'}`}
>
<ScrollArea className="flex flex-1 h-full">
{data?.map((menu, i) => (
<MenuItem
key={i}
menu={menu}
isActive={pathname === menu.link}
onClick={handleMenuItemClick}
/>
))}
</ScrollArea>
</div>
</div>
</>
);
}