Skip to content

Commit

Permalink
feat(cdk/focus-trap) Add ConfigurableFocusTrap classes
Browse files Browse the repository at this point in the history
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
vanessanschmitt committed Jan 22, 2020
1 parent 3e2e023 commit c422d1b
Show file tree
Hide file tree
Showing 11 changed files with 567 additions and 6 deletions.
11 changes: 11 additions & 0 deletions src/cdk/a11y/focus-trap/configurable-focus-trap-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* @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
*/

export class ConfigurableFocusTrapConfig<D = any> {
defer: boolean = false;
}
53 changes: 53 additions & 0 deletions src/cdk/a11y/focus-trap/configurable-focus-trap-factory.ts
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 {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 {ConfigurableFocusTrapConfig} from './configurable-focus-trap-config';
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 || 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, config: ConfigurableFocusTrapConfig =
new ConfigurableFocusTrapConfig()): ConfigurableFocusTrap {
return new ConfigurableFocusTrap(
element, this._checker, this._ngZone, this._document, this._focusTrapManager,
this._inertStrategy, config);
}
}
188 changes: 188 additions & 0 deletions src/cdk/a11y/focus-trap/configurable-focus-trap.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import {AfterViewInit, Component, ElementRef, Type, ViewChild} from '@angular/core';
import {ComponentFixture, fakeAsync, flush, TestBed} from '@angular/core/testing';
import {A11yModule, ConfigurableFocusTrapFactory, ConfigurableFocusTrap} from '../index';


describe('ConfigurableFocusTrap', () => {
describe('with EventListenerFocusTrapInertStrategy', () => {

it('refocuses the first FocusTrap element when focus moves outside the FocusTrap',
fakeAsync(() => {
const fixture = createComponent(SimpleFocusTrap);
const componentInstance = fixture.componentInstance;
fixture.detectChanges();

expect(document.activeElement).toBe(document.body, 'Expected body to be focused');

componentInstance.focusTrap.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(() => {
const fixture = createComponent(SimpleFocusTrap);
const componentInstance = fixture.componentInstance;
fixture.detectChanges();

expect(document.activeElement).toBe(document.body, 'Expected body to be focused');

componentInstance.focusTrap.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', () => {
it('traps focus in the most recently enabled FocusTrap',
fakeAsync(() => {
const fixture = createComponent(NestedFocusTraps);
const componentInstance = fixture.componentInstance;
fixture.detectChanges();

componentInstance.outerFocusTrap.enabled = true;
componentInstance.innerFocusTrap.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(() => {
const fixture = createComponent(NestedFocusTraps);
const componentInstance = fixture.componentInstance;
fixture.detectChanges();

componentInstance.outerFocusTrap.enabled = true;
componentInstance.innerFocusTrap.enabled = true;
componentInstance.innerFocusTrap.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(() => {
const fixture = createComponent(NestedFocusTraps);
const componentInstance = fixture.componentInstance;
fixture.detectChanges();

componentInstance.outerFocusTrap.enabled = true;
componentInstance.innerFocusTrap.enabled = true;
componentInstance.outerFocusTrap.enabled = false;
componentInstance.innerFocusTrap.enabled = false;

componentInstance.outsideFocusableElement.nativeElement.focus();
flush();
expect(document.activeElement).toBe(
componentInstance.outsideFocusableElement.nativeElement,
'Expected outside element to be focused');
}));
});
});

function createComponent<T>(componentType: Type<T>): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [A11yModule],
declarations: [componentType],
}).compileComponents();

return TestBed.createComponent<T>(componentType);
}

@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;
}
}
63 changes: 63 additions & 0 deletions src/cdk/a11y/focus-trap/configurable-focus-trap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* @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';
import {ConfigurableFocusTrapConfig} from './configurable-focus-trap-config';

/**
* 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.deregister(this);
}
}

constructor(
_element: HTMLElement,
_checker: InteractivityChecker,
_ngZone: NgZone,
_document: Document,
private _focusTrapManager: FocusTrapManager,
private _inertStrategy: FocusTrapInertStrategy,
config: ConfigurableFocusTrapConfig) {
super(_element, _checker, _ngZone, _document, config.defer);
this._focusTrapManager.register(this);
}

/** Notifies the FocusTrapManager that this FocusTrap will be destroyed. */
destroy() {
this._focusTrapManager.deregister(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);
}
}
63 changes: 63 additions & 0 deletions src/cdk/a11y/focus-trap/event-listener-inert-strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* @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';
import {closest} from './polyfill';

/**
* 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: ((e: FocusEvent) => void) | null = null;

/** Adds a document event listener that keeps focus inside the FocusTrap. */
preventFocus(focusTrap: ConfigurableFocusTrap): void {
// Ensure there's only one listener per document
if (this._listener) {
focusTrap._document.removeEventListener('focus', this._listener!, true);
}

this._listener = (e: FocusEvent) => this._trapFocus(focusTrap, e);
focusTrap._ngZone.runOutsideAngular(() => {
focusTrap._document.addEventListener('focus', this._listener!, true);
});
}

/** Removes the event listener added in preventFocus. */
allowFocus(focusTrap: ConfigurableFocusTrap): void {
if (!this._listener) {
return;
}
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) {
const target = event.target as HTMLElement;
// Don't refocus if target was in an overlay, because the overlay might be associated
// with an element inside the FocusTrap, ex. mat-select.
if (!focusTrap._element.contains(target) &&
closest(target, 'div.cdk-overlay-pane') === null) {
// 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();
}
});
}
}
}

0 comments on commit c422d1b

Please sign in to comment.