Skip to content
Merged
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
121 changes: 121 additions & 0 deletions integration/vite-spa-mode-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1365,4 +1365,125 @@ test.describe("SPA Mode", () => {
"app/routes/about.tsx",
]);
});

test("hydrates NavLink active state for a deep link", async ({ page }) => {
let fixture = await createFixture({
spaMode: true,
files: {
"app/root.tsx": js`
import { lazy, Suspense, useEffect, useState } from "react";
import { Outlet, Scripts, useSearchParams } from "react-router";

const Menu = lazy(() => import("./layout-menu"));

export function Layout({ children }: { children: React.ReactNode }) {
let [searchParams] = useSearchParams();
let [initialTab] = useState(() => searchParams.get("tab") ?? "");
useEffect(() => {
document.body.dataset.initialTab = initialTab;
}, [initialTab]);

return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<Suspense>
<Menu />
</Suspense>
{children}
<Scripts />
</body>
</html>
);
}

export default function App() {
return <Outlet />;
}
`,
"app/layout-menu.tsx": js`
import { NavLink } from "react-router";

export default function Menu() {
return (
<nav>
<NavLink to="/" end>Home</NavLink>
<NavLink to="/other">Other</NavLink>
</nav>
);
}
`,
"app/routes/_index.tsx": js`
export default function Index() {
return <h1>Home page</h1>;
}
`,
"app/routes/other.tsx": js`
export default function Other() {
return <h1>Other page</h1>;
}
`,
},
});
let appFixture = await createAppFixture(fixture);
let releaseMenu!: () => void;
let menuReady = new Promise<void>((resolve) => {
releaseMenu = resolve;
});

try {
await page.route("**/assets/layout-menu-*.js", async (route) => {
await menuReady;
await route.continue();
});
let html = await (await fixture.requestDocument("/")).text();
let anchors = html.match(/<a\b[^>]*>/g) ?? [];
expect(anchors).toHaveLength(2);
for (let anchor of anchors) {
expect(anchor).not.toMatch(/\bactive\b|aria-current=/);
}

let app = new PlaywrightFixture(appFixture, page);
await Promise.all([
page.waitForRequest("**/assets/layout-menu-*.js"),
app.goto("/other?tab=details", false),
]);
await expect(page.locator("body")).toHaveAttribute(
"data-initial-tab",
"details",
);
await expect(page.locator("nav a")).toHaveCount(2);
await expect(page.locator("nav a.active")).toHaveCount(0);
await expect(page.locator("nav a[aria-current]")).toHaveCount(0);
let otherLink = page.locator('a[href="/other"]');
let prerenderedOtherLink = await otherLink.evaluateHandle((link) => link);
releaseMenu();
await expect(page.locator("h1")).toHaveText("Other page");
await expect(page.locator('a[href="/"]')).not.toHaveClass(/\bactive\b/);
await expect(otherLink).toHaveClass(/\bactive\b/);
await expect(otherLink).toHaveAttribute("aria-current", "page");
expect(
await otherLink.evaluate(
(link, original) => link === original,
prerenderedOtherLink,
),
).toBe(true);
await expect(page.locator("nav a[aria-current]")).toHaveCount(1);

await app.clickLink("/");
await expect(page.locator("h1")).toHaveText("Home page");
await expect(page.locator("body")).toHaveAttribute(
"data-initial-tab",
"details",
);
await expect(page.locator('a[href="/"]')).toHaveClass(/\bactive\b/);
await expect(otherLink).not.toHaveClass(/\bactive\b/);
} finally {
releaseMenu();
appFixture.close();
}
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Keep `NavLink` inactive in the prerendered Framework SPA fallback and set its active state from the browser URL after hydration
26 changes: 21 additions & 5 deletions packages/react-router/lib/dom/lib.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1586,6 +1586,9 @@ export interface NavLinkProps extends Omit<
| ((props: NavLinkRenderProps) => React.CSSProperties | undefined);
}

const subscribeToNothing = () => () => {};
const getClientSpaFallback = () => false;

/**
* Wraps {@link Link | `<Link>`} with additional props for styling active and
* pending states.
Expand Down Expand Up @@ -1648,12 +1651,23 @@ export const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(
let location = useLocation();
let routerNavigation = React.useContext(DataRouterNavigationContext);
let { navigator, basename } = React.useContext(NavigationContext);
let isSpaMode = React.useContext(FrameworkContext)?.isSpaMode === true;

// SPA fallback HTML is reused across URLs. Keep the link state neutral
// until this link hydrates, including links inside a Suspense boundary.
let isSpaFallback = React.useSyncExternalStore(
subscribeToNothing,
getClientSpaFallback,
() => isSpaMode,
);

let isTransitioning =
routerNavigation != null &&
// Conditional usage is OK here because the usage of a data router is static
// eslint-disable-next-line react-hooks/rules-of-hooks
useViewTransitionState(path) &&
viewTransition === true;
viewTransition === true &&
!isSpaFallback;

let toPathname = navigator.encodeLocation
? navigator.encodeLocation(path).pathname
Expand Down Expand Up @@ -1686,12 +1700,14 @@ export const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(
? toPathname.length - 1
: toPathname.length;
let isActive =
locationPathname === toPathname ||
(!end &&
locationPathname.startsWith(toPathname) &&
locationPathname.charAt(endSlashPosition) === "/");
!isSpaFallback &&
(locationPathname === toPathname ||
(!end &&
locationPathname.startsWith(toPathname) &&
locationPathname.charAt(endSlashPosition) === "/"));

let isPending =
!isSpaFallback &&
nextLocationPathname != null &&
(nextLocationPathname === toPathname ||
(!end &&
Expand Down