feat: mark active or ancestor links (#1840)

This commit is contained in:
Marvin Hagemeister
2023-10-02 18:22:44 +02:00
committed by GitHub
parent d638c526f5
commit 4295dbe85d
11 changed files with 304 additions and 138 deletions
+26
View File
@@ -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";
}
}
}
+7
View File
@@ -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);
};
+3
View File
@@ -15,6 +15,7 @@ import { renderToString } from "preact-render-to-string";
import { RenderState } from "./state.ts";
import { Island } from "../types.ts";
import { DATA_KEY_ATTR, LOADING_ATTR, PartialMode } from "../../constants.ts";
import { setActiveUrl } from "../../runtime/active_url.ts";
// See: https://github.com/preactjs/preact/blob/7748dcb83cedd02e37b3713634e35b97b26028fd/src/internal.d.ts#L3C1-L16
enum HookType {
@@ -262,6 +263,8 @@ options.__b = (vnode: VNode<Record<string, unknown>>) => {
[LOADING_ATTR]: vnode.props[LOADING_ATTR],
});
vnode.props[LOADING_ATTR] = current.islandProps.length - 1;
} else if (vnode.type === "a") {
setActiveUrl(vnode, current.url.pathname);
}
} else if (typeof vnode.type === "function") {
// Detect island vnodes and wrap them with a marker
+2
View File
@@ -40,6 +40,7 @@ export class RenderState {
error: Error | null = null;
isPartial: boolean;
partialCount = 0;
url: URL;
constructor(
routeOptions: RenderStateRouteOptions,
@@ -51,6 +52,7 @@ export class RenderState {
this.routeOptions = routeOptions;
this.csp = csp;
this.componentStack = componentStack;
this.url = routeOptions.url;
this.isPartial = routeOptions.url.searchParams.has(PARTIAL_SEARCH_PARAM);
if (error) this.routeOptions.error = error;