Skip to content

Commit 5b686ef

Browse files
authored
feat: add experimental transition focus manager (#29400)
Issue number: resolves #23650 --------- <!-- Please do not submit updates to dependencies unless it fixes an issue. --> <!-- Please try to limit your pull request to one type (bugfix, feature, etc). Submit multiple pull requests if needed. --> ## What is the current behavior? <!-- Please describe the current behavior that you are modifying. --> In traditional native applications, navigation will inform screen readers that the view has changed. This allows screen readers to focus the correct view. In a single page app on the web, this same concept does not exist. As a result, transitioning from Page A to Page B results in screen reader focus remaining on Page A. This means that users who rely on screen readers are not informed of view changes. Currently, developers are responsible for implementing this on their own. ## What is the new behavior? <!-- Please describe the behavior or changes that are being added by this PR. --> - Introduces a new focus manager priority global config. When defined, the app developer can specify which area of the view focus should be moved to when the transition ends. The developer does this by specifying areas in order of priority which allows for fallbacks in the event that a particular UI component (such as a header) does not exist on a view. There is some risk here by managing focus for the application. As a result, this feature is considered experimental and disabled by default. The team should collect feedback based on usage and enable it by default when they feel this feature is stable enough. ## Does this introduce a breaking change? - [ ] Yes - [x] No <!-- If this introduces a breaking change: 1. Describe the impact and migration path for existing applications below. 2. Update the BREAKING.md file with the breaking change. 3. Add "BREAKING CHANGE: [...]" to the commit description when merging. See https://github.com/ionic-team/ionic-framework/blob/main/docs/CONTRIBUTING.md#footer for more information. --> ## Other information <!-- Any other information that is important to this PR such as screenshots of how the component looks before and after the change. --> ⚠️ Due to the `tsconfig.json` change, reviewers should restart the Stencil dev server when checking out these changes locally. Reviewers: Please test both of the test template files on physical iOS and Android device with VoiceOver and TalkBack enabled, respectively. Docs Link: ionic-team/ionic-docs#3627
1 parent 7c00351 commit 5b686ef

File tree

9 files changed

+502
-2
lines changed

9 files changed

+502
-2
lines changed

core/src/css/core.scss

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,23 @@ ion-input input::-webkit-date-and-time-value {
395395
}
396396

397397
/**
398+
* When moving focus on page transitions we call .focus() on an element which can
399+
* add an undesired outline ring. This CSS removes the outline ring.
400+
* We also remove the outline ring from elements that are actively being focused
401+
* by the focus manager. We are intentionally selective about which elements this
402+
* applies to so we do not accidentally override outlines set by the developer.
403+
*/
404+
[ion-last-focus],
405+
header[tabindex="-1"]:focus,
406+
[role="banner"][tabindex="-1"]:focus,
407+
main[tabindex="-1"]:focus,
408+
[role="main"][tabindex="-1"]:focus,
409+
h1[tabindex="-1"]:focus,
410+
[role="heading"][aria-level="1"][tabindex="-1"]:focus {
411+
outline: none;
412+
}
413+
414+
/*
398415
* If a popover has a child ion-content (or class equivalent) then the .popover-viewport element
399416
* should not be scrollable to ensure the inner content does scroll. However, if the popover
400417
* does not have a child ion-content (or class equivalent) then the .popover-viewport element

core/src/utils/config.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,14 @@ export interface IonicConfig {
204204
*/
205205
platform?: PlatformConfig;
206206

207+
/**
208+
* @experimental
209+
* When defined, Ionic will move focus to the appropriate element after each
210+
* page transition. This ensures that users relying on assistive technology
211+
* are informed when a page transition happens.
212+
*/
213+
focusManagerPriority?: FocusManagerPriority[];
214+
207215
/**
208216
* @experimental
209217
* If `true`, the [CloseWatcher API](https://github.com/WICG/close-watcher) will be used to handle
@@ -231,6 +239,8 @@ export interface IonicConfig {
231239
_ce?: (eventName: string, opts: any) => any;
232240
}
233241

242+
type FocusManagerPriority = 'content' | 'heading' | 'banner';
243+
234244
export const setupConfig = (config: IonicConfig) => {
235245
const win = window as any;
236246
const Ionic = win.Ionic;
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import { config } from '@global/config';
2+
import { printIonWarning } from '@utils/logging';
3+
4+
/**
5+
* Moves focus to a specified element. Note that we do not remove the tabindex
6+
* because that can result in an unintentional blur. Non-focusables can't be
7+
* focused, so the body will get focused again.
8+
*/
9+
const moveFocus = (el: HTMLElement) => {
10+
el.tabIndex = -1;
11+
el.focus();
12+
};
13+
14+
/**
15+
* Elements that are hidden using `display: none` should not be focused even if
16+
* they are present in the DOM.
17+
*/
18+
const isVisible = (el: HTMLElement) => {
19+
return el.offsetParent !== null;
20+
};
21+
22+
/**
23+
* The focus controller allows us to manage focus within a view so assistive
24+
* technologies can inform users of changes to the navigation state. Traditional
25+
* native apps have a way of informing assistive technology about a navigation
26+
* state change. Mobile browsers have this too, but only when doing a full page
27+
* load. In a single page app we do not do that, so we need to build this
28+
* integration ourselves.
29+
*/
30+
export const createFocusController = (): FocusController => {
31+
const saveViewFocus = (referenceEl?: HTMLElement) => {
32+
const focusManagerEnabled = config.get('focusManagerPriority', false);
33+
34+
/**
35+
* When going back to a previously visited page focus should typically be moved
36+
* back to the element that was last focused when the user was on this view.
37+
*/
38+
if (focusManagerEnabled) {
39+
const activeEl = document.activeElement;
40+
if (activeEl !== null && referenceEl?.contains(activeEl)) {
41+
activeEl.setAttribute(LAST_FOCUS, 'true');
42+
}
43+
}
44+
};
45+
46+
const setViewFocus = (referenceEl: HTMLElement) => {
47+
const focusManagerPriorities = config.get('focusManagerPriority', false);
48+
/**
49+
* If the focused element is a descendant of the referenceEl then it's possible
50+
* that the app developer manually moved focus, so we do not want to override that.
51+
* This can happen with inputs the are focused when a view transitions in.
52+
*/
53+
if (Array.isArray(focusManagerPriorities) && !referenceEl.contains(document.activeElement)) {
54+
/**
55+
* When going back to a previously visited view focus should always be moved back
56+
* to the element that the user was last focused on when they were on this view.
57+
*/
58+
const lastFocus = referenceEl.querySelector<HTMLElement>(`[${LAST_FOCUS}]`);
59+
if (lastFocus && isVisible(lastFocus)) {
60+
moveFocus(lastFocus);
61+
return;
62+
}
63+
64+
for (const priority of focusManagerPriorities) {
65+
/**
66+
* For each recognized case (excluding the default case) make sure to return
67+
* so that the fallback focus behavior does not run.
68+
*
69+
* We intentionally query for specific roles/semantic elements so that the
70+
* transition manager can work with both Ionic and non-Ionic UI components.
71+
*
72+
* If new selectors are added, be sure to remove the outline ring by adding
73+
* new selectors to rule in core.scss.
74+
*/
75+
switch (priority) {
76+
case 'content':
77+
const content = referenceEl.querySelector<HTMLElement>('main, [role="main"]');
78+
if (content && isVisible(content)) {
79+
moveFocus(content);
80+
return;
81+
}
82+
break;
83+
case 'heading':
84+
const headingOne = referenceEl.querySelector<HTMLElement>('h1, [role="heading"][aria-level="1"]');
85+
if (headingOne && isVisible(headingOne)) {
86+
moveFocus(headingOne);
87+
return;
88+
}
89+
break;
90+
case 'banner':
91+
const header = referenceEl.querySelector<HTMLElement>('header, [role="banner"]');
92+
if (header && isVisible(header)) {
93+
moveFocus(header);
94+
return;
95+
}
96+
break;
97+
default:
98+
printIonWarning(`Unrecognized focus manager priority value ${priority}`);
99+
break;
100+
}
101+
}
102+
103+
/**
104+
* If there is nothing to focus then focus the page so focus at least moves to
105+
* the correct view. The browser will then determine where within the page to
106+
* move focus to.
107+
*/
108+
moveFocus(referenceEl);
109+
}
110+
};
111+
112+
return {
113+
saveViewFocus,
114+
setViewFocus,
115+
};
116+
};
117+
118+
export type FocusController = {
119+
saveViewFocus: (referenceEl?: HTMLElement) => void;
120+
setViewFocus: (referenceEl: HTMLElement) => void;
121+
};
122+
123+
const LAST_FOCUS = 'ion-last-focus';
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { expect } from '@playwright/test';
2+
import { configs, test } from '@utils/test/playwright';
3+
import type { E2ELocator } from '@utils/test/playwright';
4+
5+
configs({ modes: ['md'], directions: ['ltr'] }).forEach(({ title, config }) => {
6+
test.describe(title('focus controller: generic components'), () => {
7+
test.beforeEach(async ({ page }) => {
8+
await page.goto('/src/utils/focus-controller/test/generic', config);
9+
});
10+
test('should focus heading', async ({ page }) => {
11+
const goToPageOneButton = page.locator('page-root button.page-one');
12+
const nav = page.locator('ion-nav') as E2ELocator;
13+
const ionNavDidChange = await (nav as any).spyOnEvent('ionNavDidChange');
14+
15+
// Focus heading on Page One
16+
await goToPageOneButton.click();
17+
await ionNavDidChange.next();
18+
19+
const pageOneTitle = page.locator('page-one h1');
20+
await expect(pageOneTitle).toBeFocused();
21+
});
22+
23+
test('should focus banner', async ({ page }) => {
24+
const goToPageThreeButton = page.locator('page-root button.page-three');
25+
const nav = page.locator('ion-nav') as E2ELocator;
26+
const ionNavDidChange = await (nav as any).spyOnEvent('ionNavDidChange');
27+
28+
const pageThreeHeader = page.locator('page-three header');
29+
await goToPageThreeButton.click();
30+
await ionNavDidChange.next();
31+
32+
await expect(pageThreeHeader).toBeFocused();
33+
});
34+
35+
test('should focus content', async ({ page }) => {
36+
const goToPageTwoButton = page.locator('page-root button.page-two');
37+
const nav = page.locator('ion-nav') as E2ELocator;
38+
const ionNavDidChange = await (nav as any).spyOnEvent('ionNavDidChange');
39+
const pageTwoContent = page.locator('page-two main');
40+
41+
await goToPageTwoButton.click();
42+
await ionNavDidChange.next();
43+
44+
await expect(pageTwoContent).toBeFocused();
45+
});
46+
47+
test('should return focus when going back', async ({ page, browserName }) => {
48+
test.skip(browserName === 'webkit', 'Desktop Safari does not consider buttons to be focusable');
49+
50+
const goToPageOneButton = page.locator('page-root button.page-one');
51+
const nav = page.locator('ion-nav') as E2ELocator;
52+
const ionNavDidChange = await (nav as any).spyOnEvent('ionNavDidChange');
53+
const pageOneBackButton = page.locator('page-one ion-back-button');
54+
55+
await goToPageOneButton.click();
56+
await ionNavDidChange.next();
57+
58+
await pageOneBackButton.click();
59+
await ionNavDidChange.next();
60+
61+
await expect(goToPageOneButton).toBeFocused();
62+
});
63+
});
64+
});
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
<!DOCTYPE html>
2+
<html lang="en" dir="ltr">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<title>Focus Manager</title>
6+
<meta
7+
name="viewport"
8+
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
9+
/>
10+
<link href="../../../../../css/ionic.bundle.css" rel="stylesheet" />
11+
<link href="../../../../../scripts/testing/styles.css" rel="stylesheet" />
12+
<script src="../../../../../scripts/testing/scripts.js"></script>
13+
<script nomodule src="../../../../../dist/ionic/ionic.js"></script>
14+
<script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script>
15+
<script>
16+
class PageRoot extends HTMLElement {
17+
connectedCallback() {
18+
this.innerHTML = `
19+
<ion-header>
20+
<ion-toolbar>
21+
<h1>Root</h1>
22+
</ion-toolbar>
23+
</ion-header>
24+
<ion-content class="ion-padding">
25+
<ion-nav-link router-direction="forward" component="page-one">
26+
<button class="page-one">Go to Page One</button>
27+
</ion-nav-link>
28+
<ion-nav-link router-direction="forward" component="page-two">
29+
<button class="page-two">Go to Page Two</button>
30+
</ion-nav-link>
31+
<ion-nav-link router-direction="forward" component="page-three">
32+
<button class="page-three">Go to Page Three</button>
33+
</ion-nav-link>
34+
</ion-content>
35+
`;
36+
}
37+
}
38+
class PageOne extends HTMLElement {
39+
connectedCallback() {
40+
this.innerHTML = `
41+
<ion-header>
42+
<ion-toolbar>
43+
<ion-buttons slot="start">
44+
<ion-back-button></ion-back-button>
45+
</ion-buttons>
46+
<h1>Page One</h1>
47+
</ion-toolbar>
48+
</ion-header>
49+
<ion-content class="ion-padding">
50+
Content
51+
</ion-content>
52+
`;
53+
}
54+
}
55+
class PageTwo extends HTMLElement {
56+
connectedCallback() {
57+
this.innerHTML = `
58+
<main class="ion-padding">
59+
Content
60+
</main>
61+
`;
62+
}
63+
}
64+
class PageThree extends HTMLElement {
65+
connectedCallback() {
66+
this.innerHTML = `
67+
<header>
68+
<ion-toolbar>
69+
<ion-buttons slot="start">
70+
<!-- Back button is hidden when not in an ion-header, so default-href makes it visible -->
71+
<ion-back-button default-href="/"></ion-back-button>
72+
</ion-buttons>
73+
</ion-toolbar>
74+
</header>
75+
<ion-content class="ion-padding">
76+
Content
77+
</ion-content>
78+
`;
79+
}
80+
}
81+
customElements.define('page-root', PageRoot);
82+
customElements.define('page-one', PageOne);
83+
customElements.define('page-two', PageTwo);
84+
customElements.define('page-three', PageThree);
85+
86+
window.Ionic = {
87+
config: {
88+
focusManagerPriority: ['heading', 'banner', 'content'],
89+
},
90+
};
91+
</script>
92+
</head>
93+
94+
<body>
95+
<ion-app>
96+
<ion-router>
97+
<ion-route url="/" component="page-root"></ion-route>
98+
<ion-route url="/page-one" component="page-one"></ion-route>
99+
<ion-route url="/page-two" component="page-two"></ion-route>
100+
<ion-route url="/page-three" component="page-three"></ion-route>
101+
</ion-router>
102+
<ion-nav></ion-nav>
103+
</ion-app>
104+
</body>
105+
</html>

0 commit comments

Comments
 (0)