feat: mark active or ancestor links (#1840)
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import { VNode } from "preact";
|
||||
|
||||
/**
|
||||
* Mark active or ancestor link
|
||||
* Note: This function is used both on the server and the client
|
||||
*/
|
||||
export function setActiveUrl(vnode: VNode, pathname: string) {
|
||||
const props = vnode.props as Record<string, unknown>;
|
||||
const hrefProp = props.href;
|
||||
if (typeof hrefProp === "string" && hrefProp.startsWith("/")) {
|
||||
let href = new URL(hrefProp, "http://localhost").pathname;
|
||||
if (href !== "/" && href.endsWith("/")) {
|
||||
href = href.slice(0, -1);
|
||||
}
|
||||
|
||||
if (pathname !== "/" && pathname.endsWith("/")) {
|
||||
pathname = pathname.slice(0, -1);
|
||||
}
|
||||
|
||||
if (pathname === href) {
|
||||
props["data-current"] = "true";
|
||||
} else if (pathname.startsWith(href + "/") || href === "/") {
|
||||
props["data-ancestor"] = "true";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
PARTIAL_SEARCH_PARAM,
|
||||
PartialMode,
|
||||
} from "../../constants.ts";
|
||||
import { setActiveUrl } from "../active_url.ts";
|
||||
|
||||
function createRootFragment(
|
||||
parent: Element,
|
||||
@@ -704,6 +705,12 @@ export async function applyPartials(res: Response): Promise<void> {
|
||||
const originalHook = options.vnode;
|
||||
options.vnode = (vnode) => {
|
||||
assetHashingHook(vnode);
|
||||
|
||||
// Mark active or ancestor links
|
||||
if (vnode.type === "a") {
|
||||
setActiveUrl(vnode, location.pathname);
|
||||
}
|
||||
|
||||
if (originalHook) originalHook(vnode);
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user