Skip to content

Commit 5d0a5dc

Browse files
committed
feat(router): add focusReset to NavigationBehaviorOptions
With the platform navigation integration, the router passes `scroll` to `NavigateEvent#intercept()` but not `focusReset`, so the browser moves focus to the body after every navigation. A search field that writes its value to a query param loses focus after the first key. Add a `focusReset` option next to `scroll` and pass it to `intercept()`, so a navigation can leave focus where it is. Without the option, the browser default still applies. Fixes angular#71594
1 parent 455b627 commit 5d0a5dc

5 files changed

Lines changed: 100 additions & 1 deletion

File tree

‎goldens/public-api/router/index.api.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,7 @@ export interface Navigation {
427427
// @public
428428
export interface NavigationBehaviorOptions {
429429
readonly browserUrl?: UrlTree | string;
430+
readonly focusReset?: 'manual' | 'after-transition';
430431
readonly info?: unknown;
431432
onSameUrlNavigation?: OnSameUrlNavigation;
432433
replaceUrl?: boolean;

‎packages/router/src/models.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1685,4 +1685,19 @@ export interface NavigationBehaviorOptions {
16851685
* @see InMemoryScrollingOptions
16861686
*/
16871687
readonly scroll?: 'manual' | 'after-transition';
1688+
1689+
/**
1690+
* Configures whether the browser resets focus when the navigation is complete. It only applies
1691+
* when the router uses the browser Navigation API (`withExperimentalPlatformNavigation`).
1692+
*
1693+
* - When 'after-transition' (the default), the browser moves focus to the first element with the
1694+
* `autofocus` attribute, or to the `<body>`.
1695+
* - When 'manual', the browser doesn't reset focus. For example, a search field that updates a
1696+
* query parameter as the user types keeps focus.
1697+
*
1698+
* @see [NavigateEvent#intercept](https://developer.mozilla.org/docs/Web/API/NavigateEvent/intercept)
1699+
*
1700+
* @experimental 22.3
1701+
*/
1702+
readonly focusReset?: 'manual' | 'after-transition';
16881703
}

‎packages/router/src/router.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ export class Router {
218218
);
219219
const extras = {
220220
scroll: currentTransition.extras.scroll,
221+
focusReset: currentTransition.extras.focusReset,
221222
browserUrl: currentTransition.extras.browserUrl,
222223
info: currentTransition.extras.info,
223224
skipLocationChange: currentTransition.extras.skipLocationChange,

‎packages/router/src/statemanager/navigation_state_manager.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,7 @@ export class NavigationStateManager extends StateManager {
458458
: (this.currentNavigation.routerTransition?.extras.scroll ?? 'after-transition');
459459
const interceptOptions: NavigationInterceptOptions = {
460460
scroll,
461+
focusReset: this.currentNavigation.routerTransition?.extras.focusReset,
461462
};
462463

463464
const {

‎packages/router/test/with_platform_navigation.spec.ts‎

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import {
3232
provideLocationMocks,
3333
MOCK_PLATFORM_LOCATION_CONFIG,
3434
} from '@angular/common/testing';
35-
import {inject} from '@angular/core';
35+
import {inject, Provider} from '@angular/core';
3636

3737
/// <reference types="dom-navigation" />
3838

@@ -510,4 +510,85 @@ if (typeof window !== 'undefined' && 'navigation' in window && !isFirefox()) {
510510
}),
511511
);
512512
});
513+
514+
describe('focusReset with real platform navigation', () => {
515+
const navigation = window.navigation as Navigation;
516+
517+
async function setup(providers: Provider[] = []) {
518+
TestBed.configureTestingModule({
519+
providers: [
520+
provideRouter(
521+
[
522+
{
523+
path: 'guarded',
524+
canActivate: [() => inject(Router).parseUrl('/search?q=redirected')],
525+
children: [],
526+
},
527+
{path: '**', children: []},
528+
],
529+
withExperimentalPlatformNavigation(),
530+
),
531+
{provide: PlatformLocation, useClass: BrowserPlatformLocation},
532+
{provide: PlatformNavigation, useFactory: () => navigation},
533+
...providers,
534+
],
535+
});
536+
const router = TestBed.inject(Router);
537+
router.initialNavigation();
538+
await timeout();
539+
return router;
540+
}
541+
542+
it(
543+
'resets focus by default',
544+
withBody('<input>', async () => {
545+
const router = await setup();
546+
const input = document.querySelector('input')!;
547+
input.focus();
548+
expect(document.activeElement).toBe(input);
549+
550+
// Each test uses its own URL: these tests share the page URL, and navigating to the
551+
// current URL again would be skipped by the router.
552+
await router.navigate(['/search'], {queryParams: {q: 'default'}});
553+
// The browser resets focus when it finishes the navigate event, after the next render.
554+
await navigation.transition?.finished;
555+
556+
expect(router.url).toBe('/search?q=default');
557+
expect(document.activeElement).toBe(document.body);
558+
}),
559+
);
560+
561+
it(
562+
"keeps focus with focusReset: 'manual'",
563+
withBody('<input>', async () => {
564+
const router = await setup();
565+
const input = document.querySelector('input')!;
566+
input.focus();
567+
expect(document.activeElement).toBe(input);
568+
569+
await router.navigate(['/search'], {queryParams: {q: 'manual'}, focusReset: 'manual'});
570+
await navigation.transition?.finished;
571+
572+
expect(router.url).toBe('/search?q=manual');
573+
expect(document.activeElement).toBe(input);
574+
}),
575+
);
576+
577+
it(
578+
"keeps focusReset: 'manual' when a guard redirects",
579+
withBody('<input>', async () => {
580+
// Without precommitHandler, the browser navigation is created for the redirect.
581+
const router = await setup([{provide: PRECOMMIT_HANDLER_SUPPORTED, useValue: false}]);
582+
const input = document.querySelector('input')!;
583+
input.focus();
584+
expect(document.activeElement).toBe(input);
585+
586+
await router.navigateByUrl('/guarded', {focusReset: 'manual'});
587+
await navigation.transition?.finished;
588+
589+
expect(router.url).toBe('/search?q=redirected');
590+
expect(document.activeElement).toBe(input);
591+
}),
592+
);
593+
});
513594
}

0 commit comments

Comments
 (0)