Skip to content

Commit d9dd65c

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 d9dd65c

13 files changed

+638
-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: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
// TODO split up the strategies into different modules, similar to DateAdapter.
38+
this._inertStrategy = _inertStrategy || new EventListenerFocusTrapInertStrategy();
39+
}
40+
41+
/**
42+
* Creates a focus-trapped region around the given element.
43+
* @param element The element around which focus will be trapped.
44+
* @param deferCaptureElements Defers the creation of focus-capturing elements to be done
45+
* manually by the user.
46+
* @returns The created focus trap instance.
47+
*/
48+
create(element: HTMLElement, config: ConfigurableFocusTrapConfig =
49+
new ConfigurableFocusTrapConfig()): ConfigurableFocusTrap {
50+
return new ConfigurableFocusTrap(
51+
element, this._checker, this._ngZone, this._document, this._focusTrapManager,
52+
this._inertStrategy, config);
53+
}
54+
}
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import {AfterViewInit, Component, ElementRef, Type, ViewChild} from '@angular/core';
2+
import {ComponentFixture, TestBed} from '@angular/core/testing';
3+
import {
4+
A11yModule,
5+
ConfigurableFocusTrap,
6+
ConfigurableFocusTrapFactory,
7+
FOCUS_TRAP_INERT_STRATEGY,
8+
FocusTrap,
9+
FocusTrapInertStrategy
10+
} from '../index';
11+
import {FocusTrapManager} from './focus-trap-manager';
12+
13+
describe('ConfigurableFocusTrap', () => {
14+
let providers: Array<Object>;
15+
16+
describe('with FocusTrapInertStrategy', () => {
17+
let mockInertStrategy: FocusTrapInertStrategy;
18+
19+
beforeEach(() => {
20+
mockInertStrategy = new MockFocusTrapInertStrategy();
21+
providers = [{provide: FOCUS_TRAP_INERT_STRATEGY, useValue: mockInertStrategy}];
22+
});
23+
24+
it('Calls preventFocus when it is created', () => {
25+
spyOn(mockInertStrategy, 'preventFocus');
26+
spyOn(mockInertStrategy, 'allowFocus');
27+
28+
const fixture = createComponent(SimpleFocusTrap, providers);
29+
fixture.detectChanges();
30+
31+
expect(mockInertStrategy.preventFocus).toHaveBeenCalledTimes(1);
32+
expect(mockInertStrategy.allowFocus).not.toHaveBeenCalled();
33+
});
34+
35+
it('Calls preventFocus when it is enabled', () => {
36+
spyOn(mockInertStrategy, 'preventFocus');
37+
38+
const fixture = createComponent(SimpleFocusTrap, providers);
39+
const componentInstance = fixture.componentInstance;
40+
fixture.detectChanges();
41+
42+
componentInstance.focusTrap.enabled = true;
43+
44+
expect(mockInertStrategy.preventFocus).toHaveBeenCalledTimes(2);
45+
});
46+
47+
it('Calls allowFocus when it is disabled', () => {
48+
spyOn(mockInertStrategy, 'allowFocus');
49+
50+
const fixture = createComponent(SimpleFocusTrap, providers);
51+
const componentInstance = fixture.componentInstance;
52+
fixture.detectChanges();
53+
54+
componentInstance.focusTrap.enabled = false;
55+
56+
expect(mockInertStrategy.allowFocus).toHaveBeenCalledTimes(1);
57+
});
58+
});
59+
60+
describe('with FocusTrapManager', () => {
61+
let manager: FocusTrapManager;
62+
63+
beforeEach(() => {
64+
manager = new FocusTrapManager();
65+
providers = [{provide: FocusTrapManager, useValue: manager}];
66+
});
67+
68+
it('Registers when it is created', () => {
69+
spyOn(manager, 'register');
70+
71+
const fixture = createComponent(SimpleFocusTrap, providers);
72+
fixture.detectChanges();
73+
74+
expect(manager.register).toHaveBeenCalledTimes(1);
75+
});
76+
77+
it('Deregisters when it is disabled', () => {
78+
spyOn(manager, 'deregister');
79+
80+
const fixture = createComponent(SimpleFocusTrap, providers);
81+
const componentInstance = fixture.componentInstance;
82+
fixture.detectChanges();
83+
84+
componentInstance.focusTrap.enabled = false;
85+
86+
expect(manager.deregister).toHaveBeenCalledTimes(1);
87+
});
88+
});
89+
});
90+
91+
function createComponent<T>(componentType: Type<T>, providers: Array<Object> = []
92+
): ComponentFixture<T> {
93+
TestBed.configureTestingModule({
94+
imports: [A11yModule],
95+
declarations: [componentType],
96+
providers: providers
97+
}).compileComponents();
98+
99+
return TestBed.createComponent<T>(componentType);
100+
}
101+
102+
@Component({
103+
template: `
104+
<div #focusTrapElement>
105+
<input>
106+
<button>SAVE</button>
107+
</div>
108+
`
109+
})
110+
class SimpleFocusTrap implements AfterViewInit {
111+
@ViewChild('focusTrapElement') focusTrapElement!: ElementRef;
112+
113+
focusTrap: ConfigurableFocusTrap;
114+
115+
constructor(private _focusTrapFactory: ConfigurableFocusTrapFactory) {
116+
}
117+
118+
ngAfterViewInit() {
119+
this.focusTrap = this._focusTrapFactory.create(this.focusTrapElement.nativeElement);
120+
}
121+
}
122+
123+
class MockFocusTrapInertStrategy implements FocusTrapInertStrategy {
124+
preventFocus(focusTrap: FocusTrap) {}
125+
126+
allowFocus(focusTrap: FocusTrap) {}
127+
}
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: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import {AfterViewInit, Component, ElementRef, Type, ViewChild} from '@angular/core';
2+
import {ComponentFixture, fakeAsync, flush, TestBed} from '@angular/core/testing';
3+
import {
4+
A11yModule,
5+
ConfigurableFocusTrapFactory,
6+
ConfigurableFocusTrap,
7+
EventListenerFocusTrapInertStrategy,
8+
FOCUS_TRAP_INERT_STRATEGY,
9+
} from '../index';
10+
11+
12+
describe('EventListenerFocusTrapInertStrategy', () => {
13+
const providers = [
14+
{provide: FOCUS_TRAP_INERT_STRATEGY, useValue: new EventListenerFocusTrapInertStrategy()}];
15+
16+
it('refocuses the first FocusTrap element when focus moves outside the FocusTrap',
17+
fakeAsync(() => {
18+
const fixture = createComponent(SimpleFocusTrap, providers);
19+
const componentInstance = fixture.componentInstance;
20+
fixture.detectChanges();
21+
22+
componentInstance.outsideFocusableElement.nativeElement.focus();
23+
flush();
24+
25+
expect(document.activeElement).toBe(
26+
componentInstance.firstFocusableElement.nativeElement,
27+
'Expected first focusable element to be focused');
28+
}));
29+
30+
it('does not intercept focus when focus moves to another element in the FocusTrap',
31+
fakeAsync(() => {
32+
const fixture = createComponent(SimpleFocusTrap, providers);
33+
const componentInstance = fixture.componentInstance;
34+
fixture.detectChanges();
35+
36+
componentInstance.secondFocusableElement.nativeElement.focus();
37+
flush();
38+
39+
expect(document.activeElement).toBe(
40+
componentInstance.secondFocusableElement.nativeElement,
41+
'Expected second focusable element to be focused');
42+
}));
43+
});
44+
45+
function createComponent<T>(componentType: Type<T>, providers: Array<Object> = []
46+
): ComponentFixture<T> {
47+
TestBed.configureTestingModule({
48+
imports: [A11yModule],
49+
declarations: [componentType],
50+
providers: providers
51+
}).compileComponents();
52+
53+
return TestBed.createComponent<T>(componentType);
54+
}
55+
56+
@Component({
57+
template: `
58+
<textarea #outsideFocusable></textarea>
59+
<div #focusTrapElement>
60+
<input #firstFocusable>
61+
<button #secondFocusable>SAVE</button>
62+
</div>
63+
`
64+
})
65+
class SimpleFocusTrap implements AfterViewInit {
66+
@ViewChild('focusTrapElement') focusTrapElement!: ElementRef;
67+
@ViewChild('outsideFocusable') outsideFocusableElement!: ElementRef;
68+
@ViewChild('firstFocusable') firstFocusableElement!: ElementRef;
69+
@ViewChild('secondFocusable') secondFocusableElement!: ElementRef;
70+
71+
focusTrap: ConfigurableFocusTrap;
72+
73+
constructor(private _focusTrapFactory: ConfigurableFocusTrapFactory) {
74+
}
75+
76+
ngAfterViewInit() {
77+
this.focusTrap = this._focusTrapFactory.create(this.focusTrapElement.nativeElement);
78+
this.focusTrap.focusFirstTabbableElementWhenReady();
79+
}
80+
}

0 commit comments

Comments
 (0)