UNPKG

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