fix: Keep current page links active after anchor navigation (#6711)

A link to the current page loses its Current page styling after an
anchor jump or when opened with a hash. Keep the page link active, and
select only the matching section link when the URL has a fragment.

Ref #5377

## Changes
- Match path and query exactly.
- With no current fragment, match all links with that path and query.
- With a current fragment, match links without a fragment and links with
that exact fragment.
- Keep the existing `:local-link` polyfill to `[aria-current=page]`. An
explicit `aria-current` value can override that styling.
- Give static pages the browser URL after hydration and update link
state on fragment changes.

## Todo
- [x] Implement the mixed path, query, and fragment matching rule.
- [x] Cover plain links, router links, direct fragment loads, anchor
navigation, and static hydration.
- [x] Document the rule and its difference from standard `:local-link`
behavior, with the MDN reference.
- [x] Remove the redundant CSS selector rewrite, parser dependency,
generated schema snapshot, and unneeded history listener.
- [x] Run focused tests, typechecks, lint, formatting, and review the
final diff.
- [x] Confirm required CI checks pass on the latest cleanup commit.

## Verification
- SDK link URL tests: 18 passed.
- Plain React Link and hydration tests: 10 passed; hydration test passed
again after narrowing the subscription to fragment changes.
- Router Link tests: 23 passed.
- SDK, React Link, router, and CSS engine typechecks passed.
- Changed code passed oxlint, oxfmt, and `git diff --check`.
- Native fragment event behavior was checked in Chromium, Firefox, and
WebKit; hydration behavior was checked in Chromium.
- Required GitHub CI passed on
`9758b19a6d92c7ab8a2efc7efa553f725a68109f`; the empty Builder core shard
passed on retry.

## Behavior note
This mixed rule is Webstudio behavior, not the current CSS `:local-link`
draft, which ignores fragments on both URLs. Local Link styling follows
this mixed match. The mixed match also sets `aria-current="page"` by
default, including on section links. Authors can set another value
explicitly.
This commit is contained in:
Oleg Isonen authored and GitHub committed 2026-11-18 00:35:46 +01:00
1 parent aeb34e3c70
commit b9801bb731
16 files changed
+472 -49

No files matched your search

@@ -127,7 +127,6 @@ test("Preview links expose current page state for components and element anchors
text: previewLinkText.pageQueryLink,
active: false,
});
const previousCanvas = canvas;
await canvas.getByRole("link", { name: previewLinkText.pageLink }).click();
expect(await getCanvasFrame(page)).toBe(previousCanvas);
@@ -157,6 +156,11 @@ test("Preview links expose current page state for components and element anchors
text: previewLinkText.pageQueryLink,
active: false,
});
await expectActiveLink({
canvas,
text: previewLinkText.hashLink,
active: true,
});
await canvas
.getByRole("link", { name: previewLinkText.pageQueryLink })
+9
View File
@@ -72,6 +72,15 @@ When using links for navigation and wanting to highlight the current page, the l
<figure><picture><source srcset="../../.gitbook/assets/link-local-link-state-dark.png" media="(prefers-color-scheme: dark)"><img src="../../.gitbook/assets/link-local-link-state-light.png" alt="Style sources menu with the local-link state" width="240"></picture></figure>
Webstudio applies the Local Link state when the link's path and query string match the current URL. The part after `#` controls which links match:
- At `/faq`, links to `/faq`, `/faq#one`, and `/faq#two` all match.
- At `/faq#one`, links to `/faq` and `/faq#one` match, but `/faq#two` does not.
This differs from the [CSS `:local-link` definition](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/:local-link), which ignores the part after `#` in both URLs. Webstudio keeps it when the current URL points to a section, so a different section link does not get the Local Link state. When the current URL has no `#`, multiple section links can be highlighted at once.
By default, Webstudio marks every matching link with `aria-current="page"`, including section links. You can set a different `aria-current` value on a link when needed.
## Related
- [Button](button.md) – Clickable action buttons
@@ -5,7 +5,7 @@ import {
PageSettingsTitle,
ReactSdkContext,
} from "@webstudio-is/react-sdk/runtime";
import { LinkCurrentUrlContext } from "@webstudio-is/sdk-components-react";
import { BrowserCurrentUrlProvider } from "@webstudio-is/sdk-components-react";
import { assetBaseUrl, imageLoader } from "../../app/constants.mjs";
import { assetUrlsByPath } from "../../app/__generated__/$resources.assets";
import {
@@ -47,9 +47,9 @@ const PageComponent = ({ data }: { data: PageContext["data"] }) => {
return (
<ReactSdkContext.Provider value={sdkContext}>
<LinkCurrentUrlContext.Provider value={url}>
<BrowserCurrentUrlProvider serverUrl={url}>
<PageBoundary pageKey={pageKey} system={system} />
</LinkCurrentUrlContext.Provider>
</BrowserCurrentUrlProvider>
<PageSettingsMeta
url={url}
pageMeta={pageMeta}
@@ -5,7 +5,7 @@ import {
PageSettingsTitle,
ReactSdkContext,
} from "@webstudio-is/react-sdk/runtime";
import { LinkCurrentUrlContext } from "@webstudio-is/sdk-components-react";
import { BrowserCurrentUrlProvider } from "@webstudio-is/sdk-components-react";
import { assetBaseUrl, imageLoader } from "../../app/constants.mjs";
import { assetUrlsByPath } from "../../app/__generated__/$resources.assets";
import { Page, breakpoints, siteName } from "../../app/__generated__/_index";
@@ -43,9 +43,9 @@ const PageComponent = ({ data }: { data: PageContext["data"] }) => {
return (
<ReactSdkContext.Provider value={sdkContext}>
<LinkCurrentUrlContext.Provider value={url}>
<BrowserCurrentUrlProvider serverUrl={url}>
<PageBoundary pageKey={pageKey} system={system} />
</LinkCurrentUrlContext.Provider>
</BrowserCurrentUrlProvider>
<PageSettingsMeta
url={url}
pageMeta={pageMeta}
@@ -5,7 +5,7 @@ import {
PageSettingsTitle,
ReactSdkContext,
} from "@webstudio-is/react-sdk/runtime";
import { LinkCurrentUrlContext } from "@webstudio-is/sdk-components-react";
import { BrowserCurrentUrlProvider } from "@webstudio-is/sdk-components-react";
import { assetBaseUrl, imageLoader } from "../../app/constants.mjs";
import { assetUrlsByPath } from "../../app/__generated__/$resources.assets";
import { Page, breakpoints, siteName } from "../../app/__generated__/_index";
@@ -43,9 +43,9 @@ const PageComponent = ({ data }: { data: PageContext["data"] }) => {
return (
<ReactSdkContext.Provider value={sdkContext}>
<LinkCurrentUrlContext.Provider value={url}>
<BrowserCurrentUrlProvider serverUrl={url}>
<PageBoundary pageKey={pageKey} system={system} />
</LinkCurrentUrlContext.Provider>
</BrowserCurrentUrlProvider>
<PageSettingsMeta
url={url}
pageMeta={pageMeta}
@@ -5,7 +5,7 @@ import {
PageSettingsTitle,
ReactSdkContext,
} from "@webstudio-is/react-sdk/runtime";
import { LinkCurrentUrlContext } from "@webstudio-is/sdk-components-react";
import { BrowserCurrentUrlProvider } from "@webstudio-is/sdk-components-react";
import { assetBaseUrl, imageLoader } from "../../app/constants.mjs";
import { assetUrlsByPath } from "../../app/__generated__/$resources.assets";
import {
@@ -47,9 +47,9 @@ const PageComponent = ({ data }: { data: PageContext["data"] }) => {
return (
<ReactSdkContext.Provider value={sdkContext}>
<LinkCurrentUrlContext.Provider value={url}>
<BrowserCurrentUrlProvider serverUrl={url}>
<PageBoundary pageKey={pageKey} system={system} />
</LinkCurrentUrlContext.Provider>
</BrowserCurrentUrlProvider>
<PageSettingsMeta
url={url}
pageMeta={pageMeta}
@@ -5,7 +5,7 @@ import {
PageSettingsTitle,
ReactSdkContext,
} from "@webstudio-is/react-sdk/runtime";
import { LinkCurrentUrlContext } from "@webstudio-is/sdk-components-react";
import { BrowserCurrentUrlProvider } from "@webstudio-is/sdk-components-react";
import { assetBaseUrl, imageLoader } from "__CONSTANTS__";
import { assetUrlsByPath } from "__ASSETS__";
import { Page, breakpoints, siteName } from "__CLIENT__";
@@ -43,9 +43,9 @@ const PageComponent = ({ data }: { data: PageContext["data"] }) => {
return (
<ReactSdkContext.Provider value={sdkContext}>
<LinkCurrentUrlContext.Provider value={url}>
<BrowserCurrentUrlProvider serverUrl={url}>
<PageBoundary pageKey={pageKey} system={system} />
</LinkCurrentUrlContext.Provider>
</BrowserCurrentUrlProvider>
<PageSettingsMeta
url={url}
pageMeta={pageMeta}
@@ -2,6 +2,7 @@ import * as React from "react";
import { createRoot, type Root } from "react-dom/client";
import { act } from "react-dom/test-utils";
import {
createBrowserRouter,
createMemoryRouter,
RouterProvider,
useLoaderData,
@@ -44,7 +45,7 @@ const sdkContext = {
onError: vi.fn(),
};
test("local link is current only when pathname, search, and hash match", async () => {
test("local link is current when pathname and search match", async () => {
const router = createMemoryRouter(
[
{
@@ -66,7 +67,7 @@ test("local link is current only when pathname, search, and hash match", async (
<Link href="/path" className="custom">
Inactive class
</Link>
<Link href="/path?tag=bla#section" aria-current="location">
<Link href="/path?tag=bla#section" aria-current="step">
Aria override
</Link>
</ReactSdkContext.Provider>
@@ -83,16 +84,16 @@ test("local link is current only when pathname, search, and hash match", async (
expect(links.map((link) => link.getAttribute("aria-current"))).toEqual([
"page",
null,
null,
"page",
null,
null,
"page",
null,
"page",
"page",
"page",
"page",
null,
"page",
null,
"location",
"step",
]);
expect(links[0]?.getAttribute("class")).toBe("active");
@@ -131,6 +132,165 @@ test("local link preserves exact pathname behavior", async () => {
]);
});
test("only the matching section link is current", async () => {
const router = createMemoryRouter(
[
{
path: "/faq",
element: (
<ReactSdkContext.Provider value={sdkContext}>
<Link href="/faq">Page</Link>
<Link href="/faq#one">Section one</Link>
<Link href="/faq#two">Section two</Link>
</ReactSdkContext.Provider>
),
},
],
{ initialEntries: ["/faq#one"] }
);
await render(<RouterProvider router={router} />);
const links = Array.from(document.querySelectorAll("a"));
expect(links.map((link) => link.getAttribute("aria-current"))).toEqual([
"page",
"page",
null,
]);
expect(links.map((link) => link.className)).toEqual(["active", "active", ""]);
});
test("route link with an encoded section is current on direct load", async () => {
const router = createMemoryRouter(
[
{
path: "/faq",
element: (
<ReactSdkContext.Provider value={sdkContext}>
<Link href="/faq#café">Section</Link>
<Link href="/faq#other">Other section</Link>
</ReactSdkContext.Provider>
),
},
],
{ initialEntries: ["/faq#caf%C3%A9"] }
);
await render(<RouterProvider router={router} />);
expect(
Array.from(document.querySelectorAll("a"), (link) =>
link.getAttribute("aria-current")
)
).toEqual(["page", null]);
});
test("route links with Unicode are current on direct load and after navigation", async () => {
const initialUrl = window.location.href;
const initialState = window.history.state;
window.history.replaceState(null, "", "/faq/caf%C3%A9?q=pi%C3%B1ata");
const router = createBrowserRouter([
{
path: "/faq/:topic",
element: (
<ReactSdkContext.Provider value={sdkContext}>
<Link href="/faq/café?q=piñata">Coffee</Link>
<Link href="/faq/résumé?q=piñata" replace>
Résumé
</Link>
</ReactSdkContext.Provider>
),
},
]);
try {
await render(<RouterProvider router={router} />);
const links = Array.from(document.querySelectorAll("a"));
expect(links.map((link) => link.getAttribute("aria-current"))).toEqual([
"page",
null,
]);
await act(async () => {
links[1]?.click();
});
expect(window.location.pathname).toBe("/faq/r%C3%A9sum%C3%A9");
expect(window.location.search).toBe("?q=pi%C3%B1ata");
expect(links.map((link) => link.getAttribute("aria-current"))).toEqual([
null,
"page",
]);
} finally {
router.dispose();
window.history.replaceState(initialState, "", initialUrl);
}
});
test("current link matching uses the link's relative path mode", async () => {
const router = createMemoryRouter(
[
{
path: "/faq/:topic",
element: (
<ReactSdkContext.Provider value={sdkContext}>
<Link href="../café" relative="path">
Path relative
</Link>
<Link href="../café">Route relative</Link>
</ReactSdkContext.Provider>
),
},
],
{ initialEntries: ["/faq/caf%C3%A9"] }
);
await render(<RouterProvider router={router} />);
const links = Array.from(document.querySelectorAll("a"));
expect(links.map((link) => link.pathname)).toEqual([
"/faq/caf%C3%A9",
"/caf%C3%A9",
]);
expect(links.map((link) => link.getAttribute("aria-current"))).toEqual([
"page",
null,
]);
});
test("all section links match when the current URL has no fragment", async () => {
const router = createMemoryRouter(
[
{
path: "/faq",
element: (
<ReactSdkContext.Provider value={sdkContext}>
<Link href="/faq">Page</Link>
<Link href="/faq#one">Section one</Link>
<Link href="/faq#two">Section two</Link>
</ReactSdkContext.Provider>
),
},
],
{ initialEntries: ["/faq"] }
);
await render(<RouterProvider router={router} />);
const links = Array.from(document.querySelectorAll("a"));
expect(links.map((link) => link.getAttribute("aria-current"))).toEqual([
"page",
"page",
"page",
]);
expect(links.map((link) => link.className)).toEqual([
"active",
"active",
"active",
]);
});
test("external link renders as plain anchor without router context", async () => {
await render(
<Link
@@ -292,7 +452,7 @@ test("bare hash link targets the current page without the current hash", async (
const link = document.querySelector("a");
expect(link?.getAttribute("href")).toBe("#");
expect(link?.getAttribute("aria-current")).toBeNull();
expect(link?.getAttribute("aria-current")).toBe("page");
});
test("empty local link preserves the current search and clears the hash", async () => {
@@ -319,7 +479,7 @@ test("empty local link preserves the current search and clears the hash", async
const link = document.querySelector("a");
expect(link?.getAttribute("href")).toBe("/path?tag=bla");
expect(link?.getAttribute("aria-current")).toBeNull();
expect(link?.getAttribute("aria-current")).toBe("page");
await act(async () => {
link?.dispatchEvent(
@@ -0,0 +1,84 @@
import { hydrateRoot, type Root } from "react-dom/client";
import { renderToString } from "react-dom/server";
import { act } from "react-dom/test-utils";
import { expect, test, vi } from "vitest";
import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";
import { BrowserCurrentUrlProvider } from "./browser-current-url";
import { Link } from "./link";
(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
test("static links follow the browser fragment after hydration and navigation", async () => {
const originalUrl = window.location.href;
const serverUrl = new URL("/faq", originalUrl).href;
window.history.replaceState(null, "", `${serverUrl}#one`);
const element = (
<ReactSdkContext.Provider
value={{
assetBaseUrl: "/assets/",
imageLoader: ({ src }: { src: string }) => src,
videoLoader: ({ src }: { src: string }) => src,
resources: {},
breakpoints: [],
onError: vi.fn(),
}}
>
<BrowserCurrentUrlProvider serverUrl={serverUrl}>
<Link href="/faq">Page</Link>
<Link href="/faq#one">One</Link>
<Link href="/faq#two">Two</Link>
</BrowserCurrentUrlProvider>
</ReactSdkContext.Provider>
);
const container = document.createElement("div");
container.innerHTML = renderToString(element);
document.body.append(container);
const getLinks = () => Array.from(container.querySelectorAll("a"));
expect(getLinks().map((link) => link.className)).toEqual([
"active",
"active",
"active",
]);
expect(getLinks().map((link) => link.getAttribute("aria-current"))).toEqual([
"page",
"page",
"page",
]);
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
let root: Root | undefined;
try {
await act(async () => {
root = hydrateRoot(container, element);
});
expect(consoleError).not.toHaveBeenCalled();
expect(getLinks().map((link) => link.className)).toEqual([
"active",
"active",
"",
]);
expect(getLinks().map((link) => link.getAttribute("aria-current"))).toEqual(
["page", "page", null]
);
await act(async () => {
window.history.replaceState(null, "", `${serverUrl}#two`);
window.dispatchEvent(new HashChangeEvent("hashchange"));
});
expect(getLinks().map((link) => link.className)).toEqual([
"active",
"",
"active",
]);
expect(getLinks().map((link) => link.getAttribute("aria-current"))).toEqual(
["page", null, "page"]
);
} finally {
await act(async () => root?.unmount());
consoleError.mockRestore();
container.remove();
window.history.replaceState(null, "", originalUrl);
}
});
@@ -0,0 +1,30 @@
import { type ReactNode, useSyncExternalStore } from "react";
import { LinkCurrentUrlContext } from "./link-current-url";
const subscribeToUrl = (listener: () => void) => {
window.addEventListener("hashchange", listener);
return () => {
window.removeEventListener("hashchange", listener);
};
};
const getBrowserUrl = () => window.location.href;
export const BrowserCurrentUrlProvider = ({
children,
serverUrl,
}: {
children: ReactNode;
serverUrl: string;
}) => {
const currentUrl = useSyncExternalStore(
subscribeToUrl,
getBrowserUrl,
() => serverUrl
);
return (
<LinkCurrentUrlContext.Provider value={currentUrl}>
{children}
</LinkCurrentUrlContext.Provider>
);
};
@@ -11,7 +11,7 @@ import { createLink } from "./create-link";
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
test("fragment links keep server classes during hydration and become active afterward", async () => {
test("page links stay active while section links hydrate with the fragment", async () => {
let hash = "";
const RouterLink = forwardRef<
HTMLAnchorElement,
@@ -46,8 +46,10 @@ test("fragment links keep server classes during hydration and become active afte
onError: vi.fn(),
}}
>
<Link href="/path#section">Route link</Link>
<Link href="/path">Page link</Link>
<Link href="/path#section">Route section link</Link>
<Link href="#section">Hash link</Link>
<Link href="#other">Other section</Link>
</ReactSdkContext.Provider>
);
const container = document.createElement("div");
@@ -55,12 +57,12 @@ test("fragment links keep server classes during hydration and become active afte
document.body.append(container);
expect(
Array.from(container.querySelectorAll("a"), (link) => link.className)
).toEqual(["", ""]);
).toEqual(["active", "active", "active", "active"]);
expect(
Array.from(container.querySelectorAll("a"), (link) =>
link.getAttribute("aria-current")
)
).toEqual([null, null]);
).toEqual(["page", "page", "page", "page"]);
hash = "#section";
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
@@ -72,12 +74,12 @@ test("fragment links keep server classes during hydration and become active afte
expect(consoleError).not.toHaveBeenCalled();
expect(
Array.from(container.querySelectorAll("a"), (link) => link.className)
).toEqual(["active", "active"]);
).toEqual(["active", "active", "active", ""]);
expect(
Array.from(container.querySelectorAll("a"), (link) =>
link.getAttribute("aria-current")
)
).toEqual(["page", "page"]);
).toEqual(["page", "page", "page", null]);
} finally {
await act(async () => root?.unmount());
consoleError.mockRestore();
@@ -94,7 +94,10 @@ export const createLink = ({
}: {
Link: ComponentType<RouterLinkComponentProps>;
useLocation: () => UrlParts;
useResolvedPath: (href: string) => UrlParts;
useResolvedPath: (
href: string,
options: Pick<LinkProps, "relative">
) => UrlParts;
}): LinkComponent => {
const RouterLink = forwardRef<
HTMLAnchorElement,
@@ -105,7 +108,7 @@ export const createLink = ({
const { linkProps, currentLinkProps } = getCurrentLinkProps(
props,
location,
useResolvedPath(props.href)
useResolvedPath(props.href, { relative: props.relative })
);
return (
+7 -1
View File
@@ -1,7 +1,13 @@
import { createLink, type LinkProps } from "./create-link";
import { LinkCurrentUrlContext } from "./link-current-url";
import { BrowserCurrentUrlProvider } from "./browser-current-url";
export { createLink, LinkCurrentUrlContext, type LinkProps };
export {
BrowserCurrentUrlProvider,
createLink,
LinkCurrentUrlContext,
type LinkProps,
};
export {
createManagedSubmissionFormData,
getFormDataEntries,
@@ -32,7 +32,7 @@ const renderLinks = (currentUrl: string) => {
<Link href="/path" className="custom">
Inactive class
</Link>
<Link href="/path?tag=bla#section" aria-current="location">
<Link href="/path?tag=bla#section" aria-current="step">
Aria override
</Link>
</LinkCurrentUrlContext.Provider>
@@ -42,28 +42,30 @@ const renderLinks = (currentUrl: string) => {
return Array.from(document.querySelectorAll("a"));
};
test("local link is current only when pathname, search, and hash match", () => {
test("local link is current when pathname and search match", () => {
const links = renderLinks("https://example.com/path?tag=bla#section");
expect(links.map((link) => link.getAttribute("aria-current"))).toEqual([
"page",
null,
null,
"page",
null,
null,
"page",
null,
"page",
"page",
"page",
"page",
null,
"page",
null,
"location",
"step",
]);
expect(links[0]?.getAttribute("class")).toBe("active");
expect(links[1]?.hasAttribute("class")).toBe(false);
expect(links[9]?.getAttribute("class")).toBe("custom active");
expect(links[10]?.getAttribute("class")).toBe("custom");
expect(links[0]?.matches("[aria-current=page]")).toBe(true);
expect(links[11]?.matches("[aria-current=page]")).toBe(false);
});
test("local link preserves exact pathname behavior", () => {
@@ -88,6 +90,52 @@ test("local link preserves exact pathname behavior", () => {
]);
});
test("only the matching section link is current", () => {
const markup = renderToStaticMarkup(
<ReactSdkContext.Provider value={sdkContext}>
<LinkCurrentUrlContext.Provider value="https://example.com/faq#one">
<Link href="/faq">Page</Link>
<Link href="/faq#one">Section one</Link>
<Link href="/faq#two">Section two</Link>
</LinkCurrentUrlContext.Provider>
</ReactSdkContext.Provider>
);
document.body.innerHTML = markup;
const links = Array.from(document.querySelectorAll("a"));
expect(links.map((link) => link.getAttribute("aria-current"))).toEqual([
"page",
"page",
null,
]);
expect(links.map((link) => link.className)).toEqual(["active", "active", ""]);
});
test("all section links match when the current URL has no fragment", () => {
const markup = renderToStaticMarkup(
<ReactSdkContext.Provider value={sdkContext}>
<LinkCurrentUrlContext.Provider value="https://example.com/faq">
<Link href="/faq">Page</Link>
<Link href="/faq#one">Section one</Link>
<Link href="/faq#two">Section two</Link>
</LinkCurrentUrlContext.Provider>
</ReactSdkContext.Provider>
);
document.body.innerHTML = markup;
const links = Array.from(document.querySelectorAll("a"));
expect(links.map((link) => link.getAttribute("aria-current"))).toEqual([
"page",
"page",
"page",
]);
expect(links.map((link) => link.className)).toEqual([
"active",
"active",
"active",
]);
});
test("external and asset links render as plain anchors", () => {
const markup = renderToStaticMarkup(
<ReactSdkContext.Provider value={sdkContext}>
+66 -2
View File
@@ -28,7 +28,7 @@ test("empty asset base url does not exclude every root-relative href", () => {
expect(isInternalHref("/assets/file.pdf", "")).toBe(true);
});
test("local link matches exact pathname, search, and hash", () => {
test("local link matches exact pathname and search", () => {
expect(
isLocalLinkActive(
{ pathname: "/path", search: "?tag=bla", hash: "#section" },
@@ -37,7 +37,7 @@ test("local link matches exact pathname, search, and hash", () => {
).toBe(true);
});
test("local link does not match when pathname, search, or hash differ", () => {
test("local link does not match when pathname or search differ", () => {
const current = { pathname: "/path", search: "?tag=bla", hash: "#section" };
expect(
@@ -54,6 +54,18 @@ test("local link does not match when pathname, search, or hash differ", () => {
hash: "#section",
})
).toBe(false);
});
test("links match the page without a fragment and only the current section with one", () => {
const current = { pathname: "/path", search: "?tag=bla", hash: "#section" };
expect(
isLocalLinkActive(current, {
pathname: "/path",
search: "?tag=bla",
hash: "",
})
).toBe(true);
expect(
isLocalLinkActive(current, {
pathname: "/path",
@@ -61,6 +73,12 @@ test("local link does not match when pathname, search, or hash differ", () => {
hash: "#other",
})
).toBe(false);
expect(
isLocalLinkActive(
{ pathname: "/path", search: "?tag=bla", hash: "" },
current
)
).toBe(true);
});
test("local link matching is case-sensitive like concrete URLs", () => {
@@ -113,6 +131,52 @@ test("hash local link resolves against current pathname and search", () => {
});
});
test("hash local link matches the browser-encoded fragment", () => {
const current = new URL("https://example.com/faq#caf%C3%A9");
const href = "#café";
const target = resolveLocalLinkUrl(href, current, new URL(href, current));
expect(target.hash).toBe(current.hash);
expect(isLocalLinkActive(current, target)).toBe(true);
});
test("local link matches encoded and unencoded forms of the same fragment", () => {
const browserUrl = new URL("https://example.com/faq#caf%C3%A9");
const routerUrl = { pathname: "/faq", search: "", hash: "#café" };
expect(isLocalLinkActive(browserUrl, routerUrl)).toBe(true);
expect(isLocalLinkActive(routerUrl, browserUrl)).toBe(true);
});
test("local link encodes Unicode without splitting escaped path segments", () => {
const browserUrl = new URL("https://example.com/faq/caf%C3%A9%2Fmenu");
const routerUrl = { pathname: "/faq/café%2Fmenu", search: "", hash: "" };
expect(isLocalLinkActive(browserUrl, routerUrl)).toBe(true);
expect(isLocalLinkActive(routerUrl, browserUrl)).toBe(true);
expect(
isLocalLinkActive(browserUrl, { ...routerUrl, pathname: "/faq/café/menu" })
).toBe(false);
});
test("local link encodes Unicode without changing query order", () => {
const browserUrl = new URL("https://example.com/faq?q=caf%C3%A9&tag=menu");
const routerUrl = { pathname: "/faq", search: "?q=café&tag=menu", hash: "" };
expect(isLocalLinkActive(browserUrl, routerUrl)).toBe(true);
expect(isLocalLinkActive(routerUrl, browserUrl)).toBe(true);
expect(
isLocalLinkActive(browserUrl, { ...routerUrl, search: "?tag=menu&q=café" })
).toBe(false);
});
test("local link preserves trailing spaces in router fragments", () => {
const browserUrl = new URL("https://example.com/faq#section%20");
const routerUrl = { pathname: "/faq", search: "", hash: "#section " };
expect(isLocalLinkActive(browserUrl, routerUrl)).toBe(true);
});
test("bare hash local link resolves to current pathname and search without hash", () => {
const current = { pathname: "/path", search: "?tag=bla", hash: "#section" };
+19 -6
View File
@@ -33,23 +33,36 @@ export const resolveLocalLinkUrl = (
return {
pathname: location.pathname,
search: location.search,
hash: href === "#" ? "" : href,
hash: new URL(href, "https://webstudio.local/").hash,
};
}
return resolvedPath;
};
const serializeUrl = ({ pathname, search, hash }: UrlParts) => {
const url = new URL("https://webstudio.local/");
// Assign the parts directly to preserve trailing spaces and query order.
url.pathname = pathname;
url.search = search;
url.hash = hash;
return url;
};
/**
* Webstudio's local link styles target the concrete URL, not just the matched
* route. This intentionally preserves the old NavLink end/exact behavior while
* also requiring query string and fragment equality.
* route. Without a current fragment, all links to the same path and query
* match. With a fragment, page links and links to that section match.
*/
export const isLocalLinkActive = (current: UrlParts, target: UrlParts) => {
const currentUrl = serializeUrl(current);
const targetUrl = serializeUrl(target);
return (
current.pathname === target.pathname &&
current.search === target.search &&
current.hash === target.hash
currentUrl.pathname === targetUrl.pathname &&
currentUrl.search === targetUrl.search &&
(currentUrl.hash === "" ||
targetUrl.hash === "" ||
currentUrl.hash === targetUrl.hash)
);
};