asb_cloud_front/src/components/MenuBreadcrumb.tsx

47 lines
1.6 KiB
TypeScript
Raw Normal View History

import { Breadcrumb, BreadcrumbItemProps } from 'antd'
import { Link } from 'react-router-dom'
import { join } from 'path'
import { PrivateWellMenuItem } from '@components/PrivateWellMenu'
import { FunctionalValue, getFunctionalValue, } from '@utils'
export const makeBreadcrumbItems = (items: PrivateWellMenuItem[], pathParts: string[], root: string = '/') => {
const out = []
const parts = [...pathParts]
let route = root
let arr: PrivateWellMenuItem[] | undefined = items
while (arr && parts.length > 0) {
const child: PrivateWellMenuItem | undefined = arr.find(elm => elm.route.toLowerCase() === parts[0].toLowerCase())
if (!child) break
route = join(route, child.route)
out.push({ ...child, route })
parts.splice(0, 1)
arr = child.children
}
return out
}
export const makeMenuBreadcrumbItems = (
menuItems: PrivateWellMenuItem[],
path: string,
pathRoot: RegExp = /^\//,
itemsProps?: FunctionalValue<(item: PrivateWellMenuItem) => BreadcrumbItemProps>,
itemRender?: (item: PrivateWellMenuItem) => JSX.Element,
) => {
const getItemProps = getFunctionalValue(itemsProps)
const rootPart = pathRoot.exec(path)
if (!rootPart || rootPart.length <= 0) return []
const root = rootPart[0]
const parts = path.trim().slice(root.length).split('/')
const items = makeBreadcrumbItems(menuItems, parts, root)
return items.map((item) => (
<Breadcrumb.Item key={item.route} {...getItemProps(item)}>
{itemRender ? itemRender(item) : (
<Link to={item.route}>{item.title}</Link>
)}
</Breadcrumb.Item>
))
}