);
}
export function NavMain({ items }: { items: NavElement[] }) {
const pathname = usePathname();
// Find the most specific matching path from all nav items
const findMostSpecificMatch = (allItems: NavElement[]): string => {
const allPaths: string[] = [];
// Collect all paths from items and subitems
const collectPaths = (items: NavElement[]) => {
for (const item of items) {
if (isGroup(item)) {
collectPaths(item.items);
} else {
allPaths.push(item.path);
for (const subItem of item.subItems ?? []) {
allPaths.push(subItem.path);
}
}
}
};
collectPaths(allItems);
// Normalize paths and find matches
const normalizedPathname = pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;
const matches = allPaths
.map((path) => (path.endsWith('/') ? path.slice(0, -1) : path))
.filter((path) => {
// Exact match for root path
if (path === '/admin' && normalizedPathname === '/admin') {
return true;
}
// For other paths, check if it's an exact match or if it's a direct parent
if (path === '/admin') {
return false;
} // Skip empty paths
if (path === normalizedPathname) {
return true;
} // Exact match
// Check if this path is a direct parent of the current path
const pathParts = path.split('/').filter(Boolean);
const pathnameParts = normalizedPathname.split('/').filter(Boolean);
// If this path has more parts than the current pathname, it can't be a parent
if (pathParts.length > pathnameParts.length) {
return false;
}
// Check if all parts match up to the length of this path
// and if the next part in pathname exists (meaning this is a direct parent)
const partsMatch = pathParts.every((part, i) => part === pathnameParts[i]);
const isDirectParent = partsMatch && pathnameParts[pathParts.length];
return isDirectParent;
})
.sort((a, b) => b.length - a.length); // Sort by length, longest first
return matches[0] || '';
};
const mostSpecificPath = findMostSpecificMatch(items);
const isActive = (path: string) => {
const normalizedPath = path.endsWith('/') ? path.slice(0, -1) : path;
return normalizedPath === mostSpecificPath;
};
return (
{items.map((item) => {
if (isGroup(item)) {
return ;
}
return ;
})}
);
}