Skip to content

Commit

Permalink
feat(cdk/focus-trap) Add ConfigurableFocusTrap classes (#18201)
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 authored and jelbourn committed Jan 24, 2020
1 parent c5923d6 commit 4e4e0e8
Show file tree
Hide file tree
Showing 13 changed files with 638 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;
}
54 changes: 54 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,54 @@
/**
* @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;
// TODO split up the strategies into different modules, similar to DateAdapter.
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);
}
}
127 changes: 127 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,127 @@
import {AfterViewInit, Component, ElementRef, Type, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {
A11yModule,
ConfigurableFocusTrap,
ConfigurableFocusTrapFactory,
FOCUS_TRAP_INERT_STRATEGY,
FocusTrap,
FocusTrapInertStrategy
} from '../index';
import {FocusTrapManager} from './focus-trap-manager';

describe('ConfigurableFocusTrap', () => {
let providers: Array<Object>;

describe('with FocusTrapInertStrategy', () => {
let mockInertStrategy: FocusTrapInertStrategy;

beforeEach(() => {
mockInertStrategy = new MockFocusTrapInertStrategy();
providers = [{provide: FOCUS_TRAP_INERT_STRATEGY, useValue: mockInertStrategy}];
});

it('Calls preventFocus when it is created', () => {
spyOn(mockInertStrategy, 'preventFocus');
spyOn(mockInertStrategy, 'allowFocus');

const fixture = createComponent(SimpleFocusTrap, providers);
fixture.detectChanges();

expect(mockInertStrategy.preventFocus).toHaveBeenCalledTimes(1);
expect(mockInertStrategy.allowFocus).not.toHaveBeenCalled();
});

it('Calls preventFocus when it is enabled', () => {
spyOn(mockInertStrategy, 'preventFocus');

const fixture = createComponent(SimpleFocusTrap, providers);
const componentInstance = fixture.componentInstance;
fixture.detectChanges();

componentInstance.focusTrap.enabled = true;

expect(mockInertStrategy.preventFocus).toHaveBeenCalledTimes(2);
});

it('Calls allowFocus when it is disabled', () => {
spyOn(mockInertStrategy, 'allowFocus');

const fixture = createComponent(SimpleFocusTrap, providers);
const componentInstance = fixture.componentInstance;
fixture.detectChanges();

componentInstance.focusTrap.enabled = false;

expect(mockInertStrategy.allowFocus).toHaveBeenCalledTimes(1);
});
});

describe('with FocusTrapManager', () => {
let manager: FocusTrapManager;

beforeEach(() => {
manager = new FocusTrapManager();
providers = [{provide: FocusTrapManager, useValue: manager}];
});

it('Registers when it is created', () => {
spyOn(manager, 'register');

const fixture = createComponent(SimpleFocusTrap, providers);
fixture.detectChanges();

expect(manager.register).toHaveBeenCalledTimes(1);
});

it('Deregisters when it is disabled', () => {
spyOn(manager, 'deregister');

const fixture = createComponent(SimpleFocusTrap, providers);
const componentInstance = fixture.componentInstance;
fixture.detectChanges();

componentInstance.focusTrap.enabled = false;

expect(manager.deregister).toHaveBeenCalledTimes(1);
});
});
});

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

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

@Component({
template: `
<div #focusTrapElement>
<input>
<button>SAVE</button>
</div>
`
})
class SimpleFocusTrap implements AfterViewInit {
@ViewChild('focusTrapElement') focusTrapElement!: ElementRef;

focusTrap: ConfigurableFocusTrap;

constructor(private _focusTrapFactory: ConfigurableFocusTrapFactory) {
}

ngAfterViewInit() {
this.focusTrap = this._focusTrapFactory.create(this.focusTrapElement.nativeElement);
}
}

class MockFocusTrapInertStrategy implements FocusTrapInertStrategy {
preventFocus(focusTrap: FocusTrap) {}

allowFocus(focusTrap: FocusTrap) {}
}
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);
}
}
80 changes: 80 additions & 0 deletions src/cdk/a11y/focus-trap/event-listener-inert-strategy.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import {AfterViewInit, Component, ElementRef, Type, ViewChild} from '@angular/core';
import {ComponentFixture, fakeAsync, flush, TestBed} from '@angular/core/testing';
import {
A11yModule,
ConfigurableFocusTrapFactory,
ConfigurableFocusTrap,
EventListenerFocusTrapInertStrategy,
FOCUS_TRAP_INERT_STRATEGY,
} from '../index';


describe('EventListenerFocusTrapInertStrategy', () => {
const providers = [
{provide: FOCUS_TRAP_INERT_STRATEGY, useValue: new EventListenerFocusTrapInertStrategy()}];

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

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, providers);
const componentInstance = fixture.componentInstance;
fixture.detectChanges();

componentInstance.secondFocusableElement.nativeElement.focus();
flush();

expect(document.activeElement).toBe(
componentInstance.secondFocusableElement.nativeElement,
'Expected second focusable element to be focused');
}));
});

function createComponent<T>(componentType: Type<T>, providers: Array<Object> = []
): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [A11yModule],
declarations: [componentType],
providers: providers
}).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);
this.focusTrap.focusFirstTabbableElementWhenReady();
}
}

0 comments on commit 4e4e0e8

Please sign in to comment.