Files
webstudio/packages/sdk-components-react/src/create-link.tsx
T
Oleg Isonen bc29c51be8 fix: Recover Linux screenshots and fragment captures (#6589)
# Screenshot failures on Linux and fragment captures

On the reported Linux host, Chrome aborted before screenshot capture.
This PR keeps the normal launch unchanged and makes the existing second
attempt use Chrome's shared-memory fallback on Linux. The original host
is unavailable, so this is a best-effort recovery, not a proven fix for
that host.

On #6580's project, a fragment URL made Webstudio mark a navigation link
active in the browser while the server rendered it inactive. That
mismatch caused a React hydration warning, which the current MCP
screenshot tool correctly rejected. The link now renders consistently
during hydration and becomes active afterward. The exact project's
managed MCP responsive capture then succeeded twice at desktop and
mobile sizes; both PNG files existed.

Closes #6587
Closes #6580

## Work

- [x] Add a Linux-only fallback on the existing browser startup retry.
- [x] Add a regression test that fails without the Linux fallback.
- [x] Make initial fragment-link rendering match server and browser
during hydration; preserve active-link behavior afterward.
- [x] Add a hydration regression test that fails before and passes after
the fix.
- [x] Verify the exact-project managed MCP fragment capture at 1440×900
and 390×844, `waitUntil: load`, `waitForSelector: img`.
- [x] Review `docs/`: the existing link and screenshot instructions
remain accurate; no docs edit is needed.
- [x] Run focused Vision/CLI, link and router-link tests; relevant
typechecks, formatting, lint, builds, and diff checks.
- [x] Independently review the complete diff.
- [x] Review required CI checks: all checks on `e79053414e` passed
(visual regression was skipped by its workflow).

Remaining costs and limits: a Linux browser still makes the first
startup attempt before the fallback. The fragment capture still needs
the generated preview and browser startup. The original CLI 0.306.0
second-viewport timeout and the Linux reporter's host were not retested
with this patch. This PR does not add a diagnostic PNG on readiness
timeout or a new section-scroll control. We are closing these reports on
merge with those limits understood; if the symptoms recur, they need a
new report.
2026-10-24 01:16:54 +02:00

166 lines
4.8 KiB
TypeScript

import {
type ComponentPropsWithoutRef,
type ComponentType,
type ForwardRefExoticComponent,
type LegacyRef,
type RefAttributes,
type ReactNode,
forwardRef,
useContext,
useSyncExternalStore,
} from "react";
import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";
import { BaseLink } from "./link";
import { LinkCurrentUrlContext } from "./link-current-url";
import { isInternalHref, type UrlParts } from "@webstudio-is/sdk/link-utils";
import { getCurrentLinkProps, stripRouterOnlyProps } from "./link-utils";
export type LinkProps = 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";
discover?: "render" | "none";
reloadDocument?: boolean;
replace?: boolean;
preventScrollReset?: boolean;
relative?: "route" | "path";
state?: unknown;
viewTransition?: boolean;
};
type LinkComponent = ForwardRefExoticComponent<
LinkProps & RefAttributes<HTMLAnchorElement>
>;
type RouterTo = string | Partial<UrlParts>;
type RouterLinkComponentProps = Omit<LinkProps, "href" | "target"> & {
target?: ComponentPropsWithoutRef<"a">["target"];
to: RouterTo;
ref?: LegacyRef<HTMLAnchorElement>;
};
const getRouterHref = (href: string, location: UrlParts) => {
if (href === "") {
return `${location.pathname}${location.search}`;
}
return href;
};
const getCurrentHref = (location: UrlParts) =>
`https://webstudio.local${location.pathname}${location.search}${location.hash}`;
const useHydrationSafeLocation = (location: UrlParts) => {
// Fragments are not sent to the server, so defer hash-dependent link state.
const isHydrated = useSyncExternalStore(
() => () => {},
() => true,
() => false
);
return isHydrated ? location : { ...location, hash: "" };
};
const CurrentUrlProvider = ({
children,
location,
}: {
children: ReactNode;
location: UrlParts;
}) => (
<LinkCurrentUrlContext.Provider value={getCurrentHref(location)}>
{children}
</LinkCurrentUrlContext.Provider>
);
/**
* Creates a framework-aware Link.
*
* Internal route links render the framework Link component so Remix/React
* Router keep their own navigation, discovery, prefetch, and transition
* behavior. Hash-only, external, and asset links fall back to BaseLink because
* they should behave like native anchors while still supporting current-link
* styling.
*/
export const createLink = ({
Link,
useLocation,
useResolvedPath,
}: {
Link: ComponentType<RouterLinkComponentProps>;
useLocation: () => UrlParts;
useResolvedPath: (href: string) => UrlParts;
}): LinkComponent => {
const RouterLink = forwardRef<
HTMLAnchorElement,
LinkProps & { href: string }
>((props, ref) => {
const location = useHydrationSafeLocation(useLocation());
const href = getRouterHref(props.href, location);
const { linkProps, currentLinkProps } = getCurrentLinkProps(
props,
location,
useResolvedPath(props.href)
);
return (
<CurrentUrlProvider location={location}>
<Link {...linkProps} {...currentLinkProps} to={href} ref={ref} />
</CurrentUrlProvider>
);
});
const HashLink = forwardRef<HTMLAnchorElement, LinkProps & { href: string }>(
(props, ref) => {
const location = useHydrationSafeLocation(useLocation());
return (
<CurrentUrlProvider location={location}>
<BaseLink
{...stripRouterOnlyProps(props)}
href={props.href}
ref={ref}
/>
</CurrentUrlProvider>
);
}
);
const FrameworkLink = forwardRef<HTMLAnchorElement, LinkProps>(
(props, ref) => {
const { assetBaseUrl } = useContext(ReactSdkContext);
if (props.href === undefined) {
return <BaseLink {...stripRouterOnlyProps(props)} ref={ref} />;
}
// cast to string when invalid value type is provided with binding
const href = String(props.href);
if (
href.startsWith("#") === false &&
isInternalHref(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} />;
}
);
FrameworkLink.displayName = BaseLink.displayName;
return FrameworkLink;
};