diff --git a/docs/guide/pages-routing/actions-and-forms.md b/docs/guide/pages-routing/actions-and-forms.md index 69023da1d..88172c079 100644 --- a/docs/guide/pages-routing/actions-and-forms.md +++ b/docs/guide/pages-routing/actions-and-forms.md @@ -203,6 +203,12 @@ If a callback awaits `router.visit()` or `router.refresh()`, pass `{ resolveOn: Vue, Svelte, and Solid submissions return a promise instead; use `await form.post()` to run work after a submission. +### Query parameters after submission + +An action or form that posts to the current page keeps the page's query parameters. From `/items?page=2&search=foo`, `action('/items?vote')` posts to `/items?vote&page=2&search=foo`, so the action and loader see `page` and `search`. The URL, scroll position, and history entry stay as they are. A parameter written in the action URL takes precedence over the page's: `action('/items?vote&page=1')` posts with `page=1`. + +A redirect from the action does not receive the page's query parameters. To clear them after an action, return `c.redirect('/items')`. + ### Scroll after submission Actions and forms keep the current scroll position when updating the page in place. Redirects and submissions that open another page scroll to the top, or to the destination's hash target. @@ -248,7 +254,7 @@ export const actions = { }; ``` -Named actions use a `?actionName` suffix, such as `/users/42?update`. `useForm` and `action()` handle this automatically. After a POST action renders the page or uses a default `c.redirect()`, the page URL keeps ordinary query parameters: `/users/42?update&tab=profile` becomes `/users/42?tab=profile`. See [redirect query parameters](../../reference/api/rewrites.md#c-rewrite-destination) for redirects that preserve the request method. +Named actions use a `?actionName` suffix, such as `/users/42?update`. `useForm` and `action()` handle this automatically. After a POST action renders the page or uses a default `c.redirect()`, the page URL keeps the action URL's ordinary query parameters: `/users/42?update&tab=profile` becomes `/users/42?tab=profile`. See [redirect query parameters](../../reference/api/rewrites.md#c-rewrite-destination) for redirects that preserve the request method. Use `action` or `actions` in a file, not both. diff --git a/docs/reference/api/rewrites.md b/docs/reference/api/rewrites.md index d11bdd0d4..97bb5e958 100644 --- a/docs/reference/api/rewrites.md +++ b/docs/reference/api/rewrites.md @@ -44,7 +44,7 @@ return c.redirect(requested.origin === new URL(c.req.url).origin ? requested : ' `c.redirect()` sends the location it is given. The request query is not added to an internal path, a protocol-relative URL, or an absolute URL, so `c.redirect('/notes')` from `/sign-in?redirectTo=/notes` goes to `/notes`. [`routing.redirects`](../../guide/edge/redirects.md) still merge the request query into the destination. -A [named action](../../guide/pages-routing/actions-and-forms.md#named-actions) is the exception. Redirecting it to a GET page drops the action key and keeps the page's other query parameters: `POST /users/42?delete&tab=profile` with `c.redirect('/users/42')` goes to `/users/42?tab=profile`. Redirects that preserve the request method keep the action key: `307` and `308`, or `301` and `302` after a `PUT`, `PATCH`, or `DELETE`. +A [named action](../../guide/pages-routing/actions-and-forms.md#named-actions) is the exception. Redirecting it to a GET page drops the action key and keeps the page's other query parameters: `POST /users/42?delete&tab=profile` with `c.redirect('/users/42')` goes to `/users/42?tab=profile`. Redirects that preserve the request method keep the action key: `307` and `308`, or `301` and `302` after a `PUT`, `PATCH`, or `DELETE`. Only the action URL's own parameters are kept: the [current page's query](../../guide/pages-routing/actions-and-forms.md#query-parameters-after-submission) that `action()` and forms add is left out. ```ts import { defineHandler } from 'void'; diff --git a/packages/solid/test/unit/form-submissions.test.ts b/packages/solid/test/unit/form-submissions.test.ts index b03698b30..0e18a7783 100644 --- a/packages/solid/test/unit/form-submissions.test.ts +++ b/packages/solid/test/unit/form-submissions.test.ts @@ -1,5 +1,5 @@ import { createComponent, createRoot } from 'solid-js'; -import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import type { VoidRouter } from 'void/pages-client'; import { RouterContext } from '../../src/runtime/context.ts'; import { useForm as typedUseForm } from '../../src/runtime/use-form.ts'; @@ -53,6 +53,10 @@ function validationResponse(errors: Record): Response { const disposers: Array<() => void> = []; +beforeEach(() => { + vi.stubGlobal('window', { location: { pathname: '/', search: '' } }); +}); + afterEach(() => { vi.unstubAllGlobals(); for (const dispose of disposers.splice(0)) { diff --git a/packages/solid/test/unit/use-form.test.ts b/packages/solid/test/unit/use-form.test.ts index cd4732c32..035c3287f 100644 --- a/packages/solid/test/unit/use-form.test.ts +++ b/packages/solid/test/unit/use-form.test.ts @@ -1,9 +1,17 @@ import { createComponent, createRoot } from 'solid-js'; -import { describe, expect, it } from 'vite-plus/test'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import type { VoidRouter } from 'void/pages-client'; import { RouterContext } from '../../src/runtime/context.ts'; import { useForm as typedUseForm } from '../../src/runtime/use-form.ts'; +beforeEach(() => { + vi.stubGlobal('window', { location: { pathname: '/', search: '' } }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + // The public overload only accepts generated action URLs; these tests use plain paths. const useForm = typedUseForm as unknown as ( url: string, diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 2562f77c3..22961af10 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -47,6 +47,8 @@ Pages navigation payloads keep `url` as a path and query string. The render call Pages clients and prerender requests send `X-VoidPages: true` with `X-VoidPages-Version` set to the shared `PAGES_PROTOCOL_VERSION` from `@void/edge` for devalue payloads. Missing or unsupported versions receive an uncached, empty `200 text/plain` response without `X-VoidPages`, which makes released clients load the document. Run legacy mutations once before that response; return validation errors as plain `422` JSON so forms retain their input. Native and hosted ISR must bypass JSON cache reads for unsupported versions without evicting current entries. HTML and JSON responses vary by both headers. +`submitAction()` appends the current page query to an action URL on the same path and names the added segments in `X-VoidPages-Preserved-Query`. Named-action `c.redirect()` strips that suffix before merging the request query, so the preserved query only feeds the in-place render. Keep the segments verbatim: history and scroll preservation compare the returned page URL with `location.pathname + location.search` as strings. + Pages `_not-found`/`_error` recovery uses finite render plans that retain logical layout slots. Never serialize original exceptions through framework hydration helpers, rerun a failed loader/action, or cache an error document. Native client boundaries reset on every visit/refresh and preserve healthy ancestor layouts. **Hono** is used as the runtime framework. The generated virtual module creates a Hono app with file-based routes and middleware. Route handlers receive a Hono `Context` object (`c`) and can use the full Hono API (`c.json()`, `c.text()`, `c.req.param()`, etc.) plus the Hono middleware ecosystem. diff --git a/packages/void/src/pages/action-key.ts b/packages/void/src/pages/action-key.ts index 2f2088aad..d7d59aa0d 100644 --- a/packages/void/src/pages/action-key.ts +++ b/packages/void/src/pages/action-key.ts @@ -36,3 +36,55 @@ export function searchWithoutActionKey(search: string): string { } return rest < search.length ? '?' + search.slice(rest) : ''; } + +/** + * Names the page query that an action request carries only because it posts + * to the page it runs on. Redirects leave that query out. + */ +export const PRESERVED_QUERY_HEADER = 'X-VoidPages-Preserved-Query'; + +export function queryKey(segment: string): string | undefined { + return new URLSearchParams(segment).keys().next().value; +} + +/** + * For an action URL on the page's own path, `url` with the page's query + * parameters after its own. A key the action URL names wins over the page's. + * `preserved` is the query that was added, as sent. + */ +export function withPageQuery( + url: string, + page: { pathname: string; search: string }, +): { url: string; preserved: string } { + const hashIndex = url.indexOf('#'); + const base = hashIndex === -1 ? url : url.slice(0, hashIndex); + const q = base.indexOf('?'); + if (!page.search || base.slice(0, q === -1 ? base.length : q) !== page.pathname) { + return { url, preserved: '' }; + } + const own = new Set(new URLSearchParams(q === -1 ? '' : base.slice(q + 1)).keys()); + const preserved = page.search + .slice(1) + .split('&') + .filter((segment) => segment !== '' && !own.has(queryKey(segment)!)) + .join('&'); + if (!preserved) { + return { url, preserved }; + } + const query = q === -1 || q === base.length - 1 ? '?' : base.slice(q) + '&'; + return { + url: base.slice(0, q === -1 ? base.length : q) + query + preserved + url.slice(base.length), + preserved, + }; +} + +/** `search` without the page query that `withPageQuery()` added to its end. */ +export function searchWithoutPreservedQuery(search: string, preserved: string | null): string { + if (!preserved) { + return search; + } + if (search === '?' + preserved) { + return ''; + } + return search.endsWith('&' + preserved) ? search.slice(0, -preserved.length - 1) : search; +} diff --git a/packages/void/src/pages/client.ts b/packages/void/src/pages/client.ts index 1a284bef3..25a039776 100644 --- a/packages/void/src/pages/client.ts +++ b/packages/void/src/pages/client.ts @@ -3,6 +3,7 @@ import type { ActionUrl, ResolveActionBody, ResolveActionParams, RouteUrlInput } from 'void/routes'; import { toUrlString } from '../runtime/route-url.ts'; import { interpolateRouteParams } from '../runtime/route-url.ts'; +import { withPageQuery } from './action-key.ts'; import { VoidActionError, isAbortError, @@ -286,6 +287,13 @@ export async function submitAction( options: VisitOptions, errorOptions?: { throwOnError?: boolean }, ): Promise { + // An action on the page it runs on re-renders that page, so its loader sees the + // page query and the URL, scroll and history entry stay as they are. + const page = withPageQuery(url, window.location); + if (page.preserved) { + url = page.url; + options = { ...options, _preservedQuery: page.preserved }; + } try { const pageData = await router.visit(url, options); if ( diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index 0aa666056..b61c17ad9 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -1,7 +1,7 @@ /// import { PAGES_PROTOCOL_VERSION } from '@void/edge'; -import { searchWithoutActionKey } from './action-key.ts'; +import { PRESERVED_QUERY_HEADER, searchWithoutActionKey } from './action-key.ts'; import { createActionErrorFromResponse, isAbortError } from './action-result.ts'; import { pageBoundarySlots, clientPageError, showTerminalPageError } from './boundary-client.ts'; import type { BoundaryManifest } from './boundary-plans.ts'; @@ -66,6 +66,8 @@ export type VisitOptions = { _popstate?: boolean; /** @internal Used by router.refresh() to refetch the current URL even when it has a hash */ _refresh?: boolean; + /** @internal Used by actions: the page query they added to the URL, which redirects leave out */ + _preservedQuery?: string; }; export type PrefetchOptions = { @@ -712,6 +714,9 @@ export async function createPageNavigationEngine( 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, Accept: 'application/json', }; + if (options._preservedQuery && method !== 'GET') { + headers[PRESERVED_QUERY_HEADER] = options._preservedQuery; + } const fetchOptions: PageFetchOptions = { method, headers, signal }; if (options.data && method !== 'GET') { diff --git a/packages/void/src/runtime/routing.ts b/packages/void/src/runtime/routing.ts index bcefdc434..7712c9556 100644 --- a/packages/void/src/runtime/routing.ts +++ b/packages/void/src/runtime/routing.ts @@ -11,10 +11,13 @@ import type { TypedResponse } from 'hono'; import type { RedirectStatusCode } from 'hono/utils/http-status'; import type { RouteDestination, RouteUrlInput } from 'void/routes'; import { + PRESERVED_QUERY_HEADER, actionKeySegment, hasActionKey, markActionKey, + queryKey, searchWithoutActionKey, + searchWithoutPreservedQuery, } from '../pages/action-key.ts'; import { SHARED_CACHE_HEADERS, authDependentRequests } from './auth-response.ts'; import { VoidAssetRewriteError, type CloudContext } from './handler.ts'; @@ -325,7 +328,11 @@ function redirectLocation( status: RedirectStatusCode | undefined, ): string { const url = new URL(request.url); - const search = url.search; + // The page query that action() added only re-renders the page in place. + const search = searchWithoutPreservedQuery( + url.search, + request.headers.get(PRESERVED_QUERY_HEADER), + ); if (!hasActionKey(request)) { return mergeQueryIntoLocation(location, search); } @@ -377,10 +384,6 @@ function redirectLocation( ); } -function queryKey(segment: string): string | undefined { - return new URLSearchParams(segment).keys().next().value; -} - /** A rewrite that keeps the query keeps the action key in it too. */ function keepActionKey(from: Request, to: Request, destinationSearch: string): void { if (!destinationSearch && hasActionKey(from)) { diff --git a/packages/void/test/unit/action-result.test.ts b/packages/void/test/unit/action-result.test.ts index bee3f82b9..9e6f5b38c 100644 --- a/packages/void/test/unit/action-result.test.ts +++ b/packages/void/test/unit/action-result.test.ts @@ -1,5 +1,5 @@ import { HTTPException } from 'hono/http-exception'; -import { describe, expect, it, vi } from 'vite-plus/test'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { createActionErrorFromResponse } from '../../src/pages/action-result.ts'; import { VoidActionError, @@ -46,6 +46,13 @@ function routerWithVisit(visit: VoidRouter['visit']): VoidRouter { }; } +function stubLocation(pathname: string, search = '') { + vi.stubGlobal('window', { location: { pathname, search } }); +} + +beforeEach(() => stubLocation('/')); +afterEach(() => vi.unstubAllGlobals()); + describe('action result handling', () => { it('categorizes expected client errors as call-site errors', () => { expect(categorizeActionError(400)).toBe('callSite'); @@ -316,6 +323,64 @@ describe('action clients', () => { }); }); +describe('the page query', () => { + it.each([ + ['/items?vote', '/items?vote&page=2&search=foo', 'page=2&search=foo'], + ['/items', '/items?page=2&search=foo', 'page=2&search=foo'], + ['/items?', '/items?page=2&search=foo', 'page=2&search=foo'], + ['/items?vote&page=3', '/items?vote&page=3&search=foo', 'search=foo'], + ['/items?vote&page=3&search=bar', '/items?vote&page=3&search=bar', undefined], + ['/items?vote#row-1', '/items?vote&page=2&search=foo#row-1', 'page=2&search=foo'], + ['/items/1?vote', '/items/1?vote', undefined], + ['/other?vote', '/other?vote', undefined], + ])('posts %s from /items?page=2&search=foo to %s', async (url, requested, preserved) => { + stubLocation('/items', '?page=2&search=foo'); + const visit = vi.fn(async () => ({ props: {} })); + + await submitAction(routerWithVisit(visit), url, { method: 'POST' }); + + expect(visit).toHaveBeenCalledWith(requested, { + method: 'POST', + ...(preserved === undefined ? {} : { _preservedQuery: preserved }), + }); + }); + + it('keeps encoded parameters as the page sent them', async () => { + stubLocation('/items', '?q=a+b%26c&&tag=x%20y'); + const visit = vi.fn(async () => ({ props: {} })); + + await submitAction(routerWithVisit(visit), '/items?vote&tag=z', { method: 'POST' }); + + expect(visit).toHaveBeenCalledWith('/items?vote&tag=z&q=a+b%26c', { + method: 'POST', + _preservedQuery: 'q=a+b%26c', + }); + }); + + it('leaves the URL alone on a page without a query', async () => { + stubLocation('/items'); + const visit = vi.fn(async () => ({ props: {} })); + + await submitAction(routerWithVisit(visit), '/items?vote', { method: 'POST' }); + + expect(visit).toHaveBeenCalledWith('/items?vote', { method: 'POST' }); + }); + + it('adds the page query to an action() call on the current page', async () => { + stubLocation('/__action-test/users/a%2Fb', '?tab=profile'); + const client = createActionClient(); + const visit = vi.fn(async () => ({ props: {} })); + client.setActionRouter(routerWithVisit(visit)); + + await client.action('/__action-test/users/:id?save', { params: { id: 'a/b' } }); + + expect(visit).toHaveBeenCalledWith( + '/__action-test/users/a%2Fb?save&tab=profile', + expect.objectContaining({ _preservedQuery: 'tab=profile' }), + ); + }); +}); + it('exposes the application message and retry deadline for structured quota responses', () => { const error = new VoidActionError({ status: 429, diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 38f745f40..33be21a96 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -424,6 +424,34 @@ describe('createVoidRouter', () => { }, ); + it('keeps the page query, scroll and history entry for an in-place action', async () => { + stubClientGlobals(); + window.location.pathname = '/editor'; + window.location.search = '?page=2&search=foo'; + window.scrollY = 1800; + const fetch = vi.fn(async () => + pageJson({ component: 'home', props: {}, url: '/editor?page=2&search=foo', errors: null }), + ); + vi.stubGlobal('fetch', fetch); + const { router } = await createTestRouter(); + + await submitAction(router, '/editor?save', { method: 'POST' }); + + expect(fetch).toHaveBeenCalledWith( + '/editor?save&page=2&search=foo', + expect.objectContaining({ + headers: expect.objectContaining({ 'X-VoidPages-Preserved-Query': 'page=2&search=foo' }), + }), + ); + expect(window.scrollTo).not.toHaveBeenCalled(); + expect(history.pushState).not.toHaveBeenCalled(); + expect(history.replaceState).toHaveBeenCalledWith( + expect.anything(), + '', + '/editor?page=2&search=foo', + ); + }); + it.each([ ['/editor', false, undefined], ['/destination', false, undefined], diff --git a/packages/void/test/unit/routing-runtime.test.ts b/packages/void/test/unit/routing-runtime.test.ts index 5c0b69f6a..64afe095e 100644 --- a/packages/void/test/unit/routing-runtime.test.ts +++ b/packages/void/test/unit/routing-runtime.test.ts @@ -928,6 +928,44 @@ describe('typed Pages and SSR execution', () => { expect(response.headers.get('location')).toBe(location); }); + it.each([ + ['/named?delete&page=2', 'page=2', 'a redirect', '/named'], + ['/named?update&tab=a&page=2&q=x', 'page=2&q=x', 'a 303 redirect', '/named?tab=a'], + ['/named?move&page=2', 'page=2', 'a 307 redirect', '/named-v2?move'], + ['/named?moveTab&page=2', 'page=2', 'a 307 redirect', '/named-v2?moveTab&tab=details'], + ['/named?delete&page=2', 'page=2', 'middleware', '/login'], + ['/named?go&page=2', 'page=2', 'a rewrite', '/done'], + ['/named?delete&page=2', 'page=3', 'a redirect', '/named?page=2'], + ])( + 'POST %s that preserves %s through %s redirects to %s', + async (path, preserved, through, location) => { + const response = await createNamedActionApp().fetch( + new Request('https://app.test' + path, { + method: path.includes('update') ? 'PUT' : 'POST', + headers: { + 'X-VoidPages-Preserved-Query': preserved, + ...(through === 'middleware' ? { 'x-anon': '1' } : {}), + }, + }), + ); + expect(response.headers.get('location')).toBe(location); + }, + ); + + it('keeps the preserved query in the page URL when the action renders the page again', async () => { + const response = await createNamedActionApp().fetch( + new Request('https://app.test/named?save&page=2', { + method: 'POST', + headers: { + 'x-voidpages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Preserved-Query': 'page=2', + }, + }), + ); + expect((decodePageData(await response.json()) as { url: string }).url).toBe('/named?page=2'); + }); + it('marks the request for a one-argument middleware that answers first', async () => { const app = new Hono(); const runtime = createRoutingRuntime(app, { nodeTarget: true }); diff --git a/packages/vue/test/unit/use-form.test.ts b/packages/vue/test/unit/use-form.test.ts index 143d5a3a7..01dbfaef4 100644 --- a/packages/vue/test/unit/use-form.test.ts +++ b/packages/vue/test/unit/use-form.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import type { VoidRouter } from 'void/pages-client'; import { createSSRApp, defineComponent, h, nextTick } from 'vue'; import { renderToString } from 'vue/server-renderer'; @@ -223,6 +223,10 @@ function validationResponse(errors: Record): Response { }); } +beforeEach(() => { + vi.stubGlobal('window', { location: { pathname: '/', search: '' } }); +}); + afterEach(() => { vi.unstubAllGlobals(); }); diff --git a/playground/react-pages/pages/scroll-restoration.server.ts b/playground/react-pages/pages/scroll-restoration.server.ts index 48a6c91a8..12466e07a 100644 --- a/playground/react-pages/pages/scroll-restoration.server.ts +++ b/playground/react-pages/pages/scroll-restoration.server.ts @@ -1,7 +1,10 @@ import { defineHandler } from 'void'; -export type Props = Readonly<{ requestId: string }>; -export const loader = defineHandler(() => ({ requestId: crypto.randomUUID() })); +export type Props = Readonly<{ requestId: string; page: string | null }>; +export const loader = defineHandler((c) => ({ + requestId: crypto.randomUUID(), + page: c.req.query('page') ?? null, +})); export const actions = { touch: defineHandler(() => {}), redirect: defineHandler((c) => c.redirect('/scroll-restoration?redirected=1')), diff --git a/playground/react-pages/pages/scroll-restoration.tsx b/playground/react-pages/pages/scroll-restoration.tsx index c1b4ca462..be6321dfa 100644 --- a/playground/react-pages/pages/scroll-restoration.tsx +++ b/playground/react-pages/pages/scroll-restoration.tsx @@ -2,13 +2,14 @@ import { action, Form, Link, useForm } from '@void/react'; import { startTransition } from 'react'; import type { Props } from './scroll-restoration.server.ts'; -export default function ScrollRestorationPage({ requestId }: Props) { +export default function ScrollRestorationPage({ requestId, page }: Props) { const form = useForm('/scroll-restoration?touch', {}); return (

Scroll restoration

Scroll down, follow a link, then use the browser Back button.

{requestId} + {page} {Array.from({ length: 80 }, (_, index) => { const row = index + 1; return ( diff --git a/playground/solid-pages/pages/scroll-restoration.server.ts b/playground/solid-pages/pages/scroll-restoration.server.ts index 48a6c91a8..12466e07a 100644 --- a/playground/solid-pages/pages/scroll-restoration.server.ts +++ b/playground/solid-pages/pages/scroll-restoration.server.ts @@ -1,7 +1,10 @@ import { defineHandler } from 'void'; -export type Props = Readonly<{ requestId: string }>; -export const loader = defineHandler(() => ({ requestId: crypto.randomUUID() })); +export type Props = Readonly<{ requestId: string; page: string | null }>; +export const loader = defineHandler((c) => ({ + requestId: crypto.randomUUID(), + page: c.req.query('page') ?? null, +})); export const actions = { touch: defineHandler(() => {}), redirect: defineHandler((c) => c.redirect('/scroll-restoration?redirected=1')), diff --git a/playground/solid-pages/pages/scroll-restoration.tsx b/playground/solid-pages/pages/scroll-restoration.tsx index b3e95675e..3af3fd940 100644 --- a/playground/solid-pages/pages/scroll-restoration.tsx +++ b/playground/solid-pages/pages/scroll-restoration.tsx @@ -11,6 +11,7 @@ export default function ScrollRestorationPage(props: Props) {

Scroll restoration

Scroll down, follow a link, then use the browser Back button.

{props.requestId} + {props.page} {(row) => (
diff --git a/playground/svelte-pages/pages/scroll-restoration.server.ts b/playground/svelte-pages/pages/scroll-restoration.server.ts index 48a6c91a8..12466e07a 100644 --- a/playground/svelte-pages/pages/scroll-restoration.server.ts +++ b/playground/svelte-pages/pages/scroll-restoration.server.ts @@ -1,7 +1,10 @@ import { defineHandler } from 'void'; -export type Props = Readonly<{ requestId: string }>; -export const loader = defineHandler(() => ({ requestId: crypto.randomUUID() })); +export type Props = Readonly<{ requestId: string; page: string | null }>; +export const loader = defineHandler((c) => ({ + requestId: crypto.randomUUID(), + page: c.req.query('page') ?? null, +})); export const actions = { touch: defineHandler(() => {}), redirect: defineHandler((c) => c.redirect('/scroll-restoration?redirected=1')), diff --git a/playground/svelte-pages/pages/scroll-restoration.svelte b/playground/svelte-pages/pages/scroll-restoration.svelte index e63005f50..09d013734 100644 --- a/playground/svelte-pages/pages/scroll-restoration.svelte +++ b/playground/svelte-pages/pages/scroll-restoration.svelte @@ -1,7 +1,7 @@ @@ -10,6 +10,7 @@

Scroll restoration

Scroll down, follow a link, then use the browser Back button.

{requestId} + {page} {#each rows as row (row)}

Row {row}

diff --git a/playground/vue-pages/pages/scroll-restoration.server.ts b/playground/vue-pages/pages/scroll-restoration.server.ts index 48a6c91a8..12466e07a 100644 --- a/playground/vue-pages/pages/scroll-restoration.server.ts +++ b/playground/vue-pages/pages/scroll-restoration.server.ts @@ -1,7 +1,10 @@ import { defineHandler } from 'void'; -export type Props = Readonly<{ requestId: string }>; -export const loader = defineHandler(() => ({ requestId: crypto.randomUUID() })); +export type Props = Readonly<{ requestId: string; page: string | null }>; +export const loader = defineHandler((c) => ({ + requestId: crypto.randomUUID(), + page: c.req.query('page') ?? null, +})); export const actions = { touch: defineHandler(() => {}), redirect: defineHandler((c) => c.redirect('/scroll-restoration?redirected=1')), diff --git a/playground/vue-pages/pages/scroll-restoration.vue b/playground/vue-pages/pages/scroll-restoration.vue index 74574fe42..75e22c76d 100644 --- a/playground/vue-pages/pages/scroll-restoration.vue +++ b/playground/vue-pages/pages/scroll-restoration.vue @@ -10,6 +10,7 @@ const form = useForm('/scroll-restoration?touch', {});

Scroll restoration

Scroll down, follow a link, then use the browser Back button.

{{ requestId }} + {{ page }}

Row {{ row }}

Go to Users diff --git a/test/pages-client-contract.ts b/test/pages-client-contract.ts index 110e3d33a..8200efa45 100644 --- a/test/pages-client-contract.ts +++ b/test/pages-client-contract.ts @@ -108,18 +108,19 @@ export function registerSharedClientTests({ BASE = getBase(); }); - it('keeps action and form scroll in place, with resets for overrides and redirects', async ({ + it('keeps the page query and scroll for actions and forms, with resets for overrides and redirects', async ({ expect, }) => { const page = await newPage(); try { await page.setViewportSize({ width: 1280, height: 800 }); - await page.goto(BASE + '/scroll-restoration'); + await page.goto(BASE + '/scroll-restoration?page=2'); await waitForHydration(page); await page.evaluate(() => { (window as TestWindow).__SPA_MARKER = true; }); const row = page.getByTestId('scroll-row-30'); + const historyLength = await page.evaluate(() => history.length); for (const [button, preserved] of [ ['Update action', true], ['Update form', true], @@ -141,8 +142,15 @@ export function registerSharedClientTests({ (scrollY) => Math.abs(window.scrollY - scrollY) < 0.5, preserved ? before : 0, ); + if (button !== 'Redirect action') { + expect(page.url()).toBe(BASE + '/scroll-restoration?page=2'); + expect(await page.getByTestId('scroll-page').textContent()).toBe('2'); + expect(await page.evaluate(() => history.length)).toBe(historyLength); + } } + // The page query only re-renders the page in place; a redirect does not carry it. expect(page.url()).toBe(BASE + '/scroll-restoration?redirected=1'); + expect(await page.getByTestId('scroll-page').textContent()).toBe(''); expect(await page.evaluate(() => (window as TestWindow).__SPA_MARKER)).toBe(true); } finally { await page.context().close();