Files
ionic-framework/core/src/utils/focus-controller/index.ts
Liam DeBeasi 5b686efc10 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: https://github.com/ionic-team/ionic-docs/pull/3627
2024-05-01 10:09:05 -04:00

124 lines
4.4 KiB
TypeScript

import { config } from '@global/config';
import { printIonWarning } from '@utils/logging';
/**
* Moves focus to a specified element. Note that we do not remove the tabindex
* because that can result in an unintentional blur. Non-focusables can't be
* focused, so the body will get focused again.
*/
const moveFocus = (el: HTMLElement) => {
el.tabIndex = -1;
el.focus();
};
/**
* Elements that are hidden using `display: none` should not be focused even if
* they are present in the DOM.
*/
const isVisible = (el: HTMLElement) => {
return el.offsetParent !== null;
};
/**
* The focus controller allows us to manage focus within a view so assistive
* technologies can inform users of changes to the navigation state. Traditional
* native apps have a way of informing assistive technology about a navigation
* state change. Mobile browsers have this too, but only when doing a full page
* load. In a single page app we do not do that, so we need to build this
* integration ourselves.
*/
export const createFocusController = (): FocusController => {
const saveViewFocus = (referenceEl?: HTMLElement) => {
const focusManagerEnabled = config.get('focusManagerPriority', false);
/**
* When going back to a previously visited page focus should typically be moved
* back to the element that was last focused when the user was on this view.
*/
if (focusManagerEnabled) {
const activeEl = document.activeElement;
if (activeEl !== null && referenceEl?.contains(activeEl)) {
activeEl.setAttribute(LAST_FOCUS, 'true');
}
}
};
const setViewFocus = (referenceEl: HTMLElement) => {
const focusManagerPriorities = config.get('focusManagerPriority', false);
/**
* If the focused element is a descendant of the referenceEl then it's possible
* that the app developer manually moved focus, so we do not want to override that.
* This can happen with inputs the are focused when a view transitions in.
*/
if (Array.isArray(focusManagerPriorities) && !referenceEl.contains(document.activeElement)) {
/**
* When going back to a previously visited view focus should always be moved back
* to the element that the user was last focused on when they were on this view.
*/
const lastFocus = referenceEl.querySelector<HTMLElement>(`[${LAST_FOCUS}]`);
if (lastFocus && isVisible(lastFocus)) {
moveFocus(lastFocus);
return;
}
for (const priority of focusManagerPriorities) {
/**
* For each recognized case (excluding the default case) make sure to return
* so that the fallback focus behavior does not run.
*
* We intentionally query for specific roles/semantic elements so that the
* transition manager can work with both Ionic and non-Ionic UI components.
*
* If new selectors are added, be sure to remove the outline ring by adding
* new selectors to rule in core.scss.
*/
switch (priority) {
case 'content':
const content = referenceEl.querySelector<HTMLElement>('main, [role="main"]');
if (content && isVisible(content)) {
moveFocus(content);
return;
}
break;
case 'heading':
const headingOne = referenceEl.querySelector<HTMLElement>('h1, [role="heading"][aria-level="1"]');
if (headingOne && isVisible(headingOne)) {
moveFocus(headingOne);
return;
}
break;
case 'banner':
const header = referenceEl.querySelector<HTMLElement>('header, [role="banner"]');
if (header && isVisible(header)) {
moveFocus(header);
return;
}
break;
default:
printIonWarning(`Unrecognized focus manager priority value ${priority}`);
break;
}
}
/**
* If there is nothing to focus then focus the page so focus at least moves to
* the correct view. The browser will then determine where within the page to
* move focus to.
*/
moveFocus(referenceEl);
}
};
return {
saveViewFocus,
setViewFocus,
};
};
export type FocusController = {
saveViewFocus: (referenceEl?: HTMLElement) => void;
setViewFocus: (referenceEl: HTMLElement) => void;
};
const LAST_FOCUS = 'ion-last-focus';