Skip to content

Commit 6b0bea0

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.
1 parent 3e2e023 commit 6b0bea0

10 files changed

+619
-109
lines changed

src/cdk/a11y/a11y-module.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {PlatformModule} from '@angular/cdk/platform';
1111
import {CommonModule} from '@angular/common';
1212
import {NgModule} from '@angular/core';
1313
import {CdkMonitorFocus} from './focus-monitor/focus-monitor';
14-
import {CdkTrapFocus} from './focus-trap/focus-trap';
14+
import {CdkTrapFocus} from './focus-trap/cdk-trap-focus';
1515
import {HighContrastModeDetector} from './high-contrast-mode/high-contrast-mode-detector';
1616
import {CdkAriaLive} from './live-announcer/live-announcer';
1717

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
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 {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion';
10+
import {DOCUMENT} from '@angular/common';
11+
import {
12+
AfterContentInit,
13+
Directive,
14+
ElementRef,
15+
Inject,
16+
Input,
17+
OnDestroy,
18+
DoCheck,
19+
} from '@angular/core';
20+
import {FocusTrap} from './focus-trap';
21+
import {FocusTrapFactory} from './focus-trap-factory';
22+
23+
/** Directive for trapping focus within a region. */
24+
@Directive({
25+
selector: '[cdkTrapFocus]',
26+
exportAs: 'cdkTrapFocus',
27+
})
28+
export class CdkTrapFocus implements OnDestroy, AfterContentInit, DoCheck {
29+
private _document: Document;
30+
31+
/** Underlying FocusTrap instance. */
32+
focusTrap: FocusTrap;
33+
34+
/** Previously focused element to restore focus to upon destroy when using autoCapture. */
35+
private _previouslyFocusedElement: HTMLElement | null = null;
36+
37+
/** Whether the focus trap is active. */
38+
@Input('cdkTrapFocus')
39+
get enabled(): boolean { return this.focusTrap.enabled; }
40+
set enabled(value: boolean) { this.focusTrap.enabled = coerceBooleanProperty(value); }
41+
42+
/**
43+
* Whether the directive should automatially move focus into the trapped region upon
44+
* initialization and return focus to the previous activeElement upon destruction.
45+
*/
46+
@Input('cdkTrapFocusAutoCapture')
47+
get autoCapture(): boolean { return this._autoCapture; }
48+
set autoCapture(value: boolean) { this._autoCapture = coerceBooleanProperty(value); }
49+
private _autoCapture: boolean;
50+
51+
constructor(
52+
private _elementRef: ElementRef<HTMLElement>,
53+
private _focusTrapFactory: FocusTrapFactory,
54+
@Inject(DOCUMENT) _document: any) {
55+
56+
this._document = _document;
57+
this.focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement, true);
58+
}
59+
60+
ngOnDestroy() {
61+
this.focusTrap.destroy();
62+
63+
// If we stored a previously focused element when using autoCapture, return focus to that
64+
// element now that the trapped region is being destroyed.
65+
if (this._previouslyFocusedElement) {
66+
this._previouslyFocusedElement.focus();
67+
this._previouslyFocusedElement = null;
68+
}
69+
}
70+
71+
ngAfterContentInit() {
72+
this.focusTrap.attachAnchors();
73+
74+
if (this.autoCapture) {
75+
this._previouslyFocusedElement = this._document.activeElement as HTMLElement;
76+
this.focusTrap.focusInitialElementWhenReady();
77+
}
78+
}
79+
80+
ngDoCheck() {
81+
if (!this.focusTrap.hasAttached()) {
82+
this.focusTrap.attachAnchors();
83+
}
84+
}
85+
86+
static ngAcceptInputType_enabled: BooleanInput;
87+
static ngAcceptInputType_autoCapture: BooleanInput;
88+
}
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+
}

0 commit comments

Comments
 (0)