Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cdk/focus-trap) Add ConfigurableFocusTrap classes #18201

Merged
merged 1 commit into from
Jan 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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; }
vanessanschmitt marked this conversation as resolved.
Show resolved Hide resolved
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();
}
}