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. Note that
cdkTrapFocus and FocusTrapFactory were moved to separate files, but there are
no functional changes for those classes.

This commit does not enable ConfigurableFocusTrap anywhere.
  • Loading branch information
vanessanschmitt committed Jan 16, 2020
1 parent 3e2e023 commit 003ecb5
Show file tree
Hide file tree
Showing 11 changed files with 657 additions and 109 deletions.
2 changes: 1 addition & 1 deletion src/cdk/a11y/a11y-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {PlatformModule} from '@angular/cdk/platform';
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {CdkMonitorFocus} from './focus-monitor/focus-monitor';
import {CdkTrapFocus} from './focus-trap/focus-trap';
import {CdkTrapFocus} from './focus-trap/cdk-trap-focus';
import {HighContrastModeDetector} from './high-contrast-mode/high-contrast-mode-detector';
import {CdkAriaLive} from './live-announcer/live-announcer';

Expand Down
88 changes: 88 additions & 0 deletions src/cdk/a11y/focus-trap/cdk-trap-focus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/**
* @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 {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion';
import {DOCUMENT} from '@angular/common';
import {
AfterContentInit,
Directive,
ElementRef,
Inject,
Input,
OnDestroy,
DoCheck,
} from '@angular/core';
import {FocusTrap} from './focus-trap';
import {FocusTrapFactory} from './focus-trap-factory';

/** Directive for trapping focus within a region. */
@Directive({
selector: '[cdkTrapFocus]',
exportAs: 'cdkTrapFocus',
})
export class CdkTrapFocus implements OnDestroy, AfterContentInit, DoCheck {
private _document: Document;

/** Underlying FocusTrap instance. */
focusTrap: FocusTrap;

/** Previously focused element to restore focus to upon destroy when using autoCapture. */
private _previouslyFocusedElement: HTMLElement | null = null;

/** Whether the focus trap is active. */
@Input('cdkTrapFocus')
get enabled(): boolean { return this.focusTrap.enabled; }
set enabled(value: boolean) { this.focusTrap.enabled = coerceBooleanProperty(value); }

/**
* Whether the directive should automatially move focus into the trapped region upon
* initialization and return focus to the previous activeElement upon destruction.
*/
@Input('cdkTrapFocusAutoCapture')
get autoCapture(): boolean { return this._autoCapture; }
set autoCapture(value: boolean) { this._autoCapture = coerceBooleanProperty(value); }
private _autoCapture: boolean;

constructor(
private _elementRef: ElementRef<HTMLElement>,
private _focusTrapFactory: FocusTrapFactory,
@Inject(DOCUMENT) _document: any) {

this._document = _document;
this.focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement, true);
}

ngOnDestroy() {
this.focusTrap.destroy();

// If we stored a previously focused element when using autoCapture, return focus to that
// element now that the trapped region is being destroyed.
if (this._previouslyFocusedElement) {
this._previouslyFocusedElement.focus();
this._previouslyFocusedElement = null;
}
}

ngAfterContentInit() {
this.focusTrap.attachAnchors();

if (this.autoCapture) {
this._previouslyFocusedElement = this._document.activeElement as HTMLElement;
this.focusTrap.focusInitialElementWhenReady();
}
}

ngDoCheck() {
if (!this.focusTrap.hasAttached()) {
this.focusTrap.attachAnchors();
}
}

static ngAcceptInputType_enabled: BooleanInput;
static ngAcceptInputType_autoCapture: BooleanInput;
}
196 changes: 196 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,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;
}
}
77 changes: 77 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,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;
}
}

0 comments on commit 003ecb5

Please sign in to comment.