UNPKG

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