You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2476 lines
111 KiB
2476 lines
111 KiB
import * as i2 from '@angular/common';
|
|
import { DOCUMENT } from '@angular/common';
|
|
import * as i0 from '@angular/core';
|
|
import { Injectable, Inject, QueryList, NgZone, Directive, ElementRef, Input, InjectionToken, Optional, EventEmitter, Output, NgModule } from '@angular/core';
|
|
import { Subject, Subscription, BehaviorSubject, of } from 'rxjs';
|
|
import { hasModifierKey, A, Z, ZERO, NINE, END, HOME, LEFT_ARROW, RIGHT_ARROW, UP_ARROW, DOWN_ARROW, TAB, ALT, CONTROL, MAC_META, META, SHIFT } from '@angular/cdk/keycodes';
|
|
import { tap, debounceTime, filter, map, take, skip, distinctUntilChanged, takeUntil } from 'rxjs/operators';
|
|
import { coerceBooleanProperty, coerceElement } from '@angular/cdk/coercion';
|
|
import * as i1 from '@angular/cdk/platform';
|
|
import { Platform, _getFocusedElementPierceShadowDom, normalizePassiveListenerOptions, _getEventTarget, _getShadowRoot, PlatformModule } from '@angular/cdk/platform';
|
|
import { ContentObserver, ObserversModule } from '@angular/cdk/observers';
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/** IDs are delimited by an empty space, as per the spec. */
|
|
import * as ɵngcc0 from '@angular/core';
|
|
import * as ɵngcc1 from '@angular/cdk/platform';
|
|
import * as ɵngcc2 from '@angular/cdk/observers';
|
|
const ID_DELIMITER = ' ';
|
|
/**
|
|
* Adds the given ID to the specified ARIA attribute on an element.
|
|
* Used for attributes such as aria-labelledby, aria-owns, etc.
|
|
*/
|
|
function addAriaReferencedId(el, attr, id) {
|
|
const ids = getAriaReferenceIds(el, attr);
|
|
if (ids.some(existingId => existingId.trim() == id.trim())) {
|
|
return;
|
|
}
|
|
ids.push(id.trim());
|
|
el.setAttribute(attr, ids.join(ID_DELIMITER));
|
|
}
|
|
/**
|
|
* Removes the given ID from the specified ARIA attribute on an element.
|
|
* Used for attributes such as aria-labelledby, aria-owns, etc.
|
|
*/
|
|
function removeAriaReferencedId(el, attr, id) {
|
|
const ids = getAriaReferenceIds(el, attr);
|
|
const filteredIds = ids.filter(val => val != id.trim());
|
|
if (filteredIds.length) {
|
|
el.setAttribute(attr, filteredIds.join(ID_DELIMITER));
|
|
}
|
|
else {
|
|
el.removeAttribute(attr);
|
|
}
|
|
}
|
|
/**
|
|
* Gets the list of IDs referenced by the given ARIA attribute on an element.
|
|
* Used for attributes such as aria-labelledby, aria-owns, etc.
|
|
*/
|
|
function getAriaReferenceIds(el, attr) {
|
|
// Get string array of all individual ids (whitespace delimited) in the attribute value
|
|
return (el.getAttribute(attr) || '').match(/\S+/g) || [];
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/** ID used for the body container where all messages are appended. */
|
|
const MESSAGES_CONTAINER_ID = 'cdk-describedby-message-container';
|
|
/** ID prefix used for each created message element. */
|
|
const CDK_DESCRIBEDBY_ID_PREFIX = 'cdk-describedby-message';
|
|
/** Attribute given to each host element that is described by a message element. */
|
|
const CDK_DESCRIBEDBY_HOST_ATTRIBUTE = 'cdk-describedby-host';
|
|
/** Global incremental identifier for each registered message element. */
|
|
let nextId = 0;
|
|
/** Global map of all registered message elements that have been placed into the document. */
|
|
const messageRegistry = new Map();
|
|
/** Container for all registered messages. */
|
|
let messagesContainer = null;
|
|
/**
|
|
* Utility that creates visually hidden elements with a message content. Useful for elements that
|
|
* want to use aria-describedby to further describe themselves without adding additional visual
|
|
* content.
|
|
*/
|
|
class AriaDescriber {
|
|
constructor(_document) {
|
|
this._document = _document;
|
|
}
|
|
describe(hostElement, message, role) {
|
|
if (!this._canBeDescribed(hostElement, message)) {
|
|
return;
|
|
}
|
|
const key = getKey(message, role);
|
|
if (typeof message !== 'string') {
|
|
// We need to ensure that the element has an ID.
|
|
setMessageId(message);
|
|
messageRegistry.set(key, { messageElement: message, referenceCount: 0 });
|
|
}
|
|
else if (!messageRegistry.has(key)) {
|
|
this._createMessageElement(message, role);
|
|
}
|
|
if (!this._isElementDescribedByMessage(hostElement, key)) {
|
|
this._addMessageReference(hostElement, key);
|
|
}
|
|
}
|
|
removeDescription(hostElement, message, role) {
|
|
if (!message || !this._isElementNode(hostElement)) {
|
|
return;
|
|
}
|
|
const key = getKey(message, role);
|
|
if (this._isElementDescribedByMessage(hostElement, key)) {
|
|
this._removeMessageReference(hostElement, key);
|
|
}
|
|
// If the message is a string, it means that it's one that we created for the
|
|
// consumer so we can remove it safely, otherwise we should leave it in place.
|
|
if (typeof message === 'string') {
|
|
const registeredMessage = messageRegistry.get(key);
|
|
if (registeredMessage && registeredMessage.referenceCount === 0) {
|
|
this._deleteMessageElement(key);
|
|
}
|
|
}
|
|
if (messagesContainer && messagesContainer.childNodes.length === 0) {
|
|
this._deleteMessagesContainer();
|
|
}
|
|
}
|
|
/** Unregisters all created message elements and removes the message container. */
|
|
ngOnDestroy() {
|
|
const describedElements = this._document.querySelectorAll(`[${CDK_DESCRIBEDBY_HOST_ATTRIBUTE}]`);
|
|
for (let i = 0; i < describedElements.length; i++) {
|
|
this._removeCdkDescribedByReferenceIds(describedElements[i]);
|
|
describedElements[i].removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);
|
|
}
|
|
if (messagesContainer) {
|
|
this._deleteMessagesContainer();
|
|
}
|
|
messageRegistry.clear();
|
|
}
|
|
/**
|
|
* Creates a new element in the visually hidden message container element with the message
|
|
* as its content and adds it to the message registry.
|
|
*/
|
|
_createMessageElement(message, role) {
|
|
const messageElement = this._document.createElement('div');
|
|
setMessageId(messageElement);
|
|
messageElement.textContent = message;
|
|
if (role) {
|
|
messageElement.setAttribute('role', role);
|
|
}
|
|
this._createMessagesContainer();
|
|
messagesContainer.appendChild(messageElement);
|
|
messageRegistry.set(getKey(message, role), { messageElement, referenceCount: 0 });
|
|
}
|
|
/** Deletes the message element from the global messages container. */
|
|
_deleteMessageElement(key) {
|
|
const registeredMessage = messageRegistry.get(key);
|
|
const messageElement = registeredMessage && registeredMessage.messageElement;
|
|
if (messagesContainer && messageElement) {
|
|
messagesContainer.removeChild(messageElement);
|
|
}
|
|
messageRegistry.delete(key);
|
|
}
|
|
/** Creates the global container for all aria-describedby messages. */
|
|
_createMessagesContainer() {
|
|
if (!messagesContainer) {
|
|
const preExistingContainer = this._document.getElementById(MESSAGES_CONTAINER_ID);
|
|
// When going from the server to the client, we may end up in a situation where there's
|
|
// already a container on the page, but we don't have a reference to it. Clear the
|
|
// old container so we don't get duplicates. Doing this, instead of emptying the previous
|
|
// container, should be slightly faster.
|
|
if (preExistingContainer && preExistingContainer.parentNode) {
|
|
preExistingContainer.parentNode.removeChild(preExistingContainer);
|
|
}
|
|
messagesContainer = this._document.createElement('div');
|
|
messagesContainer.id = MESSAGES_CONTAINER_ID;
|
|
// We add `visibility: hidden` in order to prevent text in this container from
|
|
// being searchable by the browser's Ctrl + F functionality.
|
|
// Screen-readers will still read the description for elements with aria-describedby even
|
|
// when the description element is not visible.
|
|
messagesContainer.style.visibility = 'hidden';
|
|
// Even though we use `visibility: hidden`, we still apply `cdk-visually-hidden` so that
|
|
// the description element doesn't impact page layout.
|
|
messagesContainer.classList.add('cdk-visually-hidden');
|
|
this._document.body.appendChild(messagesContainer);
|
|
}
|
|
}
|
|
/** Deletes the global messages container. */
|
|
_deleteMessagesContainer() {
|
|
if (messagesContainer && messagesContainer.parentNode) {
|
|
messagesContainer.parentNode.removeChild(messagesContainer);
|
|
messagesContainer = null;
|
|
}
|
|
}
|
|
/** Removes all cdk-describedby messages that are hosted through the element. */
|
|
_removeCdkDescribedByReferenceIds(element) {
|
|
// Remove all aria-describedby reference IDs that are prefixed by CDK_DESCRIBEDBY_ID_PREFIX
|
|
const originalReferenceIds = getAriaReferenceIds(element, 'aria-describedby')
|
|
.filter(id => id.indexOf(CDK_DESCRIBEDBY_ID_PREFIX) != 0);
|
|
element.setAttribute('aria-describedby', originalReferenceIds.join(' '));
|
|
}
|
|
/**
|
|
* Adds a message reference to the element using aria-describedby and increments the registered
|
|
* message's reference count.
|
|
*/
|
|
_addMessageReference(element, key) {
|
|
const registeredMessage = messageRegistry.get(key);
|
|
// Add the aria-describedby reference and set the
|
|
// describedby_host attribute to mark the element.
|
|
addAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);
|
|
element.setAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE, '');
|
|
registeredMessage.referenceCount++;
|
|
}
|
|
/**
|
|
* Removes a message reference from the element using aria-describedby
|
|
* and decrements the registered message's reference count.
|
|
*/
|
|
_removeMessageReference(element, key) {
|
|
const registeredMessage = messageRegistry.get(key);
|
|
registeredMessage.referenceCount--;
|
|
removeAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);
|
|
element.removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);
|
|
}
|
|
/** Returns true if the element has been described by the provided message ID. */
|
|
_isElementDescribedByMessage(element, key) {
|
|
const referenceIds = getAriaReferenceIds(element, 'aria-describedby');
|
|
const registeredMessage = messageRegistry.get(key);
|
|
const messageId = registeredMessage && registeredMessage.messageElement.id;
|
|
return !!messageId && referenceIds.indexOf(messageId) != -1;
|
|
}
|
|
/** Determines whether a message can be described on a particular element. */
|
|
_canBeDescribed(element, message) {
|
|
if (!this._isElementNode(element)) {
|
|
return false;
|
|
}
|
|
if (message && typeof message === 'object') {
|
|
// We'd have to make some assumptions about the description element's text, if the consumer
|
|
// passed in an element. Assume that if an element is passed in, the consumer has verified
|
|
// that it can be used as a description.
|
|
return true;
|
|
}
|
|
const trimmedMessage = message == null ? '' : `${message}`.trim();
|
|
const ariaLabel = element.getAttribute('aria-label');
|
|
// We shouldn't set descriptions if they're exactly the same as the `aria-label` of the
|
|
// element, because screen readers will end up reading out the same text twice in a row.
|
|
return trimmedMessage ? (!ariaLabel || ariaLabel.trim() !== trimmedMessage) : false;
|
|
}
|
|
/** Checks whether a node is an Element node. */
|
|
_isElementNode(element) {
|
|
return element.nodeType === this._document.ELEMENT_NODE;
|
|
}
|
|
}
|
|
AriaDescriber.ɵfac = function AriaDescriber_Factory(t) { return new (t || AriaDescriber)(ɵngcc0.ɵɵinject(DOCUMENT)); };
|
|
AriaDescriber.ɵprov = i0.ɵɵdefineInjectable({ factory: function AriaDescriber_Factory() { return new AriaDescriber(i0.ɵɵinject(i2.DOCUMENT)); }, token: AriaDescriber, providedIn: "root" });
|
|
AriaDescriber.ctorParameters = () => [
|
|
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
|
|
];
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(AriaDescriber, [{
|
|
type: Injectable,
|
|
args: [{ providedIn: 'root' }]
|
|
}], function () { return [{ type: undefined, decorators: [{
|
|
type: Inject,
|
|
args: [DOCUMENT]
|
|
}] }]; }, null); })();
|
|
/** Gets a key that can be used to look messages up in the registry. */
|
|
function getKey(message, role) {
|
|
return typeof message === 'string' ? `${role || ''}/${message}` : message;
|
|
}
|
|
/** Assigns a unique ID to an element, if it doesn't have one already. */
|
|
function setMessageId(element) {
|
|
if (!element.id) {
|
|
element.id = `${CDK_DESCRIBEDBY_ID_PREFIX}-${nextId++}`;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/**
|
|
* This class manages keyboard events for selectable lists. If you pass it a query list
|
|
* of items, it will set the active item correctly when arrow events occur.
|
|
*/
|
|
class ListKeyManager {
|
|
constructor(_items) {
|
|
this._items = _items;
|
|
this._activeItemIndex = -1;
|
|
this._activeItem = null;
|
|
this._wrap = false;
|
|
this._letterKeyStream = new Subject();
|
|
this._typeaheadSubscription = Subscription.EMPTY;
|
|
this._vertical = true;
|
|
this._allowedModifierKeys = [];
|
|
this._homeAndEnd = false;
|
|
/**
|
|
* Predicate function that can be used to check whether an item should be skipped
|
|
* by the key manager. By default, disabled items are skipped.
|
|
*/
|
|
this._skipPredicateFn = (item) => item.disabled;
|
|
// Buffer for the letters that the user has pressed when the typeahead option is turned on.
|
|
this._pressedLetters = [];
|
|
/**
|
|
* Stream that emits any time the TAB key is pressed, so components can react
|
|
* when focus is shifted off of the list.
|
|
*/
|
|
this.tabOut = new Subject();
|
|
/** Stream that emits whenever the active item of the list manager changes. */
|
|
this.change = new Subject();
|
|
// We allow for the items to be an array because, in some cases, the consumer may
|
|
// not have access to a QueryList of the items they want to manage (e.g. when the
|
|
// items aren't being collected via `ViewChildren` or `ContentChildren`).
|
|
if (_items instanceof QueryList) {
|
|
_items.changes.subscribe((newItems) => {
|
|
if (this._activeItem) {
|
|
const itemArray = newItems.toArray();
|
|
const newIndex = itemArray.indexOf(this._activeItem);
|
|
if (newIndex > -1 && newIndex !== this._activeItemIndex) {
|
|
this._activeItemIndex = newIndex;
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|
|
/**
|
|
* Sets the predicate function that determines which items should be skipped by the
|
|
* list key manager.
|
|
* @param predicate Function that determines whether the given item should be skipped.
|
|
*/
|
|
skipPredicate(predicate) {
|
|
this._skipPredicateFn = predicate;
|
|
return this;
|
|
}
|
|
/**
|
|
* Configures wrapping mode, which determines whether the active item will wrap to
|
|
* the other end of list when there are no more items in the given direction.
|
|
* @param shouldWrap Whether the list should wrap when reaching the end.
|
|
*/
|
|
withWrap(shouldWrap = true) {
|
|
this._wrap = shouldWrap;
|
|
return this;
|
|
}
|
|
/**
|
|
* Configures whether the key manager should be able to move the selection vertically.
|
|
* @param enabled Whether vertical selection should be enabled.
|
|
*/
|
|
withVerticalOrientation(enabled = true) {
|
|
this._vertical = enabled;
|
|
return this;
|
|
}
|
|
/**
|
|
* Configures the key manager to move the selection horizontally.
|
|
* Passing in `null` will disable horizontal movement.
|
|
* @param direction Direction in which the selection can be moved.
|
|
*/
|
|
withHorizontalOrientation(direction) {
|
|
this._horizontal = direction;
|
|
return this;
|
|
}
|
|
/**
|
|
* Modifier keys which are allowed to be held down and whose default actions will be prevented
|
|
* as the user is pressing the arrow keys. Defaults to not allowing any modifier keys.
|
|
*/
|
|
withAllowedModifierKeys(keys) {
|
|
this._allowedModifierKeys = keys;
|
|
return this;
|
|
}
|
|
/**
|
|
* Turns on typeahead mode which allows users to set the active item by typing.
|
|
* @param debounceInterval Time to wait after the last keystroke before setting the active item.
|
|
*/
|
|
withTypeAhead(debounceInterval = 200) {
|
|
if ((typeof ngDevMode === 'undefined' || ngDevMode) && (this._items.length &&
|
|
this._items.some(item => typeof item.getLabel !== 'function'))) {
|
|
throw Error('ListKeyManager items in typeahead mode must implement the `getLabel` method.');
|
|
}
|
|
this._typeaheadSubscription.unsubscribe();
|
|
// Debounce the presses of non-navigational keys, collect the ones that correspond to letters
|
|
// and convert those letters back into a string. Afterwards find the first item that starts
|
|
// with that string and select it.
|
|
this._typeaheadSubscription = this._letterKeyStream.pipe(tap(letter => this._pressedLetters.push(letter)), debounceTime(debounceInterval), filter(() => this._pressedLetters.length > 0), map(() => this._pressedLetters.join(''))).subscribe(inputString => {
|
|
const items = this._getItemsArray();
|
|
// Start at 1 because we want to start searching at the item immediately
|
|
// following the current active item.
|
|
for (let i = 1; i < items.length + 1; i++) {
|
|
const index = (this._activeItemIndex + i) % items.length;
|
|
const item = items[index];
|
|
if (!this._skipPredicateFn(item) &&
|
|
item.getLabel().toUpperCase().trim().indexOf(inputString) === 0) {
|
|
this.setActiveItem(index);
|
|
break;
|
|
}
|
|
}
|
|
this._pressedLetters = [];
|
|
});
|
|
return this;
|
|
}
|
|
/**
|
|
* Configures the key manager to activate the first and last items
|
|
* respectively when the Home or End key is pressed.
|
|
* @param enabled Whether pressing the Home or End key activates the first/last item.
|
|
*/
|
|
withHomeAndEnd(enabled = true) {
|
|
this._homeAndEnd = enabled;
|
|
return this;
|
|
}
|
|
setActiveItem(item) {
|
|
const previousActiveItem = this._activeItem;
|
|
this.updateActiveItem(item);
|
|
if (this._activeItem !== previousActiveItem) {
|
|
this.change.next(this._activeItemIndex);
|
|
}
|
|
}
|
|
/**
|
|
* Sets the active item depending on the key event passed in.
|
|
* @param event Keyboard event to be used for determining which element should be active.
|
|
*/
|
|
onKeydown(event) {
|
|
const keyCode = event.keyCode;
|
|
const modifiers = ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'];
|
|
const isModifierAllowed = modifiers.every(modifier => {
|
|
return !event[modifier] || this._allowedModifierKeys.indexOf(modifier) > -1;
|
|
});
|
|
switch (keyCode) {
|
|
case TAB:
|
|
this.tabOut.next();
|
|
return;
|
|
case DOWN_ARROW:
|
|
if (this._vertical && isModifierAllowed) {
|
|
this.setNextItemActive();
|
|
break;
|
|
}
|
|
else {
|
|
return;
|
|
}
|
|
case UP_ARROW:
|
|
if (this._vertical && isModifierAllowed) {
|
|
this.setPreviousItemActive();
|
|
break;
|
|
}
|
|
else {
|
|
return;
|
|
}
|
|
case RIGHT_ARROW:
|
|
if (this._horizontal && isModifierAllowed) {
|
|
this._horizontal === 'rtl' ? this.setPreviousItemActive() : this.setNextItemActive();
|
|
break;
|
|
}
|
|
else {
|
|
return;
|
|
}
|
|
case LEFT_ARROW:
|
|
if (this._horizontal && isModifierAllowed) {
|
|
this._horizontal === 'rtl' ? this.setNextItemActive() : this.setPreviousItemActive();
|
|
break;
|
|
}
|
|
else {
|
|
return;
|
|
}
|
|
case HOME:
|
|
if (this._homeAndEnd && isModifierAllowed) {
|
|
this.setFirstItemActive();
|
|
break;
|
|
}
|
|
else {
|
|
return;
|
|
}
|
|
case END:
|
|
if (this._homeAndEnd && isModifierAllowed) {
|
|
this.setLastItemActive();
|
|
break;
|
|
}
|
|
else {
|
|
return;
|
|
}
|
|
default:
|
|
if (isModifierAllowed || hasModifierKey(event, 'shiftKey')) {
|
|
// Attempt to use the `event.key` which also maps it to the user's keyboard language,
|
|
// otherwise fall back to resolving alphanumeric characters via the keyCode.
|
|
if (event.key && event.key.length === 1) {
|
|
this._letterKeyStream.next(event.key.toLocaleUpperCase());
|
|
}
|
|
else if ((keyCode >= A && keyCode <= Z) || (keyCode >= ZERO && keyCode <= NINE)) {
|
|
this._letterKeyStream.next(String.fromCharCode(keyCode));
|
|
}
|
|
}
|
|
// Note that we return here, in order to avoid preventing
|
|
// the default action of non-navigational keys.
|
|
return;
|
|
}
|
|
this._pressedLetters = [];
|
|
event.preventDefault();
|
|
}
|
|
/** Index of the currently active item. */
|
|
get activeItemIndex() {
|
|
return this._activeItemIndex;
|
|
}
|
|
/** The active item. */
|
|
get activeItem() {
|
|
return this._activeItem;
|
|
}
|
|
/** Gets whether the user is currently typing into the manager using the typeahead feature. */
|
|
isTyping() {
|
|
return this._pressedLetters.length > 0;
|
|
}
|
|
/** Sets the active item to the first enabled item in the list. */
|
|
setFirstItemActive() {
|
|
this._setActiveItemByIndex(0, 1);
|
|
}
|
|
/** Sets the active item to the last enabled item in the list. */
|
|
setLastItemActive() {
|
|
this._setActiveItemByIndex(this._items.length - 1, -1);
|
|
}
|
|
/** Sets the active item to the next enabled item in the list. */
|
|
setNextItemActive() {
|
|
this._activeItemIndex < 0 ? this.setFirstItemActive() : this._setActiveItemByDelta(1);
|
|
}
|
|
/** Sets the active item to a previous enabled item in the list. */
|
|
setPreviousItemActive() {
|
|
this._activeItemIndex < 0 && this._wrap ? this.setLastItemActive()
|
|
: this._setActiveItemByDelta(-1);
|
|
}
|
|
updateActiveItem(item) {
|
|
const itemArray = this._getItemsArray();
|
|
const index = typeof item === 'number' ? item : itemArray.indexOf(item);
|
|
const activeItem = itemArray[index];
|
|
// Explicitly check for `null` and `undefined` because other falsy values are valid.
|
|
this._activeItem = activeItem == null ? null : activeItem;
|
|
this._activeItemIndex = index;
|
|
}
|
|
/**
|
|
* This method sets the active item, given a list of items and the delta between the
|
|
* currently active item and the new active item. It will calculate differently
|
|
* depending on whether wrap mode is turned on.
|
|
*/
|
|
_setActiveItemByDelta(delta) {
|
|
this._wrap ? this._setActiveInWrapMode(delta) : this._setActiveInDefaultMode(delta);
|
|
}
|
|
/**
|
|
* Sets the active item properly given "wrap" mode. In other words, it will continue to move
|
|
* down the list until it finds an item that is not disabled, and it will wrap if it
|
|
* encounters either end of the list.
|
|
*/
|
|
_setActiveInWrapMode(delta) {
|
|
const items = this._getItemsArray();
|
|
for (let i = 1; i <= items.length; i++) {
|
|
const index = (this._activeItemIndex + (delta * i) + items.length) % items.length;
|
|
const item = items[index];
|
|
if (!this._skipPredicateFn(item)) {
|
|
this.setActiveItem(index);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* Sets the active item properly given the default mode. In other words, it will
|
|
* continue to move down the list until it finds an item that is not disabled. If
|
|
* it encounters either end of the list, it will stop and not wrap.
|
|
*/
|
|
_setActiveInDefaultMode(delta) {
|
|
this._setActiveItemByIndex(this._activeItemIndex + delta, delta);
|
|
}
|
|
/**
|
|
* Sets the active item to the first enabled item starting at the index specified. If the
|
|
* item is disabled, it will move in the fallbackDelta direction until it either
|
|
* finds an enabled item or encounters the end of the list.
|
|
*/
|
|
_setActiveItemByIndex(index, fallbackDelta) {
|
|
const items = this._getItemsArray();
|
|
if (!items[index]) {
|
|
return;
|
|
}
|
|
while (this._skipPredicateFn(items[index])) {
|
|
index += fallbackDelta;
|
|
if (!items[index]) {
|
|
return;
|
|
}
|
|
}
|
|
this.setActiveItem(index);
|
|
}
|
|
/** Returns the items as an array. */
|
|
_getItemsArray() {
|
|
return this._items instanceof QueryList ? this._items.toArray() : this._items;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
class ActiveDescendantKeyManager extends ListKeyManager {
|
|
setActiveItem(index) {
|
|
if (this.activeItem) {
|
|
this.activeItem.setInactiveStyles();
|
|
}
|
|
super.setActiveItem(index);
|
|
if (this.activeItem) {
|
|
this.activeItem.setActiveStyles();
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
class FocusKeyManager extends ListKeyManager {
|
|
constructor() {
|
|
super(...arguments);
|
|
this._origin = 'program';
|
|
}
|
|
/**
|
|
* Sets the focus origin that will be passed in to the items for any subsequent `focus` calls.
|
|
* @param origin Focus origin to be used when focusing items.
|
|
*/
|
|
setFocusOrigin(origin) {
|
|
this._origin = origin;
|
|
return this;
|
|
}
|
|
setActiveItem(item) {
|
|
super.setActiveItem(item);
|
|
if (this.activeItem) {
|
|
this.activeItem.focus(this._origin);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/**
|
|
* Configuration for the isFocusable method.
|
|
*/
|
|
class IsFocusableConfig {
|
|
constructor() {
|
|
/**
|
|
* Whether to count an element as focusable even if it is not currently visible.
|
|
*/
|
|
this.ignoreVisibility = false;
|
|
}
|
|
}
|
|
// The InteractivityChecker leans heavily on the ally.js accessibility utilities.
|
|
// Methods like `isTabbable` are only covering specific edge-cases for the browsers which are
|
|
// supported.
|
|
/**
|
|
* Utility for checking the interactivity of an element, such as whether is is focusable or
|
|
* tabbable.
|
|
*/
|
|
class InteractivityChecker {
|
|
constructor(_platform) {
|
|
this._platform = _platform;
|
|
}
|
|
/**
|
|
* Gets whether an element is disabled.
|
|
*
|
|
* @param element Element to be checked.
|
|
* @returns Whether the element is disabled.
|
|
*/
|
|
isDisabled(element) {
|
|
// This does not capture some cases, such as a non-form control with a disabled attribute or
|
|
// a form control inside of a disabled form, but should capture the most common cases.
|
|
return element.hasAttribute('disabled');
|
|
}
|
|
/**
|
|
* Gets whether an element is visible for the purposes of interactivity.
|
|
*
|
|
* This will capture states like `display: none` and `visibility: hidden`, but not things like
|
|
* being clipped by an `overflow: hidden` parent or being outside the viewport.
|
|
*
|
|
* @returns Whether the element is visible.
|
|
*/
|
|
isVisible(element) {
|
|
return hasGeometry(element) && getComputedStyle(element).visibility === 'visible';
|
|
}
|
|
/**
|
|
* Gets whether an element can be reached via Tab key.
|
|
* Assumes that the element has already been checked with isFocusable.
|
|
*
|
|
* @param element Element to be checked.
|
|
* @returns Whether the element is tabbable.
|
|
*/
|
|
isTabbable(element) {
|
|
// Nothing is tabbable on the server 😎
|
|
if (!this._platform.isBrowser) {
|
|
return false;
|
|
}
|
|
const frameElement = getFrameElement(getWindow(element));
|
|
if (frameElement) {
|
|
// Frame elements inherit their tabindex onto all child elements.
|
|
if (getTabIndexValue(frameElement) === -1) {
|
|
return false;
|
|
}
|
|
// Browsers disable tabbing to an element inside of an invisible frame.
|
|
if (!this.isVisible(frameElement)) {
|
|
return false;
|
|
}
|
|
}
|
|
let nodeName = element.nodeName.toLowerCase();
|
|
let tabIndexValue = getTabIndexValue(element);
|
|
if (element.hasAttribute('contenteditable')) {
|
|
return tabIndexValue !== -1;
|
|
}
|
|
if (nodeName === 'iframe' || nodeName === 'object') {
|
|
// The frame or object's content may be tabbable depending on the content, but it's
|
|
// not possibly to reliably detect the content of the frames. We always consider such
|
|
// elements as non-tabbable.
|
|
return false;
|
|
}
|
|
// In iOS, the browser only considers some specific elements as tabbable.
|
|
if (this._platform.WEBKIT && this._platform.IOS && !isPotentiallyTabbableIOS(element)) {
|
|
return false;
|
|
}
|
|
if (nodeName === 'audio') {
|
|
// Audio elements without controls enabled are never tabbable, regardless
|
|
// of the tabindex attribute explicitly being set.
|
|
if (!element.hasAttribute('controls')) {
|
|
return false;
|
|
}
|
|
// Audio elements with controls are by default tabbable unless the
|
|
// tabindex attribute is set to `-1` explicitly.
|
|
return tabIndexValue !== -1;
|
|
}
|
|
if (nodeName === 'video') {
|
|
// For all video elements, if the tabindex attribute is set to `-1`, the video
|
|
// is not tabbable. Note: We cannot rely on the default `HTMLElement.tabIndex`
|
|
// property as that one is set to `-1` in Chrome, Edge and Safari v13.1. The
|
|
// tabindex attribute is the source of truth here.
|
|
if (tabIndexValue === -1) {
|
|
return false;
|
|
}
|
|
// If the tabindex is explicitly set, and not `-1` (as per check before), the
|
|
// video element is always tabbable (regardless of whether it has controls or not).
|
|
if (tabIndexValue !== null) {
|
|
return true;
|
|
}
|
|
// Otherwise (when no explicit tabindex is set), a video is only tabbable if it
|
|
// has controls enabled. Firefox is special as videos are always tabbable regardless
|
|
// of whether there are controls or not.
|
|
return this._platform.FIREFOX || element.hasAttribute('controls');
|
|
}
|
|
return element.tabIndex >= 0;
|
|
}
|
|
/**
|
|
* Gets whether an element can be focused by the user.
|
|
*
|
|
* @param element Element to be checked.
|
|
* @param config The config object with options to customize this method's behavior
|
|
* @returns Whether the element is focusable.
|
|
*/
|
|
isFocusable(element, config) {
|
|
// Perform checks in order of left to most expensive.
|
|
// Again, naive approach that does not capture many edge cases and browser quirks.
|
|
return isPotentiallyFocusable(element) && !this.isDisabled(element) &&
|
|
((config === null || config === void 0 ? void 0 : config.ignoreVisibility) || this.isVisible(element));
|
|
}
|
|
}
|
|
InteractivityChecker.ɵfac = function InteractivityChecker_Factory(t) { return new (t || InteractivityChecker)(ɵngcc0.ɵɵinject(ɵngcc1.Platform)); };
|
|
InteractivityChecker.ɵprov = i0.ɵɵdefineInjectable({ factory: function InteractivityChecker_Factory() { return new InteractivityChecker(i0.ɵɵinject(i1.Platform)); }, token: InteractivityChecker, providedIn: "root" });
|
|
InteractivityChecker.ctorParameters = () => [
|
|
{ type: Platform }
|
|
];
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(InteractivityChecker, [{
|
|
type: Injectable,
|
|
args: [{ providedIn: 'root' }]
|
|
}], function () { return [{ type: ɵngcc1.Platform }]; }, null); })();
|
|
/**
|
|
* Returns the frame element from a window object. Since browsers like MS Edge throw errors if
|
|
* the frameElement property is being accessed from a different host address, this property
|
|
* should be accessed carefully.
|
|
*/
|
|
function getFrameElement(window) {
|
|
try {
|
|
return window.frameElement;
|
|
}
|
|
catch (_a) {
|
|
return null;
|
|
}
|
|
}
|
|
/** Checks whether the specified element has any geometry / rectangles. */
|
|
function hasGeometry(element) {
|
|
// Use logic from jQuery to check for an invisible element.
|
|
// See https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js#L12
|
|
return !!(element.offsetWidth || element.offsetHeight ||
|
|
(typeof element.getClientRects === 'function' && element.getClientRects().length));
|
|
}
|
|
/** Gets whether an element's */
|
|
function isNativeFormElement(element) {
|
|
let nodeName = element.nodeName.toLowerCase();
|
|
return nodeName === 'input' ||
|
|
nodeName === 'select' ||
|
|
nodeName === 'button' ||
|
|
nodeName === 'textarea';
|
|
}
|
|
/** Gets whether an element is an `<input type="hidden">`. */
|
|
function isHiddenInput(element) {
|
|
return isInputElement(element) && element.type == 'hidden';
|
|
}
|
|
/** Gets whether an element is an anchor that has an href attribute. */
|
|
function isAnchorWithHref(element) {
|
|
return isAnchorElement(element) && element.hasAttribute('href');
|
|
}
|
|
/** Gets whether an element is an input element. */
|
|
function isInputElement(element) {
|
|
return element.nodeName.toLowerCase() == 'input';
|
|
}
|
|
/** Gets whether an element is an anchor element. */
|
|
function isAnchorElement(element) {
|
|
return element.nodeName.toLowerCase() == 'a';
|
|
}
|
|
/** Gets whether an element has a valid tabindex. */
|
|
function hasValidTabIndex(element) {
|
|
if (!element.hasAttribute('tabindex') || element.tabIndex === undefined) {
|
|
return false;
|
|
}
|
|
let tabIndex = element.getAttribute('tabindex');
|
|
// IE11 parses tabindex="" as the value "-32768"
|
|
if (tabIndex == '-32768') {
|
|
return false;
|
|
}
|
|
return !!(tabIndex && !isNaN(parseInt(tabIndex, 10)));
|
|
}
|
|
/**
|
|
* Returns the parsed tabindex from the element attributes instead of returning the
|
|
* evaluated tabindex from the browsers defaults.
|
|
*/
|
|
function getTabIndexValue(element) {
|
|
if (!hasValidTabIndex(element)) {
|
|
return null;
|
|
}
|
|
// See browser issue in Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=1128054
|
|
const tabIndex = parseInt(element.getAttribute('tabindex') || '', 10);
|
|
return isNaN(tabIndex) ? -1 : tabIndex;
|
|
}
|
|
/** Checks whether the specified element is potentially tabbable on iOS */
|
|
function isPotentiallyTabbableIOS(element) {
|
|
let nodeName = element.nodeName.toLowerCase();
|
|
let inputType = nodeName === 'input' && element.type;
|
|
return inputType === 'text'
|
|
|| inputType === 'password'
|
|
|| nodeName === 'select'
|
|
|| nodeName === 'textarea';
|
|
}
|
|
/**
|
|
* Gets whether an element is potentially focusable without taking current visible/disabled state
|
|
* into account.
|
|
*/
|
|
function isPotentiallyFocusable(element) {
|
|
// Inputs are potentially focusable *unless* they're type="hidden".
|
|
if (isHiddenInput(element)) {
|
|
return false;
|
|
}
|
|
return isNativeFormElement(element) ||
|
|
isAnchorWithHref(element) ||
|
|
element.hasAttribute('contenteditable') ||
|
|
hasValidTabIndex(element);
|
|
}
|
|
/** Gets the parent window of a DOM node with regards of being inside of an iframe. */
|
|
function getWindow(node) {
|
|
// ownerDocument is null if `node` itself *is* a document.
|
|
return node.ownerDocument && node.ownerDocument.defaultView || window;
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/**
|
|
* Class that allows for trapping focus within a DOM element.
|
|
*
|
|
* This class currently uses a relatively simple approach to focus trapping.
|
|
* It assumes that the tab order is the same as DOM order, which is not necessarily true.
|
|
* Things like `tabIndex > 0`, flex `order`, and shadow roots can cause the two to be misaligned.
|
|
*
|
|
* @deprecated Use `ConfigurableFocusTrap` instead.
|
|
* @breaking-change 11.0.0
|
|
*/
|
|
class FocusTrap {
|
|
constructor(_element, _checker, _ngZone, _document, deferAnchors = false) {
|
|
this._element = _element;
|
|
this._checker = _checker;
|
|
this._ngZone = _ngZone;
|
|
this._document = _document;
|
|
this._hasAttached = false;
|
|
// Event listeners for the anchors. Need to be regular functions so that we can unbind them later.
|
|
this.startAnchorListener = () => this.focusLastTabbableElement();
|
|
this.endAnchorListener = () => this.focusFirstTabbableElement();
|
|
this._enabled = true;
|
|
if (!deferAnchors) {
|
|
this.attachAnchors();
|
|
}
|
|
}
|
|
/** Whether the focus trap is active. */
|
|
get enabled() { return this._enabled; }
|
|
set enabled(value) {
|
|
this._enabled = value;
|
|
if (this._startAnchor && this._endAnchor) {
|
|
this._toggleAnchorTabIndex(value, this._startAnchor);
|
|
this._toggleAnchorTabIndex(value, this._endAnchor);
|
|
}
|
|
}
|
|
/** Destroys the focus trap by cleaning up the anchors. */
|
|
destroy() {
|
|
const startAnchor = this._startAnchor;
|
|
const endAnchor = this._endAnchor;
|
|
if (startAnchor) {
|
|
startAnchor.removeEventListener('focus', this.startAnchorListener);
|
|
if (startAnchor.parentNode) {
|
|
startAnchor.parentNode.removeChild(startAnchor);
|
|
}
|
|
}
|
|
if (endAnchor) {
|
|
endAnchor.removeEventListener('focus', this.endAnchorListener);
|
|
if (endAnchor.parentNode) {
|
|
endAnchor.parentNode.removeChild(endAnchor);
|
|
}
|
|
}
|
|
this._startAnchor = this._endAnchor = null;
|
|
this._hasAttached = false;
|
|
}
|
|
/**
|
|
* Inserts the anchors into the DOM. This is usually done automatically
|
|
* in the constructor, but can be deferred for cases like directives with `*ngIf`.
|
|
* @returns Whether the focus trap managed to attach successfully. This may not be the case
|
|
* if the target element isn't currently in the DOM.
|
|
*/
|
|
attachAnchors() {
|
|
// If we're not on the browser, there can be no focus to trap.
|
|
if (this._hasAttached) {
|
|
return true;
|
|
}
|
|
this._ngZone.runOutsideAngular(() => {
|
|
if (!this._startAnchor) {
|
|
this._startAnchor = this._createAnchor();
|
|
this._startAnchor.addEventListener('focus', this.startAnchorListener);
|
|
}
|
|
if (!this._endAnchor) {
|
|
this._endAnchor = this._createAnchor();
|
|
this._endAnchor.addEventListener('focus', this.endAnchorListener);
|
|
}
|
|
});
|
|
if (this._element.parentNode) {
|
|
this._element.parentNode.insertBefore(this._startAnchor, this._element);
|
|
this._element.parentNode.insertBefore(this._endAnchor, this._element.nextSibling);
|
|
this._hasAttached = true;
|
|
}
|
|
return this._hasAttached;
|
|
}
|
|
/**
|
|
* Waits for the zone to stabilize, then either focuses the first element that the
|
|
* user specified, or the first tabbable element.
|
|
* @returns Returns a promise that resolves with a boolean, depending
|
|
* on whether focus was moved successfully.
|
|
*/
|
|
focusInitialElementWhenReady(options) {
|
|
return new Promise(resolve => {
|
|
this._executeOnStable(() => resolve(this.focusInitialElement(options)));
|
|
});
|
|
}
|
|
/**
|
|
* Waits for the zone to stabilize, then focuses
|
|
* the first tabbable element within the focus trap region.
|
|
* @returns Returns a promise that resolves with a boolean, depending
|
|
* on whether focus was moved successfully.
|
|
*/
|
|
focusFirstTabbableElementWhenReady(options) {
|
|
return new Promise(resolve => {
|
|
this._executeOnStable(() => resolve(this.focusFirstTabbableElement(options)));
|
|
});
|
|
}
|
|
/**
|
|
* Waits for the zone to stabilize, then focuses
|
|
* the last tabbable element within the focus trap region.
|
|
* @returns Returns a promise that resolves with a boolean, depending
|
|
* on whether focus was moved successfully.
|
|
*/
|
|
focusLastTabbableElementWhenReady(options) {
|
|
return new Promise(resolve => {
|
|
this._executeOnStable(() => resolve(this.focusLastTabbableElement(options)));
|
|
});
|
|
}
|
|
/**
|
|
* Get the specified boundary element of the trapped region.
|
|
* @param bound The boundary to get (start or end of trapped region).
|
|
* @returns The boundary element.
|
|
*/
|
|
_getRegionBoundary(bound) {
|
|
// Contains the deprecated version of selector, for temporary backwards comparability.
|
|
let markers = this._element.querySelectorAll(`[cdk-focus-region-${bound}], ` +
|
|
`[cdkFocusRegion${bound}], ` +
|
|
`[cdk-focus-${bound}]`);
|
|
for (let i = 0; i < markers.length; i++) {
|
|
// @breaking-change 8.0.0
|
|
if (markers[i].hasAttribute(`cdk-focus-${bound}`)) {
|
|
console.warn(`Found use of deprecated attribute 'cdk-focus-${bound}', ` +
|
|
`use 'cdkFocusRegion${bound}' instead. The deprecated ` +
|
|
`attribute will be removed in 8.0.0.`, markers[i]);
|
|
}
|
|
else if (markers[i].hasAttribute(`cdk-focus-region-${bound}`)) {
|
|
console.warn(`Found use of deprecated attribute 'cdk-focus-region-${bound}', ` +
|
|
`use 'cdkFocusRegion${bound}' instead. The deprecated attribute ` +
|
|
`will be removed in 8.0.0.`, markers[i]);
|
|
}
|
|
}
|
|
if (bound == 'start') {
|
|
return markers.length ? markers[0] : this._getFirstTabbableElement(this._element);
|
|
}
|
|
return markers.length ?
|
|
markers[markers.length - 1] : this._getLastTabbableElement(this._element);
|
|
}
|
|
/**
|
|
* Focuses the element that should be focused when the focus trap is initialized.
|
|
* @returns Whether focus was moved successfully.
|
|
*/
|
|
focusInitialElement(options) {
|
|
// Contains the deprecated version of selector, for temporary backwards comparability.
|
|
const redirectToElement = this._element.querySelector(`[cdk-focus-initial], ` +
|
|
`[cdkFocusInitial]`);
|
|
if (redirectToElement) {
|
|
// @breaking-change 8.0.0
|
|
if (redirectToElement.hasAttribute(`cdk-focus-initial`)) {
|
|
console.warn(`Found use of deprecated attribute 'cdk-focus-initial', ` +
|
|
`use 'cdkFocusInitial' instead. The deprecated attribute ` +
|
|
`will be removed in 8.0.0`, redirectToElement);
|
|
}
|
|
// Warn the consumer if the element they've pointed to
|
|
// isn't focusable, when not in production mode.
|
|
if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
|
|
!this._checker.isFocusable(redirectToElement)) {
|
|
console.warn(`Element matching '[cdkFocusInitial]' is not focusable.`, redirectToElement);
|
|
}
|
|
if (!this._checker.isFocusable(redirectToElement)) {
|
|
const focusableChild = this._getFirstTabbableElement(redirectToElement);
|
|
focusableChild === null || focusableChild === void 0 ? void 0 : focusableChild.focus(options);
|
|
return !!focusableChild;
|
|
}
|
|
redirectToElement.focus(options);
|
|
return true;
|
|
}
|
|
return this.focusFirstTabbableElement(options);
|
|
}
|
|
/**
|
|
* Focuses the first tabbable element within the focus trap region.
|
|
* @returns Whether focus was moved successfully.
|
|
*/
|
|
focusFirstTabbableElement(options) {
|
|
const redirectToElement = this._getRegionBoundary('start');
|
|
if (redirectToElement) {
|
|
redirectToElement.focus(options);
|
|
}
|
|
return !!redirectToElement;
|
|
}
|
|
/**
|
|
* Focuses the last tabbable element within the focus trap region.
|
|
* @returns Whether focus was moved successfully.
|
|
*/
|
|
focusLastTabbableElement(options) {
|
|
const redirectToElement = this._getRegionBoundary('end');
|
|
if (redirectToElement) {
|
|
redirectToElement.focus(options);
|
|
}
|
|
return !!redirectToElement;
|
|
}
|
|
/**
|
|
* Checks whether the focus trap has successfully been attached.
|
|
*/
|
|
hasAttached() {
|
|
return this._hasAttached;
|
|
}
|
|
/** Get the first tabbable element from a DOM subtree (inclusive). */
|
|
_getFirstTabbableElement(root) {
|
|
if (this._checker.isFocusable(root) && this._checker.isTabbable(root)) {
|
|
return root;
|
|
}
|
|
// Iterate in DOM order. Note that IE doesn't have `children` for SVG so we fall
|
|
// back to `childNodes` which includes text nodes, comments etc.
|
|
let children = root.children || root.childNodes;
|
|
for (let i = 0; i < children.length; i++) {
|
|
let tabbableChild = children[i].nodeType === this._document.ELEMENT_NODE ?
|
|
this._getFirstTabbableElement(children[i]) :
|
|
null;
|
|
if (tabbableChild) {
|
|
return tabbableChild;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
/** Get the last tabbable element from a DOM subtree (inclusive). */
|
|
_getLastTabbableElement(root) {
|
|
if (this._checker.isFocusable(root) && this._checker.isTabbable(root)) {
|
|
return root;
|
|
}
|
|
// Iterate in reverse DOM order.
|
|
let children = root.children || root.childNodes;
|
|
for (let i = children.length - 1; i >= 0; i--) {
|
|
let tabbableChild = children[i].nodeType === this._document.ELEMENT_NODE ?
|
|
this._getLastTabbableElement(children[i]) :
|
|
null;
|
|
if (tabbableChild) {
|
|
return tabbableChild;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
/** Creates an anchor element. */
|
|
_createAnchor() {
|
|
const anchor = this._document.createElement('div');
|
|
this._toggleAnchorTabIndex(this._enabled, anchor);
|
|
anchor.classList.add('cdk-visually-hidden');
|
|
anchor.classList.add('cdk-focus-trap-anchor');
|
|
anchor.setAttribute('aria-hidden', 'true');
|
|
return anchor;
|
|
}
|
|
/**
|
|
* Toggles the `tabindex` of an anchor, based on the enabled state of the focus trap.
|
|
* @param isEnabled Whether the focus trap is enabled.
|
|
* @param anchor Anchor on which to toggle the tabindex.
|
|
*/
|
|
_toggleAnchorTabIndex(isEnabled, anchor) {
|
|
// Remove the tabindex completely, rather than setting it to -1, because if the
|
|
// element has a tabindex, the user might still hit it when navigating with the arrow keys.
|
|
isEnabled ? anchor.setAttribute('tabindex', '0') : anchor.removeAttribute('tabindex');
|
|
}
|
|
/**
|
|
* Toggles the`tabindex` of both anchors to either trap Tab focus or allow it to escape.
|
|
* @param enabled: Whether the anchors should trap Tab.
|
|
*/
|
|
toggleAnchors(enabled) {
|
|
if (this._startAnchor && this._endAnchor) {
|
|
this._toggleAnchorTabIndex(enabled, this._startAnchor);
|
|
this._toggleAnchorTabIndex(enabled, this._endAnchor);
|
|
}
|
|
}
|
|
/** Executes a function when the zone is stable. */
|
|
_executeOnStable(fn) {
|
|
if (this._ngZone.isStable) {
|
|
fn();
|
|
}
|
|
else {
|
|
this._ngZone.onStable.pipe(take(1)).subscribe(fn);
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* Factory that allows easy instantiation of focus traps.
|
|
* @deprecated Use `ConfigurableFocusTrapFactory` instead.
|
|
* @breaking-change 11.0.0
|
|
*/
|
|
class FocusTrapFactory {
|
|
constructor(_checker, _ngZone, _document) {
|
|
this._checker = _checker;
|
|
this._ngZone = _ngZone;
|
|
this._document = _document;
|
|
}
|
|
/**
|
|
* 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, deferCaptureElements = false) {
|
|
return new FocusTrap(element, this._checker, this._ngZone, this._document, deferCaptureElements);
|
|
}
|
|
}
|
|
FocusTrapFactory.ɵfac = function FocusTrapFactory_Factory(t) { return new (t || FocusTrapFactory)(ɵngcc0.ɵɵinject(InteractivityChecker), ɵngcc0.ɵɵinject(ɵngcc0.NgZone), ɵngcc0.ɵɵinject(DOCUMENT)); };
|
|
FocusTrapFactory.ɵprov = i0.ɵɵdefineInjectable({ factory: function FocusTrapFactory_Factory() { return new FocusTrapFactory(i0.ɵɵinject(InteractivityChecker), i0.ɵɵinject(i0.NgZone), i0.ɵɵinject(i2.DOCUMENT)); }, token: FocusTrapFactory, providedIn: "root" });
|
|
FocusTrapFactory.ctorParameters = () => [
|
|
{ type: InteractivityChecker },
|
|
{ type: NgZone },
|
|
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
|
|
];
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(FocusTrapFactory, [{
|
|
type: Injectable,
|
|
args: [{ providedIn: 'root' }]
|
|
}], function () { return [{ type: InteractivityChecker }, { type: ɵngcc0.NgZone }, { type: undefined, decorators: [{
|
|
type: Inject,
|
|
args: [DOCUMENT]
|
|
}] }]; }, null); })();
|
|
/** Directive for trapping focus within a region. */
|
|
class CdkTrapFocus {
|
|
constructor(_elementRef, _focusTrapFactory,
|
|
/**
|
|
* @deprecated No longer being used. To be removed.
|
|
* @breaking-change 13.0.0
|
|
*/
|
|
_document) {
|
|
this._elementRef = _elementRef;
|
|
this._focusTrapFactory = _focusTrapFactory;
|
|
/** Previously focused element to restore focus to upon destroy when using autoCapture. */
|
|
this._previouslyFocusedElement = null;
|
|
this.focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement, true);
|
|
}
|
|
/** Whether the focus trap is active. */
|
|
get enabled() { return this.focusTrap.enabled; }
|
|
set enabled(value) { this.focusTrap.enabled = coerceBooleanProperty(value); }
|
|
/**
|
|
* Whether the directive should automatically move focus into the trapped region upon
|
|
* initialization and return focus to the previous activeElement upon destruction.
|
|
*/
|
|
get autoCapture() { return this._autoCapture; }
|
|
set autoCapture(value) { this._autoCapture = coerceBooleanProperty(value); }
|
|
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._captureFocus();
|
|
}
|
|
}
|
|
ngDoCheck() {
|
|
if (!this.focusTrap.hasAttached()) {
|
|
this.focusTrap.attachAnchors();
|
|
}
|
|
}
|
|
ngOnChanges(changes) {
|
|
const autoCaptureChange = changes['autoCapture'];
|
|
if (autoCaptureChange && !autoCaptureChange.firstChange && this.autoCapture &&
|
|
this.focusTrap.hasAttached()) {
|
|
this._captureFocus();
|
|
}
|
|
}
|
|
_captureFocus() {
|
|
this._previouslyFocusedElement = _getFocusedElementPierceShadowDom();
|
|
this.focusTrap.focusInitialElementWhenReady();
|
|
}
|
|
}
|
|
CdkTrapFocus.ɵfac = function CdkTrapFocus_Factory(t) { return new (t || CdkTrapFocus)(ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ElementRef), ɵngcc0.ɵɵdirectiveInject(FocusTrapFactory), ɵngcc0.ɵɵdirectiveInject(DOCUMENT)); };
|
|
CdkTrapFocus.ɵdir = /*@__PURE__*/ ɵngcc0.ɵɵdefineDirective({ type: CdkTrapFocus, selectors: [["", "cdkTrapFocus", ""]], inputs: { enabled: ["cdkTrapFocus", "enabled"], autoCapture: ["cdkTrapFocusAutoCapture", "autoCapture"] }, exportAs: ["cdkTrapFocus"], features: [ɵngcc0.ɵɵNgOnChangesFeature] });
|
|
CdkTrapFocus.ctorParameters = () => [
|
|
{ type: ElementRef },
|
|
{ type: FocusTrapFactory },
|
|
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
|
|
];
|
|
CdkTrapFocus.propDecorators = {
|
|
enabled: [{ type: Input, args: ['cdkTrapFocus',] }],
|
|
autoCapture: [{ type: Input, args: ['cdkTrapFocusAutoCapture',] }]
|
|
};
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(CdkTrapFocus, [{
|
|
type: Directive,
|
|
args: [{
|
|
selector: '[cdkTrapFocus]',
|
|
exportAs: 'cdkTrapFocus'
|
|
}]
|
|
}], function () { return [{ type: ɵngcc0.ElementRef }, { type: FocusTrapFactory }, { type: undefined, decorators: [{
|
|
type: Inject,
|
|
args: [DOCUMENT]
|
|
}] }]; }, { enabled: [{
|
|
type: Input,
|
|
args: ['cdkTrapFocus']
|
|
}], autoCapture: [{
|
|
type: Input,
|
|
args: ['cdkTrapFocusAutoCapture']
|
|
}] }); })();
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/**
|
|
* Class that allows for trapping focus within a DOM element.
|
|
*
|
|
* This class uses a strategy pattern that determines how it traps focus.
|
|
* See FocusTrapInertStrategy.
|
|
*/
|
|
class ConfigurableFocusTrap extends FocusTrap {
|
|
constructor(_element, _checker, _ngZone, _document, _focusTrapManager, _inertStrategy, config) {
|
|
super(_element, _checker, _ngZone, _document, config.defer);
|
|
this._focusTrapManager = _focusTrapManager;
|
|
this._inertStrategy = _inertStrategy;
|
|
this._focusTrapManager.register(this);
|
|
}
|
|
/** Whether the FocusTrap is enabled. */
|
|
get enabled() { return this._enabled; }
|
|
set enabled(value) {
|
|
this._enabled = value;
|
|
if (this._enabled) {
|
|
this._focusTrapManager.register(this);
|
|
}
|
|
else {
|
|
this._focusTrapManager.deregister(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);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/** The injection token used to specify the inert strategy. */
|
|
const FOCUS_TRAP_INERT_STRATEGY = new InjectionToken('FOCUS_TRAP_INERT_STRATEGY');
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/** IE 11 compatible closest implementation that is able to start from non-Element Nodes. */
|
|
function closest(element, selector) {
|
|
if (!(element instanceof Node)) {
|
|
return null;
|
|
}
|
|
let curr = element;
|
|
while (curr != null && !(curr instanceof Element)) {
|
|
curr = curr.parentNode;
|
|
}
|
|
return curr && (hasNativeClosest ?
|
|
curr.closest(selector) : polyfillClosest(curr, selector));
|
|
}
|
|
/** Polyfill for browsers without Element.closest. */
|
|
function polyfillClosest(element, selector) {
|
|
let curr = element;
|
|
while (curr != null && !(curr instanceof Element && matches(curr, selector))) {
|
|
curr = curr.parentNode;
|
|
}
|
|
return (curr || null);
|
|
}
|
|
const hasNativeClosest = typeof Element != 'undefined' && !!Element.prototype.closest;
|
|
/** IE 11 compatible matches implementation. */
|
|
function matches(element, selector) {
|
|
return element.matches ?
|
|
element.matches(selector) :
|
|
element['msMatchesSelector'](selector);
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/**
|
|
* Lightweight FocusTrapInertStrategy that adds a document focus event
|
|
* listener to redirect focus back inside the FocusTrap.
|
|
*/
|
|
class EventListenerFocusTrapInertStrategy {
|
|
constructor() {
|
|
/** Focus event handler. */
|
|
this._listener = null;
|
|
}
|
|
/** Adds a document event listener that keeps focus inside the FocusTrap. */
|
|
preventFocus(focusTrap) {
|
|
// Ensure there's only one listener per document
|
|
if (this._listener) {
|
|
focusTrap._document.removeEventListener('focus', this._listener, true);
|
|
}
|
|
this._listener = (e) => this._trapFocus(focusTrap, e);
|
|
focusTrap._ngZone.runOutsideAngular(() => {
|
|
focusTrap._document.addEventListener('focus', this._listener, true);
|
|
});
|
|
}
|
|
/** Removes the event listener added in preventFocus. */
|
|
allowFocus(focusTrap) {
|
|
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.
|
|
*
|
|
* This is an event listener callback. The event listener is added in runOutsideAngular,
|
|
* so all this code runs outside Angular as well.
|
|
*/
|
|
_trapFocus(focusTrap, event) {
|
|
const target = event.target;
|
|
const focusTrapRoot = focusTrap._element;
|
|
// 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 (!focusTrapRoot.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(() => {
|
|
// Check whether focus wasn't put back into the focus trap while the timeout was pending.
|
|
if (focusTrap.enabled && !focusTrapRoot.contains(focusTrap._document.activeElement)) {
|
|
focusTrap.focusFirstTabbableElement();
|
|
}
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/** Injectable that ensures only the most recently enabled FocusTrap is active. */
|
|
class FocusTrapManager {
|
|
constructor() {
|
|
// A stack of the FocusTraps on the page. Only the FocusTrap at the
|
|
// top of the stack is active.
|
|
this._focusTrapStack = [];
|
|
}
|
|
/**
|
|
* Disables the FocusTrap at the top of the stack, and then pushes
|
|
* the new FocusTrap onto the stack.
|
|
*/
|
|
register(focusTrap) {
|
|
// Dedupe focusTraps that register multiple times.
|
|
this._focusTrapStack = this._focusTrapStack.filter((ft) => ft !== focusTrap);
|
|
let stack = this._focusTrapStack;
|
|
if (stack.length) {
|
|
stack[stack.length - 1]._disable();
|
|
}
|
|
stack.push(focusTrap);
|
|
focusTrap._enable();
|
|
}
|
|
/**
|
|
* Removes the FocusTrap from the stack, and activates the
|
|
* FocusTrap that is the new top of the stack.
|
|
*/
|
|
deregister(focusTrap) {
|
|
focusTrap._disable();
|
|
const stack = this._focusTrapStack;
|
|
const i = stack.indexOf(focusTrap);
|
|
if (i !== -1) {
|
|
stack.splice(i, 1);
|
|
if (stack.length) {
|
|
stack[stack.length - 1]._enable();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
FocusTrapManager.ɵfac = function FocusTrapManager_Factory(t) { return new (t || FocusTrapManager)(); };
|
|
FocusTrapManager.ɵprov = i0.ɵɵdefineInjectable({ factory: function FocusTrapManager_Factory() { return new FocusTrapManager(); }, token: FocusTrapManager, providedIn: "root" });
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(FocusTrapManager, [{
|
|
type: Injectable,
|
|
args: [{ providedIn: 'root' }]
|
|
}], function () { return []; }, null); })();
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/** Factory that allows easy instantiation of configurable focus traps. */
|
|
class ConfigurableFocusTrapFactory {
|
|
constructor(_checker, _ngZone, _focusTrapManager, _document, _inertStrategy) {
|
|
this._checker = _checker;
|
|
this._ngZone = _ngZone;
|
|
this._focusTrapManager = _focusTrapManager;
|
|
this._document = _document;
|
|
// TODO split up the strategies into different modules, similar to DateAdapter.
|
|
this._inertStrategy = _inertStrategy || new EventListenerFocusTrapInertStrategy();
|
|
}
|
|
create(element, config = { defer: false }) {
|
|
let configObject;
|
|
if (typeof config === 'boolean') {
|
|
configObject = { defer: config };
|
|
}
|
|
else {
|
|
configObject = config;
|
|
}
|
|
return new ConfigurableFocusTrap(element, this._checker, this._ngZone, this._document, this._focusTrapManager, this._inertStrategy, configObject);
|
|
}
|
|
}
|
|
ConfigurableFocusTrapFactory.ɵfac = function ConfigurableFocusTrapFactory_Factory(t) { return new (t || ConfigurableFocusTrapFactory)(ɵngcc0.ɵɵinject(InteractivityChecker), ɵngcc0.ɵɵinject(ɵngcc0.NgZone), ɵngcc0.ɵɵinject(FocusTrapManager), ɵngcc0.ɵɵinject(DOCUMENT), ɵngcc0.ɵɵinject(FOCUS_TRAP_INERT_STRATEGY, 8)); };
|
|
ConfigurableFocusTrapFactory.ɵprov = i0.ɵɵdefineInjectable({ factory: function ConfigurableFocusTrapFactory_Factory() { return new ConfigurableFocusTrapFactory(i0.ɵɵinject(InteractivityChecker), i0.ɵɵinject(i0.NgZone), i0.ɵɵinject(FocusTrapManager), i0.ɵɵinject(i2.DOCUMENT), i0.ɵɵinject(FOCUS_TRAP_INERT_STRATEGY, 8)); }, token: ConfigurableFocusTrapFactory, providedIn: "root" });
|
|
ConfigurableFocusTrapFactory.ctorParameters = () => [
|
|
{ type: InteractivityChecker },
|
|
{ type: NgZone },
|
|
{ type: FocusTrapManager },
|
|
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
|
|
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [FOCUS_TRAP_INERT_STRATEGY,] }] }
|
|
];
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(ConfigurableFocusTrapFactory, [{
|
|
type: Injectable,
|
|
args: [{ providedIn: 'root' }]
|
|
}], function () { return [{ type: InteractivityChecker }, { type: ɵngcc0.NgZone }, { type: FocusTrapManager }, { type: undefined, decorators: [{
|
|
type: Inject,
|
|
args: [DOCUMENT]
|
|
}] }, { type: undefined, decorators: [{
|
|
type: Optional
|
|
}, {
|
|
type: Inject,
|
|
args: [FOCUS_TRAP_INERT_STRATEGY]
|
|
}] }]; }, null); })();
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/** Gets whether an event could be a faked `mousedown` event dispatched by a screen reader. */
|
|
function isFakeMousedownFromScreenReader(event) {
|
|
// Some screen readers will dispatch a fake `mousedown` event when pressing enter or space on
|
|
// a clickable element. We can distinguish these events when both `offsetX` and `offsetY` are
|
|
// zero. Note that there's an edge case where the user could click the 0x0 spot of the screen
|
|
// themselves, but that is unlikely to contain interaction elements. Historially we used to check
|
|
// `event.buttons === 0`, however that no longer works on recent versions of NVDA.
|
|
return event.offsetX === 0 && event.offsetY === 0;
|
|
}
|
|
/** Gets whether an event could be a faked `touchstart` event dispatched by a screen reader. */
|
|
function isFakeTouchstartFromScreenReader(event) {
|
|
const touch = (event.touches && event.touches[0]) ||
|
|
(event.changedTouches && event.changedTouches[0]);
|
|
// A fake `touchstart` can be distinguished from a real one by looking at the `identifier`
|
|
// which is typically >= 0 on a real device versus -1 from a screen reader. Just to be safe,
|
|
// we can also look at `radiusX` and `radiusY`. This behavior was observed against a Windows 10
|
|
// device with a touch screen running NVDA v2020.4 and Firefox 85 or Chrome 88.
|
|
return !!touch && touch.identifier === -1 && (touch.radiusX == null || touch.radiusX === 1) &&
|
|
(touch.radiusY == null || touch.radiusY === 1);
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/**
|
|
* Injectable options for the InputModalityDetector. These are shallowly merged with the default
|
|
* options.
|
|
*/
|
|
const INPUT_MODALITY_DETECTOR_OPTIONS = new InjectionToken('cdk-input-modality-detector-options');
|
|
/**
|
|
* Default options for the InputModalityDetector.
|
|
*
|
|
* Modifier keys are ignored by default (i.e. when pressed won't cause the service to detect
|
|
* keyboard input modality) for two reasons:
|
|
*
|
|
* 1. Modifier keys are commonly used with mouse to perform actions such as 'right click' or 'open
|
|
* in new tab', and are thus less representative of actual keyboard interaction.
|
|
* 2. VoiceOver triggers some keyboard events when linearly navigating with Control + Option (but
|
|
* confusingly not with Caps Lock). Thus, to have parity with other screen readers, we ignore
|
|
* these keys so as to not update the input modality.
|
|
*
|
|
* Note that we do not by default ignore the right Meta key on Safari because it has the same key
|
|
* code as the ContextMenu key on other browsers. When we switch to using event.key, we can
|
|
* distinguish between the two.
|
|
*/
|
|
const INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS = {
|
|
ignoreKeys: [ALT, CONTROL, MAC_META, META, SHIFT],
|
|
};
|
|
/**
|
|
* The amount of time needed to pass after a touchstart event in order for a subsequent mousedown
|
|
* event to be attributed as mouse and not touch.
|
|
*
|
|
* This is the value used by AngularJS Material. Through trial and error (on iPhone 6S) they found
|
|
* that a value of around 650ms seems appropriate.
|
|
*/
|
|
const TOUCH_BUFFER_MS = 650;
|
|
/**
|
|
* Event listener options that enable capturing and also mark the listener as passive if the browser
|
|
* supports it.
|
|
*/
|
|
const modalityEventListenerOptions = normalizePassiveListenerOptions({
|
|
passive: true,
|
|
capture: true,
|
|
});
|
|
/**
|
|
* Service that detects the user's input modality.
|
|
*
|
|
* This service does not update the input modality when a user navigates with a screen reader
|
|
* (e.g. linear navigation with VoiceOver, object navigation / browse mode with NVDA, virtual PC
|
|
* cursor mode with JAWS). This is in part due to technical limitations (i.e. keyboard events do not
|
|
* fire as expected in these modes) but is also arguably the correct behavior. Navigating with a
|
|
* screen reader is akin to visually scanning a page, and should not be interpreted as actual user
|
|
* input interaction.
|
|
*
|
|
* When a user is not navigating but *interacting* with a screen reader, this service attempts to
|
|
* update the input modality to keyboard, but in general this service's behavior is largely
|
|
* undefined.
|
|
*/
|
|
class InputModalityDetector {
|
|
constructor(_platform, ngZone, document, options) {
|
|
this._platform = _platform;
|
|
/**
|
|
* The most recently detected input modality event target. Is null if no input modality has been
|
|
* detected or if the associated event target is null for some unknown reason.
|
|
*/
|
|
this._mostRecentTarget = null;
|
|
/** The underlying BehaviorSubject that emits whenever an input modality is detected. */
|
|
this._modality = new BehaviorSubject(null);
|
|
/**
|
|
* The timestamp of the last touch input modality. Used to determine whether mousedown events
|
|
* should be attributed to mouse or touch.
|
|
*/
|
|
this._lastTouchMs = 0;
|
|
/**
|
|
* Handles keydown events. Must be an arrow function in order to preserve the context when it gets
|
|
* bound.
|
|
*/
|
|
this._onKeydown = (event) => {
|
|
var _a, _b;
|
|
// If this is one of the keys we should ignore, then ignore it and don't update the input
|
|
// modality to keyboard.
|
|
if ((_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.ignoreKeys) === null || _b === void 0 ? void 0 : _b.some(keyCode => keyCode === event.keyCode)) {
|
|
return;
|
|
}
|
|
this._modality.next('keyboard');
|
|
this._mostRecentTarget = _getEventTarget(event);
|
|
};
|
|
/**
|
|
* Handles mousedown events. Must be an arrow function in order to preserve the context when it
|
|
* gets bound.
|
|
*/
|
|
this._onMousedown = (event) => {
|
|
// Touches trigger both touch and mouse events, so we need to distinguish between mouse events
|
|
// that were triggered via mouse vs touch. To do so, check if the mouse event occurs closely
|
|
// after the previous touch event.
|
|
if (Date.now() - this._lastTouchMs < TOUCH_BUFFER_MS) {
|
|
return;
|
|
}
|
|
// Fake mousedown events are fired by some screen readers when controls are activated by the
|
|
// screen reader. Attribute them to keyboard input modality.
|
|
this._modality.next(isFakeMousedownFromScreenReader(event) ? 'keyboard' : 'mouse');
|
|
this._mostRecentTarget = _getEventTarget(event);
|
|
};
|
|
/**
|
|
* Handles touchstart events. Must be an arrow function in order to preserve the context when it
|
|
* gets bound.
|
|
*/
|
|
this._onTouchstart = (event) => {
|
|
// Same scenario as mentioned in _onMousedown, but on touch screen devices, fake touchstart
|
|
// events are fired. Again, attribute to keyboard input modality.
|
|
if (isFakeTouchstartFromScreenReader(event)) {
|
|
this._modality.next('keyboard');
|
|
return;
|
|
}
|
|
// Store the timestamp of this touch event, as it's used to distinguish between mouse events
|
|
// triggered via mouse vs touch.
|
|
this._lastTouchMs = Date.now();
|
|
this._modality.next('touch');
|
|
this._mostRecentTarget = _getEventTarget(event);
|
|
};
|
|
this._options = Object.assign(Object.assign({}, INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS), options);
|
|
// Skip the first emission as it's null.
|
|
this.modalityDetected = this._modality.pipe(skip(1));
|
|
this.modalityChanged = this.modalityDetected.pipe(distinctUntilChanged());
|
|
// If we're not in a browser, this service should do nothing, as there's no relevant input
|
|
// modality to detect.
|
|
if (_platform.isBrowser) {
|
|
ngZone.runOutsideAngular(() => {
|
|
document.addEventListener('keydown', this._onKeydown, modalityEventListenerOptions);
|
|
document.addEventListener('mousedown', this._onMousedown, modalityEventListenerOptions);
|
|
document.addEventListener('touchstart', this._onTouchstart, modalityEventListenerOptions);
|
|
});
|
|
}
|
|
}
|
|
/** The most recently detected input modality. */
|
|
get mostRecentModality() {
|
|
return this._modality.value;
|
|
}
|
|
ngOnDestroy() {
|
|
this._modality.complete();
|
|
if (this._platform.isBrowser) {
|
|
document.removeEventListener('keydown', this._onKeydown, modalityEventListenerOptions);
|
|
document.removeEventListener('mousedown', this._onMousedown, modalityEventListenerOptions);
|
|
document.removeEventListener('touchstart', this._onTouchstart, modalityEventListenerOptions);
|
|
}
|
|
}
|
|
}
|
|
InputModalityDetector.ɵfac = function InputModalityDetector_Factory(t) { return new (t || InputModalityDetector)(ɵngcc0.ɵɵinject(ɵngcc1.Platform), ɵngcc0.ɵɵinject(ɵngcc0.NgZone), ɵngcc0.ɵɵinject(DOCUMENT), ɵngcc0.ɵɵinject(INPUT_MODALITY_DETECTOR_OPTIONS, 8)); };
|
|
InputModalityDetector.ɵprov = i0.ɵɵdefineInjectable({ factory: function InputModalityDetector_Factory() { return new InputModalityDetector(i0.ɵɵinject(i1.Platform), i0.ɵɵinject(i0.NgZone), i0.ɵɵinject(i2.DOCUMENT), i0.ɵɵinject(INPUT_MODALITY_DETECTOR_OPTIONS, 8)); }, token: InputModalityDetector, providedIn: "root" });
|
|
InputModalityDetector.ctorParameters = () => [
|
|
{ type: Platform },
|
|
{ type: NgZone },
|
|
{ type: Document, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
|
|
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [INPUT_MODALITY_DETECTOR_OPTIONS,] }] }
|
|
];
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(InputModalityDetector, [{
|
|
type: Injectable,
|
|
args: [{ providedIn: 'root' }]
|
|
}], function () { return [{ type: ɵngcc1.Platform }, { type: ɵngcc0.NgZone }, { type: Document, decorators: [{
|
|
type: Inject,
|
|
args: [DOCUMENT]
|
|
}] }, { type: undefined, decorators: [{
|
|
type: Optional
|
|
}, {
|
|
type: Inject,
|
|
args: [INPUT_MODALITY_DETECTOR_OPTIONS]
|
|
}] }]; }, null); })();
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
const LIVE_ANNOUNCER_ELEMENT_TOKEN = new InjectionToken('liveAnnouncerElement', {
|
|
providedIn: 'root',
|
|
factory: LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY,
|
|
});
|
|
/** @docs-private */
|
|
function LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY() {
|
|
return null;
|
|
}
|
|
/** Injection token that can be used to configure the default options for the LiveAnnouncer. */
|
|
const LIVE_ANNOUNCER_DEFAULT_OPTIONS = new InjectionToken('LIVE_ANNOUNCER_DEFAULT_OPTIONS');
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
class LiveAnnouncer {
|
|
constructor(elementToken, _ngZone, _document, _defaultOptions) {
|
|
this._ngZone = _ngZone;
|
|
this._defaultOptions = _defaultOptions;
|
|
// We inject the live element and document as `any` because the constructor signature cannot
|
|
// reference browser globals (HTMLElement, Document) on non-browser environments, since having
|
|
// a class decorator causes TypeScript to preserve the constructor signature types.
|
|
this._document = _document;
|
|
this._liveElement = elementToken || this._createLiveElement();
|
|
}
|
|
announce(message, ...args) {
|
|
const defaultOptions = this._defaultOptions;
|
|
let politeness;
|
|
let duration;
|
|
if (args.length === 1 && typeof args[0] === 'number') {
|
|
duration = args[0];
|
|
}
|
|
else {
|
|
[politeness, duration] = args;
|
|
}
|
|
this.clear();
|
|
clearTimeout(this._previousTimeout);
|
|
if (!politeness) {
|
|
politeness =
|
|
(defaultOptions && defaultOptions.politeness) ? defaultOptions.politeness : 'polite';
|
|
}
|
|
if (duration == null && defaultOptions) {
|
|
duration = defaultOptions.duration;
|
|
}
|
|
// TODO: ensure changing the politeness works on all environments we support.
|
|
this._liveElement.setAttribute('aria-live', politeness);
|
|
// This 100ms timeout is necessary for some browser + screen-reader combinations:
|
|
// - Both JAWS and NVDA over IE11 will not announce anything without a non-zero timeout.
|
|
// - With Chrome and IE11 with NVDA or JAWS, a repeated (identical) message won't be read a
|
|
// second time without clearing and then using a non-zero delay.
|
|
// (using JAWS 17 at time of this writing).
|
|
return this._ngZone.runOutsideAngular(() => {
|
|
return new Promise(resolve => {
|
|
clearTimeout(this._previousTimeout);
|
|
this._previousTimeout = setTimeout(() => {
|
|
this._liveElement.textContent = message;
|
|
resolve();
|
|
if (typeof duration === 'number') {
|
|
this._previousTimeout = setTimeout(() => this.clear(), duration);
|
|
}
|
|
}, 100);
|
|
});
|
|
});
|
|
}
|
|
/**
|
|
* Clears the current text from the announcer element. Can be used to prevent
|
|
* screen readers from reading the text out again while the user is going
|
|
* through the page landmarks.
|
|
*/
|
|
clear() {
|
|
if (this._liveElement) {
|
|
this._liveElement.textContent = '';
|
|
}
|
|
}
|
|
ngOnDestroy() {
|
|
clearTimeout(this._previousTimeout);
|
|
if (this._liveElement && this._liveElement.parentNode) {
|
|
this._liveElement.parentNode.removeChild(this._liveElement);
|
|
this._liveElement = null;
|
|
}
|
|
}
|
|
_createLiveElement() {
|
|
const elementClass = 'cdk-live-announcer-element';
|
|
const previousElements = this._document.getElementsByClassName(elementClass);
|
|
const liveEl = this._document.createElement('div');
|
|
// Remove any old containers. This can happen when coming in from a server-side-rendered page.
|
|
for (let i = 0; i < previousElements.length; i++) {
|
|
previousElements[i].parentNode.removeChild(previousElements[i]);
|
|
}
|
|
liveEl.classList.add(elementClass);
|
|
liveEl.classList.add('cdk-visually-hidden');
|
|
liveEl.setAttribute('aria-atomic', 'true');
|
|
liveEl.setAttribute('aria-live', 'polite');
|
|
this._document.body.appendChild(liveEl);
|
|
return liveEl;
|
|
}
|
|
}
|
|
LiveAnnouncer.ɵfac = function LiveAnnouncer_Factory(t) { return new (t || LiveAnnouncer)(ɵngcc0.ɵɵinject(LIVE_ANNOUNCER_ELEMENT_TOKEN, 8), ɵngcc0.ɵɵinject(ɵngcc0.NgZone), ɵngcc0.ɵɵinject(DOCUMENT), ɵngcc0.ɵɵinject(LIVE_ANNOUNCER_DEFAULT_OPTIONS, 8)); };
|
|
LiveAnnouncer.ɵprov = i0.ɵɵdefineInjectable({ factory: function LiveAnnouncer_Factory() { return new LiveAnnouncer(i0.ɵɵinject(LIVE_ANNOUNCER_ELEMENT_TOKEN, 8), i0.ɵɵinject(i0.NgZone), i0.ɵɵinject(i2.DOCUMENT), i0.ɵɵinject(LIVE_ANNOUNCER_DEFAULT_OPTIONS, 8)); }, token: LiveAnnouncer, providedIn: "root" });
|
|
LiveAnnouncer.ctorParameters = () => [
|
|
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [LIVE_ANNOUNCER_ELEMENT_TOKEN,] }] },
|
|
{ type: NgZone },
|
|
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
|
|
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [LIVE_ANNOUNCER_DEFAULT_OPTIONS,] }] }
|
|
];
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(LiveAnnouncer, [{
|
|
type: Injectable,
|
|
args: [{ providedIn: 'root' }]
|
|
}], function () { return [{ type: undefined, decorators: [{
|
|
type: Optional
|
|
}, {
|
|
type: Inject,
|
|
args: [LIVE_ANNOUNCER_ELEMENT_TOKEN]
|
|
}] }, { type: ɵngcc0.NgZone }, { type: undefined, decorators: [{
|
|
type: Inject,
|
|
args: [DOCUMENT]
|
|
}] }, { type: undefined, decorators: [{
|
|
type: Optional
|
|
}, {
|
|
type: Inject,
|
|
args: [LIVE_ANNOUNCER_DEFAULT_OPTIONS]
|
|
}] }]; }, null); })();
|
|
/**
|
|
* A directive that works similarly to aria-live, but uses the LiveAnnouncer to ensure compatibility
|
|
* with a wider range of browsers and screen readers.
|
|
*/
|
|
class CdkAriaLive {
|
|
constructor(_elementRef, _liveAnnouncer, _contentObserver, _ngZone) {
|
|
this._elementRef = _elementRef;
|
|
this._liveAnnouncer = _liveAnnouncer;
|
|
this._contentObserver = _contentObserver;
|
|
this._ngZone = _ngZone;
|
|
this._politeness = 'polite';
|
|
}
|
|
/** The aria-live politeness level to use when announcing messages. */
|
|
get politeness() { return this._politeness; }
|
|
set politeness(value) {
|
|
this._politeness = value === 'off' || value === 'assertive' ? value : 'polite';
|
|
if (this._politeness === 'off') {
|
|
if (this._subscription) {
|
|
this._subscription.unsubscribe();
|
|
this._subscription = null;
|
|
}
|
|
}
|
|
else if (!this._subscription) {
|
|
this._subscription = this._ngZone.runOutsideAngular(() => {
|
|
return this._contentObserver
|
|
.observe(this._elementRef)
|
|
.subscribe(() => {
|
|
// Note that we use textContent here, rather than innerText, in order to avoid a reflow.
|
|
const elementText = this._elementRef.nativeElement.textContent;
|
|
// The `MutationObserver` fires also for attribute
|
|
// changes which we don't want to announce.
|
|
if (elementText !== this._previousAnnouncedText) {
|
|
this._liveAnnouncer.announce(elementText, this._politeness);
|
|
this._previousAnnouncedText = elementText;
|
|
}
|
|
});
|
|
});
|
|
}
|
|
}
|
|
ngOnDestroy() {
|
|
if (this._subscription) {
|
|
this._subscription.unsubscribe();
|
|
}
|
|
}
|
|
}
|
|
CdkAriaLive.ɵfac = function CdkAriaLive_Factory(t) { return new (t || CdkAriaLive)(ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ElementRef), ɵngcc0.ɵɵdirectiveInject(LiveAnnouncer), ɵngcc0.ɵɵdirectiveInject(ɵngcc2.ContentObserver), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.NgZone)); };
|
|
CdkAriaLive.ɵdir = /*@__PURE__*/ ɵngcc0.ɵɵdefineDirective({ type: CdkAriaLive, selectors: [["", "cdkAriaLive", ""]], inputs: { politeness: ["cdkAriaLive", "politeness"] }, exportAs: ["cdkAriaLive"] });
|
|
CdkAriaLive.ctorParameters = () => [
|
|
{ type: ElementRef },
|
|
{ type: LiveAnnouncer },
|
|
{ type: ContentObserver },
|
|
{ type: NgZone }
|
|
];
|
|
CdkAriaLive.propDecorators = {
|
|
politeness: [{ type: Input, args: ['cdkAriaLive',] }]
|
|
};
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(CdkAriaLive, [{
|
|
type: Directive,
|
|
args: [{
|
|
selector: '[cdkAriaLive]',
|
|
exportAs: 'cdkAriaLive'
|
|
}]
|
|
}], function () { return [{ type: ɵngcc0.ElementRef }, { type: LiveAnnouncer }, { type: ɵngcc2.ContentObserver }, { type: ɵngcc0.NgZone }]; }, { politeness: [{
|
|
type: Input,
|
|
args: ['cdkAriaLive']
|
|
}] }); })();
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/** InjectionToken for FocusMonitorOptions. */
|
|
const FOCUS_MONITOR_DEFAULT_OPTIONS = new InjectionToken('cdk-focus-monitor-default-options');
|
|
/**
|
|
* Event listener options that enable capturing and also
|
|
* mark the listener as passive if the browser supports it.
|
|
*/
|
|
const captureEventListenerOptions = normalizePassiveListenerOptions({
|
|
passive: true,
|
|
capture: true
|
|
});
|
|
/** Monitors mouse and keyboard events to determine the cause of focus events. */
|
|
class FocusMonitor {
|
|
constructor(_ngZone, _platform, _inputModalityDetector,
|
|
/** @breaking-change 11.0.0 make document required */
|
|
document, options) {
|
|
this._ngZone = _ngZone;
|
|
this._platform = _platform;
|
|
this._inputModalityDetector = _inputModalityDetector;
|
|
/** The focus origin that the next focus event is a result of. */
|
|
this._origin = null;
|
|
/** Whether the window has just been focused. */
|
|
this._windowFocused = false;
|
|
/**
|
|
* Whether the origin was determined via a touch interaction. Necessary as properly attributing
|
|
* focus events to touch interactions requires special logic.
|
|
*/
|
|
this._originFromTouchInteraction = false;
|
|
/** Map of elements being monitored to their info. */
|
|
this._elementInfo = new Map();
|
|
/** The number of elements currently being monitored. */
|
|
this._monitoredElementCount = 0;
|
|
/**
|
|
* Keeps track of the root nodes to which we've currently bound a focus/blur handler,
|
|
* as well as the number of monitored elements that they contain. We have to treat focus/blur
|
|
* handlers differently from the rest of the events, because the browser won't emit events
|
|
* to the document when focus moves inside of a shadow root.
|
|
*/
|
|
this._rootNodeFocusListenerCount = new Map();
|
|
/**
|
|
* Event listener for `focus` events on the window.
|
|
* Needs to be an arrow function in order to preserve the context when it gets bound.
|
|
*/
|
|
this._windowFocusListener = () => {
|
|
// Make a note of when the window regains focus, so we can
|
|
// restore the origin info for the focused element.
|
|
this._windowFocused = true;
|
|
this._windowFocusTimeoutId = setTimeout(() => this._windowFocused = false);
|
|
};
|
|
/** Subject for stopping our InputModalityDetector subscription. */
|
|
this._stopInputModalityDetector = new Subject();
|
|
/**
|
|
* Event listener for `focus` and 'blur' events on the document.
|
|
* Needs to be an arrow function in order to preserve the context when it gets bound.
|
|
*/
|
|
this._rootNodeFocusAndBlurListener = (event) => {
|
|
const target = _getEventTarget(event);
|
|
const handler = event.type === 'focus' ? this._onFocus : this._onBlur;
|
|
// We need to walk up the ancestor chain in order to support `checkChildren`.
|
|
for (let element = target; element; element = element.parentElement) {
|
|
handler.call(this, event, element);
|
|
}
|
|
};
|
|
this._document = document;
|
|
this._detectionMode = (options === null || options === void 0 ? void 0 : options.detectionMode) || 0 /* IMMEDIATE */;
|
|
}
|
|
monitor(element, checkChildren = false) {
|
|
const nativeElement = coerceElement(element);
|
|
// Do nothing if we're not on the browser platform or the passed in node isn't an element.
|
|
if (!this._platform.isBrowser || nativeElement.nodeType !== 1) {
|
|
return of(null);
|
|
}
|
|
// If the element is inside the shadow DOM, we need to bind our focus/blur listeners to
|
|
// the shadow root, rather than the `document`, because the browser won't emit focus events
|
|
// to the `document`, if focus is moving within the same shadow root.
|
|
const rootNode = _getShadowRoot(nativeElement) || this._getDocument();
|
|
const cachedInfo = this._elementInfo.get(nativeElement);
|
|
// Check if we're already monitoring this element.
|
|
if (cachedInfo) {
|
|
if (checkChildren) {
|
|
// TODO(COMP-318): this can be problematic, because it'll turn all non-checkChildren
|
|
// observers into ones that behave as if `checkChildren` was turned on. We need a more
|
|
// robust solution.
|
|
cachedInfo.checkChildren = true;
|
|
}
|
|
return cachedInfo.subject;
|
|
}
|
|
// Create monitored element info.
|
|
const info = {
|
|
checkChildren: checkChildren,
|
|
subject: new Subject(),
|
|
rootNode
|
|
};
|
|
this._elementInfo.set(nativeElement, info);
|
|
this._registerGlobalListeners(info);
|
|
return info.subject;
|
|
}
|
|
stopMonitoring(element) {
|
|
const nativeElement = coerceElement(element);
|
|
const elementInfo = this._elementInfo.get(nativeElement);
|
|
if (elementInfo) {
|
|
elementInfo.subject.complete();
|
|
this._setClasses(nativeElement);
|
|
this._elementInfo.delete(nativeElement);
|
|
this._removeGlobalListeners(elementInfo);
|
|
}
|
|
}
|
|
focusVia(element, origin, options) {
|
|
const nativeElement = coerceElement(element);
|
|
const focusedElement = this._getDocument().activeElement;
|
|
// If the element is focused already, calling `focus` again won't trigger the event listener
|
|
// which means that the focus classes won't be updated. If that's the case, update the classes
|
|
// directly without waiting for an event.
|
|
if (nativeElement === focusedElement) {
|
|
this._getClosestElementsInfo(nativeElement)
|
|
.forEach(([currentElement, info]) => this._originChanged(currentElement, origin, info));
|
|
}
|
|
else {
|
|
this._setOrigin(origin);
|
|
// `focus` isn't available on the server
|
|
if (typeof nativeElement.focus === 'function') {
|
|
nativeElement.focus(options);
|
|
}
|
|
}
|
|
}
|
|
ngOnDestroy() {
|
|
this._elementInfo.forEach((_info, element) => this.stopMonitoring(element));
|
|
}
|
|
/** Access injected document if available or fallback to global document reference */
|
|
_getDocument() {
|
|
return this._document || document;
|
|
}
|
|
/** Use defaultView of injected document if available or fallback to global window reference */
|
|
_getWindow() {
|
|
const doc = this._getDocument();
|
|
return doc.defaultView || window;
|
|
}
|
|
_toggleClass(element, className, shouldSet) {
|
|
if (shouldSet) {
|
|
element.classList.add(className);
|
|
}
|
|
else {
|
|
element.classList.remove(className);
|
|
}
|
|
}
|
|
_getFocusOrigin(focusEventTarget) {
|
|
if (this._origin) {
|
|
// If the origin was realized via a touch interaction, we need to perform additional checks
|
|
// to determine whether the focus origin should be attributed to touch or program.
|
|
if (this._originFromTouchInteraction) {
|
|
return this._shouldBeAttributedToTouch(focusEventTarget) ? 'touch' : 'program';
|
|
}
|
|
else {
|
|
return this._origin;
|
|
}
|
|
}
|
|
// If the window has just regained focus, we can restore the most recent origin from before the
|
|
// window blurred. Otherwise, we've reached the point where we can't identify the source of the
|
|
// focus. This typically means one of two things happened:
|
|
//
|
|
// 1) The element was programmatically focused, or
|
|
// 2) The element was focused via screen reader navigation (which generally doesn't fire
|
|
// events).
|
|
//
|
|
// Because we can't distinguish between these two cases, we default to setting `program`.
|
|
return (this._windowFocused && this._lastFocusOrigin) ? this._lastFocusOrigin : 'program';
|
|
}
|
|
/**
|
|
* Returns whether the focus event should be attributed to touch. Recall that in IMMEDIATE mode, a
|
|
* touch origin isn't immediately reset at the next tick (see _setOrigin). This means that when we
|
|
* handle a focus event following a touch interaction, we need to determine whether (1) the focus
|
|
* event was directly caused by the touch interaction or (2) the focus event was caused by a
|
|
* subsequent programmatic focus call triggered by the touch interaction.
|
|
* @param focusEventTarget The target of the focus event under examination.
|
|
*/
|
|
_shouldBeAttributedToTouch(focusEventTarget) {
|
|
// Please note that this check is not perfect. Consider the following edge case:
|
|
//
|
|
// <div #parent tabindex="0">
|
|
// <div #child tabindex="0" (click)="#parent.focus()"></div>
|
|
// </div>
|
|
//
|
|
// Suppose there is a FocusMonitor in IMMEDIATE mode attached to #parent. When the user touches
|
|
// #child, #parent is programmatically focused. This code will attribute the focus to touch
|
|
// instead of program. This is a relatively minor edge-case that can be worked around by using
|
|
// focusVia(parent, 'program') to focus #parent.
|
|
return (this._detectionMode === 1 /* EVENTUAL */) ||
|
|
!!(focusEventTarget === null || focusEventTarget === void 0 ? void 0 : focusEventTarget.contains(this._inputModalityDetector._mostRecentTarget));
|
|
}
|
|
/**
|
|
* Sets the focus classes on the element based on the given focus origin.
|
|
* @param element The element to update the classes on.
|
|
* @param origin The focus origin.
|
|
*/
|
|
_setClasses(element, origin) {
|
|
this._toggleClass(element, 'cdk-focused', !!origin);
|
|
this._toggleClass(element, 'cdk-touch-focused', origin === 'touch');
|
|
this._toggleClass(element, 'cdk-keyboard-focused', origin === 'keyboard');
|
|
this._toggleClass(element, 'cdk-mouse-focused', origin === 'mouse');
|
|
this._toggleClass(element, 'cdk-program-focused', origin === 'program');
|
|
}
|
|
/**
|
|
* Updates the focus origin. If we're using immediate detection mode, we schedule an async
|
|
* function to clear the origin at the end of a timeout. The duration of the timeout depends on
|
|
* the origin being set.
|
|
* @param origin The origin to set.
|
|
* @param isFromInteraction Whether we are setting the origin from an interaction event.
|
|
*/
|
|
_setOrigin(origin, isFromInteraction = false) {
|
|
this._ngZone.runOutsideAngular(() => {
|
|
this._origin = origin;
|
|
this._originFromTouchInteraction = (origin === 'touch') && isFromInteraction;
|
|
// If we're in IMMEDIATE mode, reset the origin at the next tick (or in `TOUCH_BUFFER_MS` ms
|
|
// for a touch event). We reset the origin at the next tick because Firefox focuses one tick
|
|
// after the interaction event. We wait `TOUCH_BUFFER_MS` ms before resetting the origin for
|
|
// a touch event because when a touch event is fired, the associated focus event isn't yet in
|
|
// the event queue. Before doing so, clear any pending timeouts.
|
|
if (this._detectionMode === 0 /* IMMEDIATE */) {
|
|
clearTimeout(this._originTimeoutId);
|
|
const ms = this._originFromTouchInteraction ? TOUCH_BUFFER_MS : 1;
|
|
this._originTimeoutId = setTimeout(() => this._origin = null, ms);
|
|
}
|
|
});
|
|
}
|
|
/**
|
|
* Handles focus events on a registered element.
|
|
* @param event The focus event.
|
|
* @param element The monitored element.
|
|
*/
|
|
_onFocus(event, element) {
|
|
// NOTE(mmalerba): We currently set the classes based on the focus origin of the most recent
|
|
// focus event affecting the monitored element. If we want to use the origin of the first event
|
|
// instead we should check for the cdk-focused class here and return if the element already has
|
|
// it. (This only matters for elements that have includesChildren = true).
|
|
// If we are not counting child-element-focus as focused, make sure that the event target is the
|
|
// monitored element itself.
|
|
const elementInfo = this._elementInfo.get(element);
|
|
const focusEventTarget = _getEventTarget(event);
|
|
if (!elementInfo || (!elementInfo.checkChildren && element !== focusEventTarget)) {
|
|
return;
|
|
}
|
|
this._originChanged(element, this._getFocusOrigin(focusEventTarget), elementInfo);
|
|
}
|
|
/**
|
|
* Handles blur events on a registered element.
|
|
* @param event The blur event.
|
|
* @param element The monitored element.
|
|
*/
|
|
_onBlur(event, element) {
|
|
// If we are counting child-element-focus as focused, make sure that we aren't just blurring in
|
|
// order to focus another child of the monitored element.
|
|
const elementInfo = this._elementInfo.get(element);
|
|
if (!elementInfo || (elementInfo.checkChildren && event.relatedTarget instanceof Node &&
|
|
element.contains(event.relatedTarget))) {
|
|
return;
|
|
}
|
|
this._setClasses(element);
|
|
this._emitOrigin(elementInfo.subject, null);
|
|
}
|
|
_emitOrigin(subject, origin) {
|
|
this._ngZone.run(() => subject.next(origin));
|
|
}
|
|
_registerGlobalListeners(elementInfo) {
|
|
if (!this._platform.isBrowser) {
|
|
return;
|
|
}
|
|
const rootNode = elementInfo.rootNode;
|
|
const rootNodeFocusListeners = this._rootNodeFocusListenerCount.get(rootNode) || 0;
|
|
if (!rootNodeFocusListeners) {
|
|
this._ngZone.runOutsideAngular(() => {
|
|
rootNode.addEventListener('focus', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
|
|
rootNode.addEventListener('blur', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
|
|
});
|
|
}
|
|
this._rootNodeFocusListenerCount.set(rootNode, rootNodeFocusListeners + 1);
|
|
// Register global listeners when first element is monitored.
|
|
if (++this._monitoredElementCount === 1) {
|
|
// Note: we listen to events in the capture phase so we
|
|
// can detect them even if the user stops propagation.
|
|
this._ngZone.runOutsideAngular(() => {
|
|
const window = this._getWindow();
|
|
window.addEventListener('focus', this._windowFocusListener);
|
|
});
|
|
// The InputModalityDetector is also just a collection of global listeners.
|
|
this._inputModalityDetector.modalityDetected
|
|
.pipe(takeUntil(this._stopInputModalityDetector))
|
|
.subscribe(modality => { this._setOrigin(modality, true /* isFromInteraction */); });
|
|
}
|
|
}
|
|
_removeGlobalListeners(elementInfo) {
|
|
const rootNode = elementInfo.rootNode;
|
|
if (this._rootNodeFocusListenerCount.has(rootNode)) {
|
|
const rootNodeFocusListeners = this._rootNodeFocusListenerCount.get(rootNode);
|
|
if (rootNodeFocusListeners > 1) {
|
|
this._rootNodeFocusListenerCount.set(rootNode, rootNodeFocusListeners - 1);
|
|
}
|
|
else {
|
|
rootNode.removeEventListener('focus', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
|
|
rootNode.removeEventListener('blur', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
|
|
this._rootNodeFocusListenerCount.delete(rootNode);
|
|
}
|
|
}
|
|
// Unregister global listeners when last element is unmonitored.
|
|
if (!--this._monitoredElementCount) {
|
|
const window = this._getWindow();
|
|
window.removeEventListener('focus', this._windowFocusListener);
|
|
// Equivalently, stop our InputModalityDetector subscription.
|
|
this._stopInputModalityDetector.next();
|
|
// Clear timeouts for all potentially pending timeouts to prevent the leaks.
|
|
clearTimeout(this._windowFocusTimeoutId);
|
|
clearTimeout(this._originTimeoutId);
|
|
}
|
|
}
|
|
/** Updates all the state on an element once its focus origin has changed. */
|
|
_originChanged(element, origin, elementInfo) {
|
|
this._setClasses(element, origin);
|
|
this._emitOrigin(elementInfo.subject, origin);
|
|
this._lastFocusOrigin = origin;
|
|
}
|
|
/**
|
|
* Collects the `MonitoredElementInfo` of a particular element and
|
|
* all of its ancestors that have enabled `checkChildren`.
|
|
* @param element Element from which to start the search.
|
|
*/
|
|
_getClosestElementsInfo(element) {
|
|
const results = [];
|
|
this._elementInfo.forEach((info, currentElement) => {
|
|
if (currentElement === element || (info.checkChildren && currentElement.contains(element))) {
|
|
results.push([currentElement, info]);
|
|
}
|
|
});
|
|
return results;
|
|
}
|
|
}
|
|
FocusMonitor.ɵfac = function FocusMonitor_Factory(t) { return new (t || FocusMonitor)(ɵngcc0.ɵɵinject(ɵngcc0.NgZone), ɵngcc0.ɵɵinject(ɵngcc1.Platform), ɵngcc0.ɵɵinject(InputModalityDetector), ɵngcc0.ɵɵinject(DOCUMENT, 8), ɵngcc0.ɵɵinject(FOCUS_MONITOR_DEFAULT_OPTIONS, 8)); };
|
|
FocusMonitor.ɵprov = i0.ɵɵdefineInjectable({ factory: function FocusMonitor_Factory() { return new FocusMonitor(i0.ɵɵinject(i0.NgZone), i0.ɵɵinject(i1.Platform), i0.ɵɵinject(InputModalityDetector), i0.ɵɵinject(i2.DOCUMENT, 8), i0.ɵɵinject(FOCUS_MONITOR_DEFAULT_OPTIONS, 8)); }, token: FocusMonitor, providedIn: "root" });
|
|
FocusMonitor.ctorParameters = () => [
|
|
{ type: NgZone },
|
|
{ type: Platform },
|
|
{ type: InputModalityDetector },
|
|
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [DOCUMENT,] }] },
|
|
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [FOCUS_MONITOR_DEFAULT_OPTIONS,] }] }
|
|
];
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(FocusMonitor, [{
|
|
type: Injectable,
|
|
args: [{ providedIn: 'root' }]
|
|
}], function () { return [{ type: ɵngcc0.NgZone }, { type: ɵngcc1.Platform }, { type: InputModalityDetector }, { type: undefined, decorators: [{
|
|
type: Optional
|
|
}, {
|
|
type: Inject,
|
|
args: [DOCUMENT]
|
|
}] }, { type: undefined, decorators: [{
|
|
type: Optional
|
|
}, {
|
|
type: Inject,
|
|
args: [FOCUS_MONITOR_DEFAULT_OPTIONS]
|
|
}] }]; }, null); })();
|
|
/**
|
|
* Directive that determines how a particular element was focused (via keyboard, mouse, touch, or
|
|
* programmatically) and adds corresponding classes to the element.
|
|
*
|
|
* There are two variants of this directive:
|
|
* 1) cdkMonitorElementFocus: does not consider an element to be focused if one of its children is
|
|
* focused.
|
|
* 2) cdkMonitorSubtreeFocus: considers an element focused if it or any of its children are focused.
|
|
*/
|
|
class CdkMonitorFocus {
|
|
constructor(_elementRef, _focusMonitor) {
|
|
this._elementRef = _elementRef;
|
|
this._focusMonitor = _focusMonitor;
|
|
this.cdkFocusChange = new EventEmitter();
|
|
}
|
|
ngAfterViewInit() {
|
|
const element = this._elementRef.nativeElement;
|
|
this._monitorSubscription = this._focusMonitor.monitor(element, element.nodeType === 1 && element.hasAttribute('cdkMonitorSubtreeFocus'))
|
|
.subscribe(origin => this.cdkFocusChange.emit(origin));
|
|
}
|
|
ngOnDestroy() {
|
|
this._focusMonitor.stopMonitoring(this._elementRef);
|
|
if (this._monitorSubscription) {
|
|
this._monitorSubscription.unsubscribe();
|
|
}
|
|
}
|
|
}
|
|
CdkMonitorFocus.ɵfac = function CdkMonitorFocus_Factory(t) { return new (t || CdkMonitorFocus)(ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ElementRef), ɵngcc0.ɵɵdirectiveInject(FocusMonitor)); };
|
|
CdkMonitorFocus.ɵdir = /*@__PURE__*/ ɵngcc0.ɵɵdefineDirective({ type: CdkMonitorFocus, selectors: [["", "cdkMonitorElementFocus", ""], ["", "cdkMonitorSubtreeFocus", ""]], outputs: { cdkFocusChange: "cdkFocusChange" } });
|
|
CdkMonitorFocus.ctorParameters = () => [
|
|
{ type: ElementRef },
|
|
{ type: FocusMonitor }
|
|
];
|
|
CdkMonitorFocus.propDecorators = {
|
|
cdkFocusChange: [{ type: Output }]
|
|
};
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(CdkMonitorFocus, [{
|
|
type: Directive,
|
|
args: [{
|
|
selector: '[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]'
|
|
}]
|
|
}], function () { return [{ type: ɵngcc0.ElementRef }, { type: FocusMonitor }]; }, { cdkFocusChange: [{
|
|
type: Output
|
|
}] }); })();
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
/** CSS class applied to the document body when in black-on-white high-contrast mode. */
|
|
const BLACK_ON_WHITE_CSS_CLASS = 'cdk-high-contrast-black-on-white';
|
|
/** CSS class applied to the document body when in white-on-black high-contrast mode. */
|
|
const WHITE_ON_BLACK_CSS_CLASS = 'cdk-high-contrast-white-on-black';
|
|
/** CSS class applied to the document body when in high-contrast mode. */
|
|
const HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS = 'cdk-high-contrast-active';
|
|
/**
|
|
* Service to determine whether the browser is currently in a high-contrast-mode environment.
|
|
*
|
|
* Microsoft Windows supports an accessibility feature called "High Contrast Mode". This mode
|
|
* changes the appearance of all applications, including web applications, to dramatically increase
|
|
* contrast.
|
|
*
|
|
* IE, Edge, and Firefox currently support this mode. Chrome does not support Windows High Contrast
|
|
* Mode. This service does not detect high-contrast mode as added by the Chrome "High Contrast"
|
|
* browser extension.
|
|
*/
|
|
class HighContrastModeDetector {
|
|
constructor(_platform, document) {
|
|
this._platform = _platform;
|
|
this._document = document;
|
|
}
|
|
/** Gets the current high-contrast-mode for the page. */
|
|
getHighContrastMode() {
|
|
if (!this._platform.isBrowser) {
|
|
return 0 /* NONE */;
|
|
}
|
|
// Create a test element with an arbitrary background-color that is neither black nor
|
|
// white; high-contrast mode will coerce the color to either black or white. Also ensure that
|
|
// appending the test element to the DOM does not affect layout by absolutely positioning it
|
|
const testElement = this._document.createElement('div');
|
|
testElement.style.backgroundColor = 'rgb(1,2,3)';
|
|
testElement.style.position = 'absolute';
|
|
this._document.body.appendChild(testElement);
|
|
// Get the computed style for the background color, collapsing spaces to normalize between
|
|
// browsers. Once we get this color, we no longer need the test element. Access the `window`
|
|
// via the document so we can fake it in tests. Note that we have extra null checks, because
|
|
// this logic will likely run during app bootstrap and throwing can break the entire app.
|
|
const documentWindow = this._document.defaultView || window;
|
|
const computedStyle = (documentWindow && documentWindow.getComputedStyle) ?
|
|
documentWindow.getComputedStyle(testElement) : null;
|
|
const computedColor = (computedStyle && computedStyle.backgroundColor || '').replace(/ /g, '');
|
|
this._document.body.removeChild(testElement);
|
|
switch (computedColor) {
|
|
case 'rgb(0,0,0)': return 2 /* WHITE_ON_BLACK */;
|
|
case 'rgb(255,255,255)': return 1 /* BLACK_ON_WHITE */;
|
|
}
|
|
return 0 /* NONE */;
|
|
}
|
|
/** Applies CSS classes indicating high-contrast mode to document body (browser-only). */
|
|
_applyBodyHighContrastModeCssClasses() {
|
|
if (!this._hasCheckedHighContrastMode && this._platform.isBrowser && this._document.body) {
|
|
const bodyClasses = this._document.body.classList;
|
|
// IE11 doesn't support `classList` operations with multiple arguments
|
|
bodyClasses.remove(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS);
|
|
bodyClasses.remove(BLACK_ON_WHITE_CSS_CLASS);
|
|
bodyClasses.remove(WHITE_ON_BLACK_CSS_CLASS);
|
|
this._hasCheckedHighContrastMode = true;
|
|
const mode = this.getHighContrastMode();
|
|
if (mode === 1 /* BLACK_ON_WHITE */) {
|
|
bodyClasses.add(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS);
|
|
bodyClasses.add(BLACK_ON_WHITE_CSS_CLASS);
|
|
}
|
|
else if (mode === 2 /* WHITE_ON_BLACK */) {
|
|
bodyClasses.add(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS);
|
|
bodyClasses.add(WHITE_ON_BLACK_CSS_CLASS);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
HighContrastModeDetector.ɵfac = function HighContrastModeDetector_Factory(t) { return new (t || HighContrastModeDetector)(ɵngcc0.ɵɵinject(ɵngcc1.Platform), ɵngcc0.ɵɵinject(DOCUMENT)); };
|
|
HighContrastModeDetector.ɵprov = i0.ɵɵdefineInjectable({ factory: function HighContrastModeDetector_Factory() { return new HighContrastModeDetector(i0.ɵɵinject(i1.Platform), i0.ɵɵinject(i2.DOCUMENT)); }, token: HighContrastModeDetector, providedIn: "root" });
|
|
HighContrastModeDetector.ctorParameters = () => [
|
|
{ type: Platform },
|
|
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
|
|
];
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(HighContrastModeDetector, [{
|
|
type: Injectable,
|
|
args: [{ providedIn: 'root' }]
|
|
}], function () { return [{ type: ɵngcc1.Platform }, { type: undefined, decorators: [{
|
|
type: Inject,
|
|
args: [DOCUMENT]
|
|
}] }]; }, null); })();
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
class A11yModule {
|
|
constructor(highContrastModeDetector) {
|
|
highContrastModeDetector._applyBodyHighContrastModeCssClasses();
|
|
}
|
|
}
|
|
A11yModule.ɵfac = function A11yModule_Factory(t) { return new (t || A11yModule)(ɵngcc0.ɵɵinject(HighContrastModeDetector)); };
|
|
A11yModule.ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: A11yModule });
|
|
A11yModule.ɵinj = /*@__PURE__*/ ɵngcc0.ɵɵdefineInjector({ imports: [[PlatformModule, ObserversModule]] });
|
|
A11yModule.ctorParameters = () => [
|
|
{ type: HighContrastModeDetector }
|
|
];
|
|
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(A11yModule, [{
|
|
type: NgModule,
|
|
args: [{
|
|
imports: [PlatformModule, ObserversModule],
|
|
declarations: [CdkAriaLive, CdkTrapFocus, CdkMonitorFocus],
|
|
exports: [CdkAriaLive, CdkTrapFocus, CdkMonitorFocus]
|
|
}]
|
|
}], function () { return [{ type: HighContrastModeDetector }]; }, null); })();
|
|
(function () { (typeof ngJitMode === "undefined" || ngJitMode) && ɵngcc0.ɵɵsetNgModuleScope(A11yModule, { declarations: function () { return [CdkAriaLive, CdkTrapFocus, CdkMonitorFocus]; }, imports: function () { return [PlatformModule, ObserversModule]; }, exports: function () { return [CdkAriaLive, CdkTrapFocus, CdkMonitorFocus]; } }); })();
|
|
|
|
/**
|
|
* @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
|
|
*/
|
|
|
|
/**
|
|
* Generated bundle index. Do not edit.
|
|
*/
|
|
|
|
export { A11yModule, ActiveDescendantKeyManager, AriaDescriber, CDK_DESCRIBEDBY_HOST_ATTRIBUTE, CDK_DESCRIBEDBY_ID_PREFIX, CdkAriaLive, CdkMonitorFocus, CdkTrapFocus, ConfigurableFocusTrap, ConfigurableFocusTrapFactory, EventListenerFocusTrapInertStrategy, FOCUS_MONITOR_DEFAULT_OPTIONS, FOCUS_TRAP_INERT_STRATEGY, FocusKeyManager, FocusMonitor, FocusTrap, FocusTrapFactory, HighContrastModeDetector, INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS, INPUT_MODALITY_DETECTOR_OPTIONS, InputModalityDetector, InteractivityChecker, IsFocusableConfig, LIVE_ANNOUNCER_DEFAULT_OPTIONS, LIVE_ANNOUNCER_ELEMENT_TOKEN, LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY, ListKeyManager, LiveAnnouncer, MESSAGES_CONTAINER_ID, isFakeMousedownFromScreenReader, isFakeTouchstartFromScreenReader, FocusTrapManager as ɵangular_material_src_cdk_a11y_a11y_a };
|
|
|
|
//# sourceMappingURL=a11y.js.map
|