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/.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 new file mode 100644 index 00000000..99e309a4 --- /dev/null +++ b/.changeset/plain-href-link-claim-miss.md @@ -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. diff --git a/src/claims.ts b/src/claims.ts index 34dc898c..656748d9 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, serverPlainHref } from "./utils.js"; /** * Claimed forms are handed to this slot instead of the claims importing the @@ -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 @@ -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; @@ -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) { + 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, @@ -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), diff --git a/src/utils.ts b/src/utils.ts index 1ec899bc..920629fa 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -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`. 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 95be3c0b..68a7991c 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 { locationMisses } from "../../src/claims.js"; const viaUrl = (path: string) => new URL(mockBase + normalizePath(path.split(/[?#]/, 1)[0])).pathname @@ -51,3 +58,64 @@ describe("plain path fast path", () => { }); }); }); + +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); + }; + + 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 (missesAt(href, location)) { + misses++; + expect(a || current, `${href} on ${location}`).toBe(false); + } + } + expect(misses).toBeGreaterThan(1000); + expect(active).toBeGreaterThan(1000); + }); + + 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(missesAt(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"], + ["/a.b", "/a"], + ["/a~b", "/x"], + ["/%61", "/a"], + ["relative", "/a"], + ["//x.example/a", "/a"] + ]) + expect(missesAt(href, loc), href).toBe(false); + }); +});