diff --git a/apps/builder/e2e/tests/preview-links.[shard-3].e2e.ts b/apps/builder/e2e/tests/preview-links.[shard-3].e2e.ts
index 9b7f34fe4e..ea7d30bf95 100644
--- a/apps/builder/e2e/tests/preview-links.[shard-3].e2e.ts
+++ b/apps/builder/e2e/tests/preview-links.[shard-3].e2e.ts
@@ -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 })
diff --git a/docs/university/core-components/link.md b/docs/university/core-components/link.md
index 31c000c09e..4c56e641f3 100644
--- a/docs/university/core-components/link.md
+++ b/docs/university/core-components/link.md
@@ -72,6 +72,15 @@ When using links for navigation and wanting to highlight the current page, the l
+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
diff --git a/fixtures/ssg-cloudflare-pages/pages/another-page/+Page.tsx b/fixtures/ssg-cloudflare-pages/pages/another-page/+Page.tsx
index 3359a47b81..2f475d1d7e 100644
--- a/fixtures/ssg-cloudflare-pages/pages/another-page/+Page.tsx
+++ b/fixtures/ssg-cloudflare-pages/pages/another-page/+Page.tsx
@@ -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 (
-
+
-
+
{
return (
-
+
-
+
{
return (
-
+
-
+
{
return (
-
+
-
+
{
return (
-
+
-
+
{
+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 (
Inactive class
-
+
Aria override
@@ -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: (
+
+ Page
+ Section one
+ Section two
+
+ ),
+ },
+ ],
+ { initialEntries: ["/faq#one"] }
+ );
+
+ await render();
+ 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: (
+
+ Section
+ Other section
+
+ ),
+ },
+ ],
+ { initialEntries: ["/faq#caf%C3%A9"] }
+ );
+
+ await render();
+
+ 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: (
+
+ Coffee
+
+ Résumé
+
+
+ ),
+ },
+ ]);
+
+ try {
+ await render();
+ 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: (
+
+
+ Path relative
+
+ Route relative
+
+ ),
+ },
+ ],
+ { initialEntries: ["/faq/caf%C3%A9"] }
+ );
+
+ await render();
+
+ 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: (
+
+ Page
+ Section one
+ Section two
+
+ ),
+ },
+ ],
+ { initialEntries: ["/faq"] }
+ );
+
+ await render();
+ 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(
{
@@ -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(
diff --git a/packages/sdk-components-react/src/browser-current-url.browser.test.tsx b/packages/sdk-components-react/src/browser-current-url.browser.test.tsx
new file mode 100644
index 0000000000..97d2305d30
--- /dev/null
+++ b/packages/sdk-components-react/src/browser-current-url.browser.test.tsx
@@ -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 = (
+ src,
+ videoLoader: ({ src }: { src: string }) => src,
+ resources: {},
+ breakpoints: [],
+ onError: vi.fn(),
+ }}
+ >
+
+ Page
+ One
+ Two
+
+
+ );
+ 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);
+ }
+});
diff --git a/packages/sdk-components-react/src/browser-current-url.tsx b/packages/sdk-components-react/src/browser-current-url.tsx
new file mode 100644
index 0000000000..72dfb28040
--- /dev/null
+++ b/packages/sdk-components-react/src/browser-current-url.tsx
@@ -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 (
+
+ {children}
+
+ );
+};
diff --git a/packages/sdk-components-react/src/create-link.browser.test.tsx b/packages/sdk-components-react/src/create-link.browser.test.tsx
index c4bb67f794..47a7163e0b 100644
--- a/packages/sdk-components-react/src/create-link.browser.test.tsx
+++ b/packages/sdk-components-react/src/create-link.browser.test.tsx
@@ -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(),
}}
>
- Route link
+ Page link
+ Route section link
Hash link
+ Other section
);
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();
diff --git a/packages/sdk-components-react/src/create-link.tsx b/packages/sdk-components-react/src/create-link.tsx
index d2ae5602e3..0934d2d4c6 100644
--- a/packages/sdk-components-react/src/create-link.tsx
+++ b/packages/sdk-components-react/src/create-link.tsx
@@ -94,7 +94,10 @@ export const createLink = ({
}: {
Link: ComponentType;
useLocation: () => UrlParts;
- useResolvedPath: (href: string) => UrlParts;
+ useResolvedPath: (
+ href: string,
+ options: Pick
+ ) => 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 (
diff --git a/packages/sdk-components-react/src/index.ts b/packages/sdk-components-react/src/index.ts
index 470d213c53..b7c60712cc 100644
--- a/packages/sdk-components-react/src/index.ts
+++ b/packages/sdk-components-react/src/index.ts
@@ -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,
diff --git a/packages/sdk-components-react/src/link.browser.test.tsx b/packages/sdk-components-react/src/link.browser.test.tsx
index 13c8fa5a66..de7a56d117 100644
--- a/packages/sdk-components-react/src/link.browser.test.tsx
+++ b/packages/sdk-components-react/src/link.browser.test.tsx
@@ -32,7 +32,7 @@ const renderLinks = (currentUrl: string) => {
Inactive class
-
+
Aria override
@@ -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(
+
+
+ Page
+ Section one
+ Section two
+
+
+ );
+ 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(
+
+
+ Page
+ Section one
+ Section two
+
+
+ );
+ 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(
diff --git a/packages/sdk/src/link-utils.test.ts b/packages/sdk/src/link-utils.test.ts
index ffe4c1aef1..7acbace2c3 100644
--- a/packages/sdk/src/link-utils.test.ts
+++ b/packages/sdk/src/link-utils.test.ts
@@ -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" };
diff --git a/packages/sdk/src/link-utils.ts b/packages/sdk/src/link-utils.ts
index c7647a9d37..d7929793be 100644
--- a/packages/sdk/src/link-utils.ts
+++ b/packages/sdk/src/link-utils.ts
@@ -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)
);
};