Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Merge navigation menus #343

Merged
merged 2 commits into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions apps/web/app/assets/svgs/dashboard.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions apps/web/app/assets/svgs/hat.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions apps/web/app/assets/svgs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export { default as UploadImageIcon } from "./upload-image.svg?react";
export { default as User } from "./user.svg?react";
export { default as Warning } from "./warning.svg?react";
export { default as Admin } from "./admin.svg?react";
export { default as Hat } from "./hat.svg?react";
export { default as Multi } from "./multi.svg?react";

export { default as Success } from "./success.svg?react";
export { default as CourseEmptyState } from "./course-empty-state.svg?react";
Expand Down
3 changes: 3 additions & 0 deletions apps/web/app/assets/svgs/multi.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 2 additions & 7 deletions apps/web/app/components/Navigation/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ type DashboardNavigationProps = { menuItems: MenuItemType[] };

export function Navigation({ menuItems }: DashboardNavigationProps) {
const { isMobileNavOpen, setIsMobileNavOpen } = useMobileNavigation();
const { isAdmin, isTeacher, role } = useUserRole();
const { role } = useUserRole();

return (
<header className="3xl:w-60 3xl:p-4 sticky top-0 z-10 h-min w-full 2xl:static 2xl:flex 2xl:h-dvh 2xl:w-14 2xl:flex-col 2xl:gap-y-6 2xl:px-2 2xl:py-4">
Expand All @@ -33,12 +33,7 @@ export function Navigation({ menuItems }: DashboardNavigationProps) {
role={role}
setIsMobileNavOpen={setIsMobileNavOpen}
/>
<NavigationFooter
role={role}
isAdmin={isAdmin}
isTeacher={isTeacher}
setIsMobileNavOpen={setIsMobileNavOpen}
/>
<NavigationFooter setIsMobileNavOpen={setIsMobileNavOpen} />
</TooltipProvider>
</nav>
</header>
Expand Down
83 changes: 4 additions & 79 deletions apps/web/app/components/Navigation/NavigationFooter.tsx
Original file line number Diff line number Diff line change
@@ -1,66 +1,25 @@
import { NavLink, useLocation } from "@remix-run/react";
import { capitalize } from "lodash-es";
import { NavLink } from "@remix-run/react";
import { type Dispatch, type SetStateAction, startTransition } from "react";

import { useLogoutUser } from "~/api/mutations";
import { Gravatar } from "~/components/Gravatar";
import { Icon } from "~/components/Icon";
import { Avatar } from "~/components/ui/avatar";
import { Separator } from "~/components/ui/separator";
import { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip";
import { cn } from "~/lib/utils";
import { useCurrentUserStore } from "~/modules/common/store/useCurrentUserStore";

type NavigationFooterProps = {
isAdmin: boolean;
isTeacher: boolean;
role: string;
setIsMobileNavOpen: Dispatch<SetStateAction<boolean>>;
};

export function NavigationFooter({
isAdmin,
isTeacher,
role,
setIsMobileNavOpen,
}: NavigationFooterProps) {
const { currentUser } = useCurrentUserStore();
export function NavigationFooter({ setIsMobileNavOpen }: NavigationFooterProps) {
const { mutate: logout } = useLogoutUser();
const { pathname } = useLocation();
const isAdminRoute = pathname.startsWith("/admin");

const isAllowed = isAdmin || isTeacher;

return (
<menu className="grid w-full grid-cols-2 gap-2 md:grid-cols-6 md:gap-4 2xl:flex 2xl:flex-col 2xl:gap-2 2xl:self-end">
<li className="col-span-2 md:col-span-6 2xl:hidden">
<Separator className="3xl:my-2 bg-primary-200 2xl:h-[1px]" />
</li>
{isAllowed && (
<li className="col-span-2 md:col-span-3">
<Tooltip>
<TooltipTrigger className="w-full">
<NavLink
onClick={() => setIsMobileNavOpen(false)}
className="flex w-full items-center gap-x-3 rounded-lg bg-white px-4 py-3.5 text-neutral-900 2xl:p-2"
to={isAdminRoute ? "/" : "/admin/courses"}
>
<Icon name={isAdminRoute ? "Dashboard" : "Admin"} className="size-6 pl-[2px]" />
<span className="3xl:not-sr-only 2xl:sr-only">
{isAdminRoute ? "Dashboard" : <>{capitalize(role)} panel</>}{" "}
</span>
</NavLink>
</TooltipTrigger>
<TooltipContent
side="right"
className="3xl:hidden hidden 2xl:block 2xl:bg-neutral-950 2xl:capitalize 2xl:text-white"
>
{isAdminRoute ? "Dashboard" : <>{capitalize(role)} panel</>}
</TooltipContent>
</Tooltip>
</li>
)}
<li className={cn("md:col-span-3", { hidden: isAllowed && isAdminRoute })}>
<li className="col-span-2 md:col-span-3">
<Tooltip>
<TooltipTrigger className="w-full">
<NavLink
Expand All @@ -85,44 +44,10 @@ export function NavigationFooter({
</TooltipContent>
</Tooltip>
</li>
<li className={cn("md:col-span-3", { "sr-only": isAdminRoute || !isAllowed })}>
<NavLink
onClick={() => setIsMobileNavOpen(false)}
to={`/teachers/${currentUser?.id}`}
className={({ isActive }) =>
cn("flex w-full items-center gap-x-3 rounded-lg px-4 py-3.5 2xl:p-2", {
"bg-primary-700 text-white": isActive,
"bg-white text-neutral-900": !isActive,
})
}
>
<Icon name="User" className="size-6" />
<span className="3xl:not-sr-only 2xl:sr-only">Profile</span>
</NavLink>
</li>
<li className="sr-only 2xl:not-sr-only">
<div className="3xl:gap-x-2 3xl:flex-row 3xl:p-3 3xl:mt-4 flex flex-col items-center justify-center rounded-lg bg-neutral-50 px-1 py-4">
<Avatar className="3xl:size-10 size-8">
<Gravatar email={currentUser?.email} size={32} />
</Avatar>
<hgroup className="3xl:not-sr-only sr-only flex flex-col justify-center">
<h2 className="body-sm-md text-neutral-950">
{currentUser?.firstName} {currentUser?.lastName}
</h2>
<p className="details text-neutral-600">{currentUser?.email}</p>
</hgroup>
</div>
</li>
<li className="hidden 2xl:block">
<Separator className="bg-primary-200 2xl:h-[1px]" />
</li>
<li
className={cn({
"col-span-1 md:col-span-6": isAllowed && isAdminRoute,
"col-span-2 md:col-span-3": isAllowed && !isAdminRoute,
"col-span-2 md:col-span-6": !isAllowed,
})}
>
<li className="col-span-2 md:col-span-3">
<Tooltip>
<TooltipTrigger className="w-full">
<button
Expand Down
73 changes: 70 additions & 3 deletions apps/web/app/config/navigationConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,37 @@ export type NavigationItem = {
iconName: IconName;
};

export const navigationConfig: NavigationItem[] = [
export const getNavigationConfig = (userId: string, isUser = true): NavigationItem[] => [
{
label: "dashboard",
path: "",
iconName: "Dashboard",
},
{
label: "courses",
path: "courses",
label: "My Courses",
path: "admin/courses",
iconName: "Course",
},
{
label: isUser ? "Courses" : "Browse Courses",
path: "courses",
iconName: isUser ? "Course" : "Multi",
},
{
label: "categories",
path: "admin/categories",
iconName: "Category",
},
{
label: "users",
path: "admin/users",
iconName: "Hat",
},
{
label: "Profile",
path: `teachers/${userId}`,
iconName: "User",
},
];

export const adminNavigationConfig: NavigationItem[] = [
Expand All @@ -52,11 +72,58 @@ export const adminNavigationConfig: NavigationItem[] = [
},
];

/**
* Finds matching route access roles for a given path by checking different types of routes in order:
* 1. Exact matches (e.g., "courses/new" matches "courses/new")
* 2. Parameter routes (e.g., "teachers/123" matches "teachers/:id")
* 3. Wildcard routes (e.g., "teachers/123/settings" matches "teachers/*")
*
* @param path - The actual URL path to match (e.g., "teachers/123")
* @returns UserRole[] | undefined - Array of user roles that can access this path, or undefined if no match
*
* @example
* // Exact match
* findMatchingRoute("courses/new") // matches "courses/new" in config
*
* // Parameter match
* findMatchingRoute("teachers/123") // matches "teachers/:id" in config
* findMatchingRoute("course/456/lesson/789") // matches "course/:courseId/lesson/:lessonId"
*
* // Wildcard match
* findMatchingRoute("teachers/123/settings") // matches "teachers/*"
*
* How matching works:
* 1. First, tries to find an exact match in routeAccessConfig
* 2. If no exact match, looks for parameter routes (:id)
* - Splits both paths into segments
* - Segments with ":" are treated as valid matches for any value
* - All other segments must match exactly
* 3. If still no match, checks wildcard routes (*)
* - Matches if path starts with the part before "*"
*/
export const findMatchingRoute = (path: string) => {
if (routeAccessConfig[path]) {
return routeAccessConfig[path];
}

const paramRoutes = Object.entries(routeAccessConfig).filter(
([route]) => route.includes(":") && !route.includes("*"),
);

for (const [route, roles] of paramRoutes) {
const routeParts = route.split("/");
const pathParts = path.split("/");

if (routeParts.length !== pathParts.length) continue;

const matches = routeParts.every((part, index) => {
if (part.startsWith(":")) return true;
return part === pathParts[index];
});

if (matches) return roles;
}

const wildcardRoutes = Object.entries(routeAccessConfig).filter(([route]) => route.includes("*"));

for (const [route, roles] of wildcardRoutes) {
Expand Down
8 changes: 6 additions & 2 deletions apps/web/app/modules/Admin/Admin.layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import { match } from "ts-pattern";
import { currentUserQueryOptions } from "~/api/queries";
import { queryClient } from "~/api/queryClient";
import { Navigation } from "~/components/Navigation";
import { adminNavigationConfig, mapNavigationItems } from "~/config/navigationConfig";
import { getNavigationConfig, mapNavigationItems } from "~/config/navigationConfig";
import { RouteGuard } from "~/Guards/RouteGuard";
import { useUserRole } from "~/hooks/useUserRole";
import { cn } from "~/lib/utils";
import { useCurrentUserStore } from "~/modules/common/store/useCurrentUserStore";

import Loader from "../common/Loader/Loader";

Expand Down Expand Up @@ -50,6 +51,7 @@ const AdminGuard = ({ children }: PropsWithChildren) => {
};

const AdminLayout = () => {
const { currentUser } = useCurrentUserStore();
const { pathname } = useLocation();

const hideTopbarAndSidebar = match(pathname)
Expand All @@ -61,7 +63,9 @@ const AdminLayout = () => {
<div className="flex h-screen flex-col">
<div className="flex flex-1 flex-col overflow-hidden 2xl:flex-row">
{!hideTopbarAndSidebar && (
<Navigation menuItems={mapNavigationItems(adminNavigationConfig)} />
<Navigation
menuItems={mapNavigationItems(getNavigationConfig(currentUser?.id ?? "", false))}
/>
)}
<main
className={cn("bg-primary-50 flex-1 overflow-y-auto max-h-dvh p-6", {
Expand Down
10 changes: 8 additions & 2 deletions apps/web/app/modules/Courses/Lesson/Lesson.layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { Outlet, redirect } from "@remix-run/react";
import { currentUserQueryOptions } from "~/api/queries/useCurrentUser";
import { queryClient } from "~/api/queryClient";
import { Navigation } from "~/components/Navigation";
import { mapNavigationItems, navigationConfig } from "~/config/navigationConfig";
import { getNavigationConfig, mapNavigationItems } from "~/config/navigationConfig";
import { RouteGuard } from "~/Guards/RouteGuard";
import { useAuthEffect } from "~/modules/Auth/authEffect";
import { useCurrentUserStore } from "~/modules/common/store/useCurrentUserStore";

export const clientLoader = async () => {
try {
Expand All @@ -22,12 +23,17 @@ export const clientLoader = async () => {
};

export default function LessonLayout() {
const { currentUser } = useCurrentUserStore();
useAuthEffect();

return (
<div className="flex min-h-dvh flex-col">
<div className="flex flex-1 flex-col 2xl:flex-row overflow-hidden">
<Navigation menuItems={mapNavigationItems(navigationConfig)} />
<Navigation
menuItems={mapNavigationItems(
getNavigationConfig(currentUser?.id ?? "", currentUser?.role === "user"),
)}
/>
<main className="flex-1 overflow-y-auto bg-primary-50">
<RouteGuard>
<Outlet />
Expand Down
Loading
Loading