Skip to content

Commit 0a5d097

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 0a5d097

File tree

9 files changed

+532
-6
lines changed

9 files changed

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

0 commit comments

Comments
 (0)