Skip to content

Commit 1300c13

Browse files
feat(cdk/focus-trap) Add ConfigurableFocusTrap classes
ConfigurableFocusTrap is part of a new FocusTrap design that will trap more than just tab focus. This commit sets up the classes for the new design, and implements the primary strategy for preventing focus outside the trap (an event listener that refocuses the trap). Logic to trap screen reader focus and wrap tab without the hidden tab stops will be in future commits. Migration of cdkTrapFocus, MatDialog, etc. will also be in future commits. This commit does not enable ConfigurableFocusTrap anywhere.
1 parent 3e2e023 commit 1300c13

11 files changed

+572
-6
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
export class ConfigurableFocusTrapConfig<D = any> {
10+
defer: boolean = false;
11+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import {DOCUMENT} from '@angular/common';
10+
import {
11+
Inject,
12+
Injectable,
13+
Optional,
14+
NgZone,
15+
} from '@angular/core';
16+
import {InteractivityChecker} from '../interactivity-checker/interactivity-checker';
17+
import {ConfigurableFocusTrap} from './configurable-focus-trap';
18+
import {ConfigurableFocusTrapConfig} from './configurable-focus-trap-config';
19+
import {FOCUS_TRAP_INERT_STRATEGY, FocusTrapInertStrategy} from './focus-trap-inert-strategy';
20+
import {EventListenerFocusTrapInertStrategy} from './event-listener-inert-strategy';
21+
import {FocusTrapManager} from './focus-trap-manager';
22+
23+
/** Factory that allows easy instantiation of configurable focus traps. */
24+
@Injectable({providedIn: 'root'})
25+
export class ConfigurableFocusTrapFactory {
26+
private _document: Document;
27+
private _inertStrategy: FocusTrapInertStrategy;
28+
29+
constructor(
30+
private _checker: InteractivityChecker,
31+
private _ngZone: NgZone,
32+
private _focusTrapManager: FocusTrapManager,
33+
@Inject(DOCUMENT) _document: any,
34+
@Optional() @Inject(FOCUS_TRAP_INERT_STRATEGY) _inertStrategy?: FocusTrapInertStrategy) {
35+
36+
this._document = _document;
37+
this._inertStrategy = _inertStrategy || new EventListenerFocusTrapInertStrategy();
38+
}
39+
40+
/**
41+
* Creates a focus-trapped region around the given element.
42+
* @param element The element around which focus will be trapped.
43+
* @param deferCaptureElements Defers the creation of focus-capturing elements to be done
44+
* manually by the user.
45+
* @returns The created focus trap instance.
46+
*/
47+
create(element: HTMLElement, config: ConfigurableFocusTrapConfig =
48+
new ConfigurableFocusTrapConfig()): ConfigurableFocusTrap {
49+
return new ConfigurableFocusTrap(
50+
element, this._checker, this._ngZone, this._document, this._focusTrapManager,
51+
this._inertStrategy, config);
52+
}
53+
}
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
2+
import {async, ComponentFixture, fakeAsync, flush, TestBed} from '@angular/core/testing';
3+
import {A11yModule, ConfigurableFocusTrapFactory, ConfigurableFocusTrap} from '../index';
4+
5+
6+
describe('ConfigurableFocusTrap', () => {
7+
8+
beforeEach(async(() => {
9+
TestBed.configureTestingModule({
10+
imports: [A11yModule],
11+
declarations: [
12+
NestedFocusTraps,
13+
SimpleFocusTrap,
14+
],
15+
});
16+
17+
TestBed.compileComponents();
18+
}));
19+
20+
describe('with EventListenerFocusTrapInertStrategy', () => {
21+
22+
it('refocuses the first FocusTrap element when focus moves outside the FocusTrap',
23+
fakeAsync(() => {
24+
const fixture = TestBed.createComponent(SimpleFocusTrap);
25+
const componentInstance = fixture.componentInstance;
26+
fixture.detectChanges();
27+
28+
expect(document.activeElement).toBe(document.body, 'Expected body to be focused');
29+
30+
componentInstance.focusTrap.focusFirstTabbableElementWhenReady();
31+
32+
expect(document.activeElement).toBe(
33+
componentInstance.firstFocusableElement.nativeElement,
34+
'Expected first focusable element to be focused');
35+
36+
componentInstance.outsideFocusableElement.nativeElement.focus();
37+
flush();
38+
39+
expect(document.activeElement).toBe(
40+
componentInstance.firstFocusableElement.nativeElement,
41+
'Expected first focusable element to be focused');
42+
}));
43+
44+
it('does not intercept focus when focus moves to another element in the FocusTrap',
45+
fakeAsync(() => {
46+
const fixture = TestBed.createComponent(SimpleFocusTrap);
47+
const componentInstance = fixture.componentInstance;
48+
fixture.detectChanges();
49+
50+
expect(document.activeElement).toBe(document.body, 'Expected body to be focused');
51+
52+
componentInstance.focusTrap.focusFirstTabbableElementWhenReady();
53+
54+
expect(document.activeElement).toBe(
55+
componentInstance.firstFocusableElement.nativeElement,
56+
'Expected first focusable element to be focused');
57+
58+
componentInstance.secondFocusableElement.nativeElement.focus();
59+
flush();
60+
61+
expect(document.activeElement).toBe(
62+
componentInstance.secondFocusableElement.nativeElement,
63+
'Expected second focusable element to be focused');
64+
}));
65+
});
66+
67+
describe('with nested FocusTraps', () => {
68+
it('traps focus in the most recently enabled FocusTrap',
69+
fakeAsync(() => {
70+
const fixture = TestBed.createComponent(NestedFocusTraps);
71+
const componentInstance = fixture.componentInstance;
72+
fixture.detectChanges();
73+
74+
componentInstance.outerFocusTrap.enabled = true;
75+
componentInstance.innerFocusTrap.enabled = true;
76+
77+
componentInstance.outsideFocusableElement.nativeElement.focus();
78+
flush();
79+
expect(document.activeElement).toBe(
80+
componentInstance.firstFocusableInnerElement.nativeElement,
81+
'Expected first focusable inner element to be focused');
82+
83+
componentInstance.firstFocusableOuterElement.nativeElement.focus();
84+
flush();
85+
86+
expect(document.activeElement).toBe(
87+
componentInstance.firstFocusableInnerElement.nativeElement,
88+
'Expected first focusable inner element to be focused');
89+
}));
90+
91+
it(`traps focus in the second most recently enabled FocusTrap when
92+
the active FocusTrap is disabled`, fakeAsync(() => {
93+
const fixture = TestBed.createComponent(NestedFocusTraps);
94+
const componentInstance = fixture.componentInstance;
95+
fixture.detectChanges();
96+
97+
componentInstance.outerFocusTrap.enabled = true;
98+
componentInstance.innerFocusTrap.enabled = true;
99+
componentInstance.innerFocusTrap.enabled = false;
100+
101+
componentInstance.outsideFocusableElement.nativeElement.focus();
102+
flush();
103+
expect(document.activeElement).toBe(
104+
componentInstance.firstFocusableOuterElement.nativeElement,
105+
'Expected first focusable outer element to be focused');
106+
107+
componentInstance.secondFocusableInnerElement.nativeElement.focus();
108+
flush();
109+
110+
expect(document.activeElement).toBe(
111+
componentInstance.secondFocusableInnerElement.nativeElement,
112+
'Expected second focusable inner element to be focused');
113+
}));
114+
115+
it('stops trapping focus when all FocusTraps are disabled',
116+
fakeAsync(() => {
117+
const fixture = TestBed.createComponent(NestedFocusTraps);
118+
const componentInstance = fixture.componentInstance;
119+
fixture.detectChanges();
120+
121+
componentInstance.outerFocusTrap.enabled = true;
122+
componentInstance.innerFocusTrap.enabled = true;
123+
componentInstance.outerFocusTrap.enabled = false;
124+
componentInstance.innerFocusTrap.enabled = false;
125+
126+
componentInstance.outsideFocusableElement.nativeElement.focus();
127+
flush();
128+
expect(document.activeElement).toBe(
129+
componentInstance.outsideFocusableElement.nativeElement,
130+
'Expected outside element to be focused');
131+
}));
132+
});
133+
});
134+
135+
136+
@Component({
137+
template: `
138+
<textarea #outsideFocusable></textarea>
139+
<div #focusTrapElement>
140+
<input #firstFocusable>
141+
<button #secondFocusable>SAVE</button>
142+
</div>
143+
`
144+
})
145+
class SimpleFocusTrap implements AfterViewInit {
146+
@ViewChild('focusTrapElement') focusTrapElement!: ElementRef;
147+
@ViewChild('outsideFocusable') outsideFocusableElement!: ElementRef;
148+
@ViewChild('firstFocusable') firstFocusableElement!: ElementRef;
149+
@ViewChild('secondFocusable') secondFocusableElement!: ElementRef;
150+
151+
focusTrap: ConfigurableFocusTrap;
152+
153+
constructor(private _focusTrapFactory: ConfigurableFocusTrapFactory) {
154+
}
155+
156+
ngAfterViewInit() {
157+
this.focusTrap = this._focusTrapFactory.create(this.focusTrapElement.nativeElement);
158+
}
159+
}
160+
161+
@Component({
162+
template: `
163+
<a #outsideFocusable href="www.google.com">link</a>
164+
<div #outerFocusTrapElement>
165+
<textarea #firstFocusableOuter></textarea>
166+
<div #innerFocusTrapElement>
167+
<input #firstFocusableInner>
168+
<button #secondFocusableInner>SAVE</button>
169+
</div>
170+
</div>
171+
`
172+
})
173+
class NestedFocusTraps implements AfterViewInit {
174+
@ViewChild('outerFocusTrapElement') outerFocusTrapElement!: ElementRef;
175+
@ViewChild('innerFocusTrapElement') innerFocusTrapElement!: ElementRef;
176+
@ViewChild('outsideFocusable') outsideFocusableElement!: ElementRef;
177+
@ViewChild('firstFocusableOuter') firstFocusableOuterElement!: ElementRef;
178+
@ViewChild('firstFocusableInner') firstFocusableInnerElement!: ElementRef;
179+
@ViewChild('secondFocusableInner') secondFocusableInnerElement!: ElementRef;
180+
181+
outerFocusTrap: ConfigurableFocusTrap;
182+
innerFocusTrap: ConfigurableFocusTrap;
183+
184+
constructor(private _focusTrapFactory: ConfigurableFocusTrapFactory) {
185+
}
186+
187+
ngAfterViewInit() {
188+
this.outerFocusTrap = this._focusTrapFactory.create(this.outerFocusTrapElement.nativeElement);
189+
this.outerFocusTrap.enabled = false;
190+
this.innerFocusTrap = this._focusTrapFactory.create(this.innerFocusTrapElement.nativeElement);
191+
this.innerFocusTrap.enabled = false;
192+
}
193+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import {NgZone} from '@angular/core';
10+
import {InteractivityChecker} from '../interactivity-checker/interactivity-checker';
11+
import {FocusTrap} from './focus-trap';
12+
import {FocusTrapManager, ManagedFocusTrap} from './focus-trap-manager';
13+
import {FocusTrapInertStrategy} from './focus-trap-inert-strategy';
14+
import {ConfigurableFocusTrapConfig} from './configurable-focus-trap-config';
15+
16+
/**
17+
* Class that allows for trapping focus within a DOM element.
18+
*
19+
* This class uses a strategy pattern that determines how it traps focus.
20+
* See FocusTrapInertStrategy.
21+
*/
22+
export class ConfigurableFocusTrap extends FocusTrap implements ManagedFocusTrap {
23+
/** Whether the FocusTrap is enabled. */
24+
get enabled(): boolean { return this._enabled; }
25+
set enabled(value: boolean) {
26+
this._enabled = value;
27+
if (this._enabled) {
28+
this._focusTrapManager.register(this);
29+
} else {
30+
this._focusTrapManager.deregister(this);
31+
}
32+
}
33+
34+
constructor(
35+
_element: HTMLElement,
36+
_checker: InteractivityChecker,
37+
_ngZone: NgZone,
38+
_document: Document,
39+
private _focusTrapManager: FocusTrapManager,
40+
private _inertStrategy: FocusTrapInertStrategy,
41+
config: ConfigurableFocusTrapConfig) {
42+
super(_element, _checker, _ngZone, _document, config.defer);
43+
this._focusTrapManager.register(this);
44+
}
45+
46+
/** Notifies the FocusTrapManager that this FocusTrap will be destroyed. */
47+
destroy() {
48+
this._focusTrapManager.deregister(this);
49+
super.destroy();
50+
}
51+
52+
/** @docs-private Implemented as part of ManagedFocusTrap. */
53+
_enable() {
54+
this._inertStrategy.preventFocus(this);
55+
this.toggleAnchors(true);
56+
}
57+
58+
/** @docs-private Implemented as part of ManagedFocusTrap. */
59+
_disable() {
60+
this._inertStrategy.allowFocus(this);
61+
this.toggleAnchors(false);
62+
}
63+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import {FocusTrapInertStrategy} from './focus-trap-inert-strategy';
10+
import {ConfigurableFocusTrap} from './configurable-focus-trap';
11+
import {closest} from './polyfill';
12+
13+
/**
14+
* Lightweight FocusTrapInertStrategy that adds a document focus event
15+
* listener to redirect focus back inside the FocusTrap.
16+
*/
17+
export class EventListenerFocusTrapInertStrategy implements FocusTrapInertStrategy {
18+
/** Focus event handler. */
19+
private _listener: ((e: FocusEvent) => void) | null = null;
20+
21+
/** Adds a document event listener that keeps focus inside the FocusTrap. */
22+
preventFocus(focusTrap: ConfigurableFocusTrap): void {
23+
// Ensure there's only one listener per document
24+
if (this._listener) {
25+
focusTrap._document.removeEventListener('focus', this._listener!, true);
26+
}
27+
28+
this._listener = (e: FocusEvent) => this._trapFocus(focusTrap, e);
29+
focusTrap._ngZone.runOutsideAngular(() => {
30+
focusTrap._document.addEventListener('focus', this._listener!, true);
31+
});
32+
}
33+
34+
/** Removes the event listener added in preventFocus. */
35+
allowFocus(focusTrap: ConfigurableFocusTrap): void {
36+
if (!this._listener) {
37+
return;
38+
}
39+
focusTrap._document.removeEventListener('focus', this._listener!, true);
40+
this._listener = null;
41+
}
42+
43+
/**
44+
* Refocuses the first element in the FocusTrap if the focus event target was outside
45+
* the FocusTrap.
46+
*/
47+
private _trapFocus(focusTrap: ConfigurableFocusTrap, event: FocusEvent) {
48+
const target = event.target as HTMLElement;
49+
// Don't refocus if target was in an overlay, because the overlay might be associated
50+
// with an element inside the FocusTrap, ex. mat-select.
51+
if (!focusTrap._element.contains(target) &&
52+
closest(target, 'div.cdk-overlay-pane') === null) {
53+
// Some legacy FocusTrap usages have logic that focuses some element on the page
54+
// just before FocusTrap is destroyed. For backwards compatibility, wait
55+
// to be sure FocusTrap is still enabled before refocusing.
56+
setTimeout(() => {
57+
if (focusTrap.enabled) {
58+
focusTrap.focusFirstTabbableElement();
59+
}
60+
});
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)