@angular/cdk
Version:
Angular Material Component Development Kit
1,175 lines (1,168 loc) • 110 kB
JavaScript
import { DOCUMENT } from '@angular/common';
import * as i0 from '@angular/core';
import { Injectable, Inject, QueryList, Directive, Input, InjectionToken, Optional, EventEmitter, Output, NgModule } from '@angular/core';
import * as i1 from '@angular/cdk/platform';
import { _getFocusedElementPierceShadowDom, normalizePassiveListenerOptions, _getEventTarget, _getShadowRoot, PlatformModule } from '@angular/cdk/platform';
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$1 from '@angular/cdk/observers';
import { 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. */
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.
* @deprecated No longer being used. To be removed.
* @breaking-change 14.0.0
*/
const MESSAGES_CONTAINER_ID = 'cdk-describedby-message-container';
/**
* ID prefix used for each created message element.
* @deprecated To be turned into a private variable.
* @breaking-change 14.0.0
*/
const CDK_DESCRIBEDBY_ID_PREFIX = 'cdk-describedby-message';
/**
* Attribute given to each host element that is described by a message element.
* @deprecated To be turned into a private variable.
* @breaking-change 14.0.0
*/
const CDK_DESCRIBEDBY_HOST_ATTRIBUTE = 'cdk-describedby-host';
/** Global incremental identifier for each registered message element. */
let nextId = 0;
/**
* 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,
/**
* @deprecated To be turned into a required parameter.
* @breaking-change 14.0.0
*/
_platform) {
this._platform = _platform;
/** Map of all registered message elements that have been placed into the document. */
this._messageRegistry = new Map();
/** Container for all registered messages. */
this._messagesContainer = null;
/** Unique ID for the service. */
this._id = `${nextId++}`;
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);
this._messageRegistry.set(key, { messageElement: message, referenceCount: 0 });
}
else if (!this._messageRegistry.has(key)) {
this._createMessageElement(message, role);
}
if (!this._isElementDescribedByMessage(hostElement, key)) {
this._addMessageReference(hostElement, key);
}
}
removeDescription(hostElement, message, role) {
var _a;
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 = this._messageRegistry.get(key);
if (registeredMessage && registeredMessage.referenceCount === 0) {
this._deleteMessageElement(key);
}
}
if (((_a = this._messagesContainer) === null || _a === void 0 ? void 0 : _a.childNodes.length) === 0) {
this._messagesContainer.remove();
this._messagesContainer = null;
}
}
/** Unregisters all created message elements and removes the message container. */
ngOnDestroy() {
var _a;
const describedElements = this._document.querySelectorAll(`[${CDK_DESCRIBEDBY_HOST_ATTRIBUTE}="${this._id}"]`);
for (let i = 0; i < describedElements.length; i++) {
this._removeCdkDescribedByReferenceIds(describedElements[i]);
describedElements[i].removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);
}
(_a = this._messagesContainer) === null || _a === void 0 ? void 0 : _a.remove();
this._messagesContainer = null;
this._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();
this._messagesContainer.appendChild(messageElement);
this._messageRegistry.set(getKey(message, role), { messageElement, referenceCount: 0 });
}
/** Deletes the message element from the global messages container. */
_deleteMessageElement(key) {
var _a, _b;
(_b = (_a = this._messageRegistry.get(key)) === null || _a === void 0 ? void 0 : _a.messageElement) === null || _b === void 0 ? void 0 : _b.remove();
this._messageRegistry.delete(key);
}
/** Creates the global container for all aria-describedby messages. */
_createMessagesContainer() {
if (this._messagesContainer) {
return;
}
const containerClassName = 'cdk-describedby-message-container';
const serverContainers = this._document.querySelectorAll(`.${containerClassName}[platform="server"]`);
for (let i = 0; i < serverContainers.length; i++) {
// 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.
serverContainers[i].remove();
}
const messagesContainer = this._document.createElement('div');
// 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(containerClassName);
messagesContainer.classList.add('cdk-visually-hidden');
// @breaking-change 14.0.0 Remove null check for `_platform`.
if (this._platform && !this._platform.isBrowser) {
messagesContainer.setAttribute('platform', 'server');
}
this._document.body.appendChild(messagesContainer);
this._messagesContainer = messagesContainer;
}
/** 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 = this._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, this._id);
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 = this._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 = this._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 = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.0", ngImport: i0, type: AriaDescriber, deps: [{ token: DOCUMENT }, { token: i1.Platform }], target: i0.ɵɵFactoryTarget.Injectable });
AriaDescriber.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.2.0", ngImport: i0, type: AriaDescriber, providedIn: 'root' });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.0", ngImport: i0, type: AriaDescriber, decorators: [{
type: Injectable,
args: [{ providedIn: 'root' }]
}], ctorParameters: function () {
return [{ type: undefined, decorators: [{
type: Inject,
args: [DOCUMENT]
}] }, { type: i1.Platform }];
} });
/** 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);
}
}
}
/**
* 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 = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.0", ngImport: i0, type: InteractivityChecker, deps: [{ token: i1.Platform }], target: i0.ɵɵFactoryTarget.Injectable });
InteractivityChecker.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.2.0", ngImport: i0, type: InteractivityChecker, providedIn: 'root' });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.0", ngImport: i0, type: InteractivityChecker, decorators: [{
type: Injectable,
args: [{ providedIn: 'root' }]
}], ctorParameters: function () { return [{ type: i1.Platform }]; } });
/**
* 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');
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);
startAnchor.remove();
}
if (endAnchor) {
endAnchor.removeEventListener('focus', this.endAnchorListener);
endAnchor.remove();
}
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 focuses 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.
const markers = this._element.querySelectorAll(`[cdk-focus-region-${bound}], ` + `[cdkFocusRegion${bound}], ` + `[cdk-focus-${bound}]`);
if (typeof ngDevMode === 'undefined' || ngDevMode) {
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 ((typeof ngDevMode === 'undefined' || ngDevMode) &&
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;
}
const children = root.children;
for (let i = 0; i < children.length; i++) {
const 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.
const children = root.children;
for (let i = children.length - 1; i >= 0; i--) {
const 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(ele