type Params = { href: string; pathname: string; /** Only match the exact path, not its sub-paths */ strict?: boolean; }; function normalizePath(path: string) { const trimmed = path.replace(/\/+$/, ""); return trimmed || "/"; } /** * # Check whether a link points to the current page * A non-strict link matches its own path and any sub-path, segment-wise: * `/blog` matches `/blog` and `/blog/post`, but not `/blogging`. The root * link `/` only ever matches `/`. Links to other origins never match. */ export default function twuiLinkMatchesPath({ href, pathname, strict, }: Params): boolean { if (href.startsWith("#")) return false; let linkPath: string; try { const origin = typeof window !== "undefined" ? window.location.origin : "http://twui.local"; const url = new URL(href, origin); if (url.origin !== origin) return false; linkPath = normalizePath(url.pathname); } catch { return false; } const currentPath = normalizePath(pathname); if (strict || linkPath === "/") return linkPath === currentPath; return currentPath === linkPath || currentPath.startsWith(`${linkPath}/`); }