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
42 changes: 4 additions & 38 deletions packages/vinext/src/server/app-browser-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,10 @@ import {
type RouteSnapshotV0,
} from "./navigation-planner.js";
import type { ClientNavigationRenderSnapshot } from "vinext/shims/navigation";

const VINEXT_PREVIOUS_NEXT_URL_HISTORY_STATE_KEY = "__vinext_previousNextUrl";

type HistoryStateRecord = {
[key: string]: unknown;
};
export {
createHistoryStateWithPreviousNextUrl,
readHistoryStatePreviousNextUrl,
} from "./app-history-state.js";

export type { OperationLane } from "./navigation-planner.js";

Expand Down Expand Up @@ -110,38 +108,6 @@ type PendingNavigationCommitDispositionDecision =
| DispatchPendingNavigationCommitDispositionDecision
| NonDispatchPendingNavigationCommitDispositionDecision;

function cloneHistoryState(state: unknown): HistoryStateRecord {
if (!state || typeof state !== "object") {
return {};
}

const nextState: HistoryStateRecord = {};
for (const [key, value] of Object.entries(state)) {
nextState[key] = value;
}
return nextState;
}

export function createHistoryStateWithPreviousNextUrl(
state: unknown,
previousNextUrl: string | null,
): HistoryStateRecord | null {
const nextState = cloneHistoryState(state);

if (previousNextUrl === null) {
delete nextState[VINEXT_PREVIOUS_NEXT_URL_HISTORY_STATE_KEY];
} else {
nextState[VINEXT_PREVIOUS_NEXT_URL_HISTORY_STATE_KEY] = previousNextUrl;
}

return Object.keys(nextState).length > 0 ? nextState : null;
}

export function readHistoryStatePreviousNextUrl(state: unknown): string | null {
const value = cloneHistoryState(state)[VINEXT_PREVIOUS_NEXT_URL_HISTORY_STATE_KEY];
return typeof value === "string" ? value : null;
}

function createOperationRecord(options: {
id: number;
lane: OperationLane;
Expand Down
49 changes: 49 additions & 0 deletions packages/vinext/src/server/app-history-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const VINEXT_PREVIOUS_NEXT_URL_HISTORY_STATE_KEY = "__vinext_previousNextUrl";

type HistoryStateRecord = {
[key: string]: unknown;
};

function cloneHistoryState(state: unknown): HistoryStateRecord {
if (!state || typeof state !== "object") {
return {};
}

const nextState: HistoryStateRecord = {};
for (const [key, value] of Object.entries(state)) {
nextState[key] = value;
}
return nextState;
}

export function createHistoryStateWithPreviousNextUrl(
state: unknown,
previousNextUrl: string | null,
): HistoryStateRecord | null {
const nextState = cloneHistoryState(state);

if (previousNextUrl === null) {
delete nextState[VINEXT_PREVIOUS_NEXT_URL_HISTORY_STATE_KEY];
} else {
nextState[VINEXT_PREVIOUS_NEXT_URL_HISTORY_STATE_KEY] = previousNextUrl;
}

return Object.keys(nextState).length > 0 ? nextState : null;
}

export function createExternalHistoryStatePreservingMetadata(
callerState: unknown,
currentHistoryState: unknown,
): unknown {
const previousNextUrl = readHistoryStatePreviousNextUrl(currentHistoryState);
if (previousNextUrl === null) {
return callerState;
}

return createHistoryStateWithPreviousNextUrl(callerState, previousNextUrl);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: createHistoryStateWithPreviousNextUrl returns HistoryStateRecord | null, but createExternalHistoryStatePreservingMetadata is typed as returning unknown. When previousNextUrl is non-null and callerState is null, the returned value is { __vinext_previousNextUrl: "/feed" } — which is fine — but on the callerState passthrough path (line 40), the return type is unknown because the caller's original value is returned as-is.

This works correctly at runtime, but the return type could be narrowed. Not blocking.

}

export function readHistoryStatePreviousNextUrl(state: unknown): string | null {
const value = cloneHistoryState(state)[VINEXT_PREVIOUS_NEXT_URL_HISTORY_STATE_KEY];
return typeof value === "string" ? value : null;
}
15 changes: 13 additions & 2 deletions packages/vinext/src/shims/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import * as React from "react";
import { notifyAppRouterTransitionStart } from "../client/instrumentation-client-state.js";
import { AppElementsWire } from "../server/app-elements.js";
import { createExternalHistoryStatePreservingMetadata } from "../server/app-history-state.js";
import {
createRscRequestHeaders,
createRscRequestUrl,
Expand Down Expand Up @@ -2049,7 +2050,12 @@ if (!isServer) {
unused: string,
url?: string | URL | null,
): void {
state.originalPushState.call(window.history, data, unused, url);
state.originalPushState.call(
window.history,
createExternalHistoryStatePreservingMetadata(data, window.history.state),
unused,
url,
);
if (state.suppressUrlNotifyCount === 0) {
commitClientNavigationState();
}
Expand All @@ -2060,7 +2066,12 @@ if (!isServer) {
unused: string,
url?: string | URL | null,
): void {
state.originalReplaceState.call(window.history, data, unused, url);
state.originalReplaceState.call(
window.history,
createExternalHistoryStatePreservingMetadata(data, window.history.state),
unused,
url,
);
if (state.suppressUrlNotifyCount === 0) {
commitClientNavigationState();
}
Expand Down
74 changes: 74 additions & 0 deletions tests/shims.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,80 @@ describe("next/navigation shim", () => {
}
});

it("preserves App Router history metadata when external history calls provide caller state", async () => {
// Matches Next.js' external History API wrapper behavior:
// https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/app-router.tsx#L114-L127
// Covered by Next.js shallow-routing tests for object, null, and undefined state:
// https://github.com/vercel/next.js/blob/canary/test/e2e/app-dir/shallow-routing/shallow-routing.test.ts
const previousWindow = (globalThis as any).window;
const historyMetadataKey = "__vinext_previousNextUrl";
const win = {
location: {
pathname: "/photo/1",
search: "",
hash: "",
href: "http://localhost/photo/1",
origin: "http://localhost",
},
history: {
state: { [historyMetadataKey]: "/feed" } as unknown,
pushState(data: unknown, _unused: string, url?: string | URL | null) {
this.state = data;
if (!url) return;
const parsed = new URL(url, win.location.href);
win.location.pathname = parsed.pathname;
win.location.search = parsed.search;
win.location.hash = parsed.hash;
win.location.href = parsed.href;
},
replaceState(data: unknown, _unused: string, url?: string | URL | null) {
this.state = data;
if (!url) return;
const parsed = new URL(url, win.location.href);
win.location.pathname = parsed.pathname;
win.location.search = parsed.search;
win.location.hash = parsed.hash;
win.location.href = parsed.href;
},
},
addEventListener: vi.fn(),
};
(globalThis as any).window = win;

try {
vi.resetModules();
await import("../packages/vinext/src/shims/navigation.js");

win.history.pushState({ myData: { foo: "bar" } }, "", "/photo/1?filter=active");
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding a test case where the current history state does not have __vinext_previousNextUrl (the no-metadata baseline). This would verify the passthrough path in createExternalHistoryStatePreservingMetadata (line 39-41 of app-history-state.ts) — i.e., that caller state is returned unchanged when there's no vinext metadata to preserve.

For example:

win.history.state = { unrelated: true };
win.history.pushState({ myData: 1 }, "", "/photo/2");
expect(win.history.state).toEqual({ myData: 1 }); // no metadata injected

Not blocking — the unit under test (createExternalHistoryStatePreservingMetadata) is simple enough that the passthrough is obvious from reading it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also worth considering: a case where the caller's own state object contains __vinext_previousNextUrl (e.g., a library naively serializing full history state). The current implementation correctly overwrites it with the current entry's value via createHistoryStateWithPreviousNextUrl. A test documenting that the internal key wins would make the intent explicit, but it's low priority given how unlikely the collision is.

expect(win.history.state).toEqual({
myData: { foo: "bar" },
[historyMetadataKey]: "/feed",
});

win.history.pushState(null, "", "/photo/1?filter=pending");
expect(win.history.state).toEqual({
[historyMetadataKey]: "/feed",
});

win.history.replaceState(null, "", "/photo/1?filter=archived");
expect(win.history.state).toEqual({
[historyMetadataKey]: "/feed",
});

win.history.replaceState(undefined, "", "/photo/1?filter=all");
expect(win.history.state).toEqual({
[historyMetadataKey]: "/feed",
});
} finally {
vi.resetModules();
if (previousWindow === undefined) {
delete (globalThis as any).window;
} else {
(globalThis as any).window = previousWindow;
}
}
});

it("exports redirect, notFound, permanentRedirect", async () => {
const nav = await import("../packages/vinext/src/shims/navigation.js");
expect(typeof nav.redirect).toBe("function");
Expand Down
Loading