diff --git a/src/components/Breadcrumbs.tsx b/src/components/Breadcrumbs.tsx index 4f24c4e3..a0b60754 100644 --- a/src/components/Breadcrumbs.tsx +++ b/src/components/Breadcrumbs.tsx @@ -1,35 +1,69 @@ import { usePathname } from 'next/navigation' import { twMerge } from 'tailwind-merge' import { Link } from './Link' -import React from 'react' +import React, { ReactNode, useMemo } from 'react' export type BreadcrumbsProps = { className?: string + rootKey?: string + delimiter?: ReactNode } -export const Breadcrumbs: React.FC = ({ className }) => { +export const Breadcrumbs: React.FC = ({ + className, + rootKey, + delimiter = '/', +}) => { const path = usePathname() - const crumbs = path - ? path + const crumbs = useMemo(() => { + if (!path) return [] + if (rootKey) { + const rootIndex = path.indexOf(rootKey) + return path + .slice(rootIndex + rootKey.length) .split('/') .filter(Boolean) .map(decodeURIComponent) .map(crumb => { return crumb[0].toUpperCase() + crumb.slice(1) }) - : [] + } + return path + .split('/') + .filter(Boolean) + .map(decodeURIComponent) + .map(crumb => { + return crumb[0].toUpperCase() + crumb.slice(1) + }) + }, [path, rootKey]) + + const root = useMemo(() => { + if (!rootKey) return 'Home' + + return rootKey[0].toUpperCase() + rootKey.slice(1) + }, [rootKey]) + + const rootPath = useMemo(() => { + if (!rootKey || !path) return '/' + + return path.slice(0, path.indexOf(rootKey) + rootKey.length) + }, [rootKey, path]) return (
- Home + {root} + {crumbs.slice(0, -1).map((crumb, i) => ( - / + {delimiter} {crumb} ))} + {crumbs.length > 0 && ( - / {crumbs[crumbs.length - 1]} + + {delimiter} {crumbs[crumbs.length - 1]} + )}
)