diff --git a/.changeset/quiet-links-match.md b/.changeset/quiet-links-match.md new file mode 100644 index 00000000..a5d07374 --- /dev/null +++ b/.changeset/quiet-links-match.md @@ -0,0 +1,5 @@ +--- +"@solidjs/router": patch +--- + +Fix hash-history link state to match the logical route in claimed anchor hrefs and `useLinkState` display strings. Preserve route-relative fragment inputs to the hook, including during server rendering. diff --git a/src/claims.ts b/src/claims.ts index 34dc898c..a15500d7 100644 --- a/src/claims.ts +++ b/src/claims.ts @@ -90,7 +90,7 @@ export function setupLinkClaims( const location = router.location; const routing = plugin && plugin.track(); const url = managedUrl(a); - const target = url && url.pathname + url.search; + const target = url && router.parsePath(url.pathname + url.search + (url.hash || "")); // no per-anchor `end` opt-out like useLinkState has const { active, current } = match(target); const pending = !!routing && plugin!.pending(target); @@ -194,13 +194,12 @@ function managedLinkUrl( page: string | URL, origin: string, basePath: string -): { pathname: string; search: string; comparable?: string } | undefined { +): { pathname: string; search: string; hash?: string; comparable?: string } | undefined { if ((explicitLinks && !a.link) || a.target || !a.href || a.download) return; 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) - : undefined; + let url: { pathname: string; search: string; hash?: string; comparable?: string } | undefined = + isServer ? plainHref(a.href) : undefined; if (!url) { let parsed; try { diff --git a/src/routing.ts b/src/routing.ts index 71f5d0f5..eaacf6de 100644 --- a/src/routing.ts +++ b/src/routing.ts @@ -409,7 +409,8 @@ export const useLinkState = ( // a paths node's brand is its logical path; toString is the display href const to = useResolvedPath(() => { const h: any = href(); - return h[HREF] || String(h); + const path = h[HREF] || String(h); + return path.startsWith("#/") ? router.parsePath(path) : path; }); const base = router.base.path(); const state = createMemo(() => linkMatcher(location, base, options.end)(to())); diff --git a/test/link-state.spec.ts b/test/link-state.spec.ts new file mode 100644 index 00000000..2c0016c4 --- /dev/null +++ b/test/link-state.spec.ts @@ -0,0 +1,112 @@ +import { claimElementTree } from "@solidjs/web"; +import { createRoot, createSignal } from "solid-js"; +import { setupLinkClaims } from "../src/claims.js"; +import { createRouter, hashHistory, useLinkState } from "../src/index.js"; +import { createRouterContext, RouterContextObj } from "../src/routing.js"; +import type { LocationChange } from "../src/types.js"; + +describe("hash-history link state", () => { + const page = window.location.href; + afterEach(() => window.history.replaceState(null, "", page)); + + test.each(["/", "/applications"])("claims logical targets at %s", pathname => { + window.history.replaceState(null, "", "/#/" + pathname.slice(1)); + createRoot(dispose => { + try { + const signal = createSignal({ value: pathname }, { ownedWrite: true }); + const router = createRouterContext({ signal, utils: hashHistory().utils }, () => []); + const targets: (string | undefined)[] = []; + setupLinkClaims(router, false, () => ({ + track: () => true, + pending: target => { + targets.push(target); + return target === "/applications"; + } + })); + const links = ["#/", "#/applications"].map(href => { + const anchor = document.createElement("a"); + anchor.setAttribute("href", href); + claimElementTree(anchor); + return anchor; + }); + expect(targets).toEqual(["/", "/applications"]); + for (const [index, anchor] of links.entries()) { + const current = index === (pathname === "/" ? 0 : 1); + expect(anchor.hasAttribute("data-active")).toBe(current); + expect(anchor.getAttribute("aria-current")).toBe(current ? "page" : null); + expect(anchor.hasAttribute("data-pending")).toBe(index === 1); + } + links[0].setAttribute("href", "#/applications"); + claimElementTree(links[0]); + expect(links[0].hasAttribute("data-active")).toBe(pathname === "/applications"); + } finally { + dispose(); + } + }); + }); + + test.each(["", "/app"])( + "resolves hook display strings without changing logical paths (base %s)", + base => { + window.history.replaceState(null, "", `${base || "/"}#${base}/applications`); + createRoot(dispose => { + try { + const history = hashHistory(); + const Router = createRouter({ + base, + history, + routes: [{ path: "/" }, { path: "/applications" }] + }); + const signal = createSignal( + { value: `${base}/applications?b=2&a=1` }, + { ownedWrite: true } + ); + const router = createRouterContext( + { signal, utils: history.utils }, + () => [], + undefined, + { + base + } + ); + let links!: ReturnType[]; + let fragments!: ReturnType[]; + let home!: ReturnType; + let node!: ReturnType; + const context = RouterContextObj({ + value: router, + get children() { + const hrefs = [ + Router.paths.applications({ a: "1", b: "2" }, "section"), + `#${base}/applications?a=1&b=2#section`, + `${base}/applications?a=1&b=2#section`, + "applications?a=1&b=2#section" + ]; + links = hrefs.map(href => useLinkState(() => href)); + fragments = ["#details", "#"].map(href => useLinkState(() => href)); + home = useLinkState(() => Router.paths()); + node = useLinkState(() => Router.paths.applications); + return null; + } + }) as () => unknown; + context(); + for (const link of links) { + expect(link.current()).toBe(true); + expect(link.active()).toBe(true); + } + for (const link of fragments) { + expect(link.current()).toBe(false); + expect(link.active()).toBe(false); + expect(link.pending()).toBe(false); + } + expect(home.current()).toBe(false); + expect(home.active()).toBe(false); + expect(node.current()).toBe(false); + expect(node.active()).toBe(true); + } finally { + dispose(); + } + }); + } + ); +}); diff --git a/test/server/ssr-link-state.spec.tsx b/test/server/ssr-link-state.spec.tsx index b129e7f9..8a0fb6d0 100644 --- a/test/server/ssr-link-state.spec.tsx +++ b/test/server/ssr-link-state.spec.tsx @@ -1,7 +1,10 @@ // Link state in server HTML (#654), marked by the client's claim rule. import { renderToString } from "@solidjs/web"; import { provideRequestEvent } from "@solidjs/web/storage"; -import { createRouter, hashHistory } from "../../src/index.js"; +import { createRoot, createSignal } from "solid-js"; +import { createRouter, hashHistory, useLinkState } from "../../src/index.js"; +import { createRouterContext, RouterContextObj } from "../../src/routing.js"; +import type { LocationChange } from "../../src/types.js"; const anchor = (html: string, text: string) => { const m = html.match(new RegExp(`]*>${text}`)); @@ -9,6 +12,41 @@ const anchor = (html: string, text: string) => { return m[0]; }; +describe("SSR hash-history hook state", () => { + test.each([ + ["#details", "/", true, true], + ["#", "/", true, true], + ["#details", "/applications", false, false], + ["#/applications", "/applications", true, true], + ["#/applications?b=2&a=1#details", "/applications?a=1&b=2", true, true], + ["#/applications?tab=other", "/applications?tab=current", false, true], + ["/applications#details", "/applications", true, true], + ["applications#details", "/applications", true, true] + ] as const)("matches %s at %s without browser globals", (href, value, current, active) => { + expect(typeof window).toBe("undefined"); + createRoot(dispose => { + try { + const signal = createSignal({ value }, { ownedWrite: true }); + const router = createRouterContext({ signal, utils: hashHistory().utils }, () => []); + let link!: ReturnType; + const context = RouterContextObj({ + value: router, + get children() { + link = useLinkState(() => href); + return null; + } + }) as () => unknown; + context(); + expect(link.current()).toBe(current); + expect(link.active()).toBe(active); + expect(link.pending()).toBe(false); + } finally { + dispose(); + } + }); + }); +}); + describe("SSR link state", () => { const Layout = (props: any) => { const dynamic = () => "/users/2";