[6a3a178] | 1 | import * as i2 from '@angular/common';
|
---|
| 2 | import { DOCUMENT } from '@angular/common';
|
---|
| 3 | import * as i0 from '@angular/core';
|
---|
| 4 | import { Injectable, Inject, QueryList, NgZone, Directive, ElementRef, Input, InjectionToken, Optional, EventEmitter, Output, NgModule } from '@angular/core';
|
---|
| 5 | import { Subject, Subscription, BehaviorSubject, of } from 'rxjs';
|
---|
| 6 | 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';
|
---|
| 7 | import { tap, debounceTime, filter, map, take, skip, distinctUntilChanged, takeUntil } from 'rxjs/operators';
|
---|
| 8 | import { coerceBooleanProperty, coerceElement } from '@angular/cdk/coercion';
|
---|
| 9 | import * as i1 from '@angular/cdk/platform';
|
---|
| 10 | import { Platform, _getFocusedElementPierceShadowDom, normalizePassiveListenerOptions, _getEventTarget, _getShadowRoot, PlatformModule } from '@angular/cdk/platform';
|
---|
| 11 | import { ContentObserver, ObserversModule } from '@angular/cdk/observers';
|
---|
| 12 |
|
---|
| 13 | /**
|
---|
| 14 | * @license
|
---|
| 15 | * Copyright Google LLC All Rights Reserved.
|
---|
| 16 | *
|
---|
| 17 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 18 | * found in the LICENSE file at https://angular.io/license
|
---|
| 19 | */
|
---|
| 20 | /** IDs are delimited by an empty space, as per the spec. */
|
---|
| 21 | import * as ɵngcc0 from '@angular/core';
|
---|
| 22 | import * as ɵngcc1 from '@angular/cdk/platform';
|
---|
| 23 | import * as ɵngcc2 from '@angular/cdk/observers';
|
---|
| 24 | const ID_DELIMITER = ' ';
|
---|
| 25 | /**
|
---|
| 26 | * Adds the given ID to the specified ARIA attribute on an element.
|
---|
| 27 | * Used for attributes such as aria-labelledby, aria-owns, etc.
|
---|
| 28 | */
|
---|
| 29 | function addAriaReferencedId(el, attr, id) {
|
---|
| 30 | const ids = getAriaReferenceIds(el, attr);
|
---|
| 31 | if (ids.some(existingId => existingId.trim() == id.trim())) {
|
---|
| 32 | return;
|
---|
| 33 | }
|
---|
| 34 | ids.push(id.trim());
|
---|
| 35 | el.setAttribute(attr, ids.join(ID_DELIMITER));
|
---|
| 36 | }
|
---|
| 37 | /**
|
---|
| 38 | * Removes the given ID from the specified ARIA attribute on an element.
|
---|
| 39 | * Used for attributes such as aria-labelledby, aria-owns, etc.
|
---|
| 40 | */
|
---|
| 41 | function removeAriaReferencedId(el, attr, id) {
|
---|
| 42 | const ids = getAriaReferenceIds(el, attr);
|
---|
| 43 | const filteredIds = ids.filter(val => val != id.trim());
|
---|
| 44 | if (filteredIds.length) {
|
---|
| 45 | el.setAttribute(attr, filteredIds.join(ID_DELIMITER));
|
---|
| 46 | }
|
---|
| 47 | else {
|
---|
| 48 | el.removeAttribute(attr);
|
---|
| 49 | }
|
---|
| 50 | }
|
---|
| 51 | /**
|
---|
| 52 | * Gets the list of IDs referenced by the given ARIA attribute on an element.
|
---|
| 53 | * Used for attributes such as aria-labelledby, aria-owns, etc.
|
---|
| 54 | */
|
---|
| 55 | function getAriaReferenceIds(el, attr) {
|
---|
| 56 | // Get string array of all individual ids (whitespace delimited) in the attribute value
|
---|
| 57 | return (el.getAttribute(attr) || '').match(/\S+/g) || [];
|
---|
| 58 | }
|
---|
| 59 |
|
---|
| 60 | /**
|
---|
| 61 | * @license
|
---|
| 62 | * Copyright Google LLC All Rights Reserved.
|
---|
| 63 | *
|
---|
| 64 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 65 | * found in the LICENSE file at https://angular.io/license
|
---|
| 66 | */
|
---|
| 67 | /** ID used for the body container where all messages are appended. */
|
---|
| 68 | const MESSAGES_CONTAINER_ID = 'cdk-describedby-message-container';
|
---|
| 69 | /** ID prefix used for each created message element. */
|
---|
| 70 | const CDK_DESCRIBEDBY_ID_PREFIX = 'cdk-describedby-message';
|
---|
| 71 | /** Attribute given to each host element that is described by a message element. */
|
---|
| 72 | const CDK_DESCRIBEDBY_HOST_ATTRIBUTE = 'cdk-describedby-host';
|
---|
| 73 | /** Global incremental identifier for each registered message element. */
|
---|
| 74 | let nextId = 0;
|
---|
| 75 | /** Global map of all registered message elements that have been placed into the document. */
|
---|
| 76 | const messageRegistry = new Map();
|
---|
| 77 | /** Container for all registered messages. */
|
---|
| 78 | let messagesContainer = null;
|
---|
| 79 | /**
|
---|
| 80 | * Utility that creates visually hidden elements with a message content. Useful for elements that
|
---|
| 81 | * want to use aria-describedby to further describe themselves without adding additional visual
|
---|
| 82 | * content.
|
---|
| 83 | */
|
---|
| 84 | class AriaDescriber {
|
---|
| 85 | constructor(_document) {
|
---|
| 86 | this._document = _document;
|
---|
| 87 | }
|
---|
| 88 | describe(hostElement, message, role) {
|
---|
| 89 | if (!this._canBeDescribed(hostElement, message)) {
|
---|
| 90 | return;
|
---|
| 91 | }
|
---|
| 92 | const key = getKey(message, role);
|
---|
| 93 | if (typeof message !== 'string') {
|
---|
| 94 | // We need to ensure that the element has an ID.
|
---|
| 95 | setMessageId(message);
|
---|
| 96 | messageRegistry.set(key, { messageElement: message, referenceCount: 0 });
|
---|
| 97 | }
|
---|
| 98 | else if (!messageRegistry.has(key)) {
|
---|
| 99 | this._createMessageElement(message, role);
|
---|
| 100 | }
|
---|
| 101 | if (!this._isElementDescribedByMessage(hostElement, key)) {
|
---|
| 102 | this._addMessageReference(hostElement, key);
|
---|
| 103 | }
|
---|
| 104 | }
|
---|
| 105 | removeDescription(hostElement, message, role) {
|
---|
| 106 | if (!message || !this._isElementNode(hostElement)) {
|
---|
| 107 | return;
|
---|
| 108 | }
|
---|
| 109 | const key = getKey(message, role);
|
---|
| 110 | if (this._isElementDescribedByMessage(hostElement, key)) {
|
---|
| 111 | this._removeMessageReference(hostElement, key);
|
---|
| 112 | }
|
---|
| 113 | // If the message is a string, it means that it's one that we created for the
|
---|
| 114 | // consumer so we can remove it safely, otherwise we should leave it in place.
|
---|
| 115 | if (typeof message === 'string') {
|
---|
| 116 | const registeredMessage = messageRegistry.get(key);
|
---|
| 117 | if (registeredMessage && registeredMessage.referenceCount === 0) {
|
---|
| 118 | this._deleteMessageElement(key);
|
---|
| 119 | }
|
---|
| 120 | }
|
---|
| 121 | if (messagesContainer && messagesContainer.childNodes.length === 0) {
|
---|
| 122 | this._deleteMessagesContainer();
|
---|
| 123 | }
|
---|
| 124 | }
|
---|
| 125 | /** Unregisters all created message elements and removes the message container. */
|
---|
| 126 | ngOnDestroy() {
|
---|
| 127 | const describedElements = this._document.querySelectorAll(`[${CDK_DESCRIBEDBY_HOST_ATTRIBUTE}]`);
|
---|
| 128 | for (let i = 0; i < describedElements.length; i++) {
|
---|
| 129 | this._removeCdkDescribedByReferenceIds(describedElements[i]);
|
---|
| 130 | describedElements[i].removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);
|
---|
| 131 | }
|
---|
| 132 | if (messagesContainer) {
|
---|
| 133 | this._deleteMessagesContainer();
|
---|
| 134 | }
|
---|
| 135 | messageRegistry.clear();
|
---|
| 136 | }
|
---|
| 137 | /**
|
---|
| 138 | * Creates a new element in the visually hidden message container element with the message
|
---|
| 139 | * as its content and adds it to the message registry.
|
---|
| 140 | */
|
---|
| 141 | _createMessageElement(message, role) {
|
---|
| 142 | const messageElement = this._document.createElement('div');
|
---|
| 143 | setMessageId(messageElement);
|
---|
| 144 | messageElement.textContent = message;
|
---|
| 145 | if (role) {
|
---|
| 146 | messageElement.setAttribute('role', role);
|
---|
| 147 | }
|
---|
| 148 | this._createMessagesContainer();
|
---|
| 149 | messagesContainer.appendChild(messageElement);
|
---|
| 150 | messageRegistry.set(getKey(message, role), { messageElement, referenceCount: 0 });
|
---|
| 151 | }
|
---|
| 152 | /** Deletes the message element from the global messages container. */
|
---|
| 153 | _deleteMessageElement(key) {
|
---|
| 154 | const registeredMessage = messageRegistry.get(key);
|
---|
| 155 | const messageElement = registeredMessage && registeredMessage.messageElement;
|
---|
| 156 | if (messagesContainer && messageElement) {
|
---|
| 157 | messagesContainer.removeChild(messageElement);
|
---|
| 158 | }
|
---|
| 159 | messageRegistry.delete(key);
|
---|
| 160 | }
|
---|
| 161 | /** Creates the global container for all aria-describedby messages. */
|
---|
| 162 | _createMessagesContainer() {
|
---|
| 163 | if (!messagesContainer) {
|
---|
| 164 | const preExistingContainer = this._document.getElementById(MESSAGES_CONTAINER_ID);
|
---|
| 165 | // When going from the server to the client, we may end up in a situation where there's
|
---|
| 166 | // already a container on the page, but we don't have a reference to it. Clear the
|
---|
| 167 | // old container so we don't get duplicates. Doing this, instead of emptying the previous
|
---|
| 168 | // container, should be slightly faster.
|
---|
| 169 | if (preExistingContainer && preExistingContainer.parentNode) {
|
---|
| 170 | preExistingContainer.parentNode.removeChild(preExistingContainer);
|
---|
| 171 | }
|
---|
| 172 | messagesContainer = this._document.createElement('div');
|
---|
| 173 | messagesContainer.id = MESSAGES_CONTAINER_ID;
|
---|
| 174 | // We add `visibility: hidden` in order to prevent text in this container from
|
---|
| 175 | // being searchable by the browser's Ctrl + F functionality.
|
---|
| 176 | // Screen-readers will still read the description for elements with aria-describedby even
|
---|
| 177 | // when the description element is not visible.
|
---|
| 178 | messagesContainer.style.visibility = 'hidden';
|
---|
| 179 | // Even though we use `visibility: hidden`, we still apply `cdk-visually-hidden` so that
|
---|
| 180 | // the description element doesn't impact page layout.
|
---|
| 181 | messagesContainer.classList.add('cdk-visually-hidden');
|
---|
| 182 | this._document.body.appendChild(messagesContainer);
|
---|
| 183 | }
|
---|
| 184 | }
|
---|
| 185 | /** Deletes the global messages container. */
|
---|
| 186 | _deleteMessagesContainer() {
|
---|
| 187 | if (messagesContainer && messagesContainer.parentNode) {
|
---|
| 188 | messagesContainer.parentNode.removeChild(messagesContainer);
|
---|
| 189 | messagesContainer = null;
|
---|
| 190 | }
|
---|
| 191 | }
|
---|
| 192 | /** Removes all cdk-describedby messages that are hosted through the element. */
|
---|
| 193 | _removeCdkDescribedByReferenceIds(element) {
|
---|
| 194 | // Remove all aria-describedby reference IDs that are prefixed by CDK_DESCRIBEDBY_ID_PREFIX
|
---|
| 195 | const originalReferenceIds = getAriaReferenceIds(element, 'aria-describedby')
|
---|
| 196 | .filter(id => id.indexOf(CDK_DESCRIBEDBY_ID_PREFIX) != 0);
|
---|
| 197 | element.setAttribute('aria-describedby', originalReferenceIds.join(' '));
|
---|
| 198 | }
|
---|
| 199 | /**
|
---|
| 200 | * Adds a message reference to the element using aria-describedby and increments the registered
|
---|
| 201 | * message's reference count.
|
---|
| 202 | */
|
---|
| 203 | _addMessageReference(element, key) {
|
---|
| 204 | const registeredMessage = messageRegistry.get(key);
|
---|
| 205 | // Add the aria-describedby reference and set the
|
---|
| 206 | // describedby_host attribute to mark the element.
|
---|
| 207 | addAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);
|
---|
| 208 | element.setAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE, '');
|
---|
| 209 | registeredMessage.referenceCount++;
|
---|
| 210 | }
|
---|
| 211 | /**
|
---|
| 212 | * Removes a message reference from the element using aria-describedby
|
---|
| 213 | * and decrements the registered message's reference count.
|
---|
| 214 | */
|
---|
| 215 | _removeMessageReference(element, key) {
|
---|
| 216 | const registeredMessage = messageRegistry.get(key);
|
---|
| 217 | registeredMessage.referenceCount--;
|
---|
| 218 | removeAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);
|
---|
| 219 | element.removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);
|
---|
| 220 | }
|
---|
| 221 | /** Returns true if the element has been described by the provided message ID. */
|
---|
| 222 | _isElementDescribedByMessage(element, key) {
|
---|
| 223 | const referenceIds = getAriaReferenceIds(element, 'aria-describedby');
|
---|
| 224 | const registeredMessage = messageRegistry.get(key);
|
---|
| 225 | const messageId = registeredMessage && registeredMessage.messageElement.id;
|
---|
| 226 | return !!messageId && referenceIds.indexOf(messageId) != -1;
|
---|
| 227 | }
|
---|
| 228 | /** Determines whether a message can be described on a particular element. */
|
---|
| 229 | _canBeDescribed(element, message) {
|
---|
| 230 | if (!this._isElementNode(element)) {
|
---|
| 231 | return false;
|
---|
| 232 | }
|
---|
| 233 | if (message && typeof message === 'object') {
|
---|
| 234 | // We'd have to make some assumptions about the description element's text, if the consumer
|
---|
| 235 | // passed in an element. Assume that if an element is passed in, the consumer has verified
|
---|
| 236 | // that it can be used as a description.
|
---|
| 237 | return true;
|
---|
| 238 | }
|
---|
| 239 | const trimmedMessage = message == null ? '' : `${message}`.trim();
|
---|
| 240 | const ariaLabel = element.getAttribute('aria-label');
|
---|
| 241 | // We shouldn't set descriptions if they're exactly the same as the `aria-label` of the
|
---|
| 242 | // element, because screen readers will end up reading out the same text twice in a row.
|
---|
| 243 | return trimmedMessage ? (!ariaLabel || ariaLabel.trim() !== trimmedMessage) : false;
|
---|
| 244 | }
|
---|
| 245 | /** Checks whether a node is an Element node. */
|
---|
| 246 | _isElementNode(element) {
|
---|
| 247 | return element.nodeType === this._document.ELEMENT_NODE;
|
---|
| 248 | }
|
---|
| 249 | }
|
---|
| 250 | AriaDescriber.ɵfac = function AriaDescriber_Factory(t) { return new (t || AriaDescriber)(ɵngcc0.ɵɵinject(DOCUMENT)); };
|
---|
| 251 | AriaDescriber.ɵprov = i0.ɵɵdefineInjectable({ factory: function AriaDescriber_Factory() { return new AriaDescriber(i0.ɵɵinject(i2.DOCUMENT)); }, token: AriaDescriber, providedIn: "root" });
|
---|
| 252 | AriaDescriber.ctorParameters = () => [
|
---|
| 253 | { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
|
---|
| 254 | ];
|
---|
| 255 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(AriaDescriber, [{
|
---|
| 256 | type: Injectable,
|
---|
| 257 | args: [{ providedIn: 'root' }]
|
---|
| 258 | }], function () { return [{ type: undefined, decorators: [{
|
---|
| 259 | type: Inject,
|
---|
| 260 | args: [DOCUMENT]
|
---|
| 261 | }] }]; }, null); })();
|
---|
| 262 | /** Gets a key that can be used to look messages up in the registry. */
|
---|
| 263 | function getKey(message, role) {
|
---|
| 264 | return typeof message === 'string' ? `${role || ''}/${message}` : message;
|
---|
| 265 | }
|
---|
| 266 | /** Assigns a unique ID to an element, if it doesn't have one already. */
|
---|
| 267 | function setMessageId(element) {
|
---|
| 268 | if (!element.id) {
|
---|
| 269 | element.id = `${CDK_DESCRIBEDBY_ID_PREFIX}-${nextId++}`;
|
---|
| 270 | }
|
---|
| 271 | }
|
---|
| 272 |
|
---|
| 273 | /**
|
---|
| 274 | * @license
|
---|
| 275 | * Copyright Google LLC All Rights Reserved.
|
---|
| 276 | *
|
---|
| 277 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 278 | * found in the LICENSE file at https://angular.io/license
|
---|
| 279 | */
|
---|
| 280 | /**
|
---|
| 281 | * This class manages keyboard events for selectable lists. If you pass it a query list
|
---|
| 282 | * of items, it will set the active item correctly when arrow events occur.
|
---|
| 283 | */
|
---|
| 284 | class ListKeyManager {
|
---|
| 285 | constructor(_items) {
|
---|
| 286 | this._items = _items;
|
---|
| 287 | this._activeItemIndex = -1;
|
---|
| 288 | this._activeItem = null;
|
---|
| 289 | this._wrap = false;
|
---|
| 290 | this._letterKeyStream = new Subject();
|
---|
| 291 | this._typeaheadSubscription = Subscription.EMPTY;
|
---|
| 292 | this._vertical = true;
|
---|
| 293 | this._allowedModifierKeys = [];
|
---|
| 294 | this._homeAndEnd = false;
|
---|
| 295 | /**
|
---|
| 296 | * Predicate function that can be used to check whether an item should be skipped
|
---|
| 297 | * by the key manager. By default, disabled items are skipped.
|
---|
| 298 | */
|
---|
| 299 | this._skipPredicateFn = (item) => item.disabled;
|
---|
| 300 | // Buffer for the letters that the user has pressed when the typeahead option is turned on.
|
---|
| 301 | this._pressedLetters = [];
|
---|
| 302 | /**
|
---|
| 303 | * Stream that emits any time the TAB key is pressed, so components can react
|
---|
| 304 | * when focus is shifted off of the list.
|
---|
| 305 | */
|
---|
| 306 | this.tabOut = new Subject();
|
---|
| 307 | /** Stream that emits whenever the active item of the list manager changes. */
|
---|
| 308 | this.change = new Subject();
|
---|
| 309 | // We allow for the items to be an array because, in some cases, the consumer may
|
---|
| 310 | // not have access to a QueryList of the items they want to manage (e.g. when the
|
---|
| 311 | // items aren't being collected via `ViewChildren` or `ContentChildren`).
|
---|
| 312 | if (_items instanceof QueryList) {
|
---|
| 313 | _items.changes.subscribe((newItems) => {
|
---|
| 314 | if (this._activeItem) {
|
---|
| 315 | const itemArray = newItems.toArray();
|
---|
| 316 | const newIndex = itemArray.indexOf(this._activeItem);
|
---|
| 317 | if (newIndex > -1 && newIndex !== this._activeItemIndex) {
|
---|
| 318 | this._activeItemIndex = newIndex;
|
---|
| 319 | }
|
---|
| 320 | }
|
---|
| 321 | });
|
---|
| 322 | }
|
---|
| 323 | }
|
---|
| 324 | /**
|
---|
| 325 | * Sets the predicate function that determines which items should be skipped by the
|
---|
| 326 | * list key manager.
|
---|
| 327 | * @param predicate Function that determines whether the given item should be skipped.
|
---|
| 328 | */
|
---|
| 329 | skipPredicate(predicate) {
|
---|
| 330 | this._skipPredicateFn = predicate;
|
---|
| 331 | return this;
|
---|
| 332 | }
|
---|
| 333 | /**
|
---|
| 334 | * Configures wrapping mode, which determines whether the active item will wrap to
|
---|
| 335 | * the other end of list when there are no more items in the given direction.
|
---|
| 336 | * @param shouldWrap Whether the list should wrap when reaching the end.
|
---|
| 337 | */
|
---|
| 338 | withWrap(shouldWrap = true) {
|
---|
| 339 | this._wrap = shouldWrap;
|
---|
| 340 | return this;
|
---|
| 341 | }
|
---|
| 342 | /**
|
---|
| 343 | * Configures whether the key manager should be able to move the selection vertically.
|
---|
| 344 | * @param enabled Whether vertical selection should be enabled.
|
---|
| 345 | */
|
---|
| 346 | withVerticalOrientation(enabled = true) {
|
---|
| 347 | this._vertical = enabled;
|
---|
| 348 | return this;
|
---|
| 349 | }
|
---|
| 350 | /**
|
---|
| 351 | * Configures the key manager to move the selection horizontally.
|
---|
| 352 | * Passing in `null` will disable horizontal movement.
|
---|
| 353 | * @param direction Direction in which the selection can be moved.
|
---|
| 354 | */
|
---|
| 355 | withHorizontalOrientation(direction) {
|
---|
| 356 | this._horizontal = direction;
|
---|
| 357 | return this;
|
---|
| 358 | }
|
---|
| 359 | /**
|
---|
| 360 | * Modifier keys which are allowed to be held down and whose default actions will be prevented
|
---|
| 361 | * as the user is pressing the arrow keys. Defaults to not allowing any modifier keys.
|
---|
| 362 | */
|
---|
| 363 | withAllowedModifierKeys(keys) {
|
---|
| 364 | this._allowedModifierKeys = keys;
|
---|
| 365 | return this;
|
---|
| 366 | }
|
---|
| 367 | /**
|
---|
| 368 | * Turns on typeahead mode which allows users to set the active item by typing.
|
---|
| 369 | * @param debounceInterval Time to wait after the last keystroke before setting the active item.
|
---|
| 370 | */
|
---|
| 371 | withTypeAhead(debounceInterval = 200) {
|
---|
| 372 | if ((typeof ngDevMode === 'undefined' || ngDevMode) && (this._items.length &&
|
---|
| 373 | this._items.some(item => typeof item.getLabel !== 'function'))) {
|
---|
| 374 | throw Error('ListKeyManager items in typeahead mode must implement the `getLabel` method.');
|
---|
| 375 | }
|
---|
| 376 | this._typeaheadSubscription.unsubscribe();
|
---|
| 377 | // Debounce the presses of non-navigational keys, collect the ones that correspond to letters
|
---|
| 378 | // and convert those letters back into a string. Afterwards find the first item that starts
|
---|
| 379 | // with that string and select it.
|
---|
| 380 | this._typeaheadSubscription = this._letterKeyStream.pipe(tap(letter => this._pressedLetters.push(letter)), debounceTime(debounceInterval), filter(() => this._pressedLetters.length > 0), map(() => this._pressedLetters.join(''))).subscribe(inputString => {
|
---|
| 381 | const items = this._getItemsArray();
|
---|
| 382 | // Start at 1 because we want to start searching at the item immediately
|
---|
| 383 | // following the current active item.
|
---|
| 384 | for (let i = 1; i < items.length + 1; i++) {
|
---|
| 385 | const index = (this._activeItemIndex + i) % items.length;
|
---|
| 386 | const item = items[index];
|
---|
| 387 | if (!this._skipPredicateFn(item) &&
|
---|
| 388 | item.getLabel().toUpperCase().trim().indexOf(inputString) === 0) {
|
---|
| 389 | this.setActiveItem(index);
|
---|
| 390 | break;
|
---|
| 391 | }
|
---|
| 392 | }
|
---|
| 393 | this._pressedLetters = [];
|
---|
| 394 | });
|
---|
| 395 | return this;
|
---|
| 396 | }
|
---|
| 397 | /**
|
---|
| 398 | * Configures the key manager to activate the first and last items
|
---|
| 399 | * respectively when the Home or End key is pressed.
|
---|
| 400 | * @param enabled Whether pressing the Home or End key activates the first/last item.
|
---|
| 401 | */
|
---|
| 402 | withHomeAndEnd(enabled = true) {
|
---|
| 403 | this._homeAndEnd = enabled;
|
---|
| 404 | return this;
|
---|
| 405 | }
|
---|
| 406 | setActiveItem(item) {
|
---|
| 407 | const previousActiveItem = this._activeItem;
|
---|
| 408 | this.updateActiveItem(item);
|
---|
| 409 | if (this._activeItem !== previousActiveItem) {
|
---|
| 410 | this.change.next(this._activeItemIndex);
|
---|
| 411 | }
|
---|
| 412 | }
|
---|
| 413 | /**
|
---|
| 414 | * Sets the active item depending on the key event passed in.
|
---|
| 415 | * @param event Keyboard event to be used for determining which element should be active.
|
---|
| 416 | */
|
---|
| 417 | onKeydown(event) {
|
---|
| 418 | const keyCode = event.keyCode;
|
---|
| 419 | const modifiers = ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'];
|
---|
| 420 | const isModifierAllowed = modifiers.every(modifier => {
|
---|
| 421 | return !event[modifier] || this._allowedModifierKeys.indexOf(modifier) > -1;
|
---|
| 422 | });
|
---|
| 423 | switch (keyCode) {
|
---|
| 424 | case TAB:
|
---|
| 425 | this.tabOut.next();
|
---|
| 426 | return;
|
---|
| 427 | case DOWN_ARROW:
|
---|
| 428 | if (this._vertical && isModifierAllowed) {
|
---|
| 429 | this.setNextItemActive();
|
---|
| 430 | break;
|
---|
| 431 | }
|
---|
| 432 | else {
|
---|
| 433 | return;
|
---|
| 434 | }
|
---|
| 435 | case UP_ARROW:
|
---|
| 436 | if (this._vertical && isModifierAllowed) {
|
---|
| 437 | this.setPreviousItemActive();
|
---|
| 438 | break;
|
---|
| 439 | }
|
---|
| 440 | else {
|
---|
| 441 | return;
|
---|
| 442 | }
|
---|
| 443 | case RIGHT_ARROW:
|
---|
| 444 | if (this._horizontal && isModifierAllowed) {
|
---|
| 445 | this._horizontal === 'rtl' ? this.setPreviousItemActive() : this.setNextItemActive();
|
---|
| 446 | break;
|
---|
| 447 | }
|
---|
| 448 | else {
|
---|
| 449 | return;
|
---|
| 450 | }
|
---|
| 451 | case LEFT_ARROW:
|
---|
| 452 | if (this._horizontal && isModifierAllowed) {
|
---|
| 453 | this._horizontal === 'rtl' ? this.setNextItemActive() : this.setPreviousItemActive();
|
---|
| 454 | break;
|
---|
| 455 | }
|
---|
| 456 | else {
|
---|
| 457 | return;
|
---|
| 458 | }
|
---|
| 459 | case HOME:
|
---|
| 460 | if (this._homeAndEnd && isModifierAllowed) {
|
---|
| 461 | this.setFirstItemActive();
|
---|
| 462 | break;
|
---|
| 463 | }
|
---|
| 464 | else {
|
---|
| 465 | return;
|
---|
| 466 | }
|
---|
| 467 | case END:
|
---|
| 468 | if (this._homeAndEnd && isModifierAllowed) {
|
---|
| 469 | this.setLastItemActive();
|
---|
| 470 | break;
|
---|
| 471 | }
|
---|
| 472 | else {
|
---|
| 473 | return;
|
---|
| 474 | }
|
---|
| 475 | default:
|
---|
| 476 | if (isModifierAllowed || hasModifierKey(event, 'shiftKey')) {
|
---|
| 477 | // Attempt to use the `event.key` which also maps it to the user's keyboard language,
|
---|
| 478 | // otherwise fall back to resolving alphanumeric characters via the keyCode.
|
---|
| 479 | if (event.key && event.key.length === 1) {
|
---|
| 480 | this._letterKeyStream.next(event.key.toLocaleUpperCase());
|
---|
| 481 | }
|
---|
| 482 | else if ((keyCode >= A && keyCode <= Z) || (keyCode >= ZERO && keyCode <= NINE)) {
|
---|
| 483 | this._letterKeyStream.next(String.fromCharCode(keyCode));
|
---|
| 484 | }
|
---|
| 485 | }
|
---|
| 486 | // Note that we return here, in order to avoid preventing
|
---|
| 487 | // the default action of non-navigational keys.
|
---|
| 488 | return;
|
---|
| 489 | }
|
---|
| 490 | this._pressedLetters = [];
|
---|
| 491 | event.preventDefault();
|
---|
| 492 | }
|
---|
| 493 | /** Index of the currently active item. */
|
---|
| 494 | get activeItemIndex() {
|
---|
| 495 | return this._activeItemIndex;
|
---|
| 496 | }
|
---|
| 497 | /** The active item. */
|
---|
| 498 | get activeItem() {
|
---|
| 499 | return this._activeItem;
|
---|
| 500 | }
|
---|
| 501 | /** Gets whether the user is currently typing into the manager using the typeahead feature. */
|
---|
| 502 | isTyping() {
|
---|
| 503 | return this._pressedLetters.length > 0;
|
---|
| 504 | }
|
---|
| 505 | /** Sets the active item to the first enabled item in the list. */
|
---|
| 506 | setFirstItemActive() {
|
---|
| 507 | this._setActiveItemByIndex(0, 1);
|
---|
| 508 | }
|
---|
| 509 | /** Sets the active item to the last enabled item in the list. */
|
---|
| 510 | setLastItemActive() {
|
---|
| 511 | this._setActiveItemByIndex(this._items.length - 1, -1);
|
---|
| 512 | }
|
---|
| 513 | /** Sets the active item to the next enabled item in the list. */
|
---|
| 514 | setNextItemActive() {
|
---|
| 515 | this._activeItemIndex < 0 ? this.setFirstItemActive() : this._setActiveItemByDelta(1);
|
---|
| 516 | }
|
---|
| 517 | /** Sets the active item to a previous enabled item in the list. */
|
---|
| 518 | setPreviousItemActive() {
|
---|
| 519 | this._activeItemIndex < 0 && this._wrap ? this.setLastItemActive()
|
---|
| 520 | : this._setActiveItemByDelta(-1);
|
---|
| 521 | }
|
---|
| 522 | updateActiveItem(item) {
|
---|
| 523 | const itemArray = this._getItemsArray();
|
---|
| 524 | const index = typeof item === 'number' ? item : itemArray.indexOf(item);
|
---|
| 525 | const activeItem = itemArray[index];
|
---|
| 526 | // Explicitly check for `null` and `undefined` because other falsy values are valid.
|
---|
| 527 | this._activeItem = activeItem == null ? null : activeItem;
|
---|
| 528 | this._activeItemIndex = index;
|
---|
| 529 | }
|
---|
| 530 | /**
|
---|
| 531 | * This method sets the active item, given a list of items and the delta between the
|
---|
| 532 | * currently active item and the new active item. It will calculate differently
|
---|
| 533 | * depending on whether wrap mode is turned on.
|
---|
| 534 | */
|
---|
| 535 | _setActiveItemByDelta(delta) {
|
---|
| 536 | this._wrap ? this._setActiveInWrapMode(delta) : this._setActiveInDefaultMode(delta);
|
---|
| 537 | }
|
---|
| 538 | /**
|
---|
| 539 | * Sets the active item properly given "wrap" mode. In other words, it will continue to move
|
---|
| 540 | * down the list until it finds an item that is not disabled, and it will wrap if it
|
---|
| 541 | * encounters either end of the list.
|
---|
| 542 | */
|
---|
| 543 | _setActiveInWrapMode(delta) {
|
---|
| 544 | const items = this._getItemsArray();
|
---|
| 545 | for (let i = 1; i <= items.length; i++) {
|
---|
| 546 | const index = (this._activeItemIndex + (delta * i) + items.length) % items.length;
|
---|
| 547 | const item = items[index];
|
---|
| 548 | if (!this._skipPredicateFn(item)) {
|
---|
| 549 | this.setActiveItem(index);
|
---|
| 550 | return;
|
---|
| 551 | }
|
---|
| 552 | }
|
---|
| 553 | }
|
---|
| 554 | /**
|
---|
| 555 | * Sets the active item properly given the default mode. In other words, it will
|
---|
| 556 | * continue to move down the list until it finds an item that is not disabled. If
|
---|
| 557 | * it encounters either end of the list, it will stop and not wrap.
|
---|
| 558 | */
|
---|
| 559 | _setActiveInDefaultMode(delta) {
|
---|
| 560 | this._setActiveItemByIndex(this._activeItemIndex + delta, delta);
|
---|
| 561 | }
|
---|
| 562 | /**
|
---|
| 563 | * Sets the active item to the first enabled item starting at the index specified. If the
|
---|
| 564 | * item is disabled, it will move in the fallbackDelta direction until it either
|
---|
| 565 | * finds an enabled item or encounters the end of the list.
|
---|
| 566 | */
|
---|
| 567 | _setActiveItemByIndex(index, fallbackDelta) {
|
---|
| 568 | const items = this._getItemsArray();
|
---|
| 569 | if (!items[index]) {
|
---|
| 570 | return;
|
---|
| 571 | }
|
---|
| 572 | while (this._skipPredicateFn(items[index])) {
|
---|
| 573 | index += fallbackDelta;
|
---|
| 574 | if (!items[index]) {
|
---|
| 575 | return;
|
---|
| 576 | }
|
---|
| 577 | }
|
---|
| 578 | this.setActiveItem(index);
|
---|
| 579 | }
|
---|
| 580 | /** Returns the items as an array. */
|
---|
| 581 | _getItemsArray() {
|
---|
| 582 | return this._items instanceof QueryList ? this._items.toArray() : this._items;
|
---|
| 583 | }
|
---|
| 584 | }
|
---|
| 585 |
|
---|
| 586 | /**
|
---|
| 587 | * @license
|
---|
| 588 | * Copyright Google LLC All Rights Reserved.
|
---|
| 589 | *
|
---|
| 590 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 591 | * found in the LICENSE file at https://angular.io/license
|
---|
| 592 | */
|
---|
| 593 | class ActiveDescendantKeyManager extends ListKeyManager {
|
---|
| 594 | setActiveItem(index) {
|
---|
| 595 | if (this.activeItem) {
|
---|
| 596 | this.activeItem.setInactiveStyles();
|
---|
| 597 | }
|
---|
| 598 | super.setActiveItem(index);
|
---|
| 599 | if (this.activeItem) {
|
---|
| 600 | this.activeItem.setActiveStyles();
|
---|
| 601 | }
|
---|
| 602 | }
|
---|
| 603 | }
|
---|
| 604 |
|
---|
| 605 | /**
|
---|
| 606 | * @license
|
---|
| 607 | * Copyright Google LLC All Rights Reserved.
|
---|
| 608 | *
|
---|
| 609 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 610 | * found in the LICENSE file at https://angular.io/license
|
---|
| 611 | */
|
---|
| 612 | class FocusKeyManager extends ListKeyManager {
|
---|
| 613 | constructor() {
|
---|
| 614 | super(...arguments);
|
---|
| 615 | this._origin = 'program';
|
---|
| 616 | }
|
---|
| 617 | /**
|
---|
| 618 | * Sets the focus origin that will be passed in to the items for any subsequent `focus` calls.
|
---|
| 619 | * @param origin Focus origin to be used when focusing items.
|
---|
| 620 | */
|
---|
| 621 | setFocusOrigin(origin) {
|
---|
| 622 | this._origin = origin;
|
---|
| 623 | return this;
|
---|
| 624 | }
|
---|
| 625 | setActiveItem(item) {
|
---|
| 626 | super.setActiveItem(item);
|
---|
| 627 | if (this.activeItem) {
|
---|
| 628 | this.activeItem.focus(this._origin);
|
---|
| 629 | }
|
---|
| 630 | }
|
---|
| 631 | }
|
---|
| 632 |
|
---|
| 633 | /**
|
---|
| 634 | * @license
|
---|
| 635 | * Copyright Google LLC All Rights Reserved.
|
---|
| 636 | *
|
---|
| 637 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 638 | * found in the LICENSE file at https://angular.io/license
|
---|
| 639 | */
|
---|
| 640 | /**
|
---|
| 641 | * Configuration for the isFocusable method.
|
---|
| 642 | */
|
---|
| 643 | class IsFocusableConfig {
|
---|
| 644 | constructor() {
|
---|
| 645 | /**
|
---|
| 646 | * Whether to count an element as focusable even if it is not currently visible.
|
---|
| 647 | */
|
---|
| 648 | this.ignoreVisibility = false;
|
---|
| 649 | }
|
---|
| 650 | }
|
---|
| 651 | // The InteractivityChecker leans heavily on the ally.js accessibility utilities.
|
---|
| 652 | // Methods like `isTabbable` are only covering specific edge-cases for the browsers which are
|
---|
| 653 | // supported.
|
---|
| 654 | /**
|
---|
| 655 | * Utility for checking the interactivity of an element, such as whether is is focusable or
|
---|
| 656 | * tabbable.
|
---|
| 657 | */
|
---|
| 658 | class InteractivityChecker {
|
---|
| 659 | constructor(_platform) {
|
---|
| 660 | this._platform = _platform;
|
---|
| 661 | }
|
---|
| 662 | /**
|
---|
| 663 | * Gets whether an element is disabled.
|
---|
| 664 | *
|
---|
| 665 | * @param element Element to be checked.
|
---|
| 666 | * @returns Whether the element is disabled.
|
---|
| 667 | */
|
---|
| 668 | isDisabled(element) {
|
---|
| 669 | // This does not capture some cases, such as a non-form control with a disabled attribute or
|
---|
| 670 | // a form control inside of a disabled form, but should capture the most common cases.
|
---|
| 671 | return element.hasAttribute('disabled');
|
---|
| 672 | }
|
---|
| 673 | /**
|
---|
| 674 | * Gets whether an element is visible for the purposes of interactivity.
|
---|
| 675 | *
|
---|
| 676 | * This will capture states like `display: none` and `visibility: hidden`, but not things like
|
---|
| 677 | * being clipped by an `overflow: hidden` parent or being outside the viewport.
|
---|
| 678 | *
|
---|
| 679 | * @returns Whether the element is visible.
|
---|
| 680 | */
|
---|
| 681 | isVisible(element) {
|
---|
| 682 | return hasGeometry(element) && getComputedStyle(element).visibility === 'visible';
|
---|
| 683 | }
|
---|
| 684 | /**
|
---|
| 685 | * Gets whether an element can be reached via Tab key.
|
---|
| 686 | * Assumes that the element has already been checked with isFocusable.
|
---|
| 687 | *
|
---|
| 688 | * @param element Element to be checked.
|
---|
| 689 | * @returns Whether the element is tabbable.
|
---|
| 690 | */
|
---|
| 691 | isTabbable(element) {
|
---|
| 692 | // Nothing is tabbable on the server 😎
|
---|
| 693 | if (!this._platform.isBrowser) {
|
---|
| 694 | return false;
|
---|
| 695 | }
|
---|
| 696 | const frameElement = getFrameElement(getWindow(element));
|
---|
| 697 | if (frameElement) {
|
---|
| 698 | // Frame elements inherit their tabindex onto all child elements.
|
---|
| 699 | if (getTabIndexValue(frameElement) === -1) {
|
---|
| 700 | return false;
|
---|
| 701 | }
|
---|
| 702 | // Browsers disable tabbing to an element inside of an invisible frame.
|
---|
| 703 | if (!this.isVisible(frameElement)) {
|
---|
| 704 | return false;
|
---|
| 705 | }
|
---|
| 706 | }
|
---|
| 707 | let nodeName = element.nodeName.toLowerCase();
|
---|
| 708 | let tabIndexValue = getTabIndexValue(element);
|
---|
| 709 | if (element.hasAttribute('contenteditable')) {
|
---|
| 710 | return tabIndexValue !== -1;
|
---|
| 711 | }
|
---|
| 712 | if (nodeName === 'iframe' || nodeName === 'object') {
|
---|
| 713 | // The frame or object's content may be tabbable depending on the content, but it's
|
---|
| 714 | // not possibly to reliably detect the content of the frames. We always consider such
|
---|
| 715 | // elements as non-tabbable.
|
---|
| 716 | return false;
|
---|
| 717 | }
|
---|
| 718 | // In iOS, the browser only considers some specific elements as tabbable.
|
---|
| 719 | if (this._platform.WEBKIT && this._platform.IOS && !isPotentiallyTabbableIOS(element)) {
|
---|
| 720 | return false;
|
---|
| 721 | }
|
---|
| 722 | if (nodeName === 'audio') {
|
---|
| 723 | // Audio elements without controls enabled are never tabbable, regardless
|
---|
| 724 | // of the tabindex attribute explicitly being set.
|
---|
| 725 | if (!element.hasAttribute('controls')) {
|
---|
| 726 | return false;
|
---|
| 727 | }
|
---|
| 728 | // Audio elements with controls are by default tabbable unless the
|
---|
| 729 | // tabindex attribute is set to `-1` explicitly.
|
---|
| 730 | return tabIndexValue !== -1;
|
---|
| 731 | }
|
---|
| 732 | if (nodeName === 'video') {
|
---|
| 733 | // For all video elements, if the tabindex attribute is set to `-1`, the video
|
---|
| 734 | // is not tabbable. Note: We cannot rely on the default `HTMLElement.tabIndex`
|
---|
| 735 | // property as that one is set to `-1` in Chrome, Edge and Safari v13.1. The
|
---|
| 736 | // tabindex attribute is the source of truth here.
|
---|
| 737 | if (tabIndexValue === -1) {
|
---|
| 738 | return false;
|
---|
| 739 | }
|
---|
| 740 | // If the tabindex is explicitly set, and not `-1` (as per check before), the
|
---|
| 741 | // video element is always tabbable (regardless of whether it has controls or not).
|
---|
| 742 | if (tabIndexValue !== null) {
|
---|
| 743 | return true;
|
---|
| 744 | }
|
---|
| 745 | // Otherwise (when no explicit tabindex is set), a video is only tabbable if it
|
---|
| 746 | // has controls enabled. Firefox is special as videos are always tabbable regardless
|
---|
| 747 | // of whether there are controls or not.
|
---|
| 748 | return this._platform.FIREFOX || element.hasAttribute('controls');
|
---|
| 749 | }
|
---|
| 750 | return element.tabIndex >= 0;
|
---|
| 751 | }
|
---|
| 752 | /**
|
---|
| 753 | * Gets whether an element can be focused by the user.
|
---|
| 754 | *
|
---|
| 755 | * @param element Element to be checked.
|
---|
| 756 | * @param config The config object with options to customize this method's behavior
|
---|
| 757 | * @returns Whether the element is focusable.
|
---|
| 758 | */
|
---|
| 759 | isFocusable(element, config) {
|
---|
| 760 | // Perform checks in order of left to most expensive.
|
---|
| 761 | // Again, naive approach that does not capture many edge cases and browser quirks.
|
---|
| 762 | return isPotentiallyFocusable(element) && !this.isDisabled(element) &&
|
---|
| 763 | ((config === null || config === void 0 ? void 0 : config.ignoreVisibility) || this.isVisible(element));
|
---|
| 764 | }
|
---|
| 765 | }
|
---|
| 766 | InteractivityChecker.ɵfac = function InteractivityChecker_Factory(t) { return new (t || InteractivityChecker)(ɵngcc0.ɵɵinject(ɵngcc1.Platform)); };
|
---|
| 767 | InteractivityChecker.ɵprov = i0.ɵɵdefineInjectable({ factory: function InteractivityChecker_Factory() { return new InteractivityChecker(i0.ɵɵinject(i1.Platform)); }, token: InteractivityChecker, providedIn: "root" });
|
---|
| 768 | InteractivityChecker.ctorParameters = () => [
|
---|
| 769 | { type: Platform }
|
---|
| 770 | ];
|
---|
| 771 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(InteractivityChecker, [{
|
---|
| 772 | type: Injectable,
|
---|
| 773 | args: [{ providedIn: 'root' }]
|
---|
| 774 | }], function () { return [{ type: ɵngcc1.Platform }]; }, null); })();
|
---|
| 775 | /**
|
---|
| 776 | * Returns the frame element from a window object. Since browsers like MS Edge throw errors if
|
---|
| 777 | * the frameElement property is being accessed from a different host address, this property
|
---|
| 778 | * should be accessed carefully.
|
---|
| 779 | */
|
---|
| 780 | function getFrameElement(window) {
|
---|
| 781 | try {
|
---|
| 782 | return window.frameElement;
|
---|
| 783 | }
|
---|
| 784 | catch (_a) {
|
---|
| 785 | return null;
|
---|
| 786 | }
|
---|
| 787 | }
|
---|
| 788 | /** Checks whether the specified element has any geometry / rectangles. */
|
---|
| 789 | function hasGeometry(element) {
|
---|
| 790 | // Use logic from jQuery to check for an invisible element.
|
---|
| 791 | // See https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js#L12
|
---|
| 792 | return !!(element.offsetWidth || element.offsetHeight ||
|
---|
| 793 | (typeof element.getClientRects === 'function' && element.getClientRects().length));
|
---|
| 794 | }
|
---|
| 795 | /** Gets whether an element's */
|
---|
| 796 | function isNativeFormElement(element) {
|
---|
| 797 | let nodeName = element.nodeName.toLowerCase();
|
---|
| 798 | return nodeName === 'input' ||
|
---|
| 799 | nodeName === 'select' ||
|
---|
| 800 | nodeName === 'button' ||
|
---|
| 801 | nodeName === 'textarea';
|
---|
| 802 | }
|
---|
| 803 | /** Gets whether an element is an `<input type="hidden">`. */
|
---|
| 804 | function isHiddenInput(element) {
|
---|
| 805 | return isInputElement(element) && element.type == 'hidden';
|
---|
| 806 | }
|
---|
| 807 | /** Gets whether an element is an anchor that has an href attribute. */
|
---|
| 808 | function isAnchorWithHref(element) {
|
---|
| 809 | return isAnchorElement(element) && element.hasAttribute('href');
|
---|
| 810 | }
|
---|
| 811 | /** Gets whether an element is an input element. */
|
---|
| 812 | function isInputElement(element) {
|
---|
| 813 | return element.nodeName.toLowerCase() == 'input';
|
---|
| 814 | }
|
---|
| 815 | /** Gets whether an element is an anchor element. */
|
---|
| 816 | function isAnchorElement(element) {
|
---|
| 817 | return element.nodeName.toLowerCase() == 'a';
|
---|
| 818 | }
|
---|
| 819 | /** Gets whether an element has a valid tabindex. */
|
---|
| 820 | function hasValidTabIndex(element) {
|
---|
| 821 | if (!element.hasAttribute('tabindex') || element.tabIndex === undefined) {
|
---|
| 822 | return false;
|
---|
| 823 | }
|
---|
| 824 | let tabIndex = element.getAttribute('tabindex');
|
---|
| 825 | // IE11 parses tabindex="" as the value "-32768"
|
---|
| 826 | if (tabIndex == '-32768') {
|
---|
| 827 | return false;
|
---|
| 828 | }
|
---|
| 829 | return !!(tabIndex && !isNaN(parseInt(tabIndex, 10)));
|
---|
| 830 | }
|
---|
| 831 | /**
|
---|
| 832 | * Returns the parsed tabindex from the element attributes instead of returning the
|
---|
| 833 | * evaluated tabindex from the browsers defaults.
|
---|
| 834 | */
|
---|
| 835 | function getTabIndexValue(element) {
|
---|
| 836 | if (!hasValidTabIndex(element)) {
|
---|
| 837 | return null;
|
---|
| 838 | }
|
---|
| 839 | // See browser issue in Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=1128054
|
---|
| 840 | const tabIndex = parseInt(element.getAttribute('tabindex') || '', 10);
|
---|
| 841 | return isNaN(tabIndex) ? -1 : tabIndex;
|
---|
| 842 | }
|
---|
| 843 | /** Checks whether the specified element is potentially tabbable on iOS */
|
---|
| 844 | function isPotentiallyTabbableIOS(element) {
|
---|
| 845 | let nodeName = element.nodeName.toLowerCase();
|
---|
| 846 | let inputType = nodeName === 'input' && element.type;
|
---|
| 847 | return inputType === 'text'
|
---|
| 848 | || inputType === 'password'
|
---|
| 849 | || nodeName === 'select'
|
---|
| 850 | || nodeName === 'textarea';
|
---|
| 851 | }
|
---|
| 852 | /**
|
---|
| 853 | * Gets whether an element is potentially focusable without taking current visible/disabled state
|
---|
| 854 | * into account.
|
---|
| 855 | */
|
---|
| 856 | function isPotentiallyFocusable(element) {
|
---|
| 857 | // Inputs are potentially focusable *unless* they're type="hidden".
|
---|
| 858 | if (isHiddenInput(element)) {
|
---|
| 859 | return false;
|
---|
| 860 | }
|
---|
| 861 | return isNativeFormElement(element) ||
|
---|
| 862 | isAnchorWithHref(element) ||
|
---|
| 863 | element.hasAttribute('contenteditable') ||
|
---|
| 864 | hasValidTabIndex(element);
|
---|
| 865 | }
|
---|
| 866 | /** Gets the parent window of a DOM node with regards of being inside of an iframe. */
|
---|
| 867 | function getWindow(node) {
|
---|
| 868 | // ownerDocument is null if `node` itself *is* a document.
|
---|
| 869 | return node.ownerDocument && node.ownerDocument.defaultView || window;
|
---|
| 870 | }
|
---|
| 871 |
|
---|
| 872 | /**
|
---|
| 873 | * @license
|
---|
| 874 | * Copyright Google LLC All Rights Reserved.
|
---|
| 875 | *
|
---|
| 876 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 877 | * found in the LICENSE file at https://angular.io/license
|
---|
| 878 | */
|
---|
| 879 | /**
|
---|
| 880 | * Class that allows for trapping focus within a DOM element.
|
---|
| 881 | *
|
---|
| 882 | * This class currently uses a relatively simple approach to focus trapping.
|
---|
| 883 | * It assumes that the tab order is the same as DOM order, which is not necessarily true.
|
---|
| 884 | * Things like `tabIndex > 0`, flex `order`, and shadow roots can cause the two to be misaligned.
|
---|
| 885 | *
|
---|
| 886 | * @deprecated Use `ConfigurableFocusTrap` instead.
|
---|
| 887 | * @breaking-change 11.0.0
|
---|
| 888 | */
|
---|
| 889 | class FocusTrap {
|
---|
| 890 | constructor(_element, _checker, _ngZone, _document, deferAnchors = false) {
|
---|
| 891 | this._element = _element;
|
---|
| 892 | this._checker = _checker;
|
---|
| 893 | this._ngZone = _ngZone;
|
---|
| 894 | this._document = _document;
|
---|
| 895 | this._hasAttached = false;
|
---|
| 896 | // Event listeners for the anchors. Need to be regular functions so that we can unbind them later.
|
---|
| 897 | this.startAnchorListener = () => this.focusLastTabbableElement();
|
---|
| 898 | this.endAnchorListener = () => this.focusFirstTabbableElement();
|
---|
| 899 | this._enabled = true;
|
---|
| 900 | if (!deferAnchors) {
|
---|
| 901 | this.attachAnchors();
|
---|
| 902 | }
|
---|
| 903 | }
|
---|
| 904 | /** Whether the focus trap is active. */
|
---|
| 905 | get enabled() { return this._enabled; }
|
---|
| 906 | set enabled(value) {
|
---|
| 907 | this._enabled = value;
|
---|
| 908 | if (this._startAnchor && this._endAnchor) {
|
---|
| 909 | this._toggleAnchorTabIndex(value, this._startAnchor);
|
---|
| 910 | this._toggleAnchorTabIndex(value, this._endAnchor);
|
---|
| 911 | }
|
---|
| 912 | }
|
---|
| 913 | /** Destroys the focus trap by cleaning up the anchors. */
|
---|
| 914 | destroy() {
|
---|
| 915 | const startAnchor = this._startAnchor;
|
---|
| 916 | const endAnchor = this._endAnchor;
|
---|
| 917 | if (startAnchor) {
|
---|
| 918 | startAnchor.removeEventListener('focus', this.startAnchorListener);
|
---|
| 919 | if (startAnchor.parentNode) {
|
---|
| 920 | startAnchor.parentNode.removeChild(startAnchor);
|
---|
| 921 | }
|
---|
| 922 | }
|
---|
| 923 | if (endAnchor) {
|
---|
| 924 | endAnchor.removeEventListener('focus', this.endAnchorListener);
|
---|
| 925 | if (endAnchor.parentNode) {
|
---|
| 926 | endAnchor.parentNode.removeChild(endAnchor);
|
---|
| 927 | }
|
---|
| 928 | }
|
---|
| 929 | this._startAnchor = this._endAnchor = null;
|
---|
| 930 | this._hasAttached = false;
|
---|
| 931 | }
|
---|
| 932 | /**
|
---|
| 933 | * Inserts the anchors into the DOM. This is usually done automatically
|
---|
| 934 | * in the constructor, but can be deferred for cases like directives with `*ngIf`.
|
---|
| 935 | * @returns Whether the focus trap managed to attach successfully. This may not be the case
|
---|
| 936 | * if the target element isn't currently in the DOM.
|
---|
| 937 | */
|
---|
| 938 | attachAnchors() {
|
---|
| 939 | // If we're not on the browser, there can be no focus to trap.
|
---|
| 940 | if (this._hasAttached) {
|
---|
| 941 | return true;
|
---|
| 942 | }
|
---|
| 943 | this._ngZone.runOutsideAngular(() => {
|
---|
| 944 | if (!this._startAnchor) {
|
---|
| 945 | this._startAnchor = this._createAnchor();
|
---|
| 946 | this._startAnchor.addEventListener('focus', this.startAnchorListener);
|
---|
| 947 | }
|
---|
| 948 | if (!this._endAnchor) {
|
---|
| 949 | this._endAnchor = this._createAnchor();
|
---|
| 950 | this._endAnchor.addEventListener('focus', this.endAnchorListener);
|
---|
| 951 | }
|
---|
| 952 | });
|
---|
| 953 | if (this._element.parentNode) {
|
---|
| 954 | this._element.parentNode.insertBefore(this._startAnchor, this._element);
|
---|
| 955 | this._element.parentNode.insertBefore(this._endAnchor, this._element.nextSibling);
|
---|
| 956 | this._hasAttached = true;
|
---|
| 957 | }
|
---|
| 958 | return this._hasAttached;
|
---|
| 959 | }
|
---|
| 960 | /**
|
---|
| 961 | * Waits for the zone to stabilize, then either focuses the first element that the
|
---|
| 962 | * user specified, or the first tabbable element.
|
---|
| 963 | * @returns Returns a promise that resolves with a boolean, depending
|
---|
| 964 | * on whether focus was moved successfully.
|
---|
| 965 | */
|
---|
| 966 | focusInitialElementWhenReady(options) {
|
---|
| 967 | return new Promise(resolve => {
|
---|
| 968 | this._executeOnStable(() => resolve(this.focusInitialElement(options)));
|
---|
| 969 | });
|
---|
| 970 | }
|
---|
| 971 | /**
|
---|
| 972 | * Waits for the zone to stabilize, then focuses
|
---|
| 973 | * the first tabbable element within the focus trap region.
|
---|
| 974 | * @returns Returns a promise that resolves with a boolean, depending
|
---|
| 975 | * on whether focus was moved successfully.
|
---|
| 976 | */
|
---|
| 977 | focusFirstTabbableElementWhenReady(options) {
|
---|
| 978 | return new Promise(resolve => {
|
---|
| 979 | this._executeOnStable(() => resolve(this.focusFirstTabbableElement(options)));
|
---|
| 980 | });
|
---|
| 981 | }
|
---|
| 982 | /**
|
---|
| 983 | * Waits for the zone to stabilize, then focuses
|
---|
| 984 | * the last tabbable element within the focus trap region.
|
---|
| 985 | * @returns Returns a promise that resolves with a boolean, depending
|
---|
| 986 | * on whether focus was moved successfully.
|
---|
| 987 | */
|
---|
| 988 | focusLastTabbableElementWhenReady(options) {
|
---|
| 989 | return new Promise(resolve => {
|
---|
| 990 | this._executeOnStable(() => resolve(this.focusLastTabbableElement(options)));
|
---|
| 991 | });
|
---|
| 992 | }
|
---|
| 993 | /**
|
---|
| 994 | * Get the specified boundary element of the trapped region.
|
---|
| 995 | * @param bound The boundary to get (start or end of trapped region).
|
---|
| 996 | * @returns The boundary element.
|
---|
| 997 | */
|
---|
| 998 | _getRegionBoundary(bound) {
|
---|
| 999 | // Contains the deprecated version of selector, for temporary backwards comparability.
|
---|
| 1000 | let markers = this._element.querySelectorAll(`[cdk-focus-region-${bound}], ` +
|
---|
| 1001 | `[cdkFocusRegion${bound}], ` +
|
---|
| 1002 | `[cdk-focus-${bound}]`);
|
---|
| 1003 | for (let i = 0; i < markers.length; i++) {
|
---|
| 1004 | // @breaking-change 8.0.0
|
---|
| 1005 | if (markers[i].hasAttribute(`cdk-focus-${bound}`)) {
|
---|
| 1006 | console.warn(`Found use of deprecated attribute 'cdk-focus-${bound}', ` +
|
---|
| 1007 | `use 'cdkFocusRegion${bound}' instead. The deprecated ` +
|
---|
| 1008 | `attribute will be removed in 8.0.0.`, markers[i]);
|
---|
| 1009 | }
|
---|
| 1010 | else if (markers[i].hasAttribute(`cdk-focus-region-${bound}`)) {
|
---|
| 1011 | console.warn(`Found use of deprecated attribute 'cdk-focus-region-${bound}', ` +
|
---|
| 1012 | `use 'cdkFocusRegion${bound}' instead. The deprecated attribute ` +
|
---|
| 1013 | `will be removed in 8.0.0.`, markers[i]);
|
---|
| 1014 | }
|
---|
| 1015 | }
|
---|
| 1016 | if (bound == 'start') {
|
---|
| 1017 | return markers.length ? markers[0] : this._getFirstTabbableElement(this._element);
|
---|
| 1018 | }
|
---|
| 1019 | return markers.length ?
|
---|
| 1020 | markers[markers.length - 1] : this._getLastTabbableElement(this._element);
|
---|
| 1021 | }
|
---|
| 1022 | /**
|
---|
| 1023 | * Focuses the element that should be focused when the focus trap is initialized.
|
---|
| 1024 | * @returns Whether focus was moved successfully.
|
---|
| 1025 | */
|
---|
| 1026 | focusInitialElement(options) {
|
---|
| 1027 | // Contains the deprecated version of selector, for temporary backwards comparability.
|
---|
| 1028 | const redirectToElement = this._element.querySelector(`[cdk-focus-initial], ` +
|
---|
| 1029 | `[cdkFocusInitial]`);
|
---|
| 1030 | if (redirectToElement) {
|
---|
| 1031 | // @breaking-change 8.0.0
|
---|
| 1032 | if (redirectToElement.hasAttribute(`cdk-focus-initial`)) {
|
---|
| 1033 | console.warn(`Found use of deprecated attribute 'cdk-focus-initial', ` +
|
---|
| 1034 | `use 'cdkFocusInitial' instead. The deprecated attribute ` +
|
---|
| 1035 | `will be removed in 8.0.0`, redirectToElement);
|
---|
| 1036 | }
|
---|
| 1037 | // Warn the consumer if the element they've pointed to
|
---|
| 1038 | // isn't focusable, when not in production mode.
|
---|
| 1039 | if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
|
---|
| 1040 | !this._checker.isFocusable(redirectToElement)) {
|
---|
| 1041 | console.warn(`Element matching '[cdkFocusInitial]' is not focusable.`, redirectToElement);
|
---|
| 1042 | }
|
---|
| 1043 | if (!this._checker.isFocusable(redirectToElement)) {
|
---|
| 1044 | const focusableChild = this._getFirstTabbableElement(redirectToElement);
|
---|
| 1045 | focusableChild === null || focusableChild === void 0 ? void 0 : focusableChild.focus(options);
|
---|
| 1046 | return !!focusableChild;
|
---|
| 1047 | }
|
---|
| 1048 | redirectToElement.focus(options);
|
---|
| 1049 | return true;
|
---|
| 1050 | }
|
---|
| 1051 | return this.focusFirstTabbableElement(options);
|
---|
| 1052 | }
|
---|
| 1053 | /**
|
---|
| 1054 | * Focuses the first tabbable element within the focus trap region.
|
---|
| 1055 | * @returns Whether focus was moved successfully.
|
---|
| 1056 | */
|
---|
| 1057 | focusFirstTabbableElement(options) {
|
---|
| 1058 | const redirectToElement = this._getRegionBoundary('start');
|
---|
| 1059 | if (redirectToElement) {
|
---|
| 1060 | redirectToElement.focus(options);
|
---|
| 1061 | }
|
---|
| 1062 | return !!redirectToElement;
|
---|
| 1063 | }
|
---|
| 1064 | /**
|
---|
| 1065 | * Focuses the last tabbable element within the focus trap region.
|
---|
| 1066 | * @returns Whether focus was moved successfully.
|
---|
| 1067 | */
|
---|
| 1068 | focusLastTabbableElement(options) {
|
---|
| 1069 | const redirectToElement = this._getRegionBoundary('end');
|
---|
| 1070 | if (redirectToElement) {
|
---|
| 1071 | redirectToElement.focus(options);
|
---|
| 1072 | }
|
---|
| 1073 | return !!redirectToElement;
|
---|
| 1074 | }
|
---|
| 1075 | /**
|
---|
| 1076 | * Checks whether the focus trap has successfully been attached.
|
---|
| 1077 | */
|
---|
| 1078 | hasAttached() {
|
---|
| 1079 | return this._hasAttached;
|
---|
| 1080 | }
|
---|
| 1081 | /** Get the first tabbable element from a DOM subtree (inclusive). */
|
---|
| 1082 | _getFirstTabbableElement(root) {
|
---|
| 1083 | if (this._checker.isFocusable(root) && this._checker.isTabbable(root)) {
|
---|
| 1084 | return root;
|
---|
| 1085 | }
|
---|
| 1086 | // Iterate in DOM order. Note that IE doesn't have `children` for SVG so we fall
|
---|
| 1087 | // back to `childNodes` which includes text nodes, comments etc.
|
---|
| 1088 | let children = root.children || root.childNodes;
|
---|
| 1089 | for (let i = 0; i < children.length; i++) {
|
---|
| 1090 | let tabbableChild = children[i].nodeType === this._document.ELEMENT_NODE ?
|
---|
| 1091 | this._getFirstTabbableElement(children[i]) :
|
---|
| 1092 | null;
|
---|
| 1093 | if (tabbableChild) {
|
---|
| 1094 | return tabbableChild;
|
---|
| 1095 | }
|
---|
| 1096 | }
|
---|
| 1097 | return null;
|
---|
| 1098 | }
|
---|
| 1099 | /** Get the last tabbable element from a DOM subtree (inclusive). */
|
---|
| 1100 | _getLastTabbableElement(root) {
|
---|
| 1101 | if (this._checker.isFocusable(root) && this._checker.isTabbable(root)) {
|
---|
| 1102 | return root;
|
---|
| 1103 | }
|
---|
| 1104 | // Iterate in reverse DOM order.
|
---|
| 1105 | let children = root.children || root.childNodes;
|
---|
| 1106 | for (let i = children.length - 1; i >= 0; i--) {
|
---|
| 1107 | let tabbableChild = children[i].nodeType === this._document.ELEMENT_NODE ?
|
---|
| 1108 | this._getLastTabbableElement(children[i]) :
|
---|
| 1109 | null;
|
---|
| 1110 | if (tabbableChild) {
|
---|
| 1111 | return tabbableChild;
|
---|
| 1112 | }
|
---|
| 1113 | }
|
---|
| 1114 | return null;
|
---|
| 1115 | }
|
---|
| 1116 | /** Creates an anchor element. */
|
---|
| 1117 | _createAnchor() {
|
---|
| 1118 | const anchor = this._document.createElement('div');
|
---|
| 1119 | this._toggleAnchorTabIndex(this._enabled, anchor);
|
---|
| 1120 | anchor.classList.add('cdk-visually-hidden');
|
---|
| 1121 | anchor.classList.add('cdk-focus-trap-anchor');
|
---|
| 1122 | anchor.setAttribute('aria-hidden', 'true');
|
---|
| 1123 | return anchor;
|
---|
| 1124 | }
|
---|
| 1125 | /**
|
---|
| 1126 | * Toggles the `tabindex` of an anchor, based on the enabled state of the focus trap.
|
---|
| 1127 | * @param isEnabled Whether the focus trap is enabled.
|
---|
| 1128 | * @param anchor Anchor on which to toggle the tabindex.
|
---|
| 1129 | */
|
---|
| 1130 | _toggleAnchorTabIndex(isEnabled, anchor) {
|
---|
| 1131 | // Remove the tabindex completely, rather than setting it to -1, because if the
|
---|
| 1132 | // element has a tabindex, the user might still hit it when navigating with the arrow keys.
|
---|
| 1133 | isEnabled ? anchor.setAttribute('tabindex', '0') : anchor.removeAttribute('tabindex');
|
---|
| 1134 | }
|
---|
| 1135 | /**
|
---|
| 1136 | * Toggles the`tabindex` of both anchors to either trap Tab focus or allow it to escape.
|
---|
| 1137 | * @param enabled: Whether the anchors should trap Tab.
|
---|
| 1138 | */
|
---|
| 1139 | toggleAnchors(enabled) {
|
---|
| 1140 | if (this._startAnchor && this._endAnchor) {
|
---|
| 1141 | this._toggleAnchorTabIndex(enabled, this._startAnchor);
|
---|
| 1142 | this._toggleAnchorTabIndex(enabled, this._endAnchor);
|
---|
| 1143 | }
|
---|
| 1144 | }
|
---|
| 1145 | /** Executes a function when the zone is stable. */
|
---|
| 1146 | _executeOnStable(fn) {
|
---|
| 1147 | if (this._ngZone.isStable) {
|
---|
| 1148 | fn();
|
---|
| 1149 | }
|
---|
| 1150 | else {
|
---|
| 1151 | this._ngZone.onStable.pipe(take(1)).subscribe(fn);
|
---|
| 1152 | }
|
---|
| 1153 | }
|
---|
| 1154 | }
|
---|
| 1155 | /**
|
---|
| 1156 | * Factory that allows easy instantiation of focus traps.
|
---|
| 1157 | * @deprecated Use `ConfigurableFocusTrapFactory` instead.
|
---|
| 1158 | * @breaking-change 11.0.0
|
---|
| 1159 | */
|
---|
| 1160 | class FocusTrapFactory {
|
---|
| 1161 | constructor(_checker, _ngZone, _document) {
|
---|
| 1162 | this._checker = _checker;
|
---|
| 1163 | this._ngZone = _ngZone;
|
---|
| 1164 | this._document = _document;
|
---|
| 1165 | }
|
---|
| 1166 | /**
|
---|
| 1167 | * Creates a focus-trapped region around the given element.
|
---|
| 1168 | * @param element The element around which focus will be trapped.
|
---|
| 1169 | * @param deferCaptureElements Defers the creation of focus-capturing elements to be done
|
---|
| 1170 | * manually by the user.
|
---|
| 1171 | * @returns The created focus trap instance.
|
---|
| 1172 | */
|
---|
| 1173 | create(element, deferCaptureElements = false) {
|
---|
| 1174 | return new FocusTrap(element, this._checker, this._ngZone, this._document, deferCaptureElements);
|
---|
| 1175 | }
|
---|
| 1176 | }
|
---|
| 1177 | FocusTrapFactory.ɵfac = function FocusTrapFactory_Factory(t) { return new (t || FocusTrapFactory)(ɵngcc0.ɵɵinject(InteractivityChecker), ɵngcc0.ɵɵinject(ɵngcc0.NgZone), ɵngcc0.ɵɵinject(DOCUMENT)); };
|
---|
| 1178 | 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" });
|
---|
| 1179 | FocusTrapFactory.ctorParameters = () => [
|
---|
| 1180 | { type: InteractivityChecker },
|
---|
| 1181 | { type: NgZone },
|
---|
| 1182 | { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
|
---|
| 1183 | ];
|
---|
| 1184 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(FocusTrapFactory, [{
|
---|
| 1185 | type: Injectable,
|
---|
| 1186 | args: [{ providedIn: 'root' }]
|
---|
| 1187 | }], function () { return [{ type: InteractivityChecker }, { type: ɵngcc0.NgZone }, { type: undefined, decorators: [{
|
---|
| 1188 | type: Inject,
|
---|
| 1189 | args: [DOCUMENT]
|
---|
| 1190 | }] }]; }, null); })();
|
---|
| 1191 | /** Directive for trapping focus within a region. */
|
---|
| 1192 | class CdkTrapFocus {
|
---|
| 1193 | constructor(_elementRef, _focusTrapFactory,
|
---|
| 1194 | /**
|
---|
| 1195 | * @deprecated No longer being used. To be removed.
|
---|
| 1196 | * @breaking-change 13.0.0
|
---|
| 1197 | */
|
---|
| 1198 | _document) {
|
---|
| 1199 | this._elementRef = _elementRef;
|
---|
| 1200 | this._focusTrapFactory = _focusTrapFactory;
|
---|
| 1201 | /** Previously focused element to restore focus to upon destroy when using autoCapture. */
|
---|
| 1202 | this._previouslyFocusedElement = null;
|
---|
| 1203 | this.focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement, true);
|
---|
| 1204 | }
|
---|
| 1205 | /** Whether the focus trap is active. */
|
---|
| 1206 | get enabled() { return this.focusTrap.enabled; }
|
---|
| 1207 | set enabled(value) { this.focusTrap.enabled = coerceBooleanProperty(value); }
|
---|
| 1208 | /**
|
---|
| 1209 | * Whether the directive should automatically move focus into the trapped region upon
|
---|
| 1210 | * initialization and return focus to the previous activeElement upon destruction.
|
---|
| 1211 | */
|
---|
| 1212 | get autoCapture() { return this._autoCapture; }
|
---|
| 1213 | set autoCapture(value) { this._autoCapture = coerceBooleanProperty(value); }
|
---|
| 1214 | ngOnDestroy() {
|
---|
| 1215 | this.focusTrap.destroy();
|
---|
| 1216 | // If we stored a previously focused element when using autoCapture, return focus to that
|
---|
| 1217 | // element now that the trapped region is being destroyed.
|
---|
| 1218 | if (this._previouslyFocusedElement) {
|
---|
| 1219 | this._previouslyFocusedElement.focus();
|
---|
| 1220 | this._previouslyFocusedElement = null;
|
---|
| 1221 | }
|
---|
| 1222 | }
|
---|
| 1223 | ngAfterContentInit() {
|
---|
| 1224 | this.focusTrap.attachAnchors();
|
---|
| 1225 | if (this.autoCapture) {
|
---|
| 1226 | this._captureFocus();
|
---|
| 1227 | }
|
---|
| 1228 | }
|
---|
| 1229 | ngDoCheck() {
|
---|
| 1230 | if (!this.focusTrap.hasAttached()) {
|
---|
| 1231 | this.focusTrap.attachAnchors();
|
---|
| 1232 | }
|
---|
| 1233 | }
|
---|
| 1234 | ngOnChanges(changes) {
|
---|
| 1235 | const autoCaptureChange = changes['autoCapture'];
|
---|
| 1236 | if (autoCaptureChange && !autoCaptureChange.firstChange && this.autoCapture &&
|
---|
| 1237 | this.focusTrap.hasAttached()) {
|
---|
| 1238 | this._captureFocus();
|
---|
| 1239 | }
|
---|
| 1240 | }
|
---|
| 1241 | _captureFocus() {
|
---|
| 1242 | this._previouslyFocusedElement = _getFocusedElementPierceShadowDom();
|
---|
| 1243 | this.focusTrap.focusInitialElementWhenReady();
|
---|
| 1244 | }
|
---|
| 1245 | }
|
---|
| 1246 | CdkTrapFocus.ɵfac = function CdkTrapFocus_Factory(t) { return new (t || CdkTrapFocus)(ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ElementRef), ɵngcc0.ɵɵdirectiveInject(FocusTrapFactory), ɵngcc0.ɵɵdirectiveInject(DOCUMENT)); };
|
---|
| 1247 | CdkTrapFocus.ɵdir = /*@__PURE__*/ ɵngcc0.ɵɵdefineDirective({ type: CdkTrapFocus, selectors: [["", "cdkTrapFocus", ""]], inputs: { enabled: ["cdkTrapFocus", "enabled"], autoCapture: ["cdkTrapFocusAutoCapture", "autoCapture"] }, exportAs: ["cdkTrapFocus"], features: [ɵngcc0.ɵɵNgOnChangesFeature] });
|
---|
| 1248 | CdkTrapFocus.ctorParameters = () => [
|
---|
| 1249 | { type: ElementRef },
|
---|
| 1250 | { type: FocusTrapFactory },
|
---|
| 1251 | { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
|
---|
| 1252 | ];
|
---|
| 1253 | CdkTrapFocus.propDecorators = {
|
---|
| 1254 | enabled: [{ type: Input, args: ['cdkTrapFocus',] }],
|
---|
| 1255 | autoCapture: [{ type: Input, args: ['cdkTrapFocusAutoCapture',] }]
|
---|
| 1256 | };
|
---|
| 1257 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(CdkTrapFocus, [{
|
---|
| 1258 | type: Directive,
|
---|
| 1259 | args: [{
|
---|
| 1260 | selector: '[cdkTrapFocus]',
|
---|
| 1261 | exportAs: 'cdkTrapFocus'
|
---|
| 1262 | }]
|
---|
| 1263 | }], function () { return [{ type: ɵngcc0.ElementRef }, { type: FocusTrapFactory }, { type: undefined, decorators: [{
|
---|
| 1264 | type: Inject,
|
---|
| 1265 | args: [DOCUMENT]
|
---|
| 1266 | }] }]; }, { enabled: [{
|
---|
| 1267 | type: Input,
|
---|
| 1268 | args: ['cdkTrapFocus']
|
---|
| 1269 | }], autoCapture: [{
|
---|
| 1270 | type: Input,
|
---|
| 1271 | args: ['cdkTrapFocusAutoCapture']
|
---|
| 1272 | }] }); })();
|
---|
| 1273 |
|
---|
| 1274 | /**
|
---|
| 1275 | * @license
|
---|
| 1276 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1277 | *
|
---|
| 1278 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1279 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1280 | */
|
---|
| 1281 | /**
|
---|
| 1282 | * Class that allows for trapping focus within a DOM element.
|
---|
| 1283 | *
|
---|
| 1284 | * This class uses a strategy pattern that determines how it traps focus.
|
---|
| 1285 | * See FocusTrapInertStrategy.
|
---|
| 1286 | */
|
---|
| 1287 | class ConfigurableFocusTrap extends FocusTrap {
|
---|
| 1288 | constructor(_element, _checker, _ngZone, _document, _focusTrapManager, _inertStrategy, config) {
|
---|
| 1289 | super(_element, _checker, _ngZone, _document, config.defer);
|
---|
| 1290 | this._focusTrapManager = _focusTrapManager;
|
---|
| 1291 | this._inertStrategy = _inertStrategy;
|
---|
| 1292 | this._focusTrapManager.register(this);
|
---|
| 1293 | }
|
---|
| 1294 | /** Whether the FocusTrap is enabled. */
|
---|
| 1295 | get enabled() { return this._enabled; }
|
---|
| 1296 | set enabled(value) {
|
---|
| 1297 | this._enabled = value;
|
---|
| 1298 | if (this._enabled) {
|
---|
| 1299 | this._focusTrapManager.register(this);
|
---|
| 1300 | }
|
---|
| 1301 | else {
|
---|
| 1302 | this._focusTrapManager.deregister(this);
|
---|
| 1303 | }
|
---|
| 1304 | }
|
---|
| 1305 | /** Notifies the FocusTrapManager that this FocusTrap will be destroyed. */
|
---|
| 1306 | destroy() {
|
---|
| 1307 | this._focusTrapManager.deregister(this);
|
---|
| 1308 | super.destroy();
|
---|
| 1309 | }
|
---|
| 1310 | /** @docs-private Implemented as part of ManagedFocusTrap. */
|
---|
| 1311 | _enable() {
|
---|
| 1312 | this._inertStrategy.preventFocus(this);
|
---|
| 1313 | this.toggleAnchors(true);
|
---|
| 1314 | }
|
---|
| 1315 | /** @docs-private Implemented as part of ManagedFocusTrap. */
|
---|
| 1316 | _disable() {
|
---|
| 1317 | this._inertStrategy.allowFocus(this);
|
---|
| 1318 | this.toggleAnchors(false);
|
---|
| 1319 | }
|
---|
| 1320 | }
|
---|
| 1321 |
|
---|
| 1322 | /**
|
---|
| 1323 | * @license
|
---|
| 1324 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1325 | *
|
---|
| 1326 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1327 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1328 | */
|
---|
| 1329 |
|
---|
| 1330 | /**
|
---|
| 1331 | * @license
|
---|
| 1332 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1333 | *
|
---|
| 1334 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1335 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1336 | */
|
---|
| 1337 | /** The injection token used to specify the inert strategy. */
|
---|
| 1338 | const FOCUS_TRAP_INERT_STRATEGY = new InjectionToken('FOCUS_TRAP_INERT_STRATEGY');
|
---|
| 1339 |
|
---|
| 1340 | /**
|
---|
| 1341 | * @license
|
---|
| 1342 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1343 | *
|
---|
| 1344 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1345 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1346 | */
|
---|
| 1347 | /** IE 11 compatible closest implementation that is able to start from non-Element Nodes. */
|
---|
| 1348 | function closest(element, selector) {
|
---|
| 1349 | if (!(element instanceof Node)) {
|
---|
| 1350 | return null;
|
---|
| 1351 | }
|
---|
| 1352 | let curr = element;
|
---|
| 1353 | while (curr != null && !(curr instanceof Element)) {
|
---|
| 1354 | curr = curr.parentNode;
|
---|
| 1355 | }
|
---|
| 1356 | return curr && (hasNativeClosest ?
|
---|
| 1357 | curr.closest(selector) : polyfillClosest(curr, selector));
|
---|
| 1358 | }
|
---|
| 1359 | /** Polyfill for browsers without Element.closest. */
|
---|
| 1360 | function polyfillClosest(element, selector) {
|
---|
| 1361 | let curr = element;
|
---|
| 1362 | while (curr != null && !(curr instanceof Element && matches(curr, selector))) {
|
---|
| 1363 | curr = curr.parentNode;
|
---|
| 1364 | }
|
---|
| 1365 | return (curr || null);
|
---|
| 1366 | }
|
---|
| 1367 | const hasNativeClosest = typeof Element != 'undefined' && !!Element.prototype.closest;
|
---|
| 1368 | /** IE 11 compatible matches implementation. */
|
---|
| 1369 | function matches(element, selector) {
|
---|
| 1370 | return element.matches ?
|
---|
| 1371 | element.matches(selector) :
|
---|
| 1372 | element['msMatchesSelector'](selector);
|
---|
| 1373 | }
|
---|
| 1374 |
|
---|
| 1375 | /**
|
---|
| 1376 | * @license
|
---|
| 1377 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1378 | *
|
---|
| 1379 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1380 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1381 | */
|
---|
| 1382 | /**
|
---|
| 1383 | * Lightweight FocusTrapInertStrategy that adds a document focus event
|
---|
| 1384 | * listener to redirect focus back inside the FocusTrap.
|
---|
| 1385 | */
|
---|
| 1386 | class EventListenerFocusTrapInertStrategy {
|
---|
| 1387 | constructor() {
|
---|
| 1388 | /** Focus event handler. */
|
---|
| 1389 | this._listener = null;
|
---|
| 1390 | }
|
---|
| 1391 | /** Adds a document event listener that keeps focus inside the FocusTrap. */
|
---|
| 1392 | preventFocus(focusTrap) {
|
---|
| 1393 | // Ensure there's only one listener per document
|
---|
| 1394 | if (this._listener) {
|
---|
| 1395 | focusTrap._document.removeEventListener('focus', this._listener, true);
|
---|
| 1396 | }
|
---|
| 1397 | this._listener = (e) => this._trapFocus(focusTrap, e);
|
---|
| 1398 | focusTrap._ngZone.runOutsideAngular(() => {
|
---|
| 1399 | focusTrap._document.addEventListener('focus', this._listener, true);
|
---|
| 1400 | });
|
---|
| 1401 | }
|
---|
| 1402 | /** Removes the event listener added in preventFocus. */
|
---|
| 1403 | allowFocus(focusTrap) {
|
---|
| 1404 | if (!this._listener) {
|
---|
| 1405 | return;
|
---|
| 1406 | }
|
---|
| 1407 | focusTrap._document.removeEventListener('focus', this._listener, true);
|
---|
| 1408 | this._listener = null;
|
---|
| 1409 | }
|
---|
| 1410 | /**
|
---|
| 1411 | * Refocuses the first element in the FocusTrap if the focus event target was outside
|
---|
| 1412 | * the FocusTrap.
|
---|
| 1413 | *
|
---|
| 1414 | * This is an event listener callback. The event listener is added in runOutsideAngular,
|
---|
| 1415 | * so all this code runs outside Angular as well.
|
---|
| 1416 | */
|
---|
| 1417 | _trapFocus(focusTrap, event) {
|
---|
| 1418 | const target = event.target;
|
---|
| 1419 | const focusTrapRoot = focusTrap._element;
|
---|
| 1420 | // Don't refocus if target was in an overlay, because the overlay might be associated
|
---|
| 1421 | // with an element inside the FocusTrap, ex. mat-select.
|
---|
| 1422 | if (!focusTrapRoot.contains(target) && closest(target, 'div.cdk-overlay-pane') === null) {
|
---|
| 1423 | // Some legacy FocusTrap usages have logic that focuses some element on the page
|
---|
| 1424 | // just before FocusTrap is destroyed. For backwards compatibility, wait
|
---|
| 1425 | // to be sure FocusTrap is still enabled before refocusing.
|
---|
| 1426 | setTimeout(() => {
|
---|
| 1427 | // Check whether focus wasn't put back into the focus trap while the timeout was pending.
|
---|
| 1428 | if (focusTrap.enabled && !focusTrapRoot.contains(focusTrap._document.activeElement)) {
|
---|
| 1429 | focusTrap.focusFirstTabbableElement();
|
---|
| 1430 | }
|
---|
| 1431 | });
|
---|
| 1432 | }
|
---|
| 1433 | }
|
---|
| 1434 | }
|
---|
| 1435 |
|
---|
| 1436 | /**
|
---|
| 1437 | * @license
|
---|
| 1438 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1439 | *
|
---|
| 1440 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1441 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1442 | */
|
---|
| 1443 | /** Injectable that ensures only the most recently enabled FocusTrap is active. */
|
---|
| 1444 | class FocusTrapManager {
|
---|
| 1445 | constructor() {
|
---|
| 1446 | // A stack of the FocusTraps on the page. Only the FocusTrap at the
|
---|
| 1447 | // top of the stack is active.
|
---|
| 1448 | this._focusTrapStack = [];
|
---|
| 1449 | }
|
---|
| 1450 | /**
|
---|
| 1451 | * Disables the FocusTrap at the top of the stack, and then pushes
|
---|
| 1452 | * the new FocusTrap onto the stack.
|
---|
| 1453 | */
|
---|
| 1454 | register(focusTrap) {
|
---|
| 1455 | // Dedupe focusTraps that register multiple times.
|
---|
| 1456 | this._focusTrapStack = this._focusTrapStack.filter((ft) => ft !== focusTrap);
|
---|
| 1457 | let stack = this._focusTrapStack;
|
---|
| 1458 | if (stack.length) {
|
---|
| 1459 | stack[stack.length - 1]._disable();
|
---|
| 1460 | }
|
---|
| 1461 | stack.push(focusTrap);
|
---|
| 1462 | focusTrap._enable();
|
---|
| 1463 | }
|
---|
| 1464 | /**
|
---|
| 1465 | * Removes the FocusTrap from the stack, and activates the
|
---|
| 1466 | * FocusTrap that is the new top of the stack.
|
---|
| 1467 | */
|
---|
| 1468 | deregister(focusTrap) {
|
---|
| 1469 | focusTrap._disable();
|
---|
| 1470 | const stack = this._focusTrapStack;
|
---|
| 1471 | const i = stack.indexOf(focusTrap);
|
---|
| 1472 | if (i !== -1) {
|
---|
| 1473 | stack.splice(i, 1);
|
---|
| 1474 | if (stack.length) {
|
---|
| 1475 | stack[stack.length - 1]._enable();
|
---|
| 1476 | }
|
---|
| 1477 | }
|
---|
| 1478 | }
|
---|
| 1479 | }
|
---|
| 1480 | FocusTrapManager.ɵfac = function FocusTrapManager_Factory(t) { return new (t || FocusTrapManager)(); };
|
---|
| 1481 | FocusTrapManager.ɵprov = i0.ɵɵdefineInjectable({ factory: function FocusTrapManager_Factory() { return new FocusTrapManager(); }, token: FocusTrapManager, providedIn: "root" });
|
---|
| 1482 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(FocusTrapManager, [{
|
---|
| 1483 | type: Injectable,
|
---|
| 1484 | args: [{ providedIn: 'root' }]
|
---|
| 1485 | }], function () { return []; }, null); })();
|
---|
| 1486 |
|
---|
| 1487 | /**
|
---|
| 1488 | * @license
|
---|
| 1489 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1490 | *
|
---|
| 1491 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1492 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1493 | */
|
---|
| 1494 | /** Factory that allows easy instantiation of configurable focus traps. */
|
---|
| 1495 | class ConfigurableFocusTrapFactory {
|
---|
| 1496 | constructor(_checker, _ngZone, _focusTrapManager, _document, _inertStrategy) {
|
---|
| 1497 | this._checker = _checker;
|
---|
| 1498 | this._ngZone = _ngZone;
|
---|
| 1499 | this._focusTrapManager = _focusTrapManager;
|
---|
| 1500 | this._document = _document;
|
---|
| 1501 | // TODO split up the strategies into different modules, similar to DateAdapter.
|
---|
| 1502 | this._inertStrategy = _inertStrategy || new EventListenerFocusTrapInertStrategy();
|
---|
| 1503 | }
|
---|
| 1504 | create(element, config = { defer: false }) {
|
---|
| 1505 | let configObject;
|
---|
| 1506 | if (typeof config === 'boolean') {
|
---|
| 1507 | configObject = { defer: config };
|
---|
| 1508 | }
|
---|
| 1509 | else {
|
---|
| 1510 | configObject = config;
|
---|
| 1511 | }
|
---|
| 1512 | return new ConfigurableFocusTrap(element, this._checker, this._ngZone, this._document, this._focusTrapManager, this._inertStrategy, configObject);
|
---|
| 1513 | }
|
---|
| 1514 | }
|
---|
| 1515 | 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)); };
|
---|
| 1516 | 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" });
|
---|
| 1517 | ConfigurableFocusTrapFactory.ctorParameters = () => [
|
---|
| 1518 | { type: InteractivityChecker },
|
---|
| 1519 | { type: NgZone },
|
---|
| 1520 | { type: FocusTrapManager },
|
---|
| 1521 | { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
|
---|
| 1522 | { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [FOCUS_TRAP_INERT_STRATEGY,] }] }
|
---|
| 1523 | ];
|
---|
| 1524 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(ConfigurableFocusTrapFactory, [{
|
---|
| 1525 | type: Injectable,
|
---|
| 1526 | args: [{ providedIn: 'root' }]
|
---|
| 1527 | }], function () { return [{ type: InteractivityChecker }, { type: ɵngcc0.NgZone }, { type: FocusTrapManager }, { type: undefined, decorators: [{
|
---|
| 1528 | type: Inject,
|
---|
| 1529 | args: [DOCUMENT]
|
---|
| 1530 | }] }, { type: undefined, decorators: [{
|
---|
| 1531 | type: Optional
|
---|
| 1532 | }, {
|
---|
| 1533 | type: Inject,
|
---|
| 1534 | args: [FOCUS_TRAP_INERT_STRATEGY]
|
---|
| 1535 | }] }]; }, null); })();
|
---|
| 1536 |
|
---|
| 1537 | /**
|
---|
| 1538 | * @license
|
---|
| 1539 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1540 | *
|
---|
| 1541 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1542 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1543 | */
|
---|
| 1544 | /** Gets whether an event could be a faked `mousedown` event dispatched by a screen reader. */
|
---|
| 1545 | function isFakeMousedownFromScreenReader(event) {
|
---|
| 1546 | // Some screen readers will dispatch a fake `mousedown` event when pressing enter or space on
|
---|
| 1547 | // a clickable element. We can distinguish these events when both `offsetX` and `offsetY` are
|
---|
| 1548 | // zero. Note that there's an edge case where the user could click the 0x0 spot of the screen
|
---|
| 1549 | // themselves, but that is unlikely to contain interaction elements. Historially we used to check
|
---|
| 1550 | // `event.buttons === 0`, however that no longer works on recent versions of NVDA.
|
---|
| 1551 | return event.offsetX === 0 && event.offsetY === 0;
|
---|
| 1552 | }
|
---|
| 1553 | /** Gets whether an event could be a faked `touchstart` event dispatched by a screen reader. */
|
---|
| 1554 | function isFakeTouchstartFromScreenReader(event) {
|
---|
| 1555 | const touch = (event.touches && event.touches[0]) ||
|
---|
| 1556 | (event.changedTouches && event.changedTouches[0]);
|
---|
| 1557 | // A fake `touchstart` can be distinguished from a real one by looking at the `identifier`
|
---|
| 1558 | // which is typically >= 0 on a real device versus -1 from a screen reader. Just to be safe,
|
---|
| 1559 | // we can also look at `radiusX` and `radiusY`. This behavior was observed against a Windows 10
|
---|
| 1560 | // device with a touch screen running NVDA v2020.4 and Firefox 85 or Chrome 88.
|
---|
| 1561 | return !!touch && touch.identifier === -1 && (touch.radiusX == null || touch.radiusX === 1) &&
|
---|
| 1562 | (touch.radiusY == null || touch.radiusY === 1);
|
---|
| 1563 | }
|
---|
| 1564 |
|
---|
| 1565 | /**
|
---|
| 1566 | * @license
|
---|
| 1567 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1568 | *
|
---|
| 1569 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1570 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1571 | */
|
---|
| 1572 | /**
|
---|
| 1573 | * Injectable options for the InputModalityDetector. These are shallowly merged with the default
|
---|
| 1574 | * options.
|
---|
| 1575 | */
|
---|
| 1576 | const INPUT_MODALITY_DETECTOR_OPTIONS = new InjectionToken('cdk-input-modality-detector-options');
|
---|
| 1577 | /**
|
---|
| 1578 | * Default options for the InputModalityDetector.
|
---|
| 1579 | *
|
---|
| 1580 | * Modifier keys are ignored by default (i.e. when pressed won't cause the service to detect
|
---|
| 1581 | * keyboard input modality) for two reasons:
|
---|
| 1582 | *
|
---|
| 1583 | * 1. Modifier keys are commonly used with mouse to perform actions such as 'right click' or 'open
|
---|
| 1584 | * in new tab', and are thus less representative of actual keyboard interaction.
|
---|
| 1585 | * 2. VoiceOver triggers some keyboard events when linearly navigating with Control + Option (but
|
---|
| 1586 | * confusingly not with Caps Lock). Thus, to have parity with other screen readers, we ignore
|
---|
| 1587 | * these keys so as to not update the input modality.
|
---|
| 1588 | *
|
---|
| 1589 | * Note that we do not by default ignore the right Meta key on Safari because it has the same key
|
---|
| 1590 | * code as the ContextMenu key on other browsers. When we switch to using event.key, we can
|
---|
| 1591 | * distinguish between the two.
|
---|
| 1592 | */
|
---|
| 1593 | const INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS = {
|
---|
| 1594 | ignoreKeys: [ALT, CONTROL, MAC_META, META, SHIFT],
|
---|
| 1595 | };
|
---|
| 1596 | /**
|
---|
| 1597 | * The amount of time needed to pass after a touchstart event in order for a subsequent mousedown
|
---|
| 1598 | * event to be attributed as mouse and not touch.
|
---|
| 1599 | *
|
---|
| 1600 | * This is the value used by AngularJS Material. Through trial and error (on iPhone 6S) they found
|
---|
| 1601 | * that a value of around 650ms seems appropriate.
|
---|
| 1602 | */
|
---|
| 1603 | const TOUCH_BUFFER_MS = 650;
|
---|
| 1604 | /**
|
---|
| 1605 | * Event listener options that enable capturing and also mark the listener as passive if the browser
|
---|
| 1606 | * supports it.
|
---|
| 1607 | */
|
---|
| 1608 | const modalityEventListenerOptions = normalizePassiveListenerOptions({
|
---|
| 1609 | passive: true,
|
---|
| 1610 | capture: true,
|
---|
| 1611 | });
|
---|
| 1612 | /**
|
---|
| 1613 | * Service that detects the user's input modality.
|
---|
| 1614 | *
|
---|
| 1615 | * This service does not update the input modality when a user navigates with a screen reader
|
---|
| 1616 | * (e.g. linear navigation with VoiceOver, object navigation / browse mode with NVDA, virtual PC
|
---|
| 1617 | * cursor mode with JAWS). This is in part due to technical limitations (i.e. keyboard events do not
|
---|
| 1618 | * fire as expected in these modes) but is also arguably the correct behavior. Navigating with a
|
---|
| 1619 | * screen reader is akin to visually scanning a page, and should not be interpreted as actual user
|
---|
| 1620 | * input interaction.
|
---|
| 1621 | *
|
---|
| 1622 | * When a user is not navigating but *interacting* with a screen reader, this service attempts to
|
---|
| 1623 | * update the input modality to keyboard, but in general this service's behavior is largely
|
---|
| 1624 | * undefined.
|
---|
| 1625 | */
|
---|
| 1626 | class InputModalityDetector {
|
---|
| 1627 | constructor(_platform, ngZone, document, options) {
|
---|
| 1628 | this._platform = _platform;
|
---|
| 1629 | /**
|
---|
| 1630 | * The most recently detected input modality event target. Is null if no input modality has been
|
---|
| 1631 | * detected or if the associated event target is null for some unknown reason.
|
---|
| 1632 | */
|
---|
| 1633 | this._mostRecentTarget = null;
|
---|
| 1634 | /** The underlying BehaviorSubject that emits whenever an input modality is detected. */
|
---|
| 1635 | this._modality = new BehaviorSubject(null);
|
---|
| 1636 | /**
|
---|
| 1637 | * The timestamp of the last touch input modality. Used to determine whether mousedown events
|
---|
| 1638 | * should be attributed to mouse or touch.
|
---|
| 1639 | */
|
---|
| 1640 | this._lastTouchMs = 0;
|
---|
| 1641 | /**
|
---|
| 1642 | * Handles keydown events. Must be an arrow function in order to preserve the context when it gets
|
---|
| 1643 | * bound.
|
---|
| 1644 | */
|
---|
| 1645 | this._onKeydown = (event) => {
|
---|
| 1646 | var _a, _b;
|
---|
| 1647 | // If this is one of the keys we should ignore, then ignore it and don't update the input
|
---|
| 1648 | // modality to keyboard.
|
---|
| 1649 | 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)) {
|
---|
| 1650 | return;
|
---|
| 1651 | }
|
---|
| 1652 | this._modality.next('keyboard');
|
---|
| 1653 | this._mostRecentTarget = _getEventTarget(event);
|
---|
| 1654 | };
|
---|
| 1655 | /**
|
---|
| 1656 | * Handles mousedown events. Must be an arrow function in order to preserve the context when it
|
---|
| 1657 | * gets bound.
|
---|
| 1658 | */
|
---|
| 1659 | this._onMousedown = (event) => {
|
---|
| 1660 | // Touches trigger both touch and mouse events, so we need to distinguish between mouse events
|
---|
| 1661 | // that were triggered via mouse vs touch. To do so, check if the mouse event occurs closely
|
---|
| 1662 | // after the previous touch event.
|
---|
| 1663 | if (Date.now() - this._lastTouchMs < TOUCH_BUFFER_MS) {
|
---|
| 1664 | return;
|
---|
| 1665 | }
|
---|
| 1666 | // Fake mousedown events are fired by some screen readers when controls are activated by the
|
---|
| 1667 | // screen reader. Attribute them to keyboard input modality.
|
---|
| 1668 | this._modality.next(isFakeMousedownFromScreenReader(event) ? 'keyboard' : 'mouse');
|
---|
| 1669 | this._mostRecentTarget = _getEventTarget(event);
|
---|
| 1670 | };
|
---|
| 1671 | /**
|
---|
| 1672 | * Handles touchstart events. Must be an arrow function in order to preserve the context when it
|
---|
| 1673 | * gets bound.
|
---|
| 1674 | */
|
---|
| 1675 | this._onTouchstart = (event) => {
|
---|
| 1676 | // Same scenario as mentioned in _onMousedown, but on touch screen devices, fake touchstart
|
---|
| 1677 | // events are fired. Again, attribute to keyboard input modality.
|
---|
| 1678 | if (isFakeTouchstartFromScreenReader(event)) {
|
---|
| 1679 | this._modality.next('keyboard');
|
---|
| 1680 | return;
|
---|
| 1681 | }
|
---|
| 1682 | // Store the timestamp of this touch event, as it's used to distinguish between mouse events
|
---|
| 1683 | // triggered via mouse vs touch.
|
---|
| 1684 | this._lastTouchMs = Date.now();
|
---|
| 1685 | this._modality.next('touch');
|
---|
| 1686 | this._mostRecentTarget = _getEventTarget(event);
|
---|
| 1687 | };
|
---|
| 1688 | this._options = Object.assign(Object.assign({}, INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS), options);
|
---|
| 1689 | // Skip the first emission as it's null.
|
---|
| 1690 | this.modalityDetected = this._modality.pipe(skip(1));
|
---|
| 1691 | this.modalityChanged = this.modalityDetected.pipe(distinctUntilChanged());
|
---|
| 1692 | // If we're not in a browser, this service should do nothing, as there's no relevant input
|
---|
| 1693 | // modality to detect.
|
---|
| 1694 | if (_platform.isBrowser) {
|
---|
| 1695 | ngZone.runOutsideAngular(() => {
|
---|
| 1696 | document.addEventListener('keydown', this._onKeydown, modalityEventListenerOptions);
|
---|
| 1697 | document.addEventListener('mousedown', this._onMousedown, modalityEventListenerOptions);
|
---|
| 1698 | document.addEventListener('touchstart', this._onTouchstart, modalityEventListenerOptions);
|
---|
| 1699 | });
|
---|
| 1700 | }
|
---|
| 1701 | }
|
---|
| 1702 | /** The most recently detected input modality. */
|
---|
| 1703 | get mostRecentModality() {
|
---|
| 1704 | return this._modality.value;
|
---|
| 1705 | }
|
---|
| 1706 | ngOnDestroy() {
|
---|
| 1707 | this._modality.complete();
|
---|
| 1708 | if (this._platform.isBrowser) {
|
---|
| 1709 | document.removeEventListener('keydown', this._onKeydown, modalityEventListenerOptions);
|
---|
| 1710 | document.removeEventListener('mousedown', this._onMousedown, modalityEventListenerOptions);
|
---|
| 1711 | document.removeEventListener('touchstart', this._onTouchstart, modalityEventListenerOptions);
|
---|
| 1712 | }
|
---|
| 1713 | }
|
---|
| 1714 | }
|
---|
| 1715 | 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)); };
|
---|
| 1716 | 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" });
|
---|
| 1717 | InputModalityDetector.ctorParameters = () => [
|
---|
| 1718 | { type: Platform },
|
---|
| 1719 | { type: NgZone },
|
---|
| 1720 | { type: Document, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
|
---|
| 1721 | { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [INPUT_MODALITY_DETECTOR_OPTIONS,] }] }
|
---|
| 1722 | ];
|
---|
| 1723 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(InputModalityDetector, [{
|
---|
| 1724 | type: Injectable,
|
---|
| 1725 | args: [{ providedIn: 'root' }]
|
---|
| 1726 | }], function () { return [{ type: ɵngcc1.Platform }, { type: ɵngcc0.NgZone }, { type: Document, decorators: [{
|
---|
| 1727 | type: Inject,
|
---|
| 1728 | args: [DOCUMENT]
|
---|
| 1729 | }] }, { type: undefined, decorators: [{
|
---|
| 1730 | type: Optional
|
---|
| 1731 | }, {
|
---|
| 1732 | type: Inject,
|
---|
| 1733 | args: [INPUT_MODALITY_DETECTOR_OPTIONS]
|
---|
| 1734 | }] }]; }, null); })();
|
---|
| 1735 |
|
---|
| 1736 | /**
|
---|
| 1737 | * @license
|
---|
| 1738 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1739 | *
|
---|
| 1740 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1741 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1742 | */
|
---|
| 1743 | const LIVE_ANNOUNCER_ELEMENT_TOKEN = new InjectionToken('liveAnnouncerElement', {
|
---|
| 1744 | providedIn: 'root',
|
---|
| 1745 | factory: LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY,
|
---|
| 1746 | });
|
---|
| 1747 | /** @docs-private */
|
---|
| 1748 | function LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY() {
|
---|
| 1749 | return null;
|
---|
| 1750 | }
|
---|
| 1751 | /** Injection token that can be used to configure the default options for the LiveAnnouncer. */
|
---|
| 1752 | const LIVE_ANNOUNCER_DEFAULT_OPTIONS = new InjectionToken('LIVE_ANNOUNCER_DEFAULT_OPTIONS');
|
---|
| 1753 |
|
---|
| 1754 | /**
|
---|
| 1755 | * @license
|
---|
| 1756 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1757 | *
|
---|
| 1758 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1759 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1760 | */
|
---|
| 1761 | class LiveAnnouncer {
|
---|
| 1762 | constructor(elementToken, _ngZone, _document, _defaultOptions) {
|
---|
| 1763 | this._ngZone = _ngZone;
|
---|
| 1764 | this._defaultOptions = _defaultOptions;
|
---|
| 1765 | // We inject the live element and document as `any` because the constructor signature cannot
|
---|
| 1766 | // reference browser globals (HTMLElement, Document) on non-browser environments, since having
|
---|
| 1767 | // a class decorator causes TypeScript to preserve the constructor signature types.
|
---|
| 1768 | this._document = _document;
|
---|
| 1769 | this._liveElement = elementToken || this._createLiveElement();
|
---|
| 1770 | }
|
---|
| 1771 | announce(message, ...args) {
|
---|
| 1772 | const defaultOptions = this._defaultOptions;
|
---|
| 1773 | let politeness;
|
---|
| 1774 | let duration;
|
---|
| 1775 | if (args.length === 1 && typeof args[0] === 'number') {
|
---|
| 1776 | duration = args[0];
|
---|
| 1777 | }
|
---|
| 1778 | else {
|
---|
| 1779 | [politeness, duration] = args;
|
---|
| 1780 | }
|
---|
| 1781 | this.clear();
|
---|
| 1782 | clearTimeout(this._previousTimeout);
|
---|
| 1783 | if (!politeness) {
|
---|
| 1784 | politeness =
|
---|
| 1785 | (defaultOptions && defaultOptions.politeness) ? defaultOptions.politeness : 'polite';
|
---|
| 1786 | }
|
---|
| 1787 | if (duration == null && defaultOptions) {
|
---|
| 1788 | duration = defaultOptions.duration;
|
---|
| 1789 | }
|
---|
| 1790 | // TODO: ensure changing the politeness works on all environments we support.
|
---|
| 1791 | this._liveElement.setAttribute('aria-live', politeness);
|
---|
| 1792 | // This 100ms timeout is necessary for some browser + screen-reader combinations:
|
---|
| 1793 | // - Both JAWS and NVDA over IE11 will not announce anything without a non-zero timeout.
|
---|
| 1794 | // - With Chrome and IE11 with NVDA or JAWS, a repeated (identical) message won't be read a
|
---|
| 1795 | // second time without clearing and then using a non-zero delay.
|
---|
| 1796 | // (using JAWS 17 at time of this writing).
|
---|
| 1797 | return this._ngZone.runOutsideAngular(() => {
|
---|
| 1798 | return new Promise(resolve => {
|
---|
| 1799 | clearTimeout(this._previousTimeout);
|
---|
| 1800 | this._previousTimeout = setTimeout(() => {
|
---|
| 1801 | this._liveElement.textContent = message;
|
---|
| 1802 | resolve();
|
---|
| 1803 | if (typeof duration === 'number') {
|
---|
| 1804 | this._previousTimeout = setTimeout(() => this.clear(), duration);
|
---|
| 1805 | }
|
---|
| 1806 | }, 100);
|
---|
| 1807 | });
|
---|
| 1808 | });
|
---|
| 1809 | }
|
---|
| 1810 | /**
|
---|
| 1811 | * Clears the current text from the announcer element. Can be used to prevent
|
---|
| 1812 | * screen readers from reading the text out again while the user is going
|
---|
| 1813 | * through the page landmarks.
|
---|
| 1814 | */
|
---|
| 1815 | clear() {
|
---|
| 1816 | if (this._liveElement) {
|
---|
| 1817 | this._liveElement.textContent = '';
|
---|
| 1818 | }
|
---|
| 1819 | }
|
---|
| 1820 | ngOnDestroy() {
|
---|
| 1821 | clearTimeout(this._previousTimeout);
|
---|
| 1822 | if (this._liveElement && this._liveElement.parentNode) {
|
---|
| 1823 | this._liveElement.parentNode.removeChild(this._liveElement);
|
---|
| 1824 | this._liveElement = null;
|
---|
| 1825 | }
|
---|
| 1826 | }
|
---|
| 1827 | _createLiveElement() {
|
---|
| 1828 | const elementClass = 'cdk-live-announcer-element';
|
---|
| 1829 | const previousElements = this._document.getElementsByClassName(elementClass);
|
---|
| 1830 | const liveEl = this._document.createElement('div');
|
---|
| 1831 | // Remove any old containers. This can happen when coming in from a server-side-rendered page.
|
---|
| 1832 | for (let i = 0; i < previousElements.length; i++) {
|
---|
| 1833 | previousElements[i].parentNode.removeChild(previousElements[i]);
|
---|
| 1834 | }
|
---|
| 1835 | liveEl.classList.add(elementClass);
|
---|
| 1836 | liveEl.classList.add('cdk-visually-hidden');
|
---|
| 1837 | liveEl.setAttribute('aria-atomic', 'true');
|
---|
| 1838 | liveEl.setAttribute('aria-live', 'polite');
|
---|
| 1839 | this._document.body.appendChild(liveEl);
|
---|
| 1840 | return liveEl;
|
---|
| 1841 | }
|
---|
| 1842 | }
|
---|
| 1843 | 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)); };
|
---|
| 1844 | 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" });
|
---|
| 1845 | LiveAnnouncer.ctorParameters = () => [
|
---|
| 1846 | { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [LIVE_ANNOUNCER_ELEMENT_TOKEN,] }] },
|
---|
| 1847 | { type: NgZone },
|
---|
| 1848 | { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
|
---|
| 1849 | { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [LIVE_ANNOUNCER_DEFAULT_OPTIONS,] }] }
|
---|
| 1850 | ];
|
---|
| 1851 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(LiveAnnouncer, [{
|
---|
| 1852 | type: Injectable,
|
---|
| 1853 | args: [{ providedIn: 'root' }]
|
---|
| 1854 | }], function () { return [{ type: undefined, decorators: [{
|
---|
| 1855 | type: Optional
|
---|
| 1856 | }, {
|
---|
| 1857 | type: Inject,
|
---|
| 1858 | args: [LIVE_ANNOUNCER_ELEMENT_TOKEN]
|
---|
| 1859 | }] }, { type: ɵngcc0.NgZone }, { type: undefined, decorators: [{
|
---|
| 1860 | type: Inject,
|
---|
| 1861 | args: [DOCUMENT]
|
---|
| 1862 | }] }, { type: undefined, decorators: [{
|
---|
| 1863 | type: Optional
|
---|
| 1864 | }, {
|
---|
| 1865 | type: Inject,
|
---|
| 1866 | args: [LIVE_ANNOUNCER_DEFAULT_OPTIONS]
|
---|
| 1867 | }] }]; }, null); })();
|
---|
| 1868 | /**
|
---|
| 1869 | * A directive that works similarly to aria-live, but uses the LiveAnnouncer to ensure compatibility
|
---|
| 1870 | * with a wider range of browsers and screen readers.
|
---|
| 1871 | */
|
---|
| 1872 | class CdkAriaLive {
|
---|
| 1873 | constructor(_elementRef, _liveAnnouncer, _contentObserver, _ngZone) {
|
---|
| 1874 | this._elementRef = _elementRef;
|
---|
| 1875 | this._liveAnnouncer = _liveAnnouncer;
|
---|
| 1876 | this._contentObserver = _contentObserver;
|
---|
| 1877 | this._ngZone = _ngZone;
|
---|
| 1878 | this._politeness = 'polite';
|
---|
| 1879 | }
|
---|
| 1880 | /** The aria-live politeness level to use when announcing messages. */
|
---|
| 1881 | get politeness() { return this._politeness; }
|
---|
| 1882 | set politeness(value) {
|
---|
| 1883 | this._politeness = value === 'off' || value === 'assertive' ? value : 'polite';
|
---|
| 1884 | if (this._politeness === 'off') {
|
---|
| 1885 | if (this._subscription) {
|
---|
| 1886 | this._subscription.unsubscribe();
|
---|
| 1887 | this._subscription = null;
|
---|
| 1888 | }
|
---|
| 1889 | }
|
---|
| 1890 | else if (!this._subscription) {
|
---|
| 1891 | this._subscription = this._ngZone.runOutsideAngular(() => {
|
---|
| 1892 | return this._contentObserver
|
---|
| 1893 | .observe(this._elementRef)
|
---|
| 1894 | .subscribe(() => {
|
---|
| 1895 | // Note that we use textContent here, rather than innerText, in order to avoid a reflow.
|
---|
| 1896 | const elementText = this._elementRef.nativeElement.textContent;
|
---|
| 1897 | // The `MutationObserver` fires also for attribute
|
---|
| 1898 | // changes which we don't want to announce.
|
---|
| 1899 | if (elementText !== this._previousAnnouncedText) {
|
---|
| 1900 | this._liveAnnouncer.announce(elementText, this._politeness);
|
---|
| 1901 | this._previousAnnouncedText = elementText;
|
---|
| 1902 | }
|
---|
| 1903 | });
|
---|
| 1904 | });
|
---|
| 1905 | }
|
---|
| 1906 | }
|
---|
| 1907 | ngOnDestroy() {
|
---|
| 1908 | if (this._subscription) {
|
---|
| 1909 | this._subscription.unsubscribe();
|
---|
| 1910 | }
|
---|
| 1911 | }
|
---|
| 1912 | }
|
---|
| 1913 | 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)); };
|
---|
| 1914 | CdkAriaLive.ɵdir = /*@__PURE__*/ ɵngcc0.ɵɵdefineDirective({ type: CdkAriaLive, selectors: [["", "cdkAriaLive", ""]], inputs: { politeness: ["cdkAriaLive", "politeness"] }, exportAs: ["cdkAriaLive"] });
|
---|
| 1915 | CdkAriaLive.ctorParameters = () => [
|
---|
| 1916 | { type: ElementRef },
|
---|
| 1917 | { type: LiveAnnouncer },
|
---|
| 1918 | { type: ContentObserver },
|
---|
| 1919 | { type: NgZone }
|
---|
| 1920 | ];
|
---|
| 1921 | CdkAriaLive.propDecorators = {
|
---|
| 1922 | politeness: [{ type: Input, args: ['cdkAriaLive',] }]
|
---|
| 1923 | };
|
---|
| 1924 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(CdkAriaLive, [{
|
---|
| 1925 | type: Directive,
|
---|
| 1926 | args: [{
|
---|
| 1927 | selector: '[cdkAriaLive]',
|
---|
| 1928 | exportAs: 'cdkAriaLive'
|
---|
| 1929 | }]
|
---|
| 1930 | }], function () { return [{ type: ɵngcc0.ElementRef }, { type: LiveAnnouncer }, { type: ɵngcc2.ContentObserver }, { type: ɵngcc0.NgZone }]; }, { politeness: [{
|
---|
| 1931 | type: Input,
|
---|
| 1932 | args: ['cdkAriaLive']
|
---|
| 1933 | }] }); })();
|
---|
| 1934 |
|
---|
| 1935 | /**
|
---|
| 1936 | * @license
|
---|
| 1937 | * Copyright Google LLC All Rights Reserved.
|
---|
| 1938 | *
|
---|
| 1939 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 1940 | * found in the LICENSE file at https://angular.io/license
|
---|
| 1941 | */
|
---|
| 1942 | /** InjectionToken for FocusMonitorOptions. */
|
---|
| 1943 | const FOCUS_MONITOR_DEFAULT_OPTIONS = new InjectionToken('cdk-focus-monitor-default-options');
|
---|
| 1944 | /**
|
---|
| 1945 | * Event listener options that enable capturing and also
|
---|
| 1946 | * mark the listener as passive if the browser supports it.
|
---|
| 1947 | */
|
---|
| 1948 | const captureEventListenerOptions = normalizePassiveListenerOptions({
|
---|
| 1949 | passive: true,
|
---|
| 1950 | capture: true
|
---|
| 1951 | });
|
---|
| 1952 | /** Monitors mouse and keyboard events to determine the cause of focus events. */
|
---|
| 1953 | class FocusMonitor {
|
---|
| 1954 | constructor(_ngZone, _platform, _inputModalityDetector,
|
---|
| 1955 | /** @breaking-change 11.0.0 make document required */
|
---|
| 1956 | document, options) {
|
---|
| 1957 | this._ngZone = _ngZone;
|
---|
| 1958 | this._platform = _platform;
|
---|
| 1959 | this._inputModalityDetector = _inputModalityDetector;
|
---|
| 1960 | /** The focus origin that the next focus event is a result of. */
|
---|
| 1961 | this._origin = null;
|
---|
| 1962 | /** Whether the window has just been focused. */
|
---|
| 1963 | this._windowFocused = false;
|
---|
| 1964 | /**
|
---|
| 1965 | * Whether the origin was determined via a touch interaction. Necessary as properly attributing
|
---|
| 1966 | * focus events to touch interactions requires special logic.
|
---|
| 1967 | */
|
---|
| 1968 | this._originFromTouchInteraction = false;
|
---|
| 1969 | /** Map of elements being monitored to their info. */
|
---|
| 1970 | this._elementInfo = new Map();
|
---|
| 1971 | /** The number of elements currently being monitored. */
|
---|
| 1972 | this._monitoredElementCount = 0;
|
---|
| 1973 | /**
|
---|
| 1974 | * Keeps track of the root nodes to which we've currently bound a focus/blur handler,
|
---|
| 1975 | * as well as the number of monitored elements that they contain. We have to treat focus/blur
|
---|
| 1976 | * handlers differently from the rest of the events, because the browser won't emit events
|
---|
| 1977 | * to the document when focus moves inside of a shadow root.
|
---|
| 1978 | */
|
---|
| 1979 | this._rootNodeFocusListenerCount = new Map();
|
---|
| 1980 | /**
|
---|
| 1981 | * Event listener for `focus` events on the window.
|
---|
| 1982 | * Needs to be an arrow function in order to preserve the context when it gets bound.
|
---|
| 1983 | */
|
---|
| 1984 | this._windowFocusListener = () => {
|
---|
| 1985 | // Make a note of when the window regains focus, so we can
|
---|
| 1986 | // restore the origin info for the focused element.
|
---|
| 1987 | this._windowFocused = true;
|
---|
| 1988 | this._windowFocusTimeoutId = setTimeout(() => this._windowFocused = false);
|
---|
| 1989 | };
|
---|
| 1990 | /** Subject for stopping our InputModalityDetector subscription. */
|
---|
| 1991 | this._stopInputModalityDetector = new Subject();
|
---|
| 1992 | /**
|
---|
| 1993 | * Event listener for `focus` and 'blur' events on the document.
|
---|
| 1994 | * Needs to be an arrow function in order to preserve the context when it gets bound.
|
---|
| 1995 | */
|
---|
| 1996 | this._rootNodeFocusAndBlurListener = (event) => {
|
---|
| 1997 | const target = _getEventTarget(event);
|
---|
| 1998 | const handler = event.type === 'focus' ? this._onFocus : this._onBlur;
|
---|
| 1999 | // We need to walk up the ancestor chain in order to support `checkChildren`.
|
---|
| 2000 | for (let element = target; element; element = element.parentElement) {
|
---|
| 2001 | handler.call(this, event, element);
|
---|
| 2002 | }
|
---|
| 2003 | };
|
---|
| 2004 | this._document = document;
|
---|
| 2005 | this._detectionMode = (options === null || options === void 0 ? void 0 : options.detectionMode) || 0 /* IMMEDIATE */;
|
---|
| 2006 | }
|
---|
| 2007 | monitor(element, checkChildren = false) {
|
---|
| 2008 | const nativeElement = coerceElement(element);
|
---|
| 2009 | // Do nothing if we're not on the browser platform or the passed in node isn't an element.
|
---|
| 2010 | if (!this._platform.isBrowser || nativeElement.nodeType !== 1) {
|
---|
| 2011 | return of(null);
|
---|
| 2012 | }
|
---|
| 2013 | // If the element is inside the shadow DOM, we need to bind our focus/blur listeners to
|
---|
| 2014 | // the shadow root, rather than the `document`, because the browser won't emit focus events
|
---|
| 2015 | // to the `document`, if focus is moving within the same shadow root.
|
---|
| 2016 | const rootNode = _getShadowRoot(nativeElement) || this._getDocument();
|
---|
| 2017 | const cachedInfo = this._elementInfo.get(nativeElement);
|
---|
| 2018 | // Check if we're already monitoring this element.
|
---|
| 2019 | if (cachedInfo) {
|
---|
| 2020 | if (checkChildren) {
|
---|
| 2021 | // TODO(COMP-318): this can be problematic, because it'll turn all non-checkChildren
|
---|
| 2022 | // observers into ones that behave as if `checkChildren` was turned on. We need a more
|
---|
| 2023 | // robust solution.
|
---|
| 2024 | cachedInfo.checkChildren = true;
|
---|
| 2025 | }
|
---|
| 2026 | return cachedInfo.subject;
|
---|
| 2027 | }
|
---|
| 2028 | // Create monitored element info.
|
---|
| 2029 | const info = {
|
---|
| 2030 | checkChildren: checkChildren,
|
---|
| 2031 | subject: new Subject(),
|
---|
| 2032 | rootNode
|
---|
| 2033 | };
|
---|
| 2034 | this._elementInfo.set(nativeElement, info);
|
---|
| 2035 | this._registerGlobalListeners(info);
|
---|
| 2036 | return info.subject;
|
---|
| 2037 | }
|
---|
| 2038 | stopMonitoring(element) {
|
---|
| 2039 | const nativeElement = coerceElement(element);
|
---|
| 2040 | const elementInfo = this._elementInfo.get(nativeElement);
|
---|
| 2041 | if (elementInfo) {
|
---|
| 2042 | elementInfo.subject.complete();
|
---|
| 2043 | this._setClasses(nativeElement);
|
---|
| 2044 | this._elementInfo.delete(nativeElement);
|
---|
| 2045 | this._removeGlobalListeners(elementInfo);
|
---|
| 2046 | }
|
---|
| 2047 | }
|
---|
| 2048 | focusVia(element, origin, options) {
|
---|
| 2049 | const nativeElement = coerceElement(element);
|
---|
| 2050 | const focusedElement = this._getDocument().activeElement;
|
---|
| 2051 | // If the element is focused already, calling `focus` again won't trigger the event listener
|
---|
| 2052 | // which means that the focus classes won't be updated. If that's the case, update the classes
|
---|
| 2053 | // directly without waiting for an event.
|
---|
| 2054 | if (nativeElement === focusedElement) {
|
---|
| 2055 | this._getClosestElementsInfo(nativeElement)
|
---|
| 2056 | .forEach(([currentElement, info]) => this._originChanged(currentElement, origin, info));
|
---|
| 2057 | }
|
---|
| 2058 | else {
|
---|
| 2059 | this._setOrigin(origin);
|
---|
| 2060 | // `focus` isn't available on the server
|
---|
| 2061 | if (typeof nativeElement.focus === 'function') {
|
---|
| 2062 | nativeElement.focus(options);
|
---|
| 2063 | }
|
---|
| 2064 | }
|
---|
| 2065 | }
|
---|
| 2066 | ngOnDestroy() {
|
---|
| 2067 | this._elementInfo.forEach((_info, element) => this.stopMonitoring(element));
|
---|
| 2068 | }
|
---|
| 2069 | /** Access injected document if available or fallback to global document reference */
|
---|
| 2070 | _getDocument() {
|
---|
| 2071 | return this._document || document;
|
---|
| 2072 | }
|
---|
| 2073 | /** Use defaultView of injected document if available or fallback to global window reference */
|
---|
| 2074 | _getWindow() {
|
---|
| 2075 | const doc = this._getDocument();
|
---|
| 2076 | return doc.defaultView || window;
|
---|
| 2077 | }
|
---|
| 2078 | _toggleClass(element, className, shouldSet) {
|
---|
| 2079 | if (shouldSet) {
|
---|
| 2080 | element.classList.add(className);
|
---|
| 2081 | }
|
---|
| 2082 | else {
|
---|
| 2083 | element.classList.remove(className);
|
---|
| 2084 | }
|
---|
| 2085 | }
|
---|
| 2086 | _getFocusOrigin(focusEventTarget) {
|
---|
| 2087 | if (this._origin) {
|
---|
| 2088 | // If the origin was realized via a touch interaction, we need to perform additional checks
|
---|
| 2089 | // to determine whether the focus origin should be attributed to touch or program.
|
---|
| 2090 | if (this._originFromTouchInteraction) {
|
---|
| 2091 | return this._shouldBeAttributedToTouch(focusEventTarget) ? 'touch' : 'program';
|
---|
| 2092 | }
|
---|
| 2093 | else {
|
---|
| 2094 | return this._origin;
|
---|
| 2095 | }
|
---|
| 2096 | }
|
---|
| 2097 | // If the window has just regained focus, we can restore the most recent origin from before the
|
---|
| 2098 | // window blurred. Otherwise, we've reached the point where we can't identify the source of the
|
---|
| 2099 | // focus. This typically means one of two things happened:
|
---|
| 2100 | //
|
---|
| 2101 | // 1) The element was programmatically focused, or
|
---|
| 2102 | // 2) The element was focused via screen reader navigation (which generally doesn't fire
|
---|
| 2103 | // events).
|
---|
| 2104 | //
|
---|
| 2105 | // Because we can't distinguish between these two cases, we default to setting `program`.
|
---|
| 2106 | return (this._windowFocused && this._lastFocusOrigin) ? this._lastFocusOrigin : 'program';
|
---|
| 2107 | }
|
---|
| 2108 | /**
|
---|
| 2109 | * Returns whether the focus event should be attributed to touch. Recall that in IMMEDIATE mode, a
|
---|
| 2110 | * touch origin isn't immediately reset at the next tick (see _setOrigin). This means that when we
|
---|
| 2111 | * handle a focus event following a touch interaction, we need to determine whether (1) the focus
|
---|
| 2112 | * event was directly caused by the touch interaction or (2) the focus event was caused by a
|
---|
| 2113 | * subsequent programmatic focus call triggered by the touch interaction.
|
---|
| 2114 | * @param focusEventTarget The target of the focus event under examination.
|
---|
| 2115 | */
|
---|
| 2116 | _shouldBeAttributedToTouch(focusEventTarget) {
|
---|
| 2117 | // Please note that this check is not perfect. Consider the following edge case:
|
---|
| 2118 | //
|
---|
| 2119 | // <div #parent tabindex="0">
|
---|
| 2120 | // <div #child tabindex="0" (click)="#parent.focus()"></div>
|
---|
| 2121 | // </div>
|
---|
| 2122 | //
|
---|
| 2123 | // Suppose there is a FocusMonitor in IMMEDIATE mode attached to #parent. When the user touches
|
---|
| 2124 | // #child, #parent is programmatically focused. This code will attribute the focus to touch
|
---|
| 2125 | // instead of program. This is a relatively minor edge-case that can be worked around by using
|
---|
| 2126 | // focusVia(parent, 'program') to focus #parent.
|
---|
| 2127 | return (this._detectionMode === 1 /* EVENTUAL */) ||
|
---|
| 2128 | !!(focusEventTarget === null || focusEventTarget === void 0 ? void 0 : focusEventTarget.contains(this._inputModalityDetector._mostRecentTarget));
|
---|
| 2129 | }
|
---|
| 2130 | /**
|
---|
| 2131 | * Sets the focus classes on the element based on the given focus origin.
|
---|
| 2132 | * @param element The element to update the classes on.
|
---|
| 2133 | * @param origin The focus origin.
|
---|
| 2134 | */
|
---|
| 2135 | _setClasses(element, origin) {
|
---|
| 2136 | this._toggleClass(element, 'cdk-focused', !!origin);
|
---|
| 2137 | this._toggleClass(element, 'cdk-touch-focused', origin === 'touch');
|
---|
| 2138 | this._toggleClass(element, 'cdk-keyboard-focused', origin === 'keyboard');
|
---|
| 2139 | this._toggleClass(element, 'cdk-mouse-focused', origin === 'mouse');
|
---|
| 2140 | this._toggleClass(element, 'cdk-program-focused', origin === 'program');
|
---|
| 2141 | }
|
---|
| 2142 | /**
|
---|
| 2143 | * Updates the focus origin. If we're using immediate detection mode, we schedule an async
|
---|
| 2144 | * function to clear the origin at the end of a timeout. The duration of the timeout depends on
|
---|
| 2145 | * the origin being set.
|
---|
| 2146 | * @param origin The origin to set.
|
---|
| 2147 | * @param isFromInteraction Whether we are setting the origin from an interaction event.
|
---|
| 2148 | */
|
---|
| 2149 | _setOrigin(origin, isFromInteraction = false) {
|
---|
| 2150 | this._ngZone.runOutsideAngular(() => {
|
---|
| 2151 | this._origin = origin;
|
---|
| 2152 | this._originFromTouchInteraction = (origin === 'touch') && isFromInteraction;
|
---|
| 2153 | // If we're in IMMEDIATE mode, reset the origin at the next tick (or in `TOUCH_BUFFER_MS` ms
|
---|
| 2154 | // for a touch event). We reset the origin at the next tick because Firefox focuses one tick
|
---|
| 2155 | // after the interaction event. We wait `TOUCH_BUFFER_MS` ms before resetting the origin for
|
---|
| 2156 | // a touch event because when a touch event is fired, the associated focus event isn't yet in
|
---|
| 2157 | // the event queue. Before doing so, clear any pending timeouts.
|
---|
| 2158 | if (this._detectionMode === 0 /* IMMEDIATE */) {
|
---|
| 2159 | clearTimeout(this._originTimeoutId);
|
---|
| 2160 | const ms = this._originFromTouchInteraction ? TOUCH_BUFFER_MS : 1;
|
---|
| 2161 | this._originTimeoutId = setTimeout(() => this._origin = null, ms);
|
---|
| 2162 | }
|
---|
| 2163 | });
|
---|
| 2164 | }
|
---|
| 2165 | /**
|
---|
| 2166 | * Handles focus events on a registered element.
|
---|
| 2167 | * @param event The focus event.
|
---|
| 2168 | * @param element The monitored element.
|
---|
| 2169 | */
|
---|
| 2170 | _onFocus(event, element) {
|
---|
| 2171 | // NOTE(mmalerba): We currently set the classes based on the focus origin of the most recent
|
---|
| 2172 | // focus event affecting the monitored element. If we want to use the origin of the first event
|
---|
| 2173 | // instead we should check for the cdk-focused class here and return if the element already has
|
---|
| 2174 | // it. (This only matters for elements that have includesChildren = true).
|
---|
| 2175 | // If we are not counting child-element-focus as focused, make sure that the event target is the
|
---|
| 2176 | // monitored element itself.
|
---|
| 2177 | const elementInfo = this._elementInfo.get(element);
|
---|
| 2178 | const focusEventTarget = _getEventTarget(event);
|
---|
| 2179 | if (!elementInfo || (!elementInfo.checkChildren && element !== focusEventTarget)) {
|
---|
| 2180 | return;
|
---|
| 2181 | }
|
---|
| 2182 | this._originChanged(element, this._getFocusOrigin(focusEventTarget), elementInfo);
|
---|
| 2183 | }
|
---|
| 2184 | /**
|
---|
| 2185 | * Handles blur events on a registered element.
|
---|
| 2186 | * @param event The blur event.
|
---|
| 2187 | * @param element The monitored element.
|
---|
| 2188 | */
|
---|
| 2189 | _onBlur(event, element) {
|
---|
| 2190 | // If we are counting child-element-focus as focused, make sure that we aren't just blurring in
|
---|
| 2191 | // order to focus another child of the monitored element.
|
---|
| 2192 | const elementInfo = this._elementInfo.get(element);
|
---|
| 2193 | if (!elementInfo || (elementInfo.checkChildren && event.relatedTarget instanceof Node &&
|
---|
| 2194 | element.contains(event.relatedTarget))) {
|
---|
| 2195 | return;
|
---|
| 2196 | }
|
---|
| 2197 | this._setClasses(element);
|
---|
| 2198 | this._emitOrigin(elementInfo.subject, null);
|
---|
| 2199 | }
|
---|
| 2200 | _emitOrigin(subject, origin) {
|
---|
| 2201 | this._ngZone.run(() => subject.next(origin));
|
---|
| 2202 | }
|
---|
| 2203 | _registerGlobalListeners(elementInfo) {
|
---|
| 2204 | if (!this._platform.isBrowser) {
|
---|
| 2205 | return;
|
---|
| 2206 | }
|
---|
| 2207 | const rootNode = elementInfo.rootNode;
|
---|
| 2208 | const rootNodeFocusListeners = this._rootNodeFocusListenerCount.get(rootNode) || 0;
|
---|
| 2209 | if (!rootNodeFocusListeners) {
|
---|
| 2210 | this._ngZone.runOutsideAngular(() => {
|
---|
| 2211 | rootNode.addEventListener('focus', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
|
---|
| 2212 | rootNode.addEventListener('blur', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
|
---|
| 2213 | });
|
---|
| 2214 | }
|
---|
| 2215 | this._rootNodeFocusListenerCount.set(rootNode, rootNodeFocusListeners + 1);
|
---|
| 2216 | // Register global listeners when first element is monitored.
|
---|
| 2217 | if (++this._monitoredElementCount === 1) {
|
---|
| 2218 | // Note: we listen to events in the capture phase so we
|
---|
| 2219 | // can detect them even if the user stops propagation.
|
---|
| 2220 | this._ngZone.runOutsideAngular(() => {
|
---|
| 2221 | const window = this._getWindow();
|
---|
| 2222 | window.addEventListener('focus', this._windowFocusListener);
|
---|
| 2223 | });
|
---|
| 2224 | // The InputModalityDetector is also just a collection of global listeners.
|
---|
| 2225 | this._inputModalityDetector.modalityDetected
|
---|
| 2226 | .pipe(takeUntil(this._stopInputModalityDetector))
|
---|
| 2227 | .subscribe(modality => { this._setOrigin(modality, true /* isFromInteraction */); });
|
---|
| 2228 | }
|
---|
| 2229 | }
|
---|
| 2230 | _removeGlobalListeners(elementInfo) {
|
---|
| 2231 | const rootNode = elementInfo.rootNode;
|
---|
| 2232 | if (this._rootNodeFocusListenerCount.has(rootNode)) {
|
---|
| 2233 | const rootNodeFocusListeners = this._rootNodeFocusListenerCount.get(rootNode);
|
---|
| 2234 | if (rootNodeFocusListeners > 1) {
|
---|
| 2235 | this._rootNodeFocusListenerCount.set(rootNode, rootNodeFocusListeners - 1);
|
---|
| 2236 | }
|
---|
| 2237 | else {
|
---|
| 2238 | rootNode.removeEventListener('focus', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
|
---|
| 2239 | rootNode.removeEventListener('blur', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
|
---|
| 2240 | this._rootNodeFocusListenerCount.delete(rootNode);
|
---|
| 2241 | }
|
---|
| 2242 | }
|
---|
| 2243 | // Unregister global listeners when last element is unmonitored.
|
---|
| 2244 | if (!--this._monitoredElementCount) {
|
---|
| 2245 | const window = this._getWindow();
|
---|
| 2246 | window.removeEventListener('focus', this._windowFocusListener);
|
---|
| 2247 | // Equivalently, stop our InputModalityDetector subscription.
|
---|
| 2248 | this._stopInputModalityDetector.next();
|
---|
| 2249 | // Clear timeouts for all potentially pending timeouts to prevent the leaks.
|
---|
| 2250 | clearTimeout(this._windowFocusTimeoutId);
|
---|
| 2251 | clearTimeout(this._originTimeoutId);
|
---|
| 2252 | }
|
---|
| 2253 | }
|
---|
| 2254 | /** Updates all the state on an element once its focus origin has changed. */
|
---|
| 2255 | _originChanged(element, origin, elementInfo) {
|
---|
| 2256 | this._setClasses(element, origin);
|
---|
| 2257 | this._emitOrigin(elementInfo.subject, origin);
|
---|
| 2258 | this._lastFocusOrigin = origin;
|
---|
| 2259 | }
|
---|
| 2260 | /**
|
---|
| 2261 | * Collects the `MonitoredElementInfo` of a particular element and
|
---|
| 2262 | * all of its ancestors that have enabled `checkChildren`.
|
---|
| 2263 | * @param element Element from which to start the search.
|
---|
| 2264 | */
|
---|
| 2265 | _getClosestElementsInfo(element) {
|
---|
| 2266 | const results = [];
|
---|
| 2267 | this._elementInfo.forEach((info, currentElement) => {
|
---|
| 2268 | if (currentElement === element || (info.checkChildren && currentElement.contains(element))) {
|
---|
| 2269 | results.push([currentElement, info]);
|
---|
| 2270 | }
|
---|
| 2271 | });
|
---|
| 2272 | return results;
|
---|
| 2273 | }
|
---|
| 2274 | }
|
---|
| 2275 | 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)); };
|
---|
| 2276 | 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" });
|
---|
| 2277 | FocusMonitor.ctorParameters = () => [
|
---|
| 2278 | { type: NgZone },
|
---|
| 2279 | { type: Platform },
|
---|
| 2280 | { type: InputModalityDetector },
|
---|
| 2281 | { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [DOCUMENT,] }] },
|
---|
| 2282 | { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [FOCUS_MONITOR_DEFAULT_OPTIONS,] }] }
|
---|
| 2283 | ];
|
---|
| 2284 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(FocusMonitor, [{
|
---|
| 2285 | type: Injectable,
|
---|
| 2286 | args: [{ providedIn: 'root' }]
|
---|
| 2287 | }], function () { return [{ type: ɵngcc0.NgZone }, { type: ɵngcc1.Platform }, { type: InputModalityDetector }, { type: undefined, decorators: [{
|
---|
| 2288 | type: Optional
|
---|
| 2289 | }, {
|
---|
| 2290 | type: Inject,
|
---|
| 2291 | args: [DOCUMENT]
|
---|
| 2292 | }] }, { type: undefined, decorators: [{
|
---|
| 2293 | type: Optional
|
---|
| 2294 | }, {
|
---|
| 2295 | type: Inject,
|
---|
| 2296 | args: [FOCUS_MONITOR_DEFAULT_OPTIONS]
|
---|
| 2297 | }] }]; }, null); })();
|
---|
| 2298 | /**
|
---|
| 2299 | * Directive that determines how a particular element was focused (via keyboard, mouse, touch, or
|
---|
| 2300 | * programmatically) and adds corresponding classes to the element.
|
---|
| 2301 | *
|
---|
| 2302 | * There are two variants of this directive:
|
---|
| 2303 | * 1) cdkMonitorElementFocus: does not consider an element to be focused if one of its children is
|
---|
| 2304 | * focused.
|
---|
| 2305 | * 2) cdkMonitorSubtreeFocus: considers an element focused if it or any of its children are focused.
|
---|
| 2306 | */
|
---|
| 2307 | class CdkMonitorFocus {
|
---|
| 2308 | constructor(_elementRef, _focusMonitor) {
|
---|
| 2309 | this._elementRef = _elementRef;
|
---|
| 2310 | this._focusMonitor = _focusMonitor;
|
---|
| 2311 | this.cdkFocusChange = new EventEmitter();
|
---|
| 2312 | }
|
---|
| 2313 | ngAfterViewInit() {
|
---|
| 2314 | const element = this._elementRef.nativeElement;
|
---|
| 2315 | this._monitorSubscription = this._focusMonitor.monitor(element, element.nodeType === 1 && element.hasAttribute('cdkMonitorSubtreeFocus'))
|
---|
| 2316 | .subscribe(origin => this.cdkFocusChange.emit(origin));
|
---|
| 2317 | }
|
---|
| 2318 | ngOnDestroy() {
|
---|
| 2319 | this._focusMonitor.stopMonitoring(this._elementRef);
|
---|
| 2320 | if (this._monitorSubscription) {
|
---|
| 2321 | this._monitorSubscription.unsubscribe();
|
---|
| 2322 | }
|
---|
| 2323 | }
|
---|
| 2324 | }
|
---|
| 2325 | CdkMonitorFocus.ɵfac = function CdkMonitorFocus_Factory(t) { return new (t || CdkMonitorFocus)(ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ElementRef), ɵngcc0.ɵɵdirectiveInject(FocusMonitor)); };
|
---|
| 2326 | CdkMonitorFocus.ɵdir = /*@__PURE__*/ ɵngcc0.ɵɵdefineDirective({ type: CdkMonitorFocus, selectors: [["", "cdkMonitorElementFocus", ""], ["", "cdkMonitorSubtreeFocus", ""]], outputs: { cdkFocusChange: "cdkFocusChange" } });
|
---|
| 2327 | CdkMonitorFocus.ctorParameters = () => [
|
---|
| 2328 | { type: ElementRef },
|
---|
| 2329 | { type: FocusMonitor }
|
---|
| 2330 | ];
|
---|
| 2331 | CdkMonitorFocus.propDecorators = {
|
---|
| 2332 | cdkFocusChange: [{ type: Output }]
|
---|
| 2333 | };
|
---|
| 2334 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(CdkMonitorFocus, [{
|
---|
| 2335 | type: Directive,
|
---|
| 2336 | args: [{
|
---|
| 2337 | selector: '[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]'
|
---|
| 2338 | }]
|
---|
| 2339 | }], function () { return [{ type: ɵngcc0.ElementRef }, { type: FocusMonitor }]; }, { cdkFocusChange: [{
|
---|
| 2340 | type: Output
|
---|
| 2341 | }] }); })();
|
---|
| 2342 |
|
---|
| 2343 | /**
|
---|
| 2344 | * @license
|
---|
| 2345 | * Copyright Google LLC All Rights Reserved.
|
---|
| 2346 | *
|
---|
| 2347 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 2348 | * found in the LICENSE file at https://angular.io/license
|
---|
| 2349 | */
|
---|
| 2350 | /** CSS class applied to the document body when in black-on-white high-contrast mode. */
|
---|
| 2351 | const BLACK_ON_WHITE_CSS_CLASS = 'cdk-high-contrast-black-on-white';
|
---|
| 2352 | /** CSS class applied to the document body when in white-on-black high-contrast mode. */
|
---|
| 2353 | const WHITE_ON_BLACK_CSS_CLASS = 'cdk-high-contrast-white-on-black';
|
---|
| 2354 | /** CSS class applied to the document body when in high-contrast mode. */
|
---|
| 2355 | const HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS = 'cdk-high-contrast-active';
|
---|
| 2356 | /**
|
---|
| 2357 | * Service to determine whether the browser is currently in a high-contrast-mode environment.
|
---|
| 2358 | *
|
---|
| 2359 | * Microsoft Windows supports an accessibility feature called "High Contrast Mode". This mode
|
---|
| 2360 | * changes the appearance of all applications, including web applications, to dramatically increase
|
---|
| 2361 | * contrast.
|
---|
| 2362 | *
|
---|
| 2363 | * IE, Edge, and Firefox currently support this mode. Chrome does not support Windows High Contrast
|
---|
| 2364 | * Mode. This service does not detect high-contrast mode as added by the Chrome "High Contrast"
|
---|
| 2365 | * browser extension.
|
---|
| 2366 | */
|
---|
| 2367 | class HighContrastModeDetector {
|
---|
| 2368 | constructor(_platform, document) {
|
---|
| 2369 | this._platform = _platform;
|
---|
| 2370 | this._document = document;
|
---|
| 2371 | }
|
---|
| 2372 | /** Gets the current high-contrast-mode for the page. */
|
---|
| 2373 | getHighContrastMode() {
|
---|
| 2374 | if (!this._platform.isBrowser) {
|
---|
| 2375 | return 0 /* NONE */;
|
---|
| 2376 | }
|
---|
| 2377 | // Create a test element with an arbitrary background-color that is neither black nor
|
---|
| 2378 | // white; high-contrast mode will coerce the color to either black or white. Also ensure that
|
---|
| 2379 | // appending the test element to the DOM does not affect layout by absolutely positioning it
|
---|
| 2380 | const testElement = this._document.createElement('div');
|
---|
| 2381 | testElement.style.backgroundColor = 'rgb(1,2,3)';
|
---|
| 2382 | testElement.style.position = 'absolute';
|
---|
| 2383 | this._document.body.appendChild(testElement);
|
---|
| 2384 | // Get the computed style for the background color, collapsing spaces to normalize between
|
---|
| 2385 | // browsers. Once we get this color, we no longer need the test element. Access the `window`
|
---|
| 2386 | // via the document so we can fake it in tests. Note that we have extra null checks, because
|
---|
| 2387 | // this logic will likely run during app bootstrap and throwing can break the entire app.
|
---|
| 2388 | const documentWindow = this._document.defaultView || window;
|
---|
| 2389 | const computedStyle = (documentWindow && documentWindow.getComputedStyle) ?
|
---|
| 2390 | documentWindow.getComputedStyle(testElement) : null;
|
---|
| 2391 | const computedColor = (computedStyle && computedStyle.backgroundColor || '').replace(/ /g, '');
|
---|
| 2392 | this._document.body.removeChild(testElement);
|
---|
| 2393 | switch (computedColor) {
|
---|
| 2394 | case 'rgb(0,0,0)': return 2 /* WHITE_ON_BLACK */;
|
---|
| 2395 | case 'rgb(255,255,255)': return 1 /* BLACK_ON_WHITE */;
|
---|
| 2396 | }
|
---|
| 2397 | return 0 /* NONE */;
|
---|
| 2398 | }
|
---|
| 2399 | /** Applies CSS classes indicating high-contrast mode to document body (browser-only). */
|
---|
| 2400 | _applyBodyHighContrastModeCssClasses() {
|
---|
| 2401 | if (!this._hasCheckedHighContrastMode && this._platform.isBrowser && this._document.body) {
|
---|
| 2402 | const bodyClasses = this._document.body.classList;
|
---|
| 2403 | // IE11 doesn't support `classList` operations with multiple arguments
|
---|
| 2404 | bodyClasses.remove(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS);
|
---|
| 2405 | bodyClasses.remove(BLACK_ON_WHITE_CSS_CLASS);
|
---|
| 2406 | bodyClasses.remove(WHITE_ON_BLACK_CSS_CLASS);
|
---|
| 2407 | this._hasCheckedHighContrastMode = true;
|
---|
| 2408 | const mode = this.getHighContrastMode();
|
---|
| 2409 | if (mode === 1 /* BLACK_ON_WHITE */) {
|
---|
| 2410 | bodyClasses.add(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS);
|
---|
| 2411 | bodyClasses.add(BLACK_ON_WHITE_CSS_CLASS);
|
---|
| 2412 | }
|
---|
| 2413 | else if (mode === 2 /* WHITE_ON_BLACK */) {
|
---|
| 2414 | bodyClasses.add(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS);
|
---|
| 2415 | bodyClasses.add(WHITE_ON_BLACK_CSS_CLASS);
|
---|
| 2416 | }
|
---|
| 2417 | }
|
---|
| 2418 | }
|
---|
| 2419 | }
|
---|
| 2420 | HighContrastModeDetector.ɵfac = function HighContrastModeDetector_Factory(t) { return new (t || HighContrastModeDetector)(ɵngcc0.ɵɵinject(ɵngcc1.Platform), ɵngcc0.ɵɵinject(DOCUMENT)); };
|
---|
| 2421 | HighContrastModeDetector.ɵprov = i0.ɵɵdefineInjectable({ factory: function HighContrastModeDetector_Factory() { return new HighContrastModeDetector(i0.ɵɵinject(i1.Platform), i0.ɵɵinject(i2.DOCUMENT)); }, token: HighContrastModeDetector, providedIn: "root" });
|
---|
| 2422 | HighContrastModeDetector.ctorParameters = () => [
|
---|
| 2423 | { type: Platform },
|
---|
| 2424 | { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
|
---|
| 2425 | ];
|
---|
| 2426 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(HighContrastModeDetector, [{
|
---|
| 2427 | type: Injectable,
|
---|
| 2428 | args: [{ providedIn: 'root' }]
|
---|
| 2429 | }], function () { return [{ type: ɵngcc1.Platform }, { type: undefined, decorators: [{
|
---|
| 2430 | type: Inject,
|
---|
| 2431 | args: [DOCUMENT]
|
---|
| 2432 | }] }]; }, null); })();
|
---|
| 2433 |
|
---|
| 2434 | /**
|
---|
| 2435 | * @license
|
---|
| 2436 | * Copyright Google LLC All Rights Reserved.
|
---|
| 2437 | *
|
---|
| 2438 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 2439 | * found in the LICENSE file at https://angular.io/license
|
---|
| 2440 | */
|
---|
| 2441 | class A11yModule {
|
---|
| 2442 | constructor(highContrastModeDetector) {
|
---|
| 2443 | highContrastModeDetector._applyBodyHighContrastModeCssClasses();
|
---|
| 2444 | }
|
---|
| 2445 | }
|
---|
| 2446 | A11yModule.ɵfac = function A11yModule_Factory(t) { return new (t || A11yModule)(ɵngcc0.ɵɵinject(HighContrastModeDetector)); };
|
---|
| 2447 | A11yModule.ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: A11yModule });
|
---|
| 2448 | A11yModule.ɵinj = /*@__PURE__*/ ɵngcc0.ɵɵdefineInjector({ imports: [[PlatformModule, ObserversModule]] });
|
---|
| 2449 | A11yModule.ctorParameters = () => [
|
---|
| 2450 | { type: HighContrastModeDetector }
|
---|
| 2451 | ];
|
---|
| 2452 | (function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(A11yModule, [{
|
---|
| 2453 | type: NgModule,
|
---|
| 2454 | args: [{
|
---|
| 2455 | imports: [PlatformModule, ObserversModule],
|
---|
| 2456 | declarations: [CdkAriaLive, CdkTrapFocus, CdkMonitorFocus],
|
---|
| 2457 | exports: [CdkAriaLive, CdkTrapFocus, CdkMonitorFocus]
|
---|
| 2458 | }]
|
---|
| 2459 | }], function () { return [{ type: HighContrastModeDetector }]; }, null); })();
|
---|
| 2460 | (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]; } }); })();
|
---|
| 2461 |
|
---|
| 2462 | /**
|
---|
| 2463 | * @license
|
---|
| 2464 | * Copyright Google LLC All Rights Reserved.
|
---|
| 2465 | *
|
---|
| 2466 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 2467 | * found in the LICENSE file at https://angular.io/license
|
---|
| 2468 | */
|
---|
| 2469 |
|
---|
| 2470 | /**
|
---|
| 2471 | * Generated bundle index. Do not edit.
|
---|
| 2472 | */
|
---|
| 2473 |
|
---|
| 2474 | 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 };
|
---|
| 2475 |
|
---|
| 2476 | //# sourceMappingURL=a11y.js.map |
---|