Skip to content

Commit

Permalink
refactor: BreadCrumb component refact
Browse files Browse the repository at this point in the history
  • Loading branch information
d3george authored and d3george committed Oct 29, 2024
1 parent 7d17ec1 commit 8ca361b
Showing 1 changed file with 22 additions and 23 deletions.
45 changes: 22 additions & 23 deletions src/layouts/_common/bread-crumb.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { Breadcrumb, type BreadcrumbProps, type GetProp } from 'antd';
import { useEffect, useState } from 'react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useMatches, Link } from 'react-router-dom';

import { Iconify } from '@/components/icon';
import { useFlattenedRoutes, usePermissionRoutes } from '@/router/hooks';
import { menuFilter } from '@/router/utils';

import { AppRouteObject } from '#/router';

type MenuItem = GetProp<BreadcrumbProps, 'items'>[number];

/**
Expand All @@ -17,38 +15,39 @@ type MenuItem = GetProp<BreadcrumbProps, 'items'>[number];
export default function BreadCrumb() {
const { t } = useTranslation();
const matches = useMatches();
const [breadCrumbs, setBreadCrumbs] = useState<MenuItem[]>([]);

const flattenedRoutes = useFlattenedRoutes();
const permissionRoutes = usePermissionRoutes();

useEffect(() => {
const breadCrumbs = useMemo(() => {
const menuRoutes = menuFilter(permissionRoutes);
const paths = matches.filter((item) => item.pathname !== '/').map((item) => item.pathname);

const pathRouteMetas = flattenedRoutes.filter((item) => paths.indexOf(item.key) !== -1);
const pathRouteMetas = flattenedRoutes.filter((item) => paths.includes(item.key));

let currentMenuItems = [...menuRoutes];

let items: AppRouteObject[] | undefined = [...menuRoutes];
const breadCrumbs = pathRouteMetas.map((routeMeta) => {
return pathRouteMetas.map((routeMeta): MenuItem => {
const { key, label } = routeMeta;
items = items!
.find((item) => item.meta?.key === key)
?.children?.filter((item) => !item.meta?.hideMenu);
const result: MenuItem = {

// Find current level menu items
const currentRoute = currentMenuItems.find((item) => item.meta?.key === key);

// Update menu items for next level
currentMenuItems = currentRoute?.children?.filter((item) => !item.meta?.hideMenu) ?? [];

return {
key,
title: t(label),
...(currentMenuItems.length > 0 && {
menu: {
items: currentMenuItems.map((item) => ({
key: item.meta?.key,
label: <Link to={item.meta!.key!}>{t(item.meta!.label)}</Link>,
})),
},
}),
};
if (items) {
result.menu = {
items: items.map((item) => ({
key: item.meta?.key,
label: <Link to={item.meta!.key!}>{t(item.meta!.label)}</Link>,
})),
};
}
return result;
});
setBreadCrumbs(breadCrumbs);
}, [matches, flattenedRoutes, t, permissionRoutes]);

return (
Expand Down

0 comments on commit 8ca361b

Please sign in to comment.