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/quiet-links-match.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 4 additions & 5 deletions src/claims.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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 {
Expand Down
3 changes: 2 additions & 1 deletion src/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()));
Expand Down
112 changes: 112 additions & 0 deletions test/link-state.spec.ts
Original file line number Diff line number Diff line change
@@ -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<LocationChange>({ 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<LocationChange>(
{ value: `${base}/applications?b=2&a=1` },
{ ownedWrite: true }
);
const router = createRouterContext(
{ signal, utils: history.utils },
() => [],
undefined,
{
base
}
);
let links!: ReturnType<typeof useLinkState>[];
let fragments!: ReturnType<typeof useLinkState>[];
let home!: ReturnType<typeof useLinkState>;
let node!: ReturnType<typeof useLinkState>;
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();
}
});
}
);
});
40 changes: 39 additions & 1 deletion test/server/ssr-link-state.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,52 @@
// 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(`<a\\b[^>]*>${text}</a>`));
if (!m) throw new Error(`no anchor ${text} in ${html}`);
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<LocationChange>({ value }, { ownedWrite: true });
const router = createRouterContext({ signal, utils: hashHistory().utils }, () => []);
let link!: ReturnType<typeof useLinkState>;
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";
Expand Down