From 60fed3f2cf05d7bc356ca77e226b08201a8f38db Mon Sep 17 00:00:00 2001 From: Brenley Dueck Date: Mon, 23 Nov 2026 20:11:45 -0600 Subject: [PATCH 1/3] perf(claims): return early for plain hrefs that cannot match the location --- .changeset/plain-href-link-claim-miss.md | 5 ++ src/claims.ts | 14 ++++- src/utils.ts | 3 ++ test/server/plain-href-fast-path.spec.ts | 65 +++++++++++++++++++++++- 4 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 .changeset/plain-href-link-claim-miss.md diff --git a/.changeset/plain-href-link-claim-miss.md b/.changeset/plain-href-link-claim-miss.md new file mode 100644 index 00000000..5173e928 --- /dev/null +++ b/.changeset/plain-href-link-claim-miss.md @@ -0,0 +1,5 @@ +--- +"@solidjs/router": patch +--- + +Server link claims return early for a plain root-relative href that cannot be the current location or one of its parents, so those links skip href resolution and matching. diff --git a/src/claims.ts b/src/claims.ts index 34dc898c..1e18249c 100644 --- a/src/claims.ts +++ b/src/claims.ts @@ -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, plainHref, serverPlainPath } from "./utils.js"; /** * Claimed forms are handed to this slot instead of the claims importing the @@ -233,6 +233,13 @@ 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)); +/** Whether a plain href's path can't be `loc` or a parent of it; lives here so client builds drop it. */ +export function plainHrefMisses(href: string, loc: string) { + if (!serverPlainPath!(href) || href[0] !== "/" || href[1] === "/" || href.endsWith("/")) + return false; + return 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, @@ -242,7 +249,12 @@ export function setupServerLinkClaims( const basePath = router.base.path(); const origin = page.origin; const match = locationMatcher(router, basePath); + let pathname: string | undefined; + let loc = ""; setLinkClaim(attrs => { + const locationPath = router.location.pathname; + if (locationPath !== pathname) loc = comparablePath((pathname = locationPath)); + if (typeof attrs.href === "string" && plainHrefMisses(attrs.href, loc)) return ""; const url = managedLinkUrl( { href: attr(attrs.href), diff --git a/src/utils.ts b/src/utils.ts index 1ec899bc..7a421efd 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -42,6 +42,9 @@ const hasDotSegment = (path: string) => path.includes("/.") && dotSegmentRegex.t /** Whether `URL` would report this pathname unchanged, so it can skip the parse. */ const isPlainPath = (path: string) => plainPathRegex.test(path) && !hasDotSegment(path); +/** `isPlainPath` for server-only callers in other modules; `undefined` in client builds so they drop it. */ +export const serverPlainPath = isServer ? isPlainPath : undefined; + /** A root-relative href's pathname, search and comparable path, or `undefined` if `URL` would change them. */ export function plainHref(href: string) { const m = plainHrefRegex.exec(href); diff --git a/test/server/plain-href-fast-path.spec.ts b/test/server/plain-href-fast-path.spec.ts index 95be3c0b..e499b70f 100644 --- a/test/server/plain-href-fast-path.spec.ts +++ b/test/server/plain-href-fast-path.spec.ts @@ -1,5 +1,12 @@ import { describe, expect, test } from "vitest"; -import { comparablePath, mockBase, normalizePath, plainHref } from "../../src/utils.js"; +import { + comparablePath, + linkMatcher, + mockBase, + normalizePath, + plainHref +} from "../../src/utils.js"; +import { plainHrefMisses } from "../../src/claims.js"; const viaUrl = (path: string) => new URL(mockBase + normalizePath(path.split(/[?#]/, 1)[0])).pathname @@ -51,3 +58,59 @@ describe("plain path fast path", () => { }); }); }); + +describe("plainHrefMisses", () => { + const state = (href: string, location: string) => { + const url = new URL(href, "http://sr/page/here?x=1"); + return linkMatcher({ pathname: location, search: "" }, "")(url.pathname + url.search); + }; + + test("never rejects a link the matcher would mark", () => { + const r = rand(2); + const segment = () => ["a", "B", "ab", "a.b", "%41", ".", "..", ""][Math.floor(r() * 8)]; + const path = () => { + let s = ""; + for (let n = Math.floor(r() * 4); n >= 0; n--) s += "/" + segment(); + return s; + }; + const suffix = ["", "", "", "/", "//", "?x=1", "/?x=1", "#y", "/#y"]; + let misses = 0; + let active = 0; + for (let i = 0; i < 100000; i++) { + const location = new URL("http://sr" + path()).pathname; + const href = (r() < 0.5 ? location : path()) + suffix[Math.floor(r() * suffix.length)]; + if (!URL.canParse(href, "http://sr/page/here?x=1")) continue; + const { active: a, current } = state(href, location); + if (a) active++; + if (plainHrefMisses(href, comparablePath(location))) { + misses++; + expect(a || current, `${href} on ${location}`).toBe(false); + } + } + expect(misses).toBeGreaterThan(1000); + expect(active).toBeGreaterThan(1000); + }); + + test("rejects unrelated plain paths and leaves the rest to the matcher", () => { + for (const [href, loc] of [ + ["/server-side-rendered/1", "/server-side-rendered"], + ["/a", ""], + ["/About/x", "/about"] + ]) + expect(plainHrefMisses(href, loc), href).toBe(true); + for (const [href, loc] of [ + ["/a", "/a"], + ["/A/", "/a"], + ["/a", "/a/b"], + ["/a?x=1", "/a"], + ["/b?x=1", "/a"], + ["/a//#y", "/a"], + ["/", ""], + ["/a/../b", "/b"], + ["/%61", "/a"], + ["relative", "/a"], + ["//x.example/a", "/a"] + ]) + expect(plainHrefMisses(href, loc), href).toBe(false); + }); +}); From 62459a736a5e6562a38171f6f91df64982c189a8 Mon Sep 17 00:00:00 2001 From: Brenley Dueck Date: Mon, 23 Nov 2026 20:20:24 -0600 Subject: [PATCH 2/3] perf(claims): keep plainHref out of client builds --- .changeset/client-drop-plain-href.md | 5 +++++ src/claims.ts | 10 ++++++++-- src/utils.ts | 3 +++ 3 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 .changeset/client-drop-plain-href.md diff --git a/.changeset/client-drop-plain-href.md b/.changeset/client-drop-plain-href.md new file mode 100644 index 00000000..df84c99f --- /dev/null +++ b/.changeset/client-drop-plain-href.md @@ -0,0 +1,5 @@ +--- +"@solidjs/router": patch +--- + +Client builds no longer ship `plainHref` and its regex, which only server link claims call. diff --git a/src/claims.ts b/src/claims.ts index 1e18249c..89d25ab9 100644 --- a/src/claims.ts +++ b/src/claims.ts @@ -1,7 +1,13 @@ 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 { comparablePath, isUnderBase, linkMatcher, plainHref, serverPlainPath } from "./utils.js"; +import { + comparablePath, + isUnderBase, + linkMatcher, + serverPlainHref, + serverPlainPath +} from "./utils.js"; /** * Claimed forms are handed to this slot instead of the claims importing the @@ -199,7 +205,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; diff --git a/src/utils.ts b/src/utils.ts index 7a421efd..e2992d30 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -56,6 +56,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`. From f4607e146684bbc03ae6050c43143655cdde2c97 Mon Sep 17 00:00:00 2001 From: Brenley Dueck Date: Mon, 30 Nov 2026 18:09:51 -0600 Subject: [PATCH 3/3] perf(claims): skip client link refresh for hrefs that can't match --- .changeset/client-link-claim-miss.md | 5 + .changeset/plain-href-link-claim-miss.md | 2 +- src/claims.ts | 43 ++-- src/utils.ts | 3 - test/claims-plain-miss.spec.tsx | 254 +++++++++++++++++++++++ test/server/plain-href-fast-path.spec.ts | 17 +- 6 files changed, 296 insertions(+), 28 deletions(-) create mode 100644 .changeset/client-link-claim-miss.md create mode 100644 test/claims-plain-miss.spec.tsx diff --git a/.changeset/client-link-claim-miss.md b/.changeset/client-link-claim-miss.md new file mode 100644 index 00000000..19803cf6 --- /dev/null +++ b/.changeset/client-link-claim-miss.md @@ -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. diff --git a/.changeset/plain-href-link-claim-miss.md b/.changeset/plain-href-link-claim-miss.md index 5173e928..99e309a4 100644 --- a/.changeset/plain-href-link-claim-miss.md +++ b/.changeset/plain-href-link-claim-miss.md @@ -2,4 +2,4 @@ "@solidjs/router": patch --- -Server link claims return early for a plain root-relative href that cannot be the current location or one of its parents, so those links skip href resolution and matching. +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. diff --git a/src/claims.ts b/src/claims.ts index 89d25ab9..656748d9 100644 --- a/src/claims.ts +++ b/src/claims.ts @@ -1,13 +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 { - comparablePath, - isUnderBase, - linkMatcher, - serverPlainHref, - serverPlainPath -} from "./utils.js"; +import { comparablePath, isUnderBase, linkMatcher, serverPlainHref } from "./utils.js"; /** * Claimed forms are handed to this slot instead of the claims importing the @@ -128,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 @@ -239,11 +238,22 @@ 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)); -/** Whether a plain href's path can't be `loc` or a parent of it; lives here so client builds drop it. */ -export function plainHrefMisses(href: string, loc: string) { - if (!serverPlainPath!(href) || href[0] !== "/" || href[1] === "/" || href.endsWith("/")) - return false; - return href.length > loc.length || !loc.startsWith(href.toLowerCase()); +// 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) { + 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`. */ @@ -255,12 +265,9 @@ export function setupServerLinkClaims( const basePath = router.base.path(); const origin = page.origin; const match = locationMatcher(router, basePath); - let pathname: string | undefined; - let loc = ""; + const misses = locationMisses(router); setLinkClaim(attrs => { - const locationPath = router.location.pathname; - if (locationPath !== pathname) loc = comparablePath((pathname = locationPath)); - if (typeof attrs.href === "string" && plainHrefMisses(attrs.href, loc)) return ""; + if (misses(attrs.href)) return ""; const url = managedLinkUrl( { href: attr(attrs.href), diff --git a/src/utils.ts b/src/utils.ts index e2992d30..920629fa 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -42,9 +42,6 @@ const hasDotSegment = (path: string) => path.includes("/.") && dotSegmentRegex.t /** Whether `URL` would report this pathname unchanged, so it can skip the parse. */ const isPlainPath = (path: string) => plainPathRegex.test(path) && !hasDotSegment(path); -/** `isPlainPath` for server-only callers in other modules; `undefined` in client builds so they drop it. */ -export const serverPlainPath = isServer ? isPlainPath : undefined; - /** A root-relative href's pathname, search and comparable path, or `undefined` if `URL` would change them. */ export function plainHref(href: string) { const m = plainHrefRegex.exec(href); diff --git a/test/claims-plain-miss.spec.tsx b/test/claims-plain-miss.spec.tsx new file mode 100644 index 00000000..7e99501c --- /dev/null +++ b/test/claims-plain-miss.spec.tsx @@ -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(resolve => queueMicrotask(() => resolve())); + await new Promise(resolve => setTimeout(resolve, 0)); +}; + +const routes = [ + { path: "/", component: () =>
}, + { path: "/about", component: () =>
}, + { path: "/users/:id", component: () =>
}, + { path: "/users/:id/settings", component: () =>
} +] 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( + () => ( + + {props => { + navigate = useNavigate(); + return ( + <> + {href => link} + {props.children} + + ); + }} + + ), + 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( + () => ( + + {props => ( + <> + + stale + + {props.children} + + )} + + ), + 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(() => {props => props.children}, 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; + } + }); +}); diff --git a/test/server/plain-href-fast-path.spec.ts b/test/server/plain-href-fast-path.spec.ts index e499b70f..68a7991c 100644 --- a/test/server/plain-href-fast-path.spec.ts +++ b/test/server/plain-href-fast-path.spec.ts @@ -6,7 +6,7 @@ import { normalizePath, plainHref } from "../../src/utils.js"; -import { plainHrefMisses } from "../../src/claims.js"; +import { locationMisses } from "../../src/claims.js"; const viaUrl = (path: string) => new URL(mockBase + normalizePath(path.split(/[?#]/, 1)[0])).pathname @@ -59,7 +59,10 @@ describe("plain path fast path", () => { }); }); -describe("plainHrefMisses", () => { +describe("locationMisses", () => { + const missesAt = (href: string, location: string) => + locationMisses({ location: { pathname: location } as any })(href); + const state = (href: string, location: string) => { const url = new URL(href, "http://sr/page/here?x=1"); return linkMatcher({ pathname: location, search: "" }, "")(url.pathname + url.search); @@ -82,7 +85,7 @@ describe("plainHrefMisses", () => { if (!URL.canParse(href, "http://sr/page/here?x=1")) continue; const { active: a, current } = state(href, location); if (a) active++; - if (plainHrefMisses(href, comparablePath(location))) { + if (missesAt(href, location)) { misses++; expect(a || current, `${href} on ${location}`).toBe(false); } @@ -91,13 +94,13 @@ describe("plainHrefMisses", () => { expect(active).toBeGreaterThan(1000); }); - test("rejects unrelated plain paths and leaves the rest to the matcher", () => { + test("rejects unrelated simple paths and leaves the rest to the matcher", () => { for (const [href, loc] of [ ["/server-side-rendered/1", "/server-side-rendered"], ["/a", ""], ["/About/x", "/about"] ]) - expect(plainHrefMisses(href, loc), href).toBe(true); + expect(missesAt(href, loc), href).toBe(true); for (const [href, loc] of [ ["/a", "/a"], ["/A/", "/a"], @@ -107,10 +110,12 @@ describe("plainHrefMisses", () => { ["/a//#y", "/a"], ["/", ""], ["/a/../b", "/b"], + ["/a.b", "/a"], + ["/a~b", "/x"], ["/%61", "/a"], ["relative", "/a"], ["//x.example/a", "/a"] ]) - expect(plainHrefMisses(href, loc), href).toBe(false); + expect(missesAt(href, loc), href).toBe(false); }); });