-
Notifications
You must be signed in to change notification settings - Fork 6.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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.
- Loading branch information
1 parent
3e2e023
commit e81545f
Showing
9 changed files
with
528 additions
and
6 deletions.
There are no files selected for viewing
52 changes: 52 additions & 0 deletions
52
src/cdk/a11y/focus-trap/configurable-focus-trap-factory.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
/** | ||
* @license | ||
* Copyright Google LLC All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.io/license | ||
*/ | ||
|
||
import {DOCUMENT} from '@angular/common'; | ||
import { | ||
Inject, | ||
Injectable, | ||
Optional, | ||
NgZone, | ||
} from '@angular/core'; | ||
import {InteractivityChecker} from '../interactivity-checker/interactivity-checker'; | ||
import {ConfigurableFocusTrap} from './configurable-focus-trap'; | ||
import {FOCUS_TRAP_INERT_STRATEGY, FocusTrapInertStrategy} from './focus-trap-inert-strategy'; | ||
import {EventListenerFocusTrapInertStrategy} from './event-listener-inert-strategy'; | ||
import {FocusTrapManager} from './focus-trap-manager'; | ||
|
||
/** Factory that allows easy instantiation of configurable focus traps. */ | ||
@Injectable({providedIn: 'root'}) | ||
export class ConfigurableFocusTrapFactory { | ||
private _document: Document; | ||
private _inertStrategy: FocusTrapInertStrategy; | ||
|
||
constructor( | ||
private _checker: InteractivityChecker, | ||
private _ngZone: NgZone, | ||
private _focusTrapManager: FocusTrapManager, | ||
@Inject(DOCUMENT) _document: any, | ||
@Optional() @Inject(FOCUS_TRAP_INERT_STRATEGY) _inertStrategy?: FocusTrapInertStrategy) { | ||
|
||
this._document = _document; | ||
this._inertStrategy = (_inertStrategy ? _inertStrategy : | ||
new EventListenerFocusTrapInertStrategy()); | ||
} | ||
|
||
/** | ||
* Creates a focus-trapped region around the given element. | ||
* @param element The element around which focus will be trapped. | ||
* @param deferCaptureElements Defers the creation of focus-capturing elements to be done | ||
* manually by the user. | ||
* @returns The created focus trap instance. | ||
*/ | ||
create(element: HTMLElement, deferCaptureElements: boolean = false): ConfigurableFocusTrap { | ||
return new ConfigurableFocusTrap( | ||
element, this._checker, this._ngZone, this._document, this._focusTrapManager, | ||
this._inertStrategy, deferCaptureElements); | ||
} | ||
} |
196 changes: 196 additions & 0 deletions
196
src/cdk/a11y/focus-trap/configurable-focus-trap.spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,196 @@ | ||
import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core'; | ||
import {async, ComponentFixture, fakeAsync, flush, TestBed} from '@angular/core/testing'; | ||
import {A11yModule, ConfigurableFocusTrapFactory, ConfigurableFocusTrap} from '../index'; | ||
|
||
|
||
describe('ConfigurableFocusTrap', () => { | ||
|
||
beforeEach(async(() => { | ||
TestBed.configureTestingModule({ | ||
imports: [A11yModule], | ||
declarations: [ | ||
NestedFocusTraps, | ||
SimpleFocusTrap, | ||
], | ||
}); | ||
|
||
TestBed.compileComponents(); | ||
})); | ||
|
||
describe('with EventListenerFocusTrapInertStrategy', () => { | ||
let fixture: ComponentFixture<SimpleFocusTrap>; | ||
let componentInstance: SimpleFocusTrap; | ||
let focusTrapInstance: ConfigurableFocusTrap; | ||
|
||
beforeEach(() => { | ||
fixture = TestBed.createComponent(SimpleFocusTrap); | ||
fixture.detectChanges(); | ||
componentInstance = fixture.componentInstance; | ||
focusTrapInstance = componentInstance.focusTrap; | ||
}); | ||
|
||
it('refocuses the first FocusTrap element when focus moves outside the FocusTrap', | ||
fakeAsync(() => { | ||
expect(document.activeElement).toBe(document.body, 'Expected body to be focused'); | ||
|
||
focusTrapInstance.focusFirstTabbableElementWhenReady(); | ||
|
||
expect(document.activeElement).toBe( | ||
componentInstance.firstFocusableElement.nativeElement, | ||
'Expected first focusable element to be focused'); | ||
|
||
componentInstance.outsideFocusableElement.nativeElement.focus(); | ||
flush(); | ||
|
||
expect(document.activeElement).toBe( | ||
componentInstance.firstFocusableElement.nativeElement, | ||
'Expected first focusable element to be focused'); | ||
})); | ||
|
||
it('does not intercept focus when focus moves to another element in the FocusTrap', | ||
fakeAsync(() => { | ||
expect(document.activeElement).toBe(document.body, 'Expected body to be focused'); | ||
|
||
focusTrapInstance.focusFirstTabbableElementWhenReady(); | ||
|
||
expect(document.activeElement).toBe( | ||
componentInstance.firstFocusableElement.nativeElement, | ||
'Expected first focusable element to be focused'); | ||
|
||
componentInstance.secondFocusableElement.nativeElement.focus(); | ||
flush(); | ||
|
||
expect(document.activeElement).toBe( | ||
componentInstance.secondFocusableElement.nativeElement, | ||
'Expected second focusable element to be focused'); | ||
})); | ||
}); | ||
|
||
describe('with nested FocusTraps', () => { | ||
let fixture: ComponentFixture<NestedFocusTraps>; | ||
let componentInstance: NestedFocusTraps; | ||
let outerFocusTrapInstance: ConfigurableFocusTrap; | ||
let innerFocusTrapInstance: ConfigurableFocusTrap; | ||
|
||
beforeEach(() => { | ||
fixture = TestBed.createComponent(NestedFocusTraps); | ||
fixture.detectChanges(); | ||
componentInstance = fixture.componentInstance; | ||
outerFocusTrapInstance = componentInstance.outerFocusTrap; | ||
innerFocusTrapInstance = componentInstance.innerFocusTrap; | ||
}); | ||
|
||
it('traps focus in the most recently enabled FocusTrap', | ||
fakeAsync(() => { | ||
outerFocusTrapInstance.enabled = true; | ||
innerFocusTrapInstance.enabled = true; | ||
|
||
componentInstance.outsideFocusableElement.nativeElement.focus(); | ||
flush(); | ||
expect(document.activeElement).toBe( | ||
componentInstance.firstFocusableInnerElement.nativeElement, | ||
'Expected first focusable inner element to be focused'); | ||
|
||
componentInstance.firstFocusableOuterElement.nativeElement.focus(); | ||
flush(); | ||
|
||
expect(document.activeElement).toBe( | ||
componentInstance.firstFocusableInnerElement.nativeElement, | ||
'Expected first focusable inner element to be focused'); | ||
})); | ||
|
||
it(`traps focus in the second most recently enabled FocusTrap when | ||
the active FocusTrap is disabled`, fakeAsync(() => { | ||
outerFocusTrapInstance.enabled = true; | ||
innerFocusTrapInstance.enabled = true; | ||
innerFocusTrapInstance.enabled = false; | ||
|
||
componentInstance.outsideFocusableElement.nativeElement.focus(); | ||
flush(); | ||
expect(document.activeElement).toBe( | ||
componentInstance.firstFocusableOuterElement.nativeElement, | ||
'Expected first focusable outer element to be focused'); | ||
|
||
componentInstance.secondFocusableInnerElement.nativeElement.focus(); | ||
flush(); | ||
|
||
expect(document.activeElement).toBe( | ||
componentInstance.secondFocusableInnerElement.nativeElement, | ||
'Expected second focusable inner element to be focused'); | ||
})); | ||
|
||
it('stops trapping focus when all FocusTraps are disabled', | ||
fakeAsync(() => { | ||
outerFocusTrapInstance.enabled = true; | ||
innerFocusTrapInstance.enabled = true; | ||
outerFocusTrapInstance.enabled = false; | ||
innerFocusTrapInstance.enabled = false; | ||
|
||
componentInstance.outsideFocusableElement.nativeElement.focus(); | ||
flush(); | ||
expect(document.activeElement).toBe( | ||
componentInstance.outsideFocusableElement.nativeElement, | ||
'Expected outside element to be focused'); | ||
})); | ||
}); | ||
}); | ||
|
||
|
||
@Component({ | ||
template: ` | ||
<textarea #outsideFocusable></textarea> | ||
<div #focusTrapElement> | ||
<input #firstFocusable> | ||
<button #secondFocusable>SAVE</button> | ||
</div> | ||
` | ||
}) | ||
class SimpleFocusTrap implements AfterViewInit { | ||
@ViewChild('focusTrapElement') focusTrapElement!: ElementRef; | ||
@ViewChild('outsideFocusable') outsideFocusableElement!: ElementRef; | ||
@ViewChild('firstFocusable') firstFocusableElement!: ElementRef; | ||
@ViewChild('secondFocusable') secondFocusableElement!: ElementRef; | ||
|
||
focusTrap: ConfigurableFocusTrap; | ||
|
||
constructor(private _focusTrapFactory: ConfigurableFocusTrapFactory) { | ||
} | ||
|
||
ngAfterViewInit() { | ||
this.focusTrap = this._focusTrapFactory.create(this.focusTrapElement.nativeElement); | ||
} | ||
} | ||
|
||
@Component({ | ||
template: ` | ||
<a #outsideFocusable href="www.google.com">link</a> | ||
<div #outerFocusTrapElement> | ||
<textarea #firstFocusableOuter></textarea> | ||
<div #innerFocusTrapElement> | ||
<input #firstFocusableInner> | ||
<button #secondFocusableInner>SAVE</button> | ||
</div> | ||
</div> | ||
` | ||
}) | ||
class NestedFocusTraps implements AfterViewInit { | ||
@ViewChild('outerFocusTrapElement') outerFocusTrapElement!: ElementRef; | ||
@ViewChild('innerFocusTrapElement') innerFocusTrapElement!: ElementRef; | ||
@ViewChild('outsideFocusable') outsideFocusableElement!: ElementRef; | ||
@ViewChild('firstFocusableOuter') firstFocusableOuterElement!: ElementRef; | ||
@ViewChild('firstFocusableInner') firstFocusableInnerElement!: ElementRef; | ||
@ViewChild('secondFocusableInner') secondFocusableInnerElement!: ElementRef; | ||
|
||
outerFocusTrap: ConfigurableFocusTrap; | ||
innerFocusTrap: ConfigurableFocusTrap; | ||
|
||
constructor(private _focusTrapFactory: ConfigurableFocusTrapFactory) { | ||
} | ||
|
||
ngAfterViewInit() { | ||
this.outerFocusTrap = this._focusTrapFactory.create(this.outerFocusTrapElement.nativeElement); | ||
this.outerFocusTrap.enabled = false; | ||
this.innerFocusTrap = this._focusTrapFactory.create(this.innerFocusTrapElement.nativeElement); | ||
this.innerFocusTrap.enabled = false; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
/** | ||
* @license | ||
* Copyright Google LLC All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.io/license | ||
*/ | ||
|
||
import {NgZone} from '@angular/core'; | ||
import {InteractivityChecker} from '../interactivity-checker/interactivity-checker'; | ||
import {FocusTrap} from './focus-trap'; | ||
import {FocusTrapManager, ManagedFocusTrap} from './focus-trap-manager'; | ||
import {FocusTrapInertStrategy} from './focus-trap-inert-strategy'; | ||
|
||
/** | ||
* Class that allows for trapping focus within a DOM element. | ||
* | ||
* This class uses a strategy pattern that determines how it traps focus. | ||
* See FocusTrapInertStrategy. | ||
*/ | ||
export class ConfigurableFocusTrap extends FocusTrap implements ManagedFocusTrap { | ||
/** Whether the FocusTrap is enabled. */ | ||
get enabled(): boolean { return this._enabled; } | ||
set enabled(value: boolean) { | ||
this._enabled = value; | ||
if (this._enabled) { | ||
this._focusTrapManager.register(this); | ||
} else { | ||
this._focusTrapManager.unregister(this); | ||
} | ||
} | ||
|
||
constructor( | ||
_element: HTMLElement, | ||
_checker: InteractivityChecker, | ||
_ngZone: NgZone, | ||
_document: Document, | ||
private _focusTrapManager: FocusTrapManager, | ||
private _inertStrategy: FocusTrapInertStrategy, | ||
defer = false) { | ||
super(_element, _checker, _ngZone, _document, defer); | ||
this._focusTrapManager.register(this); | ||
} | ||
|
||
/** Notifies the FocusTrapManager that this FocusTrap will be destroyed. */ | ||
destroy() { | ||
this._focusTrapManager.unregister(this); | ||
super.destroy(); | ||
} | ||
|
||
/** @docs-private Implemented as part of ManagedFocusTrap. */ | ||
enable() { | ||
this._inertStrategy.preventFocus(this); | ||
this.toggleAnchors(true); | ||
} | ||
|
||
/** @docs-private Implemented as part of ManagedFocusTrap. */ | ||
disable() { | ||
this._inertStrategy.allowFocus(this); | ||
this.toggleAnchors(false); | ||
} | ||
|
||
/** @docs-private Used by EventListenerFocusTrapInertStrategy. */ | ||
get element(): HTMLElement { | ||
return this._element; | ||
} | ||
|
||
/** @docs-private Used by EventListenerFocusTrapInertStrategy. */ | ||
get document(): Document { | ||
return this._document; | ||
} | ||
|
||
/** @docs-private Used by EventListenerFocusTrapInertStrategy. */ | ||
get ngZone(): NgZone { | ||
return this._ngZone; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
/** | ||
* @license | ||
* Copyright Google LLC All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.io/license | ||
*/ | ||
|
||
import {FocusTrapInertStrategy} from './focus-trap-inert-strategy'; | ||
import {ConfigurableFocusTrap} from './configurable-focus-trap'; | ||
|
||
/** | ||
* Lightweight FocusTrapInertStrategy that adds a document focus event | ||
* listener to redirect focus back inside the FocusTrap. | ||
*/ | ||
export class EventListenerFocusTrapInertStrategy implements FocusTrapInertStrategy { | ||
/** Focus event handler. */ | ||
private _listener: any; | ||
|
||
/** Adds a document event listener that keeps focus inside the FocusTrap. */ | ||
preventFocus(focusTrap: ConfigurableFocusTrap): void { | ||
this._listener = this._trapFocus.bind(null, focusTrap); | ||
focusTrap.ngZone.runOutsideAngular(() => { | ||
focusTrap.document.addEventListener('focus', this._listener, true); | ||
}); | ||
} | ||
|
||
/** Removes the event listener added in preventFocus. */ | ||
allowFocus(focusTrap: ConfigurableFocusTrap): void { | ||
focusTrap.document.removeEventListener('focus', this._listener, true); | ||
this._listener = null; | ||
} | ||
|
||
/** | ||
* Refocuses the first element in the FocusTrap if the focus event target was outside | ||
* the FocusTrap. | ||
*/ | ||
private _trapFocus(focusTrap: ConfigurableFocusTrap, event: FocusEvent) { | ||
if (!focusTrap.element.contains(event.target as HTMLElement)) { | ||
// Some legacy FocusTrap usages have logic that focuses some element on the page | ||
// just before FocusTrap is destroyed. For backwards compatibility, wait | ||
// to be sure FocusTrap is still enabled before refocusing. | ||
setTimeout(() => { | ||
if (focusTrap.enabled) { | ||
focusTrap.focusFirstTabbableElement(); | ||
event.stopImmediatePropagation(); | ||
event.preventDefault(); | ||
event.stopPropagation(); | ||
} | ||
}); | ||
} | ||
} | ||
} |
Oops, something went wrong.