Files

35 lines
1006 B
TypeScript

import UrlUtils from "~/utils/app/UrlUtils";
function pathnameOnly(value: string) {
const [path] = value.split(/[?#]/);
return UrlUtils.stripTrailingSlash(path || "/") || "/";
}
export function isRouteActive(currentPathname: string, targetHref: string, options?: { exact?: boolean }) {
const current = pathnameOnly(currentPathname);
const target = pathnameOnly(targetHref);
if (options?.exact) {
return current === target;
}
return current === target || current.startsWith(`${target}/`);
}
export function getBestActiveRouteIndex<T extends { routePath?: string; exact?: boolean }>(items: T[], currentPathname: string) {
let bestIndex = -1;
let bestLength = -1;
items.forEach((item, index) => {
if (!item.routePath || !isRouteActive(currentPathname, item.routePath, { exact: item.exact })) return;
const length = pathnameOnly(item.routePath).length;
if (length > bestLength) {
bestIndex = index;
bestLength = length;
}
});
return bestIndex;
}