Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/client-drop-plain-href.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@solidjs/router": patch
---

Client builds no longer ship `plainHref` and its regex, which only server link claims call.
5 changes: 5 additions & 0 deletions .changeset/client-link-claim-miss.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@solidjs/router": patch
---

Client link claims skip href resolution and matching for the same kind of href when it cannot be the current location or one of its parents, when the anchor has no link state to clear and no links plugin is installed.
5 changes: 5 additions & 0 deletions .changeset/plain-href-link-claim-miss.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@solidjs/router": patch
---

Server link claims return early for a root-relative href made of letter, digit, `_` and `-` segments that cannot be the current location or one of its parents, so those links skip href resolution and matching.
31 changes: 28 additions & 3 deletions src/claims.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { hasServerLinkState, isServer, registerElementClaim, setLinkClaim } from "@solidjs/web";
import { createRenderEffect, getOwner, isHydrating, onCleanup, untrack } from "solid-js";
import type { LinksPlugin, RouterContext } from "./types.js";
import { isUnderBase, linkMatcher, plainHref } from "./utils.js";
import { comparablePath, isUnderBase, linkMatcher, serverPlainHref } from "./utils.js";

/**
* Claimed forms are handed to this slot instead of the claims importing the
Expand Down Expand Up @@ -122,8 +122,13 @@ export function setupLinkClaims(
}
}

const misses = locationMisses(router);
// `apply` is a no-op for a link that can't be active and carries no state to clear
const refresh = (a: HTMLAnchorElement | SVGAElement, rec: { owned: boolean }) =>
untrack(() => apply(a, rec, linkState(a)));
untrack(() => {
if (plugin || rec.owned || a.hasAttribute("data-active") || !misses(a.getAttribute("href")))
apply(a, rec, linkState(a));
});

// The one subscription for every anchor: compute tracks the sources
// linkState derives from (with the plugin, its pending read — the
Expand Down Expand Up @@ -199,7 +204,7 @@ function managedLinkUrl(
if (a.rel && a.rel.split(/\s+/).includes("external")) return;
// server pages resolve root-relative hrefs against `origin`, so plain ones skip `URL`
let url: { pathname: string; search: string; comparable?: string } | undefined = isServer
? plainHref(a.href)
? serverPlainHref!(a.href)
: undefined;
if (!url) {
let parsed;
Expand Down Expand Up @@ -233,6 +238,24 @@ function locationMatcher(router: RouterContext, basePath: string) {
// a raw SSR attribute value as the DOM would read it back
const attr = (v: unknown) => (v == null || v === false ? null : v === true ? "" : String(v));

// a root-relative path `URL` keeps verbatim, with no dot or empty segments
const simplePathRegex = /^(?:\/[\w-]+)+$/;

/** Whether an href is a simple path that can't be the router's location or a parent of it. */
export function locationMisses(router: Pick<RouterContext, "location">) {
let pathname: string | undefined;
let loc = "";
return (href: unknown) => {
const locationPath = router.location.pathname;
if (locationPath !== pathname) loc = comparablePath((pathname = locationPath));
return (
typeof href === "string" &&
simplePathRegex.test(href) &&
(href.length > loc.length || !loc.startsWith(href.toLowerCase()))
);
};
}

/** Server link handler: marks anchors by the client's rule, resolved against `page`. */
export function setupServerLinkClaims(
router: RouterContext,
Expand All @@ -242,7 +265,9 @@ export function setupServerLinkClaims(
const basePath = router.base.path();
const origin = page.origin;
const match = locationMatcher(router, basePath);
const misses = locationMisses(router);
setLinkClaim(attrs => {
if (misses(attrs.href)) return "";
const url = managedLinkUrl(
{
href: attr(attrs.href),
Expand Down
3 changes: 3 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ export function plainHref(href: string) {
return { pathname, search: m[2] ? "?" + m[2] : "", comparable };
}

/** `plainHref` for server-only callers in other modules; `undefined` in client builds so they drop it. */
export const serverPlainHref = isServer ? plainHref : undefined;

/**
* Whether a URL path (query and hash ignored) is the router's base path or under it, on a segment
* boundary: base `/app` covers `/app`, `/app/` and `/app/x`, not `/apple`.
Expand Down
254 changes: 254 additions & 0 deletions test/claims-plain-miss.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
// Counts `URL` constructions to show which claimed links skip resolution and which fall back.
import { claimElementTree, render } from "@solidjs/web";
import { For } from "solid-js";
import { vi } from "vitest";
import { createRouter, memoryHistory, pendingLinks } from "../src/index.js";
import type { Navigator } from "../src/index.js";
import { useNavigate } from "../src/index.js";

const settle = async () => {
await new Promise<void>(resolve => queueMicrotask(() => resolve()));
await new Promise(resolve => setTimeout(resolve, 0));
};

const routes = [
{ path: "/", component: () => <div data-route="home" /> },
{ path: "/about", component: () => <div data-route="about" /> },
{ path: "/users/:id", component: () => <div data-route="user" /> },
{ path: "/users/:id/settings", component: () => <div data-route="settings" /> }
] as const;

const NativeURL = URL;
let parses = 0;

function renderLinks(
hrefs: string[],
options: { location: string; base?: string; links?: typeof pendingLinks }
) {
const div = document.createElement("div");
document.body.appendChild(div);
let navigate!: Navigator;
const Router = createRouter({
routes,
base: options.base,
history: memoryHistory(options.location),
links: options.links
});
parses = 0;
const dispose = render(
() => (
<Router>
{props => {
navigate = useNavigate();
return (
<>
<For each={hrefs}>{href => <a href={href}>link</a>}</For>
{props.children}
</>
);
}}
</Router>
),
div
);
const anchors = [...div.querySelectorAll("a")];
return {
navigate,
state: () =>
anchors.map(a =>
a.getAttribute("aria-current")
? "current"
: a.hasAttribute("data-active")
? "active"
: a.hasAttribute("data-pending")
? "pending"
: "none"
),
dispose: () => {
dispose();
div.remove();
}
};
}

describe("claimed anchors that can't match the location", () => {
const originalScrollTo = window.scrollTo;
beforeEach(() => {
window.scrollTo = vi.fn();
globalThis.URL = class extends NativeURL {
constructor(url: string | URL, base?: string | URL) {
super(url, base);
parses++;
}
} as typeof URL;
});
afterEach(() => {
globalThis.URL = NativeURL;
});
afterAll(() => {
window.scrollTo = originalScrollTo;
});

const unrelated = Array.from({ length: 20 }, (_, i) => `/server-side-rendered/${i}`);

test("unrelated links get no attributes and no URL parse, at claim or on navigation", async () => {
const { state, navigate, dispose } = renderLinks(unrelated, {
location: "/client-side-rendered"
});
try {
expect(state()).toEqual(unrelated.map(() => "none"));
expect(parses).toBeLessThan(5);
parses = 0;
navigate("/about");
await settle();
expect(state()).toEqual(unrelated.map(() => "none"));
expect(parses).toBeLessThan(10);
} finally {
dispose();
}
});

test("the location and its parents are still marked", () => {
const hrefs = [
"/users/1/settings",
"/Users/1",
"/users",
"/users/2",
"/users/1/settingsx",
"/"
];
const { state, dispose } = renderLinks(hrefs, { location: "/users/1/settings" });
try {
expect(state()).toEqual(["current", "active", "active", "none", "none", "none"]);
} finally {
dispose();
}
});

test("under a base path, only managed links under it are marked", () => {
const hrefs = ["/app/about", "/app", "/about", "/app/users/1", "/apple"];
const { state, dispose } = renderLinks(hrefs, { location: "/app/about", base: "/app" });
try {
expect(state()).toEqual(["current", "none", "none", "none", "none"]);
} finally {
dispose();
}
});

test("a query, hash or non-plain href falls back to URL resolution", () => {
const hrefs = [
"/about?x=1",
"/about#top",
"/other?x=1",
"/%61bout",
"/users/../about",
"//about",
"/about/",
"about",
"/a\\b"
];
const { state, dispose } = renderLinks(hrefs, { location: "/about" });
try {
expect(state()).toEqual([
"active",
"current",
"none",
"none",
"current",
"none",
"current",
"current",
"none"
]);
expect(parses).toBeGreaterThanOrEqual(hrefs.length);
} finally {
dispose();
}
});

test("a links plugin resolves every link for its pending state", async () => {
const { state, navigate, dispose } = renderLinks(unrelated, {
location: "/about",
links: pendingLinks
});
try {
expect(state()).toEqual(unrelated.map(() => "none"));
expect(parses).toBeGreaterThanOrEqual(unrelated.length);
navigate("/users/1");
await settle();
expect(state()).toEqual(unrelated.map(() => "none"));
} finally {
dispose();
}
});

test("a later navigation marks a link that was skipped at claim", async () => {
const { state, navigate, dispose } = renderLinks(["/users/1", "/users/1/settings"], {
location: "/about"
});
try {
expect(state()).toEqual(["none", "none"]);
navigate("/users/1/settings");
await settle();
expect(state()).toEqual(["active", "current"]);
navigate("/about");
await settle();
expect(state()).toEqual(["none", "none"]);
} finally {
dispose();
}
});

test("an authored data-active on an unrelated link is still cleared", () => {
const div = document.createElement("div");
document.body.appendChild(div);
const Router = createRouter({ routes, history: memoryHistory("/about") });
const dispose = render(
() => (
<Router>
{props => (
<>
<a data-testid="stale" href="/users/1" data-active>
stale
</a>
{props.children}
</>
)}
</Router>
),
div
);
try {
expect(div.querySelector('[data-testid="stale"]')!.hasAttribute("data-active")).toBe(false);
} finally {
dispose();
div.remove();
}
});

test("server state on a connected unrelated link is cleared, an authored aria-current kept", () => {
const div = document.createElement("div");
document.body.appendChild(div);
(globalThis as any)._$HY = { r: { links: 1 } };
const Router = createRouter({ routes, history: memoryHistory("/about") });
const dispose = render(() => <Router>{props => props.children}</Router>, div);
const owned = document.createElement("a");
owned.setAttribute("href", "/users/1");
owned.setAttribute("aria-current", "page");
owned.setAttribute("data-active", "");
const authored = document.createElement("a");
authored.setAttribute("href", "/users/2");
authored.setAttribute("aria-current", "step");
div.append(owned, authored);
try {
claimElementTree(div);
expect(owned.hasAttribute("aria-current")).toBe(false);
expect(owned.hasAttribute("data-active")).toBe(false);
expect(authored.getAttribute("aria-current")).toBe("step");
} finally {
dispose();
div.remove();
delete (globalThis as any)._$HY;
}
});
});
Loading