Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: Fix local link matching when query params are used (#5802)
Oleg Isonen03f398d9b267
diff --git a/packages/sdk-components-react-remix/src/link.tsx b/packages/sdk-components-react-remix/src/link.tsxindex aa5f39edc4..5e630ada21 100644--- a/packages/sdk-components-react-remix/src/link.tsx+++ b/packages/sdk-components-react-remix/src/link.tsx@@ -1,42 +1,12 @@-import { forwardRef, type ComponentPropsWithoutRef, useContext } from "react";-import { NavLink as RemixLink } from "@remix-run/react";-import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";-import { Link as BaseLink } from "@webstudio-is/sdk-components-react";--type Props = Omit<ComponentPropsWithoutRef<typeof BaseLink>, "target"> & {- // override (string & {}) in target to generate keywords- target?: "_self" | "_blank" | "_parent" | "_top";-- // useful remix props- prefetch?: "none" | "intent" | "render" | "viewport";- reloadDocument?: boolean;- replace?: boolean;- preventScrollReset?: boolean;-};--export const Link = forwardRef<HTMLAnchorElement, Props>((props, ref) => {- const { assetBaseUrl } = useContext(ReactSdkContext);- // cast to string when invalid value type is provided with binding- const href = String(props.href ?? "");-- // use remix link for self reference and all relative urls- // ignore asset paths which can be relative too- // urls starting with # should be handled natively to not override search params- if (- // remix appends ?index in runtime but not in ssr- href === "" ||- href.startsWith("?") ||- (href.startsWith("/") && href.startsWith(assetBaseUrl) === false)- ) {- // In the future, we will switch to the :local-link pseudo-class (https://developer.mozilla.org/en-US/docs/Web/CSS/:local-link). (aria-current="page" is used now)- // Therefore, we decided to use end={true} (exact route matching) for all links to facilitate easier migration.- return <RemixLink {...props} to={href} ref={ref} end />;- }-- const { prefetch, reloadDocument, replace, preventScrollReset, ...rest } =- props;-- return <BaseLink {...rest} ref={ref} />;+import {+ Link as RemixLink,+ useLocation,+ useResolvedPath,+} from "@remix-run/react";+import { createLocalLink } from "@webstudio-is/sdk-components-react/local-link";++export const Link = createLocalLink({+ Link: RemixLink,+ useLocation,+ useResolvedPath,});--Link.displayName = BaseLink.displayName;diff --git a/packages/sdk-components-react-router/src/link.test.tsx b/packages/sdk-components-react-router/src/link.test.tsxindex a60887b18d..21b261b5a8 100644--- a/packages/sdk-components-react-router/src/link.test.tsx+++ b/packages/sdk-components-react-router/src/link.test.tsx@@ -38,6 +38,393 @@ const render = async (children: React.ReactNode) => {});};+const sdkContext = {+ assetBaseUrl: "/assets/",+ imageLoader: ({ src }: { src: string }) => src,+ videoLoader: ({ src }: { src: string }) => src,+ resources: {},+ breakpoints: [],+ onError: vi.fn(),+};++test("local link is current only when pathname, search, and hash match", async () => {+ const router = createMemoryRouter(+ [+ {+ path: "/path",+ element: (+ <ReactSdkContext.Provider value={sdkContext}>+ <Link href="/path?tag=bla#section">Exact</Link>+ <Link href="/path">Path only</Link>+ <Link href="/path?tag=bla">Missing hash</Link>+ <Link href="/path?tag=other#section">Different query</Link>+ <Link href="/path#section">Missing query</Link>+ <Link href="#section">Hash only</Link>+ <Link href="#">Bare hash</Link>+ <Link href="?tag=bla#section">Search only</Link>+ <Link href="">Empty</Link>+ <Link href="/path?tag=bla#section" className="custom">+ Active class+ </Link>+ <Link href="/path" className="custom">+ Inactive class+ </Link>+ <Link href="/path?tag=bla#section" aria-current="location">+ Aria override+ </Link>+ </ReactSdkContext.Provider>+ ),+ },+ ],+ { initialEntries: ["/path?tag=bla#section"] }+ );++ await render(<RouterProvider router={router} />);++ const links = Array.from(document.querySelectorAll("a"));++ expect(links.map((link) => link.getAttribute("aria-current"))).toEqual([+ "page",+ null,+ null,+ null,+ null,+ "page",+ null,+ "page",+ null,+ "page",+ null,+ "location",+ ]);++ 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");+});++test("local link preserves exact pathname behavior", async () => {+ const router = createMemoryRouter(+ [+ {+ path: "/path/*",+ element: (+ <ReactSdkContext.Provider value={sdkContext}>+ <Link href="/path">Parent</Link>+ <Link href="/path/child">Child</Link>+ <Link href="/path/">Trailing slash</Link>+ <Link href="/Path/child">Different case</Link>+ </ReactSdkContext.Provider>+ ),+ },+ ],+ { initialEntries: ["/path/child"] }+ );++ await render(<RouterProvider router={router} />);++ const links = Array.from(document.querySelectorAll("a"));++ expect(links.map((link) => link.getAttribute("aria-current"))).toEqual([+ null,+ "page",+ null,+ null,+ ]);+});++test("external link renders as plain anchor without router context", async () => {+ await render(+ <Link+ href="https://example.com/page"+ prefetch="intent"+ preventScrollReset+ reloadDocument+ replace+ target="_blank"+ >+ External+ </Link>+ );++ const link = document.querySelector("a");++ expect(link?.getAttribute("href")).toBe("https://example.com/page");+ expect(link?.getAttribute("target")).toBe("_blank");+ expect(link?.hasAttribute("prefetch")).toBe(false);+ expect(link?.hasAttribute("preventscrollreset")).toBe(false);+ expect(link?.hasAttribute("reloaddocument")).toBe(false);+ expect(link?.hasAttribute("replace")).toBe(false);+});++test("protocol-relative link renders as plain anchor without router context", async () => {+ await render(<Link href="//example.com/page">Protocol relative</Link>);++ const link = document.querySelector("a");++ expect(link?.getAttribute("href")).toBe("//example.com/page");+});++test("protocol links render as plain anchors without router context", async () => {+ await render(+ <>+ <Link href="mailto:[email protected]">Email</Link>+ <Link href="tel:+15555555555">Phone</Link>+ </>+ );++ const links = Array.from(document.querySelectorAll("a"));++ expect(links[0]?.getAttribute("href")).toBe("mailto:[email protected]");+ expect(links[1]?.getAttribute("href")).toBe("tel:+15555555555");+});++test("asset link renders as plain anchor without router context", async () => {+ await render(+ <ReactSdkContext.Provider value={sdkContext}>+ <Link href="/assets/file.pdf">Asset</Link>+ </ReactSdkContext.Provider>+ );++ const link = document.querySelector("a");++ expect(link?.getAttribute("href")).toBe("/assets/file.pdf");+ expect(link?.getAttribute("aria-current")).toBeNull();+});++test("asset base url only excludes matching root-relative asset paths", async () => {+ const router = createMemoryRouter(+ [+ {+ path: "/path",+ element: (+ <ReactSdkContext.Provider+ value={{ ...sdkContext, assetBaseUrl: "/assets/" }}+ >+ <Link href="/assets">Asset-looking page</Link>+ <Link href="/assets2/file.pdf">Similar prefix page</Link>+ </ReactSdkContext.Provider>+ ),+ },+ ],+ { initialEntries: ["/path"] }+ );++ await render(<RouterProvider router={router} />);++ const links = Array.from(document.querySelectorAll("a"));++ expect(links[0]?.getAttribute("data-discover")).toBe("true");+ expect(links[1]?.getAttribute("data-discover")).toBe("true");+});++test("hash-only link does not start router navigation", async () => {+ const router = createMemoryRouter(+ [+ {+ path: "/path",+ element: (+ <ReactSdkContext.Provider value={sdkContext}>+ <Link+ href="#section"+ prefetch="intent"+ preventScrollReset+ reloadDocument+ replace+ >+ Hash+ </Link>+ </ReactSdkContext.Provider>+ ),+ },+ {+ path: "/other",+ element: <div>Other page</div>,+ },+ ],+ { initialEntries: ["/path?tag=bla#section"] }+ );++ await render(<RouterProvider router={router} />);++ const link = document.querySelector("a");++ expect(link?.getAttribute("href")).toBe("#section");+ expect(link?.getAttribute("aria-current")).toBe("page");+ expect(link?.hasAttribute("prefetch")).toBe(false);+ expect(link?.hasAttribute("preventscrollreset")).toBe(false);+ expect(link?.hasAttribute("reloaddocument")).toBe(false);+ expect(link?.hasAttribute("replace")).toBe(false);++ await act(async () => {+ link?.dispatchEvent(+ new MouseEvent("click", {+ bubbles: true,+ cancelable: true,+ button: 0,+ })+ );+ await Promise.resolve();+ });++ expect(router.state.location.pathname).toBe("/path");+ expect(router.state.location.search).toBe("?tag=bla");+ expect(router.state.location.hash).toBe("#section");+});++test("bare hash link targets the current page without the current hash", async () => {+ const router = createMemoryRouter(+ [+ {+ path: "/path",+ element: (+ <ReactSdkContext.Provider value={sdkContext}>+ <Link href="#">Hash</Link>+ </ReactSdkContext.Provider>+ ),+ },+ ],+ { initialEntries: ["/path?tag=bla#section"] }+ );++ await render(<RouterProvider router={router} />);++ const link = document.querySelector("a");++ expect(link?.getAttribute("href")).toBe("#");+ expect(link?.getAttribute("aria-current")).toBeNull();+});++test("empty local link preserves the current search and clears the hash", async () => {+ const router = createMemoryRouter(+ [+ {+ path: "/path",+ element: (+ <ReactSdkContext.Provider value={sdkContext}>+ <Link href="">Empty</Link>+ </ReactSdkContext.Provider>+ ),+ },+ {+ path: "/other",+ element: <div>Other page</div>,+ },+ ],+ { initialEntries: ["/path?tag=bla#section"] }+ );++ await render(<RouterProvider router={router} />);++ const link = document.querySelector("a");++ expect(link?.getAttribute("href")).toBe("/path?tag=bla");+ expect(link?.getAttribute("aria-current")).toBeNull();++ await act(async () => {+ link?.dispatchEvent(+ new MouseEvent("click", {+ bubbles: true,+ cancelable: true,+ button: 0,+ })+ );+ await Promise.resolve();+ });++ expect(router.state.location.pathname).toBe("/path");+ expect(router.state.location.search).toBe("?tag=bla");+ expect(router.state.location.hash).toBe("");+});++test("router link forwards navigation props and resolves relative href", async () => {+ const router = createMemoryRouter(+ [+ {+ path: "/parent/child",+ element: (+ <ReactSdkContext.Provider value={sdkContext}>+ <Link href="../next?tab=1#section" preventScrollReset replace>+ Relative+ </Link>+ </ReactSdkContext.Provider>+ ),+ },+ {+ path: "/next",+ element: <div>Next route</div>,+ },+ ],+ { initialEntries: ["/parent/child"] }+ );++ await render(<RouterProvider router={router} />);++ const link = document.querySelector("a");++ expect(link?.getAttribute("href")).toBe("/next?tab=1#section");+ expect(link?.getAttribute("data-discover")).toBe("true");++ await act(async () => {+ link?.dispatchEvent(+ new MouseEvent("click", {+ bubbles: true,+ cancelable: true,+ button: 0,+ })+ );+ await Promise.resolve();+ });++ expect(router.state.location.pathname).toBe("/next");+ expect(router.state.location.search).toBe("?tab=1");+ expect(router.state.location.hash).toBe("#section");+});++test("router link calls onClick and respects preventDefault", async () => {+ const onClick = vi.fn((event: React.MouseEvent<HTMLAnchorElement>) => {+ event.preventDefault();+ });+ const router = createMemoryRouter(+ [+ {+ path: "/",+ element: (+ <ReactSdkContext.Provider value={sdkContext}>+ <Link href="/next" onClick={onClick}>+ Next+ </Link>+ </ReactSdkContext.Provider>+ ),+ },+ {+ path: "/next",+ element: <div>Next page</div>,+ },+ ],+ { initialEntries: ["/"] }+ );++ await render(<RouterProvider router={router} />);++ const link = document.querySelector("a");++ await act(async () => {+ link?.dispatchEvent(+ new MouseEvent("click", {+ bubbles: true,+ cancelable: true,+ button: 0,+ })+ );+ await Promise.resolve();+ });++ expect(onClick).toHaveBeenCalledTimes(1);+ expect(router.state.location.pathname).toBe("/");+});+test("internal link click does not rerender current generated page while destination is pending", async () => {let pageRenderCount = 0;let linkContentRenderCount = 0;diff --git a/packages/sdk-components-react-router/src/link.tsx b/packages/sdk-components-react-router/src/link.tsxindex dd5bc824fd..66c3541fb5 100644--- a/packages/sdk-components-react-router/src/link.tsx+++ b/packages/sdk-components-react-router/src/link.tsx@@ -1,42 +1,8 @@-import { type ComponentPropsWithoutRef, forwardRef, useContext } from "react";-import { NavLink as RemixLink } from "react-router";-import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";-import { Link as BaseLink } from "@webstudio-is/sdk-components-react";+import { Link as RemixLink, useLocation, useResolvedPath } from "react-router";+import { createLocalLink } from "@webstudio-is/sdk-components-react/local-link";-type Props = Omit<ComponentPropsWithoutRef<typeof BaseLink>, "target"> & {- // override (string & {}) in target to generate keywords- target?: "_self" | "_blank" | "_parent" | "_top";-- // useful remix props- prefetch?: "none" | "intent" | "render" | "viewport";- reloadDocument?: boolean;- replace?: boolean;- preventScrollReset?: boolean;-};--export const Link = forwardRef<HTMLAnchorElement, Props>((props, ref) => {- const { assetBaseUrl } = useContext(ReactSdkContext);- // cast to string when invalid value type is provided with binding- const href = String(props.href ?? "");-- // use remix link for self reference and all relative urls- // ignore asset paths which can be relative too- // urls starting with # should be handled natively to not override search params- if (- // remix appends ?index in runtime but not in ssr- href === "" ||- href.startsWith("?") ||- (href.startsWith("/") && href.startsWith(assetBaseUrl) === false)- ) {- // In the future, we will switch to the :local-link pseudo-class (https://developer.mozilla.org/en-US/docs/Web/CSS/:local-link). (aria-current="page" is used now)- // Therefore, we decided to use end={true} (exact route matching) for all links to facilitate easier migration.- return <RemixLink {...props} to={href} ref={ref} end />;- }-- const { prefetch, reloadDocument, replace, preventScrollReset, ...rest } =- props;-- return <BaseLink {...rest} ref={ref} />;+export const Link = createLocalLink({+ Link: RemixLink,+ useLocation,+ useResolvedPath,});--Link.displayName = BaseLink.displayName;diff --git a/packages/sdk-components-react/package.json b/packages/sdk-components-react/package.jsonindex 63b7ba1586..ac1d22bc69 100644--- a/packages/sdk-components-react/package.json+++ b/packages/sdk-components-react/package.json@@ -28,6 +28,11 @@"types": "./lib/types/hooks.d.ts","import": "./lib/hooks.js"},+ "./local-link": {+ "webstudio": "./src/local-link.tsx",+ "types": "./lib/types/local-link.d.ts",+ "import": "./lib/local-link.js"+ },"./templates": {"webstudio": "./src/templates.ts","types": "./lib/types/templates.d.ts",diff --git a/packages/sdk-components-react/src/link-utils.test.ts b/packages/sdk-components-react/src/link-utils.test.tsnew file mode 100644index 0000000000..44a723f1f5--- /dev/null+++ b/packages/sdk-components-react/src/link-utils.test.ts@@ -0,0 +1,119 @@+import { expect, test } from "vitest";+import { isLocalLinkActive, resolveLocalLinkUrl } from "./link-utils";++test("local link matches exact pathname, search, and hash", () => {+ expect(+ isLocalLinkActive(+ { pathname: "/path", search: "?tag=bla", hash: "#section" },+ { pathname: "/path", search: "?tag=bla", hash: "#section" }+ )+ ).toBe(true);+});++test("local link does not match when pathname, search, or hash differ", () => {+ const current = { pathname: "/path", search: "?tag=bla", hash: "#section" };++ expect(+ isLocalLinkActive(current, {+ pathname: "/path/child",+ search: "?tag=bla",+ hash: "#section",+ })+ ).toBe(false);+ expect(+ isLocalLinkActive(current, {+ pathname: "/path",+ search: "?tag=other",+ hash: "#section",+ })+ ).toBe(false);+ expect(+ isLocalLinkActive(current, {+ pathname: "/path",+ search: "?tag=bla",+ hash: "#other",+ })+ ).toBe(false);+});++test("local link matching is case-sensitive like concrete URLs", () => {+ expect(+ isLocalLinkActive(+ { pathname: "/Path", search: "?Tag=bla", hash: "#Section" },+ { pathname: "/path", search: "?tag=bla", hash: "#section" }+ )+ ).toBe(false);+});++test("local link matching preserves trailing slash exactness", () => {+ expect(+ isLocalLinkActive(+ { pathname: "/path/", search: "", hash: "" },+ { pathname: "/path", search: "", hash: "" }+ )+ ).toBe(false);+});++test("empty local link resolves to current pathname and search without hash", () => {+ const current = { pathname: "/path", search: "?tag=bla", hash: "#section" };++ expect(+ resolveLocalLinkUrl("", current, {+ pathname: "/path",+ search: "",+ hash: "",+ })+ ).toEqual({+ pathname: "/path",+ search: "?tag=bla",+ hash: "",+ });+});++test("hash local link resolves against current pathname and search", () => {+ const current = { pathname: "/path", search: "?tag=bla", hash: "" };++ expect(+ resolveLocalLinkUrl("#section", current, {+ pathname: "/other",+ search: "?tag=other",+ hash: "#section",+ })+ ).toEqual({+ pathname: "/path",+ search: "?tag=bla",+ hash: "#section",+ });+});++test("bare hash local link resolves to current pathname and search without hash", () => {+ const current = { pathname: "/path", search: "?tag=bla", hash: "#section" };++ expect(+ resolveLocalLinkUrl("#", current, {+ pathname: "/other",+ search: "?tag=other",+ hash: "#section",+ })+ ).toEqual({+ pathname: "/path",+ search: "?tag=bla",+ hash: "",+ });+});++test("path local link uses router resolved path", () => {+ const resolvedPath = {+ pathname: "/resolved",+ search: "?tag=bla",+ hash: "#section",+ };++ expect(+ resolveLocalLinkUrl(+ "/resolved?tag=bla#section",+ { pathname: "/path", search: "", hash: "" },+ resolvedPath+ )+ ).toBe(resolvedPath);+});diff --git a/packages/sdk-components-react/src/link-utils.ts b/packages/sdk-components-react/src/link-utils.tsnew file mode 100644index 0000000000..0d51985a7c--- /dev/null+++ b/packages/sdk-components-react/src/link-utils.ts@@ -0,0 +1,48 @@+export type UrlParts = {+ pathname: string;+ search: string;+ hash: string;+};++/**+ * React Router resolves href="" and hash-only hrefs without preserving the+ * concrete browser URL shape Webstudio uses for :local-link-like matching.+ * Normalize those cases before comparing so aria-current follows anchor URL+ * semantics instead of route-only semantics.+ */+export const resolveLocalLinkUrl = (+ href: string,+ location: UrlParts,+ resolvedPath: UrlParts+): UrlParts => {+ if (href === "") {+ return {+ pathname: location.pathname,+ search: location.search,+ hash: "",+ };+ }++ if (href.startsWith("#")) {+ return {+ pathname: location.pathname,+ search: location.search,+ hash: href === "#" ? "" : href,+ };+ }++ return resolvedPath;+};++/**+ * 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.+ */+export const isLocalLinkActive = (current: UrlParts, target: UrlParts) => {+ return (+ current.pathname === target.pathname &&+ current.search === target.search &&+ current.hash === target.hash+ );+};diff --git a/packages/sdk-components-react/src/local-link.tsx b/packages/sdk-components-react/src/local-link.tsxnew file mode 100644index 0000000000..0fee316293--- /dev/null+++ b/packages/sdk-components-react/src/local-link.tsx@@ -0,0 +1,185 @@+import {+ type ComponentPropsWithoutRef,+ type ComponentType,+ type ForwardRefExoticComponent,+ type LegacyRef,+ type RefAttributes,+ forwardRef,+ useContext,+} from "react";+import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";+import { Link as BaseLink } from "./link";+import {+ isLocalLinkActive,+ resolveLocalLinkUrl,+ type UrlParts,+} from "./link-utils";++export type LocalLinkProps = Omit<+ ComponentPropsWithoutRef<typeof BaseLink>,+ "target"+> & {+ // override (string & {}) in target to generate keywords+ target?: "_self" | "_blank" | "_parent" | "_top";++ // useful remix props+ prefetch?: "none" | "intent" | "render" | "viewport";+ reloadDocument?: boolean;+ replace?: boolean;+ preventScrollReset?: boolean;+};++type LocalLinkComponent = ForwardRefExoticComponent<+ LocalLinkProps & RefAttributes<HTMLAnchorElement>+>;++type RouterTo = string | Partial<UrlParts>;++type RouterLinkComponentProps = Omit<LocalLinkProps, "href" | "target"> & {+ target?: ComponentPropsWithoutRef<"a">["target"];+ to: RouterTo;+ ref?: LegacyRef<HTMLAnchorElement>;+};++const absoluteUrlPattern = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;++const shouldUseRouterLink = (href: string, assetBaseUrl: string) => {+ if (href.startsWith("#") || absoluteUrlPattern.test(href)) {+ return false;+ }++ if (href.startsWith("/") && href.startsWith(assetBaseUrl)) {+ return false;+ }++ return true;+};++const getLocalLinkProps = (+ props: LocalLinkProps & { href: string },+ location: UrlParts,+ resolvedPath: UrlParts+) => {+ const { href, "aria-current": ariaCurrent, className, ...linkProps } = props;+ const target = resolveLocalLinkUrl(href, location, resolvedPath);+ const isActive = isLocalLinkActive(location, target);+ const classNameValue = [className, isActive ? "active" : undefined]+ .filter(Boolean)+ .join(" ");++ return {+ href,+ linkProps,+ localLinkProps: {+ ...(isActive ? { "aria-current": ariaCurrent ?? "page" } : {}),+ ...(classNameValue === "" ? {} : { className: classNameValue }),+ },+ };+};++const getRouterHref = (href: string, location: UrlParts) => {+ if (href === "") {+ return `${location.pathname}${location.search}`;+ }++ return href;+};++const stripRouterOnlyProps = <+ Props extends Pick<+ LocalLinkProps,+ "prefetch" | "reloadDocument" | "replace" | "preventScrollReset"+ >,+>({+ prefetch,+ reloadDocument,+ replace,+ preventScrollReset,+ ...props+}: Props) => props;++/**+ * Remix and React Router expose compatible navigation hooks but from different+ * packages. This factory keeps Webstudio's local-link semantics in one place+ * while each integration supplies its own router primitives.+ */+export const createLocalLink = ({+ Link,+ useLocation,+ useResolvedPath,+}: {+ // Remix v2 and React Router v7 expose compatible Link behavior but different+ // public prop types. This adapter boundary captures only the props Webstudio+ // actually forwards.+ Link: ComponentType<RouterLinkComponentProps>;+ useLocation: () => UrlParts;+ useResolvedPath: (href: string) => UrlParts;+}): LocalLinkComponent => {+ const RouterLink = forwardRef<+ HTMLAnchorElement,+ LocalLinkProps & { href: string }+ >((props, ref) => {+ const location = useLocation();+ const { href, linkProps, localLinkProps } = getLocalLinkProps(+ props,+ location,+ useResolvedPath(props.href)+ );++ return (+ <Link+ {...linkProps}+ {...localLinkProps}+ to={getRouterHref(href, location)}+ ref={ref}+ />+ );+ });++ const HashLink = forwardRef<+ HTMLAnchorElement,+ LocalLinkProps & { href: string }+ >((props, ref) => {+ const location = useLocation();+ const { linkProps, localLinkProps } = getLocalLinkProps(+ props,+ location,+ location+ );+ return (+ <BaseLink+ {...stripRouterOnlyProps(linkProps)}+ {...localLinkProps}+ href={props.href}+ ref={ref}+ />+ );+ });++ const LocalLink = forwardRef<HTMLAnchorElement, LocalLinkProps>(+ (props, ref) => {+ const { assetBaseUrl } = useContext(ReactSdkContext);+ // cast to string when invalid value type is provided with binding+ const href = String(props.href ?? "");++ if (shouldUseRouterLink(href, assetBaseUrl)) {+ // Route through the framework only for navigations it should own. Asset+ // paths can also be root-relative, so they must stay plain anchors.+ return <RouterLink {...props} href={href} ref={ref} />;+ }++ if (href.startsWith("#")) {+ // Hash-only links should preserve the current search params. React Router+ // navigation rewrites them, so keep native anchor behavior and only add+ // Webstudio's aria-current state.+ return <HashLink {...props} href={href} ref={ref} />;+ }++ return <BaseLink {...stripRouterOnlyProps(props)} ref={ref} />;+ }+ );++ LocalLink.displayName = BaseLink.displayName;++ return LocalLink;+};diff --git a/packages/sdk-components-react/tsconfig.dts.json b/packages/sdk-components-react/tsconfig.dts.jsonindex 9142cd191c..37609ac8e3 100644--- a/packages/sdk-components-react/tsconfig.dts.json+++ b/packages/sdk-components-react/tsconfig.dts.json@@ -1,6 +1,11 @@{"extends": "./tsconfig.json",- "include": ["src/components.ts", "src/metas.ts", "src/hooks.ts"],+ "include": [+ "src/components.ts",+ "src/metas.ts",+ "src/hooks.ts",+ "src/local-link.tsx"+ ],"compilerOptions": {"declarationDir": "lib/types"}diff --git a/vite.sdk-components.config.ts b/vite.sdk-components.config.tsindex fcd5e1157f..5f01ec1991 100644--- a/vite.sdk-components.config.ts+++ b/vite.sdk-components.config.ts@@ -5,6 +5,9 @@ import path from "node:path";const hasPrivateFolders = existsSync(path.join(process.cwd(), "private-src", "README.md"));+const maybeEntry = (entry: string) => {+ return existsSync(path.join(process.cwd(), entry)) ? entry : undefined;+};const isBareImport = (id: string) =>id.startsWith("@") || id.includes(".") === false;@@ -16,8 +19,9 @@ export default defineConfig({hasPrivateFolders ? "private-src/components.ts" : "src/components.ts","src/metas.ts","src/hooks.ts",+ maybeEntry("src/local-link.tsx"),"src/templates.ts",- ],+ ].filter((entry) => entry !== undefined),formats: ["es"],},rollupOptions: {