Skip to content

Commit 9de45c4

Browse files
committed
Preserve action scroll only for in-place updates.
1 parent f792734 commit 9de45c4

19 files changed

Lines changed: 355 additions & 25 deletions

‎docs/guide/pages-routing/actions-and-forms.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,22 @@ If a callback awaits `router.visit()` or `router.refresh()`, pass `{ resolveOn:
202202

203203
Vue, Svelte, and Solid submissions return a promise instead; use `await form.post()` to run work after a submission.
204204

205+
### Scroll after submission
206+
207+
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.
208+
209+
Pass `preserveScroll: false` to reset scroll after an in-place update, or `true` to keep it even after a redirect:
210+
211+
```ts
212+
await action('/users/:id?update', {
213+
params: { id: '42' },
214+
data: { name: 'Alice' },
215+
preserveScroll: false,
216+
});
217+
```
218+
219+
In React, set `preserveScroll` in the third argument to `useForm()`. In Vue, Svelte, and Solid, pass it to the submit method, such as `form.post({ preserveScroll: false })`.
220+
205221
## Named Actions
206222

207223
When a page needs multiple mutations, such as updating and deleting a user on the same page, export `actions` (plural) instead of `action`:

‎docs/guide/pages-routing/overview.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,7 @@ Void manages scroll position for Pages automatically:
371371

372372
- **Back/forward navigation and reloads** restore the saved scroll position.
373373
- **New navigation** scrolls to the top of the page.
374+
- **Actions and forms** keep scroll when updating the current page. Redirects follow normal navigation behavior.
374375
- **Hash links** (`/docs#api`) scroll to the target element. Same-page hash links (`#section`) skip the server fetch entirely.
375376

376377
To keep the current scroll position, pass `preserveScroll: true`:

‎docs/reference/api/pages.md‎

Lines changed: 4 additions & 4 deletions
Large diffs are not rendered by default.

‎packages/react/src/runtime/use-form.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ type FormReturn<TData> = FormState<TData, 'setters'> &
3636
type FormOptions = {
3737
params?: Record<string, string>;
3838
resetOnSuccess?: boolean;
39+
preserveScroll?: boolean;
3940
onSuccess?: () => void | Promise<void>;
4041
onError?: (error: Record<string, string> | VoidActionError) => void | Promise<void>;
4142
};
@@ -44,7 +45,7 @@ type FormOptions = {
4445
export function useForm<U extends ActionUrl & string>(
4546
url: U,
4647
defaults: ResolveActionBody<U>,
47-
options?: ActionFormOptions<U> & Pick<FormOptions, 'onSuccess' | 'onError'>,
48+
options?: ActionFormOptions<U> & Pick<FormOptions, 'onSuccess' | 'onError' | 'preserveScroll'>,
4849
): FormReturn<ResolveActionBody<U>>;
4950

5051
export function useForm(
@@ -147,6 +148,7 @@ export function useForm(
147148
result = await submitAction(router, interpolateRouteParams(url, options?.params), {
148149
method,
149150
data: { ...dataRef.current },
151+
preserveScroll: options?.preserveScroll,
150152
_resolveOnShell: true,
151153
});
152154
} catch (submitError) {

‎packages/react/test/unit/use-form.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,15 @@ async function submitPost(form: TestForm) {
107107
}
108108

109109
describe('useForm callbacks', () => {
110+
it.each([true, false])('forwards preserveScroll: %s from useForm()', async (preserveScroll) => {
111+
const visit = vi.fn(async () => ({}));
112+
const { formRef } = await mountForm(visit, { preserveScroll });
113+
114+
await submitPost(formRef.current!);
115+
116+
expect(visit).toHaveBeenCalledWith(actionUrl, expect.objectContaining({ preserveScroll }));
117+
});
118+
110119
it('calls onSuccess once after a successful submit in Strict Mode', async () => {
111120
const onSuccess = vi.fn();
112121
const { formRef } = await mountForm(

‎packages/react/test/unit/use-form.typecheck.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export function checkFormOptions(): void {
1414
{ title: '' },
1515
{
1616
resetOnSuccess: true,
17+
preserveScroll: false,
1718
onSuccess: async () => {},
1819
onError: async (error) => {
1920
if (error instanceof VoidActionError) {
@@ -53,4 +54,6 @@ export function checkFormOptions(): void {
5354
useForm('/__form-options/notes?create', { missing: '' }, { onSuccess: () => {} });
5455
// @ts-expect-error Success callbacks return void or a promise of void.
5556
useForm('/__form-options/notes?create', { title: '' }, { onSuccess: () => 123 });
57+
// @ts-expect-error Scroll preservation must be a boolean.
58+
useForm('/__form-options/notes?create', { title: '' }, { preserveScroll: 'yes' });
5659
}

‎packages/void/src/pages/client.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -284,10 +284,7 @@ export async function submitAction(
284284
options: VisitOptions,
285285
): Promise<ActionResult> {
286286
try {
287-
const pageData = await router.visit(url, {
288-
preserveScroll: true,
289-
...options,
290-
});
287+
const pageData = await router.visit(url, options);
291288
if (
292289
typeof pageData === 'object' &&
293290
pageData !== null &&
@@ -320,6 +317,7 @@ type HasParams<U extends string> = [ResolveActionParams<U>] extends [never] ? fa
320317
type ActionOptions<U extends string> = {
321318
data?: ResolveActionBody<U>;
322319
method?: ActionMethod;
320+
preserveScroll?: boolean;
323321
} & (HasParams<U> extends true ? { params: ResolveActionParams<U> } : { params?: never });
324322

325323
export type ActionClient = {
@@ -358,7 +356,12 @@ export function createActionClient(
358356
url,
359357
options?.params as Record<string, string> | undefined,
360358
);
361-
return submitAction(_router, resolvedUrl, { method, data, ...defaults });
359+
return submitAction(_router, resolvedUrl, {
360+
method,
361+
data,
362+
preserveScroll: options?.preserveScroll,
363+
...defaults,
364+
});
362365
}
363366

364367
return { action, setActionRouter };

‎packages/void/src/pages/navigation-engine.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ type PageFetchOptions = RequestInit & { headers: Record<string, string> };
4343

4444
type StaticPageDataResult = { pageData: PageData; resolvedDeferred: boolean };
4545

46+
type NavigationCommitTarget = { fetchUrl: string; hash: string; method: string };
47+
4648
export type VisitOptions = {
4749
method?: string;
4850
data?: unknown;
@@ -619,7 +621,7 @@ export async function createPageNavigationEngine(
619621
method: string,
620622
options: VisitOptions,
621623
signal: AbortSignal,
622-
commitTarget: { fetchUrl: string; hash: string },
624+
commitTarget: NavigationCommitTarget,
623625
deferredRegistry: DeferredRegistry,
624626
): Promise<PageNavigationResult | undefined> {
625627
// Page data only comes from this origin. Other http(s) URLs get a full page
@@ -731,6 +733,7 @@ export async function createPageNavigationEngine(
731733
url = fetchUrl + redirectUrl.hash;
732734
commitTarget.fetchUrl = fetchUrl;
733735
commitTarget.hash = redirectUrl.hash;
736+
commitTarget.method = method;
734737
}
735738

736739
if (response && method !== 'GET' && !response.ok) {
@@ -863,7 +866,7 @@ export async function createPageNavigationEngine(
863866
}
864867

865868
function makeCommit(
866-
commitTarget: { fetchUrl: string; hash: string },
869+
commitTarget: NavigationCommitTarget,
867870
options: VisitOptions,
868871
shell: Promise<PageNavigationResult | undefined>,
869872
deferredRegistry: DeferredRegistry,
@@ -885,6 +888,12 @@ export async function createPageNavigationEngine(
885888
if (resourceId < _urlNavigationId) {
886889
return false;
887890
}
891+
// Mutations that update the current page keep scroll. A redirect's GET
892+
// response or an action that opens another page follows normal navigation.
893+
const preserveScroll =
894+
options.preserveScroll ??
895+
(commitTarget.method !== 'GET' &&
896+
commitTarget.fetchUrl === window.location.pathname + window.location.search);
888897
// Write history before anything else changes. Disposing the previous page and handing
889898
// over its Deferred values cannot be undone, so a failed write must find them untouched.
890899
// preserveState only controls component state; back/forward traversal already moved history.
@@ -954,7 +963,7 @@ export async function createPageNavigationEngine(
954963
scrollRestoration.commit();
955964

956965
requestAnimationFrame(() => {
957-
if (!options.preserveScroll) {
966+
if (!preserveScroll) {
958967
restoreScroll(options._scrollPosition, commitTarget.hash);
959968
}
960969
});
@@ -1054,7 +1063,7 @@ export async function createPageNavigationEngine(
10541063

10551064
const controller = new AbortController();
10561065
const deferredRegistry = new DeferredRegistry();
1057-
const commitTarget = { fetchUrl: effectiveFetchUrl, hash };
1066+
const commitTarget = { fetchUrl: effectiveFetchUrl, hash, method };
10581067
const shell = loadNavigationShell(
10591068
id,
10601069
url,

‎packages/void/test/unit/action-result.test.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ describe('action result handling', () => {
127127
expect(isAbortError(new Error('Boom'))).toBe(false);
128128
});
129129

130-
it('preserves scroll by default when submitting an action', async () => {
130+
it('leaves the default scroll decision to the router', async () => {
131131
const visit = vi.fn(async () => ({ props: {} }));
132132
const router = routerWithVisit(visit);
133133

@@ -137,7 +137,6 @@ describe('action result handling', () => {
137137
});
138138

139139
expect(visit).toHaveBeenCalledWith('/users', {
140-
preserveScroll: true,
141140
method: 'POST',
142141
data: { name: 'Alice' },
143142
});
@@ -160,6 +159,19 @@ describe('action result handling', () => {
160159
});
161160

162161
describe('action clients', () => {
162+
it.each([true, false])('forwards preserveScroll: %s from action()', async (preserveScroll) => {
163+
const client = createActionClient();
164+
const visit = vi.fn(async () => ({ props: {} }));
165+
client.setActionRouter(routerWithVisit(visit));
166+
167+
await client.action('/__action-test/static', { preserveScroll });
168+
169+
expect(visit).toHaveBeenCalledWith(
170+
'/__action-test/static',
171+
expect.objectContaining({ preserveScroll }),
172+
);
173+
});
174+
163175
it('uses the adapter completion mode for action calls', async () => {
164176
const client = createActionClient({ _resolveOnShell: true });
165177
const visit = vi.fn(async () => ({ props: {} }));
@@ -169,7 +181,7 @@ describe('action clients', () => {
169181
method: 'POST',
170182
data: undefined,
171183
_resolveOnShell: true,
172-
preserveScroll: true,
184+
preserveScroll: undefined,
173185
});
174186
});
175187

@@ -201,7 +213,7 @@ describe('action clients', () => {
201213
expect(firstVisit).toHaveBeenCalledWith('/__action-test/static', {
202214
method: 'POST',
203215
data: undefined,
204-
preserveScroll: true,
216+
preserveScroll: undefined,
205217
});
206218
});
207219

@@ -219,7 +231,7 @@ describe('action clients', () => {
219231
expect(visit).toHaveBeenCalledWith('/__action-test/users/a%2Fb%3Fc?save', {
220232
method: 'PATCH',
221233
data: { name: 'Alice' },
222-
preserveScroll: true,
234+
preserveScroll: undefined,
223235
});
224236
});
225237

‎packages/void/test/unit/pages-client.test.ts‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
createVoidRouter,
77
mergeDataIntoHref,
88
ssrProxy,
9+
submitAction,
910
type VoidRouterConfig,
1011
} from '../../src/pages/client.ts';
1112
import { createPageNavigationEngine } from '../../src/pages/navigation-engine.ts';
@@ -125,6 +126,127 @@ afterEach(() => {
125126
});
126127

127128
describe('createVoidRouter', () => {
129+
it.each(['POST', 'PUT', 'PATCH', 'DELETE'])(
130+
'preserves scroll for an in-place %s action',
131+
async (method) => {
132+
stubClientGlobals();
133+
window.location.pathname = '/editor';
134+
window.scrollY = 1800;
135+
vi.stubGlobal(
136+
'fetch',
137+
vi.fn(async () => pageJson({ component: 'home', props: {}, url: '/editor', errors: null })),
138+
);
139+
const { router } = await createTestRouter();
140+
141+
await submitAction(router, '/editor?save', { method });
142+
143+
expect(window.scrollTo).not.toHaveBeenCalled();
144+
expect(history.replaceState).toHaveBeenCalledWith(expect.anything(), '', '/editor');
145+
},
146+
);
147+
148+
it.each([
149+
['/editor', false, undefined],
150+
['/destination', false, undefined],
151+
['/destination', false, false],
152+
['/destination', true, true],
153+
])(
154+
'handles scroll for an action redirect to %s (preserved: %s, override: %s)',
155+
async (destination, preserved, preserveScroll) => {
156+
stubClientGlobals();
157+
window.location.pathname = '/editor';
158+
window.scrollY = 1800;
159+
const response = pageJson({ component: 'home', props: {}, url: destination, errors: null });
160+
Object.defineProperties(response, {
161+
redirected: { value: true },
162+
url: { value: `http://localhost${destination}` },
163+
});
164+
vi.stubGlobal(
165+
'fetch',
166+
vi.fn(async () => response),
167+
);
168+
const { router } = await createTestRouter();
169+
170+
await submitAction(router, '/editor?save', {
171+
method: 'POST',
172+
...(preserveScroll === undefined ? {} : { preserveScroll }),
173+
});
174+
175+
const writeHistory = destination === '/editor' ? history.replaceState : history.pushState;
176+
expect(writeHistory).toHaveBeenCalledWith(expect.anything(), '', destination);
177+
if (preserved) {
178+
expect(window.scrollTo).not.toHaveBeenCalled();
179+
} else {
180+
expect(window.scrollTo).toHaveBeenCalledWith(0, 0);
181+
}
182+
},
183+
);
184+
185+
it('scrolls to the fragment when an action redirects to an anchor', async () => {
186+
const documentStub = stubClientGlobals();
187+
window.location.pathname = '/editor';
188+
const scrollIntoView = vi.fn();
189+
const response = pageJson({ component: 'home', props: {}, url: '/destination', errors: null });
190+
Object.defineProperties(response, {
191+
redirected: { value: true },
192+
url: { value: 'http://localhost/destination#details' },
193+
});
194+
vi.stubGlobal(
195+
'fetch',
196+
vi.fn(async () => response),
197+
);
198+
const { router } = await createTestRouter();
199+
vi.stubGlobal('document', {
200+
...documentStub,
201+
getElementById: vi.fn((id: string) => (id === 'details' ? { scrollIntoView } : null)),
202+
});
203+
204+
await submitAction(router, '/editor?save', { method: 'POST' });
205+
206+
expect(scrollIntoView).toHaveBeenCalledOnce();
207+
expect(history.pushState).toHaveBeenCalledWith(expect.anything(), '', '/destination#details');
208+
});
209+
210+
it.each([undefined, false])(
211+
'resets action scroll with override %s when leaving the page',
212+
async (preserveScroll) => {
213+
stubClientGlobals();
214+
window.location.pathname = '/editor';
215+
const response = pageJson({
216+
component: 'home',
217+
props: {},
218+
url: '/destination',
219+
errors: null,
220+
});
221+
vi.stubGlobal(
222+
'fetch',
223+
vi.fn(async () => response),
224+
);
225+
const { router } = await createTestRouter();
226+
227+
await submitAction(router, '/destination?save', {
228+
method: 'POST',
229+
...(preserveScroll === undefined ? {} : { preserveScroll }),
230+
});
231+
232+
expect(window.scrollTo).toHaveBeenCalledWith(0, 0);
233+
},
234+
);
235+
236+
it('allows an in-place action to reset scroll explicitly', async () => {
237+
stubClientGlobals();
238+
window.location.pathname = '/editor';
239+
vi.stubGlobal(
240+
'fetch',
241+
vi.fn(async () => pageJson({ component: 'home', props: {}, url: '/editor', errors: null })),
242+
);
243+
const { router } = await createTestRouter();
244+
245+
await submitAction(router, '/editor?save', { method: 'POST', preserveScroll: false });
246+
247+
expect(window.scrollTo).toHaveBeenCalledWith(0, 0);
248+
});
249+
128250
it('exposes the default prefetch strategy to Links', async () => {
129251
stubClientGlobals();
130252
const { router } = await createTestRouter({ prefetchDefaultStrategy: ['hover', 'click'] });

0 commit comments

Comments
 (0)