Skip to content

fix(a11y): not being able to escape disabled focus trap using arrow keys #13133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/cdk/a11y/focus-trap/focus-trap.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ describe('FocusTrap', () => {
fixture.componentInstance._isFocusTrapEnabled = false;
fixture.detectChanges();

expect(anchors.every(current => current.getAttribute('tabindex') === '-1')).toBe(true);
expect(anchors.every(current => !current.hasAttribute('tabindex'))).toBe(true);
});
});

Expand Down
20 changes: 16 additions & 4 deletions src/cdk/a11y/focus-trap/focus-trap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,12 @@ export class FocusTrap {

/** Whether the focus trap is active. */
get enabled(): boolean { return this._enabled; }
set enabled(val: boolean) {
this._enabled = val;
set enabled(value: boolean) {
this._enabled = value;

if (this._startAnchor && this._endAnchor) {
this._startAnchor.tabIndex = this._endAnchor.tabIndex = this._enabled ? 0 : -1;
this._toggleAnchorTabIndex(value, this._startAnchor);
this._toggleAnchorTabIndex(value, this._endAnchor);
}
}
private _enabled: boolean = true;
Expand Down Expand Up @@ -278,12 +279,23 @@ export class FocusTrap {
/** Creates an anchor element. */
private _createAnchor(): HTMLElement {
const anchor = this._document.createElement('div');
anchor.tabIndex = this._enabled ? 0 : -1;
this._toggleAnchorTabIndex(this._enabled, anchor);
anchor.classList.add('cdk-visually-hidden');
anchor.classList.add('cdk-focus-trap-anchor');
return anchor;
}

/**
* Toggles the `tabindex` of an anchor, based on the enabled state of the focus trap.
* @param isEnabled Whether the focus trap is enabled.
* @param anchor Anchor on which to toggle the tabindex.
*/
private _toggleAnchorTabIndex(isEnabled: boolean, anchor: HTMLElement) {
// Remove the tabindex completely, rather than setting it to -1, because if the
// element has a tabindex, the user might still hit it when navigating with the arrow keys.
isEnabled ? anchor.setAttribute('tabindex', '0') : anchor.removeAttribute('tabindex');
}

/** Executes a function when the zone is stable. */
private _executeOnStable(fn: () => any): void {
if (this._ngZone.isStable) {
Expand Down