@angular/cdk 20.0.0-next.0 → 20.0.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/a11y/index.d.ts +330 -1234
  2. package/a11y-module.d-7d03e079.d.ts +313 -0
  3. package/accordion/index.d.ts +8 -27
  4. package/activedescendant-key-manager.d-11921e3a.d.ts +31 -0
  5. package/bidi/index.d.ts +3 -62
  6. package/bidi-module.d-f8648621.d.ts +53 -0
  7. package/clipboard/index.d.ts +61 -75
  8. package/coercion/index.d.ts +10 -33
  9. package/coercion/private/index.d.ts +2 -2
  10. package/collections/index.d.ts +13 -291
  11. package/data-source.d-7cab2c9d.d.ts +42 -0
  12. package/dialog/index.d.ts +204 -249
  13. package/drag-drop/index.d.ts +1077 -1157
  14. package/fesm2022/a11y-module-e6996d20.mjs +952 -0
  15. package/fesm2022/a11y-module-e6996d20.mjs.map +1 -0
  16. package/fesm2022/a11y.mjs +47 -2445
  17. package/fesm2022/a11y.mjs.map +1 -1
  18. package/fesm2022/accordion.mjs +12 -16
  19. package/fesm2022/accordion.mjs.map +1 -1
  20. package/fesm2022/activedescendant-key-manager-1351a9d3.mjs +16 -0
  21. package/fesm2022/activedescendant-key-manager-1351a9d3.mjs.map +1 -0
  22. package/fesm2022/array-ee3b4bab.mjs +6 -0
  23. package/fesm2022/array-ee3b4bab.mjs.map +1 -0
  24. package/fesm2022/backwards-compatibility-bcbe473e.mjs +25 -0
  25. package/fesm2022/backwards-compatibility-bcbe473e.mjs.map +1 -0
  26. package/fesm2022/bidi-module-0726b65c.mjs +78 -0
  27. package/fesm2022/bidi-module-0726b65c.mjs.map +1 -0
  28. package/fesm2022/bidi.mjs +4 -143
  29. package/fesm2022/bidi.mjs.map +1 -1
  30. package/fesm2022/breakpoints-observer-d4584b66.mjs +179 -0
  31. package/fesm2022/breakpoints-observer-d4584b66.mjs.map +1 -0
  32. package/fesm2022/cdk.mjs +1 -1
  33. package/fesm2022/cdk.mjs.map +1 -1
  34. package/fesm2022/clipboard.mjs +10 -14
  35. package/fesm2022/clipboard.mjs.map +1 -1
  36. package/fesm2022/coercion/private.mjs +2 -18
  37. package/fesm2022/coercion/private.mjs.map +1 -1
  38. package/fesm2022/coercion.mjs +5 -39
  39. package/fesm2022/coercion.mjs.map +1 -1
  40. package/fesm2022/collections.mjs +7 -476
  41. package/fesm2022/collections.mjs.map +1 -1
  42. package/fesm2022/css-pixel-value-286c9a60.mjs +10 -0
  43. package/fesm2022/css-pixel-value-286c9a60.mjs.map +1 -0
  44. package/fesm2022/data-source-5320b6fd.mjs +15 -0
  45. package/fesm2022/data-source-5320b6fd.mjs.map +1 -0
  46. package/fesm2022/dialog.mjs +37 -39
  47. package/fesm2022/dialog.mjs.map +1 -1
  48. package/fesm2022/directionality-7ea26429.mjs +72 -0
  49. package/fesm2022/directionality-7ea26429.mjs.map +1 -0
  50. package/fesm2022/dispose-view-repeater-strategy-b11b87ea.mjs +44 -0
  51. package/fesm2022/dispose-view-repeater-strategy-b11b87ea.mjs.map +1 -0
  52. package/fesm2022/drag-drop.mjs +48 -50
  53. package/fesm2022/drag-drop.mjs.map +1 -1
  54. package/fesm2022/element-705567fe.mjs +29 -0
  55. package/fesm2022/element-705567fe.mjs.map +1 -0
  56. package/fesm2022/fake-event-detection-7055b1bd.mjs +24 -0
  57. package/fesm2022/fake-event-detection-7055b1bd.mjs.map +1 -0
  58. package/fesm2022/focus-key-manager-58d29acd.mjs +22 -0
  59. package/fesm2022/focus-key-manager-58d29acd.mjs.map +1 -0
  60. package/fesm2022/focus-monitor-cebaa0d1.mjs +629 -0
  61. package/fesm2022/focus-monitor-cebaa0d1.mjs.map +1 -0
  62. package/fesm2022/id-generator-fba495fb.mjs +37 -0
  63. package/fesm2022/id-generator-fba495fb.mjs.map +1 -0
  64. package/fesm2022/keycodes-107cd3e4.mjs +122 -0
  65. package/fesm2022/keycodes-107cd3e4.mjs.map +1 -0
  66. package/fesm2022/keycodes.mjs +2 -136
  67. package/fesm2022/keycodes.mjs.map +1 -1
  68. package/fesm2022/layout.mjs +12 -184
  69. package/fesm2022/layout.mjs.map +1 -1
  70. package/fesm2022/list-key-manager-c7b5cefb.mjs +360 -0
  71. package/fesm2022/list-key-manager-c7b5cefb.mjs.map +1 -0
  72. package/fesm2022/listbox.mjs +21 -20
  73. package/fesm2022/listbox.mjs.map +1 -1
  74. package/fesm2022/menu.mjs +76 -60
  75. package/fesm2022/menu.mjs.map +1 -1
  76. package/fesm2022/modifiers-33a5859e.mjs +13 -0
  77. package/fesm2022/modifiers-33a5859e.mjs.map +1 -0
  78. package/fesm2022/observable-97c0792c.mjs +15 -0
  79. package/fesm2022/observable-97c0792c.mjs.map +1 -0
  80. package/fesm2022/observe-content-d2a6b5a0.mjs +210 -0
  81. package/fesm2022/observe-content-d2a6b5a0.mjs.map +1 -0
  82. package/fesm2022/observers/private.mjs +3 -7
  83. package/fesm2022/observers/private.mjs.map +1 -1
  84. package/fesm2022/observers.mjs +5 -213
  85. package/fesm2022/observers.mjs.map +1 -1
  86. package/fesm2022/overlay-module-863b82c9.mjs +3029 -0
  87. package/fesm2022/overlay-module-863b82c9.mjs.map +1 -0
  88. package/fesm2022/overlay.mjs +28 -3019
  89. package/fesm2022/overlay.mjs.map +1 -1
  90. package/fesm2022/passive-listeners-c0bdc49f.mjs +31 -0
  91. package/fesm2022/passive-listeners-c0bdc49f.mjs.map +1 -0
  92. package/fesm2022/platform-1be098b0.mjs +77 -0
  93. package/fesm2022/platform-1be098b0.mjs.map +1 -0
  94. package/fesm2022/platform.mjs +13 -293
  95. package/fesm2022/platform.mjs.map +1 -1
  96. package/fesm2022/portal-directives-c88fea11.mjs +615 -0
  97. package/fesm2022/portal-directives-c88fea11.mjs.map +1 -0
  98. package/fesm2022/portal.mjs +3 -650
  99. package/fesm2022/portal.mjs.map +1 -1
  100. package/fesm2022/private.mjs +3 -63
  101. package/fesm2022/private.mjs.map +1 -1
  102. package/fesm2022/recycle-view-repeater-strategy-c1712813.mjs +156 -0
  103. package/fesm2022/recycle-view-repeater-strategy-c1712813.mjs.map +1 -0
  104. package/fesm2022/scrolling-61955dd1.mjs +99 -0
  105. package/fesm2022/scrolling-61955dd1.mjs.map +1 -0
  106. package/fesm2022/scrolling-module-aa9eeac5.mjs +1463 -0
  107. package/fesm2022/scrolling-module-aa9eeac5.mjs.map +1 -0
  108. package/fesm2022/scrolling.mjs +12 -1463
  109. package/fesm2022/scrolling.mjs.map +1 -1
  110. package/fesm2022/selection-model-30243dba.mjs +221 -0
  111. package/fesm2022/selection-model-30243dba.mjs.map +1 -0
  112. package/fesm2022/shadow-dom-9f403d00.mjs +49 -0
  113. package/fesm2022/shadow-dom-9f403d00.mjs.map +1 -0
  114. package/fesm2022/stepper.mjs +32 -30
  115. package/fesm2022/stepper.mjs.map +1 -1
  116. package/fesm2022/style-loader-e14dc585.mjs +47 -0
  117. package/fesm2022/style-loader-e14dc585.mjs.map +1 -0
  118. package/fesm2022/table.mjs +88 -132
  119. package/fesm2022/table.mjs.map +1 -1
  120. package/fesm2022/test-environment-34eef1ee.mjs +19 -0
  121. package/fesm2022/test-environment-34eef1ee.mjs.map +1 -0
  122. package/fesm2022/testing/selenium-webdriver.mjs +2 -1
  123. package/fesm2022/testing/selenium-webdriver.mjs.map +1 -1
  124. package/fesm2022/testing/testbed.mjs +33 -74
  125. package/fesm2022/testing/testbed.mjs.map +1 -1
  126. package/fesm2022/testing.mjs +2 -697
  127. package/fesm2022/testing.mjs.map +1 -1
  128. package/fesm2022/text-field.mjs +24 -23
  129. package/fesm2022/text-field.mjs.map +1 -1
  130. package/fesm2022/text-filtering-b60ba8a2.mjs +698 -0
  131. package/fesm2022/text-filtering-b60ba8a2.mjs.map +1 -0
  132. package/fesm2022/tree-key-manager-2f20c79c.mjs +360 -0
  133. package/fesm2022/tree-key-manager-2f20c79c.mjs.map +1 -0
  134. package/fesm2022/tree.mjs +33 -33
  135. package/fesm2022/tree.mjs.map +1 -1
  136. package/fesm2022/typeahead-11ae39bd.mjs +88 -0
  137. package/fesm2022/typeahead-11ae39bd.mjs.map +1 -0
  138. package/fesm2022/unique-selection-dispatcher-1d6f91d8.mjs +49 -0
  139. package/fesm2022/unique-selection-dispatcher-1d6f91d8.mjs.map +1 -0
  140. package/fesm2022/visually-hidden-83aea4a0.mjs +18 -0
  141. package/fesm2022/visually-hidden-83aea4a0.mjs.map +1 -0
  142. package/focus-key-manager.d-415a6958.d.ts +33 -0
  143. package/focus-monitor.d-810a02e6.d.ts +209 -0
  144. package/harness-environment.d-4d615248.d.ts +619 -0
  145. package/index.d.ts +2 -2
  146. package/keycodes/index.d.ts +123 -244
  147. package/layout/index.d.ts +23 -25
  148. package/list-key-manager.d-72e9a2e7.d.ts +164 -0
  149. package/listbox/index.d.ts +91 -107
  150. package/menu/index.d.ts +596 -682
  151. package/number-property.d-ce316715.d.ts +15 -0
  152. package/observe-content.d-c08bc882.d.ts +84 -0
  153. package/observers/index.d.ts +4 -90
  154. package/observers/private/index.d.ts +3 -3
  155. package/overlay/index.d.ts +110 -951
  156. package/overlay-module.d-5d06db8a.d.ts +790 -0
  157. package/package.json +1 -1
  158. package/platform/index.d.ts +45 -86
  159. package/platform.d-0a5b4792.d.ts +33 -0
  160. package/portal/index.d.ts +5 -264
  161. package/portal-directives.d-d345bd53.d.ts +210 -0
  162. package/private/index.d.ts +3 -20
  163. package/schematics/ng-add/index.js +1 -1
  164. package/schematics/ng-add/index.mjs +1 -1
  165. package/schematics/ng-update/html-parsing/angular.js +2 -2
  166. package/schematics/ng-update/html-parsing/angular.mjs +2 -2
  167. package/scrolling/index.d.ts +7 -687
  168. package/scrolling-module.d-a08a462d.d.ts +551 -0
  169. package/selection-model.d-1a70542c.d.ts +111 -0
  170. package/stepper/index.d.ts +74 -124
  171. package/style-loader.d-19baab84.d.ts +21 -0
  172. package/table/index.d.ts +329 -453
  173. package/testing/index.d.ts +32 -675
  174. package/testing/selenium-webdriver/index.d.ts +30 -20
  175. package/testing/testbed/index.d.ts +9 -19
  176. package/text-field/index.d.ts +11 -30
  177. package/tree/index.d.ts +205 -271
  178. package/tree-key-manager-strategy.d-603161dd.d.ts +116 -0
  179. package/unique-selection-dispatcher.d-7993b9f5.d.ts +32 -0
  180. package/view-repeater.d-79039e1f.d.ts +88 -0
  181. package/viewport-ruler.d-f3d3e82f.d.ts +57 -0
package/fesm2022/a11y.mjs CHANGED
@@ -1,15 +1,32 @@
1
+ export { C as CdkMonitorFocus, c as FOCUS_MONITOR_DEFAULT_OPTIONS, d as FocusMonitor, F as FocusMonitorDetectionMode, a as INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS, b as INPUT_MODALITY_DETECTOR_OPTIONS, I as InputModalityDetector } from './focus-monitor-cebaa0d1.mjs';
2
+ import { F as FocusTrap, I as InteractivityChecker } from './a11y-module-e6996d20.mjs';
3
+ export { A as A11yModule, d as CdkAriaLive, C as CdkTrapFocus, F as FocusTrap, b as FocusTrapFactory, a as HighContrastMode, H as HighContrastModeDetector, I as InteractivityChecker, c as IsFocusableConfig, g as LIVE_ANNOUNCER_DEFAULT_OPTIONS, e as LIVE_ANNOUNCER_ELEMENT_TOKEN, f as LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY, L as LiveAnnouncer } from './a11y-module-e6996d20.mjs';
4
+ export { _ as _IdGenerator } from './id-generator-fba495fb.mjs';
1
5
  import { DOCUMENT } from '@angular/common';
2
6
  import * as i0 from '@angular/core';
3
- import { inject, APP_ID, Injectable, signal, QueryList, isSignal, effect, InjectionToken, afterNextRender, NgZone, Injector, ElementRef, booleanAttribute, Directive, Input, RendererFactory2, EventEmitter, Output, NgModule } from '@angular/core';
4
- import { Platform, _getFocusedElementPierceShadowDom, _getEventTarget, _bindEventWithOptions, normalizePassiveListenerOptions, _getShadowRoot } from '@angular/cdk/platform';
5
- import { _CdkPrivateStyleLoader, _VisuallyHiddenLoader } from '@angular/cdk/private';
6
- import { A, Z, ZERO, NINE, hasModifierKey, 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';
7
- import { Subject, Subscription, isObservable, of, BehaviorSubject } from 'rxjs';
8
- import { tap, debounceTime, filter, map, take, skip, distinctUntilChanged, takeUntil } from 'rxjs/operators';
9
- import { coerceObservable } from '@angular/cdk/coercion/private';
10
- import { ContentObserver, ObserversModule } from '@angular/cdk/observers';
11
- import { coerceElement } from '@angular/cdk/coercion';
12
- import { BreakpointObserver } from '@angular/cdk/layout';
7
+ import { inject, APP_ID, Injectable, InjectionToken, NgZone, Injector } from '@angular/core';
8
+ import { P as Platform } from './platform-1be098b0.mjs';
9
+ import { _ as _CdkPrivateStyleLoader } from './style-loader-e14dc585.mjs';
10
+ import { _ as _VisuallyHiddenLoader } from './visually-hidden-83aea4a0.mjs';
11
+ export { A as ActiveDescendantKeyManager } from './activedescendant-key-manager-1351a9d3.mjs';
12
+ export { F as FocusKeyManager } from './focus-key-manager-58d29acd.mjs';
13
+ export { L as ListKeyManager } from './list-key-manager-c7b5cefb.mjs';
14
+ import { Subject } from 'rxjs';
15
+ import { T as TREE_KEY_MANAGER } from './tree-key-manager-2f20c79c.mjs';
16
+ export { T as TREE_KEY_MANAGER, b as TREE_KEY_MANAGER_FACTORY, c as TREE_KEY_MANAGER_FACTORY_PROVIDER, a as TreeKeyManager } from './tree-key-manager-2f20c79c.mjs';
17
+ export { i as isFakeMousedownFromScreenReader, a as isFakeTouchstartFromScreenReader } from './fake-event-detection-7055b1bd.mjs';
18
+ import 'rxjs/operators';
19
+ import './keycodes-107cd3e4.mjs';
20
+ import './shadow-dom-9f403d00.mjs';
21
+ import './backwards-compatibility-bcbe473e.mjs';
22
+ import './passive-listeners-c0bdc49f.mjs';
23
+ import './element-705567fe.mjs';
24
+ import './breakpoints-observer-d4584b66.mjs';
25
+ import './array-ee3b4bab.mjs';
26
+ import './observe-content-d2a6b5a0.mjs';
27
+ import './typeahead-11ae39bd.mjs';
28
+ import './modifiers-33a5859e.mjs';
29
+ import './observable-97c0792c.mjs';
13
30
 
14
31
  /** IDs are delimited by an empty space, as per the spec. */
15
32
  const ID_DELIMITER = ' ';
@@ -244,10 +261,10 @@ class AriaDescriber {
244
261
  _isElementNode(element) {
245
262
  return element.nodeType === this._document.ELEMENT_NODE;
246
263
  }
247
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: AriaDescriber, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
248
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: AriaDescriber, providedIn: 'root' });
264
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.0.0-next.1", ngImport: i0, type: AriaDescriber, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
265
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.0.0-next.1", ngImport: i0, type: AriaDescriber, providedIn: 'root' });
249
266
  }
250
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: AriaDescriber, decorators: [{
267
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.0.0-next.1", ngImport: i0, type: AriaDescriber, decorators: [{
251
268
  type: Injectable,
252
269
  args: [{ providedIn: 'root' }]
253
270
  }], ctorParameters: () => [] });
@@ -262,814 +279,6 @@ function setMessageId(element, serviceId) {
262
279
  }
263
280
  }
264
281
 
265
- const DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL_MS = 200;
266
- /**
267
- * Selects items based on keyboard inputs. Implements the typeahead functionality of
268
- * `role="listbox"` or `role="tree"` and other related roles.
269
- */
270
- class Typeahead {
271
- _letterKeyStream = new Subject();
272
- _items = [];
273
- _selectedItemIndex = -1;
274
- /** Buffer for the letters that the user has pressed */
275
- _pressedLetters = [];
276
- _skipPredicateFn;
277
- _selectedItem = new Subject();
278
- selectedItem = this._selectedItem;
279
- constructor(initialItems, config) {
280
- const typeAheadInterval = typeof config?.debounceInterval === 'number'
281
- ? config.debounceInterval
282
- : DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL_MS;
283
- if (config?.skipPredicate) {
284
- this._skipPredicateFn = config.skipPredicate;
285
- }
286
- if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
287
- initialItems.length &&
288
- initialItems.some(item => typeof item.getLabel !== 'function')) {
289
- throw new Error('KeyManager items in typeahead mode must implement the `getLabel` method.');
290
- }
291
- this.setItems(initialItems);
292
- this._setupKeyHandler(typeAheadInterval);
293
- }
294
- destroy() {
295
- this._pressedLetters = [];
296
- this._letterKeyStream.complete();
297
- this._selectedItem.complete();
298
- }
299
- setCurrentSelectedItemIndex(index) {
300
- this._selectedItemIndex = index;
301
- }
302
- setItems(items) {
303
- this._items = items;
304
- }
305
- handleKey(event) {
306
- const keyCode = event.keyCode;
307
- // Attempt to use the `event.key` which also maps it to the user's keyboard language,
308
- // otherwise fall back to resolving alphanumeric characters via the keyCode.
309
- if (event.key && event.key.length === 1) {
310
- this._letterKeyStream.next(event.key.toLocaleUpperCase());
311
- }
312
- else if ((keyCode >= A && keyCode <= Z) || (keyCode >= ZERO && keyCode <= NINE)) {
313
- this._letterKeyStream.next(String.fromCharCode(keyCode));
314
- }
315
- }
316
- /** Gets whether the user is currently typing into the manager using the typeahead feature. */
317
- isTyping() {
318
- return this._pressedLetters.length > 0;
319
- }
320
- /** Resets the currently stored sequence of typed letters. */
321
- reset() {
322
- this._pressedLetters = [];
323
- }
324
- _setupKeyHandler(typeAheadInterval) {
325
- // Debounce the presses of non-navigational keys, collect the ones that correspond to letters
326
- // and convert those letters back into a string. Afterwards find the first item that starts
327
- // with that string and select it.
328
- this._letterKeyStream
329
- .pipe(tap(letter => this._pressedLetters.push(letter)), debounceTime(typeAheadInterval), filter(() => this._pressedLetters.length > 0), map(() => this._pressedLetters.join('').toLocaleUpperCase()))
330
- .subscribe(inputString => {
331
- // Start at 1 because we want to start searching at the item immediately
332
- // following the current active item.
333
- for (let i = 1; i < this._items.length + 1; i++) {
334
- const index = (this._selectedItemIndex + i) % this._items.length;
335
- const item = this._items[index];
336
- if (!this._skipPredicateFn?.(item) &&
337
- item.getLabel?.().toLocaleUpperCase().trim().indexOf(inputString) === 0) {
338
- this._selectedItem.next(item);
339
- break;
340
- }
341
- }
342
- this._pressedLetters = [];
343
- });
344
- }
345
- }
346
-
347
- /**
348
- * This class manages keyboard events for selectable lists. If you pass it a query list
349
- * of items, it will set the active item correctly when arrow events occur.
350
- */
351
- class ListKeyManager {
352
- _items;
353
- _activeItemIndex = -1;
354
- _activeItem = signal(null);
355
- _wrap = false;
356
- _typeaheadSubscription = Subscription.EMPTY;
357
- _itemChangesSubscription;
358
- _vertical = true;
359
- _horizontal;
360
- _allowedModifierKeys = [];
361
- _homeAndEnd = false;
362
- _pageUpAndDown = { enabled: false, delta: 10 };
363
- _effectRef;
364
- _typeahead;
365
- /**
366
- * Predicate function that can be used to check whether an item should be skipped
367
- * by the key manager. By default, disabled items are skipped.
368
- */
369
- _skipPredicateFn = (item) => item.disabled;
370
- constructor(_items, injector) {
371
- this._items = _items;
372
- // We allow for the items to be an array because, in some cases, the consumer may
373
- // not have access to a QueryList of the items they want to manage (e.g. when the
374
- // items aren't being collected via `ViewChildren` or `ContentChildren`).
375
- if (_items instanceof QueryList) {
376
- this._itemChangesSubscription = _items.changes.subscribe((newItems) => this._itemsChanged(newItems.toArray()));
377
- }
378
- else if (isSignal(_items)) {
379
- if (!injector && (typeof ngDevMode === 'undefined' || ngDevMode)) {
380
- throw new Error('ListKeyManager constructed with a signal must receive an injector');
381
- }
382
- this._effectRef = effect(() => this._itemsChanged(_items()), { injector });
383
- }
384
- }
385
- /**
386
- * Stream that emits any time the TAB key is pressed, so components can react
387
- * when focus is shifted off of the list.
388
- */
389
- tabOut = new Subject();
390
- /** Stream that emits whenever the active item of the list manager changes. */
391
- change = new Subject();
392
- /**
393
- * Sets the predicate function that determines which items should be skipped by the
394
- * list key manager.
395
- * @param predicate Function that determines whether the given item should be skipped.
396
- */
397
- skipPredicate(predicate) {
398
- this._skipPredicateFn = predicate;
399
- return this;
400
- }
401
- /**
402
- * Configures wrapping mode, which determines whether the active item will wrap to
403
- * the other end of list when there are no more items in the given direction.
404
- * @param shouldWrap Whether the list should wrap when reaching the end.
405
- */
406
- withWrap(shouldWrap = true) {
407
- this._wrap = shouldWrap;
408
- return this;
409
- }
410
- /**
411
- * Configures whether the key manager should be able to move the selection vertically.
412
- * @param enabled Whether vertical selection should be enabled.
413
- */
414
- withVerticalOrientation(enabled = true) {
415
- this._vertical = enabled;
416
- return this;
417
- }
418
- /**
419
- * Configures the key manager to move the selection horizontally.
420
- * Passing in `null` will disable horizontal movement.
421
- * @param direction Direction in which the selection can be moved.
422
- */
423
- withHorizontalOrientation(direction) {
424
- this._horizontal = direction;
425
- return this;
426
- }
427
- /**
428
- * Modifier keys which are allowed to be held down and whose default actions will be prevented
429
- * as the user is pressing the arrow keys. Defaults to not allowing any modifier keys.
430
- */
431
- withAllowedModifierKeys(keys) {
432
- this._allowedModifierKeys = keys;
433
- return this;
434
- }
435
- /**
436
- * Turns on typeahead mode which allows users to set the active item by typing.
437
- * @param debounceInterval Time to wait after the last keystroke before setting the active item.
438
- */
439
- withTypeAhead(debounceInterval = 200) {
440
- if (typeof ngDevMode === 'undefined' || ngDevMode) {
441
- const items = this._getItemsArray();
442
- if (items.length > 0 && items.some(item => typeof item.getLabel !== 'function')) {
443
- throw Error('ListKeyManager items in typeahead mode must implement the `getLabel` method.');
444
- }
445
- }
446
- this._typeaheadSubscription.unsubscribe();
447
- const items = this._getItemsArray();
448
- this._typeahead = new Typeahead(items, {
449
- debounceInterval: typeof debounceInterval === 'number' ? debounceInterval : undefined,
450
- skipPredicate: item => this._skipPredicateFn(item),
451
- });
452
- this._typeaheadSubscription = this._typeahead.selectedItem.subscribe(item => {
453
- this.setActiveItem(item);
454
- });
455
- return this;
456
- }
457
- /** Cancels the current typeahead sequence. */
458
- cancelTypeahead() {
459
- this._typeahead?.reset();
460
- return this;
461
- }
462
- /**
463
- * Configures the key manager to activate the first and last items
464
- * respectively when the Home or End key is pressed.
465
- * @param enabled Whether pressing the Home or End key activates the first/last item.
466
- */
467
- withHomeAndEnd(enabled = true) {
468
- this._homeAndEnd = enabled;
469
- return this;
470
- }
471
- /**
472
- * Configures the key manager to activate every 10th, configured or first/last element in up/down direction
473
- * respectively when the Page-Up or Page-Down key is pressed.
474
- * @param enabled Whether pressing the Page-Up or Page-Down key activates the first/last item.
475
- * @param delta Whether pressing the Home or End key activates the first/last item.
476
- */
477
- withPageUpDown(enabled = true, delta = 10) {
478
- this._pageUpAndDown = { enabled, delta };
479
- return this;
480
- }
481
- setActiveItem(item) {
482
- const previousActiveItem = this._activeItem();
483
- this.updateActiveItem(item);
484
- if (this._activeItem() !== previousActiveItem) {
485
- this.change.next(this._activeItemIndex);
486
- }
487
- }
488
- /**
489
- * Sets the active item depending on the key event passed in.
490
- * @param event Keyboard event to be used for determining which element should be active.
491
- */
492
- onKeydown(event) {
493
- const keyCode = event.keyCode;
494
- const modifiers = ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'];
495
- const isModifierAllowed = modifiers.every(modifier => {
496
- return !event[modifier] || this._allowedModifierKeys.indexOf(modifier) > -1;
497
- });
498
- switch (keyCode) {
499
- case TAB:
500
- this.tabOut.next();
501
- return;
502
- case DOWN_ARROW:
503
- if (this._vertical && isModifierAllowed) {
504
- this.setNextItemActive();
505
- break;
506
- }
507
- else {
508
- return;
509
- }
510
- case UP_ARROW:
511
- if (this._vertical && isModifierAllowed) {
512
- this.setPreviousItemActive();
513
- break;
514
- }
515
- else {
516
- return;
517
- }
518
- case RIGHT_ARROW:
519
- if (this._horizontal && isModifierAllowed) {
520
- this._horizontal === 'rtl' ? this.setPreviousItemActive() : this.setNextItemActive();
521
- break;
522
- }
523
- else {
524
- return;
525
- }
526
- case LEFT_ARROW:
527
- if (this._horizontal && isModifierAllowed) {
528
- this._horizontal === 'rtl' ? this.setNextItemActive() : this.setPreviousItemActive();
529
- break;
530
- }
531
- else {
532
- return;
533
- }
534
- case HOME:
535
- if (this._homeAndEnd && isModifierAllowed) {
536
- this.setFirstItemActive();
537
- break;
538
- }
539
- else {
540
- return;
541
- }
542
- case END:
543
- if (this._homeAndEnd && isModifierAllowed) {
544
- this.setLastItemActive();
545
- break;
546
- }
547
- else {
548
- return;
549
- }
550
- case PAGE_UP:
551
- if (this._pageUpAndDown.enabled && isModifierAllowed) {
552
- const targetIndex = this._activeItemIndex - this._pageUpAndDown.delta;
553
- this._setActiveItemByIndex(targetIndex > 0 ? targetIndex : 0, 1);
554
- break;
555
- }
556
- else {
557
- return;
558
- }
559
- case PAGE_DOWN:
560
- if (this._pageUpAndDown.enabled && isModifierAllowed) {
561
- const targetIndex = this._activeItemIndex + this._pageUpAndDown.delta;
562
- const itemsLength = this._getItemsArray().length;
563
- this._setActiveItemByIndex(targetIndex < itemsLength ? targetIndex : itemsLength - 1, -1);
564
- break;
565
- }
566
- else {
567
- return;
568
- }
569
- default:
570
- if (isModifierAllowed || hasModifierKey(event, 'shiftKey')) {
571
- this._typeahead?.handleKey(event);
572
- }
573
- // Note that we return here, in order to avoid preventing
574
- // the default action of non-navigational keys.
575
- return;
576
- }
577
- this._typeahead?.reset();
578
- event.preventDefault();
579
- }
580
- /** Index of the currently active item. */
581
- get activeItemIndex() {
582
- return this._activeItemIndex;
583
- }
584
- /** The active item. */
585
- get activeItem() {
586
- return this._activeItem();
587
- }
588
- /** Gets whether the user is currently typing into the manager using the typeahead feature. */
589
- isTyping() {
590
- return !!this._typeahead && this._typeahead.isTyping();
591
- }
592
- /** Sets the active item to the first enabled item in the list. */
593
- setFirstItemActive() {
594
- this._setActiveItemByIndex(0, 1);
595
- }
596
- /** Sets the active item to the last enabled item in the list. */
597
- setLastItemActive() {
598
- this._setActiveItemByIndex(this._getItemsArray().length - 1, -1);
599
- }
600
- /** Sets the active item to the next enabled item in the list. */
601
- setNextItemActive() {
602
- this._activeItemIndex < 0 ? this.setFirstItemActive() : this._setActiveItemByDelta(1);
603
- }
604
- /** Sets the active item to a previous enabled item in the list. */
605
- setPreviousItemActive() {
606
- this._activeItemIndex < 0 && this._wrap
607
- ? this.setLastItemActive()
608
- : this._setActiveItemByDelta(-1);
609
- }
610
- updateActiveItem(item) {
611
- const itemArray = this._getItemsArray();
612
- const index = typeof item === 'number' ? item : itemArray.indexOf(item);
613
- const activeItem = itemArray[index];
614
- // Explicitly check for `null` and `undefined` because other falsy values are valid.
615
- this._activeItem.set(activeItem == null ? null : activeItem);
616
- this._activeItemIndex = index;
617
- this._typeahead?.setCurrentSelectedItemIndex(index);
618
- }
619
- /** Cleans up the key manager. */
620
- destroy() {
621
- this._typeaheadSubscription.unsubscribe();
622
- this._itemChangesSubscription?.unsubscribe();
623
- this._effectRef?.destroy();
624
- this._typeahead?.destroy();
625
- this.tabOut.complete();
626
- this.change.complete();
627
- }
628
- /**
629
- * This method sets the active item, given a list of items and the delta between the
630
- * currently active item and the new active item. It will calculate differently
631
- * depending on whether wrap mode is turned on.
632
- */
633
- _setActiveItemByDelta(delta) {
634
- this._wrap ? this._setActiveInWrapMode(delta) : this._setActiveInDefaultMode(delta);
635
- }
636
- /**
637
- * Sets the active item properly given "wrap" mode. In other words, it will continue to move
638
- * down the list until it finds an item that is not disabled, and it will wrap if it
639
- * encounters either end of the list.
640
- */
641
- _setActiveInWrapMode(delta) {
642
- const items = this._getItemsArray();
643
- for (let i = 1; i <= items.length; i++) {
644
- const index = (this._activeItemIndex + delta * i + items.length) % items.length;
645
- const item = items[index];
646
- if (!this._skipPredicateFn(item)) {
647
- this.setActiveItem(index);
648
- return;
649
- }
650
- }
651
- }
652
- /**
653
- * Sets the active item properly given the default mode. In other words, it will
654
- * continue to move down the list until it finds an item that is not disabled. If
655
- * it encounters either end of the list, it will stop and not wrap.
656
- */
657
- _setActiveInDefaultMode(delta) {
658
- this._setActiveItemByIndex(this._activeItemIndex + delta, delta);
659
- }
660
- /**
661
- * Sets the active item to the first enabled item starting at the index specified. If the
662
- * item is disabled, it will move in the fallbackDelta direction until it either
663
- * finds an enabled item or encounters the end of the list.
664
- */
665
- _setActiveItemByIndex(index, fallbackDelta) {
666
- const items = this._getItemsArray();
667
- if (!items[index]) {
668
- return;
669
- }
670
- while (this._skipPredicateFn(items[index])) {
671
- index += fallbackDelta;
672
- if (!items[index]) {
673
- return;
674
- }
675
- }
676
- this.setActiveItem(index);
677
- }
678
- /** Returns the items as an array. */
679
- _getItemsArray() {
680
- if (isSignal(this._items)) {
681
- return this._items();
682
- }
683
- return this._items instanceof QueryList ? this._items.toArray() : this._items;
684
- }
685
- /** Callback for when the items have changed. */
686
- _itemsChanged(newItems) {
687
- this._typeahead?.setItems(newItems);
688
- const activeItem = this._activeItem();
689
- if (activeItem) {
690
- const newIndex = newItems.indexOf(activeItem);
691
- if (newIndex > -1 && newIndex !== this._activeItemIndex) {
692
- this._activeItemIndex = newIndex;
693
- this._typeahead?.setCurrentSelectedItemIndex(newIndex);
694
- }
695
- }
696
- }
697
- }
698
-
699
- class ActiveDescendantKeyManager extends ListKeyManager {
700
- setActiveItem(index) {
701
- if (this.activeItem) {
702
- this.activeItem.setInactiveStyles();
703
- }
704
- super.setActiveItem(index);
705
- if (this.activeItem) {
706
- this.activeItem.setActiveStyles();
707
- }
708
- }
709
- }
710
-
711
- class FocusKeyManager extends ListKeyManager {
712
- _origin = 'program';
713
- /**
714
- * Sets the focus origin that will be passed in to the items for any subsequent `focus` calls.
715
- * @param origin Focus origin to be used when focusing items.
716
- */
717
- setFocusOrigin(origin) {
718
- this._origin = origin;
719
- return this;
720
- }
721
- setActiveItem(item) {
722
- super.setActiveItem(item);
723
- if (this.activeItem) {
724
- this.activeItem.focus(this._origin);
725
- }
726
- }
727
- }
728
-
729
- /**
730
- * This class manages keyboard events for trees. If you pass it a QueryList or other list of tree
731
- * items, it will set the active item, focus, handle expansion and typeahead correctly when
732
- * keyboard events occur.
733
- */
734
- class TreeKeyManager {
735
- /** The index of the currently active (focused) item. */
736
- _activeItemIndex = -1;
737
- /** The currently active (focused) item. */
738
- _activeItem = null;
739
- /** Whether or not we activate the item when it's focused. */
740
- _shouldActivationFollowFocus = false;
741
- /**
742
- * The orientation that the tree is laid out in. In `rtl` mode, the behavior of Left and
743
- * Right arrow are switched.
744
- */
745
- _horizontalOrientation = 'ltr';
746
- /**
747
- * Predicate function that can be used to check whether an item should be skipped
748
- * by the key manager.
749
- *
750
- * The default value for this doesn't skip any elements in order to keep tree items focusable
751
- * when disabled. This aligns with ARIA guidelines:
752
- * https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/#focusabilityofdisabledcontrols.
753
- */
754
- _skipPredicateFn = (_item) => false;
755
- /** Function to determine equivalent items. */
756
- _trackByFn = (item) => item;
757
- /** Synchronous cache of the items to manage. */
758
- _items = [];
759
- _typeahead;
760
- _typeaheadSubscription = Subscription.EMPTY;
761
- _hasInitialFocused = false;
762
- _initializeFocus() {
763
- if (this._hasInitialFocused || this._items.length === 0) {
764
- return;
765
- }
766
- let activeIndex = 0;
767
- for (let i = 0; i < this._items.length; i++) {
768
- if (!this._skipPredicateFn(this._items[i]) && !this._isItemDisabled(this._items[i])) {
769
- activeIndex = i;
770
- break;
771
- }
772
- }
773
- const activeItem = this._items[activeIndex];
774
- // Use `makeFocusable` here, because we want the item to just be focusable, not actually
775
- // capture the focus since the user isn't interacting with it. See #29628.
776
- if (activeItem.makeFocusable) {
777
- this._activeItem?.unfocus();
778
- this._activeItemIndex = activeIndex;
779
- this._activeItem = activeItem;
780
- this._typeahead?.setCurrentSelectedItemIndex(activeIndex);
781
- activeItem.makeFocusable();
782
- }
783
- else {
784
- // Backwards compatibility for items that don't implement `makeFocusable`.
785
- this.focusItem(activeIndex);
786
- }
787
- this._hasInitialFocused = true;
788
- }
789
- /**
790
- *
791
- * @param items List of TreeKeyManager options. Can be synchronous or asynchronous.
792
- * @param config Optional configuration options. By default, use 'ltr' horizontal orientation. By
793
- * default, do not skip any nodes. By default, key manager only calls `focus` method when items
794
- * are focused and does not call `activate`. If `typeaheadDefaultInterval` is `true`, use a
795
- * default interval of 200ms.
796
- */
797
- constructor(items, config) {
798
- // We allow for the items to be an array or Observable because, in some cases, the consumer may
799
- // not have access to a QueryList of the items they want to manage (e.g. when the
800
- // items aren't being collected via `ViewChildren` or `ContentChildren`).
801
- if (items instanceof QueryList) {
802
- this._items = items.toArray();
803
- items.changes.subscribe((newItems) => {
804
- this._items = newItems.toArray();
805
- this._typeahead?.setItems(this._items);
806
- this._updateActiveItemIndex(this._items);
807
- this._initializeFocus();
808
- });
809
- }
810
- else if (isObservable(items)) {
811
- items.subscribe(newItems => {
812
- this._items = newItems;
813
- this._typeahead?.setItems(newItems);
814
- this._updateActiveItemIndex(newItems);
815
- this._initializeFocus();
816
- });
817
- }
818
- else {
819
- this._items = items;
820
- this._initializeFocus();
821
- }
822
- if (typeof config.shouldActivationFollowFocus === 'boolean') {
823
- this._shouldActivationFollowFocus = config.shouldActivationFollowFocus;
824
- }
825
- if (config.horizontalOrientation) {
826
- this._horizontalOrientation = config.horizontalOrientation;
827
- }
828
- if (config.skipPredicate) {
829
- this._skipPredicateFn = config.skipPredicate;
830
- }
831
- if (config.trackBy) {
832
- this._trackByFn = config.trackBy;
833
- }
834
- if (typeof config.typeAheadDebounceInterval !== 'undefined') {
835
- this._setTypeAhead(config.typeAheadDebounceInterval);
836
- }
837
- }
838
- /** Stream that emits any time the focused item changes. */
839
- change = new Subject();
840
- /** Cleans up the key manager. */
841
- destroy() {
842
- this._typeaheadSubscription.unsubscribe();
843
- this._typeahead?.destroy();
844
- this.change.complete();
845
- }
846
- /**
847
- * Handles a keyboard event on the tree.
848
- * @param event Keyboard event that represents the user interaction with the tree.
849
- */
850
- onKeydown(event) {
851
- const key = event.key;
852
- switch (key) {
853
- case 'Tab':
854
- // Return early here, in order to allow Tab to actually tab out of the tree
855
- return;
856
- case 'ArrowDown':
857
- this._focusNextItem();
858
- break;
859
- case 'ArrowUp':
860
- this._focusPreviousItem();
861
- break;
862
- case 'ArrowRight':
863
- this._horizontalOrientation === 'rtl'
864
- ? this._collapseCurrentItem()
865
- : this._expandCurrentItem();
866
- break;
867
- case 'ArrowLeft':
868
- this._horizontalOrientation === 'rtl'
869
- ? this._expandCurrentItem()
870
- : this._collapseCurrentItem();
871
- break;
872
- case 'Home':
873
- this._focusFirstItem();
874
- break;
875
- case 'End':
876
- this._focusLastItem();
877
- break;
878
- case 'Enter':
879
- case ' ':
880
- this._activateCurrentItem();
881
- break;
882
- default:
883
- if (event.key === '*') {
884
- this._expandAllItemsAtCurrentItemLevel();
885
- break;
886
- }
887
- this._typeahead?.handleKey(event);
888
- // Return here, in order to avoid preventing the default action of non-navigational
889
- // keys or resetting the buffer of pressed letters.
890
- return;
891
- }
892
- // Reset the typeahead since the user has used a navigational key.
893
- this._typeahead?.reset();
894
- event.preventDefault();
895
- }
896
- /** Index of the currently active item. */
897
- getActiveItemIndex() {
898
- return this._activeItemIndex;
899
- }
900
- /** The currently active item. */
901
- getActiveItem() {
902
- return this._activeItem;
903
- }
904
- /** Focus the first available item. */
905
- _focusFirstItem() {
906
- this.focusItem(this._findNextAvailableItemIndex(-1));
907
- }
908
- /** Focus the last available item. */
909
- _focusLastItem() {
910
- this.focusItem(this._findPreviousAvailableItemIndex(this._items.length));
911
- }
912
- /** Focus the next available item. */
913
- _focusNextItem() {
914
- this.focusItem(this._findNextAvailableItemIndex(this._activeItemIndex));
915
- }
916
- /** Focus the previous available item. */
917
- _focusPreviousItem() {
918
- this.focusItem(this._findPreviousAvailableItemIndex(this._activeItemIndex));
919
- }
920
- focusItem(itemOrIndex, options = {}) {
921
- // Set default options
922
- options.emitChangeEvent ??= true;
923
- let index = typeof itemOrIndex === 'number'
924
- ? itemOrIndex
925
- : this._items.findIndex(item => this._trackByFn(item) === this._trackByFn(itemOrIndex));
926
- if (index < 0 || index >= this._items.length) {
927
- return;
928
- }
929
- const activeItem = this._items[index];
930
- // If we're just setting the same item, don't re-call activate or focus
931
- if (this._activeItem !== null &&
932
- this._trackByFn(activeItem) === this._trackByFn(this._activeItem)) {
933
- return;
934
- }
935
- const previousActiveItem = this._activeItem;
936
- this._activeItem = activeItem ?? null;
937
- this._activeItemIndex = index;
938
- this._typeahead?.setCurrentSelectedItemIndex(index);
939
- this._activeItem?.focus();
940
- previousActiveItem?.unfocus();
941
- if (options.emitChangeEvent) {
942
- this.change.next(this._activeItem);
943
- }
944
- if (this._shouldActivationFollowFocus) {
945
- this._activateCurrentItem();
946
- }
947
- }
948
- _updateActiveItemIndex(newItems) {
949
- const activeItem = this._activeItem;
950
- if (!activeItem) {
951
- return;
952
- }
953
- const newIndex = newItems.findIndex(item => this._trackByFn(item) === this._trackByFn(activeItem));
954
- if (newIndex > -1 && newIndex !== this._activeItemIndex) {
955
- this._activeItemIndex = newIndex;
956
- this._typeahead?.setCurrentSelectedItemIndex(newIndex);
957
- }
958
- }
959
- _setTypeAhead(debounceInterval) {
960
- this._typeahead = new Typeahead(this._items, {
961
- debounceInterval: typeof debounceInterval === 'number' ? debounceInterval : undefined,
962
- skipPredicate: item => this._skipPredicateFn(item),
963
- });
964
- this._typeaheadSubscription = this._typeahead.selectedItem.subscribe(item => {
965
- this.focusItem(item);
966
- });
967
- }
968
- _findNextAvailableItemIndex(startingIndex) {
969
- for (let i = startingIndex + 1; i < this._items.length; i++) {
970
- if (!this._skipPredicateFn(this._items[i])) {
971
- return i;
972
- }
973
- }
974
- return startingIndex;
975
- }
976
- _findPreviousAvailableItemIndex(startingIndex) {
977
- for (let i = startingIndex - 1; i >= 0; i--) {
978
- if (!this._skipPredicateFn(this._items[i])) {
979
- return i;
980
- }
981
- }
982
- return startingIndex;
983
- }
984
- /**
985
- * If the item is already expanded, we collapse the item. Otherwise, we will focus the parent.
986
- */
987
- _collapseCurrentItem() {
988
- if (!this._activeItem) {
989
- return;
990
- }
991
- if (this._isCurrentItemExpanded()) {
992
- this._activeItem.collapse();
993
- }
994
- else {
995
- const parent = this._activeItem.getParent();
996
- if (!parent || this._skipPredicateFn(parent)) {
997
- return;
998
- }
999
- this.focusItem(parent);
1000
- }
1001
- }
1002
- /**
1003
- * If the item is already collapsed, we expand the item. Otherwise, we will focus the first child.
1004
- */
1005
- _expandCurrentItem() {
1006
- if (!this._activeItem) {
1007
- return;
1008
- }
1009
- if (!this._isCurrentItemExpanded()) {
1010
- this._activeItem.expand();
1011
- }
1012
- else {
1013
- coerceObservable(this._activeItem.getChildren())
1014
- .pipe(take(1))
1015
- .subscribe(children => {
1016
- const firstChild = children.find(child => !this._skipPredicateFn(child));
1017
- if (!firstChild) {
1018
- return;
1019
- }
1020
- this.focusItem(firstChild);
1021
- });
1022
- }
1023
- }
1024
- _isCurrentItemExpanded() {
1025
- if (!this._activeItem) {
1026
- return false;
1027
- }
1028
- return typeof this._activeItem.isExpanded === 'boolean'
1029
- ? this._activeItem.isExpanded
1030
- : this._activeItem.isExpanded();
1031
- }
1032
- _isItemDisabled(item) {
1033
- return typeof item.isDisabled === 'boolean' ? item.isDisabled : item.isDisabled?.();
1034
- }
1035
- /** For all items that are the same level as the current item, we expand those items. */
1036
- _expandAllItemsAtCurrentItemLevel() {
1037
- if (!this._activeItem) {
1038
- return;
1039
- }
1040
- const parent = this._activeItem.getParent();
1041
- let itemsToExpand;
1042
- if (!parent) {
1043
- itemsToExpand = of(this._items.filter(item => item.getParent() === null));
1044
- }
1045
- else {
1046
- itemsToExpand = coerceObservable(parent.getChildren());
1047
- }
1048
- itemsToExpand.pipe(take(1)).subscribe(items => {
1049
- for (const item of items) {
1050
- item.expand();
1051
- }
1052
- });
1053
- }
1054
- _activateCurrentItem() {
1055
- this._activeItem?.activate();
1056
- }
1057
- }
1058
- /** @docs-private */
1059
- function TREE_KEY_MANAGER_FACTORY() {
1060
- return (items, options) => new TreeKeyManager(items, options);
1061
- }
1062
- /** Injection token that determines the key manager to use. */
1063
- const TREE_KEY_MANAGER = new InjectionToken('tree-key-manager', {
1064
- providedIn: 'root',
1065
- factory: TREE_KEY_MANAGER_FACTORY,
1066
- });
1067
- /** @docs-private */
1068
- const TREE_KEY_MANAGER_FACTORY_PROVIDER = {
1069
- provide: TREE_KEY_MANAGER,
1070
- useFactory: TREE_KEY_MANAGER_FACTORY,
1071
- };
1072
-
1073
282
  // NoopTreeKeyManager is a "noop" implementation of TreeKeyMangerStrategy. Methods are noops. Does
1074
283
  // not emit to streams.
1075
284
  //
@@ -1154,627 +363,17 @@ const NOOP_TREE_KEY_MANAGER_FACTORY_PROVIDER = {
1154
363
  };
1155
364
 
1156
365
  /**
1157
- * Configuration for the isFocusable method.
1158
- */
1159
- class IsFocusableConfig {
1160
- /**
1161
- * Whether to count an element as focusable even if it is not currently visible.
1162
- */
1163
- ignoreVisibility = false;
1164
- }
1165
- // The InteractivityChecker leans heavily on the ally.js accessibility utilities.
1166
- // Methods like `isTabbable` are only covering specific edge-cases for the browsers which are
1167
- // supported.
1168
- /**
1169
- * Utility for checking the interactivity of an element, such as whether it is focusable or
1170
- * tabbable.
366
+ * Class that allows for trapping focus within a DOM element.
367
+ *
368
+ * This class uses a strategy pattern that determines how it traps focus.
369
+ * See FocusTrapInertStrategy.
1171
370
  */
1172
- class InteractivityChecker {
1173
- _platform = inject(Platform);
1174
- constructor() { }
1175
- /**
1176
- * Gets whether an element is disabled.
1177
- *
1178
- * @param element Element to be checked.
1179
- * @returns Whether the element is disabled.
1180
- */
1181
- isDisabled(element) {
1182
- // This does not capture some cases, such as a non-form control with a disabled attribute or
1183
- // a form control inside of a disabled form, but should capture the most common cases.
1184
- return element.hasAttribute('disabled');
1185
- }
1186
- /**
1187
- * Gets whether an element is visible for the purposes of interactivity.
1188
- *
1189
- * This will capture states like `display: none` and `visibility: hidden`, but not things like
1190
- * being clipped by an `overflow: hidden` parent or being outside the viewport.
1191
- *
1192
- * @returns Whether the element is visible.
1193
- */
1194
- isVisible(element) {
1195
- return hasGeometry(element) && getComputedStyle(element).visibility === 'visible';
1196
- }
1197
- /**
1198
- * Gets whether an element can be reached via Tab key.
1199
- * Assumes that the element has already been checked with isFocusable.
1200
- *
1201
- * @param element Element to be checked.
1202
- * @returns Whether the element is tabbable.
1203
- */
1204
- isTabbable(element) {
1205
- // Nothing is tabbable on the server 😎
1206
- if (!this._platform.isBrowser) {
1207
- return false;
1208
- }
1209
- const frameElement = getFrameElement(getWindow(element));
1210
- if (frameElement) {
1211
- // Frame elements inherit their tabindex onto all child elements.
1212
- if (getTabIndexValue(frameElement) === -1) {
1213
- return false;
1214
- }
1215
- // Browsers disable tabbing to an element inside of an invisible frame.
1216
- if (!this.isVisible(frameElement)) {
1217
- return false;
1218
- }
1219
- }
1220
- let nodeName = element.nodeName.toLowerCase();
1221
- let tabIndexValue = getTabIndexValue(element);
1222
- if (element.hasAttribute('contenteditable')) {
1223
- return tabIndexValue !== -1;
1224
- }
1225
- if (nodeName === 'iframe' || nodeName === 'object') {
1226
- // The frame or object's content may be tabbable depending on the content, but it's
1227
- // not possibly to reliably detect the content of the frames. We always consider such
1228
- // elements as non-tabbable.
1229
- return false;
1230
- }
1231
- // In iOS, the browser only considers some specific elements as tabbable.
1232
- if (this._platform.WEBKIT && this._platform.IOS && !isPotentiallyTabbableIOS(element)) {
1233
- return false;
1234
- }
1235
- if (nodeName === 'audio') {
1236
- // Audio elements without controls enabled are never tabbable, regardless
1237
- // of the tabindex attribute explicitly being set.
1238
- if (!element.hasAttribute('controls')) {
1239
- return false;
1240
- }
1241
- // Audio elements with controls are by default tabbable unless the
1242
- // tabindex attribute is set to `-1` explicitly.
1243
- return tabIndexValue !== -1;
1244
- }
1245
- if (nodeName === 'video') {
1246
- // For all video elements, if the tabindex attribute is set to `-1`, the video
1247
- // is not tabbable. Note: We cannot rely on the default `HTMLElement.tabIndex`
1248
- // property as that one is set to `-1` in Chrome, Edge and Safari v13.1. The
1249
- // tabindex attribute is the source of truth here.
1250
- if (tabIndexValue === -1) {
1251
- return false;
1252
- }
1253
- // If the tabindex is explicitly set, and not `-1` (as per check before), the
1254
- // video element is always tabbable (regardless of whether it has controls or not).
1255
- if (tabIndexValue !== null) {
1256
- return true;
1257
- }
1258
- // Otherwise (when no explicit tabindex is set), a video is only tabbable if it
1259
- // has controls enabled. Firefox is special as videos are always tabbable regardless
1260
- // of whether there are controls or not.
1261
- return this._platform.FIREFOX || element.hasAttribute('controls');
1262
- }
1263
- return element.tabIndex >= 0;
1264
- }
1265
- /**
1266
- * Gets whether an element can be focused by the user.
1267
- *
1268
- * @param element Element to be checked.
1269
- * @param config The config object with options to customize this method's behavior
1270
- * @returns Whether the element is focusable.
1271
- */
1272
- isFocusable(element, config) {
1273
- // Perform checks in order of left to most expensive.
1274
- // Again, naive approach that does not capture many edge cases and browser quirks.
1275
- return (isPotentiallyFocusable(element) &&
1276
- !this.isDisabled(element) &&
1277
- (config?.ignoreVisibility || this.isVisible(element)));
1278
- }
1279
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: InteractivityChecker, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1280
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: InteractivityChecker, providedIn: 'root' });
1281
- }
1282
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: InteractivityChecker, decorators: [{
1283
- type: Injectable,
1284
- args: [{ providedIn: 'root' }]
1285
- }], ctorParameters: () => [] });
1286
- /**
1287
- * Returns the frame element from a window object. Since browsers like MS Edge throw errors if
1288
- * the frameElement property is being accessed from a different host address, this property
1289
- * should be accessed carefully.
1290
- */
1291
- function getFrameElement(window) {
1292
- try {
1293
- return window.frameElement;
1294
- }
1295
- catch {
1296
- return null;
1297
- }
1298
- }
1299
- /** Checks whether the specified element has any geometry / rectangles. */
1300
- function hasGeometry(element) {
1301
- // Use logic from jQuery to check for an invisible element.
1302
- // See https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js#L12
1303
- return !!(element.offsetWidth ||
1304
- element.offsetHeight ||
1305
- (typeof element.getClientRects === 'function' && element.getClientRects().length));
1306
- }
1307
- /** Gets whether an element's */
1308
- function isNativeFormElement(element) {
1309
- let nodeName = element.nodeName.toLowerCase();
1310
- return (nodeName === 'input' ||
1311
- nodeName === 'select' ||
1312
- nodeName === 'button' ||
1313
- nodeName === 'textarea');
1314
- }
1315
- /** Gets whether an element is an `<input type="hidden">`. */
1316
- function isHiddenInput(element) {
1317
- return isInputElement(element) && element.type == 'hidden';
1318
- }
1319
- /** Gets whether an element is an anchor that has an href attribute. */
1320
- function isAnchorWithHref(element) {
1321
- return isAnchorElement(element) && element.hasAttribute('href');
1322
- }
1323
- /** Gets whether an element is an input element. */
1324
- function isInputElement(element) {
1325
- return element.nodeName.toLowerCase() == 'input';
1326
- }
1327
- /** Gets whether an element is an anchor element. */
1328
- function isAnchorElement(element) {
1329
- return element.nodeName.toLowerCase() == 'a';
1330
- }
1331
- /** Gets whether an element has a valid tabindex. */
1332
- function hasValidTabIndex(element) {
1333
- if (!element.hasAttribute('tabindex') || element.tabIndex === undefined) {
1334
- return false;
1335
- }
1336
- let tabIndex = element.getAttribute('tabindex');
1337
- return !!(tabIndex && !isNaN(parseInt(tabIndex, 10)));
1338
- }
1339
- /**
1340
- * Returns the parsed tabindex from the element attributes instead of returning the
1341
- * evaluated tabindex from the browsers defaults.
1342
- */
1343
- function getTabIndexValue(element) {
1344
- if (!hasValidTabIndex(element)) {
1345
- return null;
1346
- }
1347
- // See browser issue in Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=1128054
1348
- const tabIndex = parseInt(element.getAttribute('tabindex') || '', 10);
1349
- return isNaN(tabIndex) ? -1 : tabIndex;
1350
- }
1351
- /** Checks whether the specified element is potentially tabbable on iOS */
1352
- function isPotentiallyTabbableIOS(element) {
1353
- let nodeName = element.nodeName.toLowerCase();
1354
- let inputType = nodeName === 'input' && element.type;
1355
- return (inputType === 'text' ||
1356
- inputType === 'password' ||
1357
- nodeName === 'select' ||
1358
- nodeName === 'textarea');
1359
- }
1360
- /**
1361
- * Gets whether an element is potentially focusable without taking current visible/disabled state
1362
- * into account.
1363
- */
1364
- function isPotentiallyFocusable(element) {
1365
- // Inputs are potentially focusable *unless* they're type="hidden".
1366
- if (isHiddenInput(element)) {
1367
- return false;
1368
- }
1369
- return (isNativeFormElement(element) ||
1370
- isAnchorWithHref(element) ||
1371
- element.hasAttribute('contenteditable') ||
1372
- hasValidTabIndex(element));
1373
- }
1374
- /** Gets the parent window of a DOM node with regards of being inside of an iframe. */
1375
- function getWindow(node) {
1376
- // ownerDocument is null if `node` itself *is* a document.
1377
- return (node.ownerDocument && node.ownerDocument.defaultView) || window;
1378
- }
1379
-
1380
- /**
1381
- * Class that allows for trapping focus within a DOM element.
1382
- *
1383
- * This class currently uses a relatively simple approach to focus trapping.
1384
- * It assumes that the tab order is the same as DOM order, which is not necessarily true.
1385
- * Things like `tabIndex > 0`, flex `order`, and shadow roots can cause the two to be misaligned.
1386
- */
1387
- class FocusTrap {
1388
- _element;
1389
- _checker;
1390
- _ngZone;
1391
- _document;
1392
- _injector;
1393
- _startAnchor;
1394
- _endAnchor;
1395
- _hasAttached = false;
1396
- // Event listeners for the anchors. Need to be regular functions so that we can unbind them later.
1397
- startAnchorListener = () => this.focusLastTabbableElement();
1398
- endAnchorListener = () => this.focusFirstTabbableElement();
1399
- /** Whether the focus trap is active. */
1400
- get enabled() {
1401
- return this._enabled;
1402
- }
1403
- set enabled(value) {
1404
- this._enabled = value;
1405
- if (this._startAnchor && this._endAnchor) {
1406
- this._toggleAnchorTabIndex(value, this._startAnchor);
1407
- this._toggleAnchorTabIndex(value, this._endAnchor);
1408
- }
1409
- }
1410
- _enabled = true;
1411
- constructor(_element, _checker, _ngZone, _document, deferAnchors = false,
1412
- /** @breaking-change 20.0.0 param to become required */
1413
- _injector) {
1414
- this._element = _element;
1415
- this._checker = _checker;
1416
- this._ngZone = _ngZone;
1417
- this._document = _document;
1418
- this._injector = _injector;
1419
- if (!deferAnchors) {
1420
- this.attachAnchors();
1421
- }
1422
- }
1423
- /** Destroys the focus trap by cleaning up the anchors. */
1424
- destroy() {
1425
- const startAnchor = this._startAnchor;
1426
- const endAnchor = this._endAnchor;
1427
- if (startAnchor) {
1428
- startAnchor.removeEventListener('focus', this.startAnchorListener);
1429
- startAnchor.remove();
1430
- }
1431
- if (endAnchor) {
1432
- endAnchor.removeEventListener('focus', this.endAnchorListener);
1433
- endAnchor.remove();
1434
- }
1435
- this._startAnchor = this._endAnchor = null;
1436
- this._hasAttached = false;
1437
- }
1438
- /**
1439
- * Inserts the anchors into the DOM. This is usually done automatically
1440
- * in the constructor, but can be deferred for cases like directives with `*ngIf`.
1441
- * @returns Whether the focus trap managed to attach successfully. This may not be the case
1442
- * if the target element isn't currently in the DOM.
1443
- */
1444
- attachAnchors() {
1445
- // If we're not on the browser, there can be no focus to trap.
1446
- if (this._hasAttached) {
1447
- return true;
1448
- }
1449
- this._ngZone.runOutsideAngular(() => {
1450
- if (!this._startAnchor) {
1451
- this._startAnchor = this._createAnchor();
1452
- this._startAnchor.addEventListener('focus', this.startAnchorListener);
1453
- }
1454
- if (!this._endAnchor) {
1455
- this._endAnchor = this._createAnchor();
1456
- this._endAnchor.addEventListener('focus', this.endAnchorListener);
1457
- }
1458
- });
1459
- if (this._element.parentNode) {
1460
- this._element.parentNode.insertBefore(this._startAnchor, this._element);
1461
- this._element.parentNode.insertBefore(this._endAnchor, this._element.nextSibling);
1462
- this._hasAttached = true;
1463
- }
1464
- return this._hasAttached;
1465
- }
1466
- /**
1467
- * Waits for the zone to stabilize, then focuses the first tabbable element.
1468
- * @returns Returns a promise that resolves with a boolean, depending
1469
- * on whether focus was moved successfully.
1470
- */
1471
- focusInitialElementWhenReady(options) {
1472
- return new Promise(resolve => {
1473
- this._executeOnStable(() => resolve(this.focusInitialElement(options)));
1474
- });
1475
- }
1476
- /**
1477
- * Waits for the zone to stabilize, then focuses
1478
- * the first tabbable element within the focus trap region.
1479
- * @returns Returns a promise that resolves with a boolean, depending
1480
- * on whether focus was moved successfully.
1481
- */
1482
- focusFirstTabbableElementWhenReady(options) {
1483
- return new Promise(resolve => {
1484
- this._executeOnStable(() => resolve(this.focusFirstTabbableElement(options)));
1485
- });
1486
- }
1487
- /**
1488
- * Waits for the zone to stabilize, then focuses
1489
- * the last tabbable element within the focus trap region.
1490
- * @returns Returns a promise that resolves with a boolean, depending
1491
- * on whether focus was moved successfully.
1492
- */
1493
- focusLastTabbableElementWhenReady(options) {
1494
- return new Promise(resolve => {
1495
- this._executeOnStable(() => resolve(this.focusLastTabbableElement(options)));
1496
- });
1497
- }
1498
- /**
1499
- * Get the specified boundary element of the trapped region.
1500
- * @param bound The boundary to get (start or end of trapped region).
1501
- * @returns The boundary element.
1502
- */
1503
- _getRegionBoundary(bound) {
1504
- // Contains the deprecated version of selector, for temporary backwards comparability.
1505
- const markers = this._element.querySelectorAll(`[cdk-focus-region-${bound}], ` + `[cdkFocusRegion${bound}], ` + `[cdk-focus-${bound}]`);
1506
- if (typeof ngDevMode === 'undefined' || ngDevMode) {
1507
- for (let i = 0; i < markers.length; i++) {
1508
- // @breaking-change 8.0.0
1509
- if (markers[i].hasAttribute(`cdk-focus-${bound}`)) {
1510
- console.warn(`Found use of deprecated attribute 'cdk-focus-${bound}', ` +
1511
- `use 'cdkFocusRegion${bound}' instead. The deprecated ` +
1512
- `attribute will be removed in 8.0.0.`, markers[i]);
1513
- }
1514
- else if (markers[i].hasAttribute(`cdk-focus-region-${bound}`)) {
1515
- console.warn(`Found use of deprecated attribute 'cdk-focus-region-${bound}', ` +
1516
- `use 'cdkFocusRegion${bound}' instead. The deprecated attribute ` +
1517
- `will be removed in 8.0.0.`, markers[i]);
1518
- }
1519
- }
1520
- }
1521
- if (bound == 'start') {
1522
- return markers.length ? markers[0] : this._getFirstTabbableElement(this._element);
1523
- }
1524
- return markers.length
1525
- ? markers[markers.length - 1]
1526
- : this._getLastTabbableElement(this._element);
1527
- }
1528
- /**
1529
- * Focuses the element that should be focused when the focus trap is initialized.
1530
- * @returns Whether focus was moved successfully.
1531
- */
1532
- focusInitialElement(options) {
1533
- // Contains the deprecated version of selector, for temporary backwards comparability.
1534
- const redirectToElement = this._element.querySelector(`[cdk-focus-initial], ` + `[cdkFocusInitial]`);
1535
- if (redirectToElement) {
1536
- // @breaking-change 8.0.0
1537
- if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
1538
- redirectToElement.hasAttribute(`cdk-focus-initial`)) {
1539
- console.warn(`Found use of deprecated attribute 'cdk-focus-initial', ` +
1540
- `use 'cdkFocusInitial' instead. The deprecated attribute ` +
1541
- `will be removed in 8.0.0`, redirectToElement);
1542
- }
1543
- // Warn the consumer if the element they've pointed to
1544
- // isn't focusable, when not in production mode.
1545
- if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
1546
- !this._checker.isFocusable(redirectToElement)) {
1547
- console.warn(`Element matching '[cdkFocusInitial]' is not focusable.`, redirectToElement);
1548
- }
1549
- if (!this._checker.isFocusable(redirectToElement)) {
1550
- const focusableChild = this._getFirstTabbableElement(redirectToElement);
1551
- focusableChild?.focus(options);
1552
- return !!focusableChild;
1553
- }
1554
- redirectToElement.focus(options);
1555
- return true;
1556
- }
1557
- return this.focusFirstTabbableElement(options);
1558
- }
1559
- /**
1560
- * Focuses the first tabbable element within the focus trap region.
1561
- * @returns Whether focus was moved successfully.
1562
- */
1563
- focusFirstTabbableElement(options) {
1564
- const redirectToElement = this._getRegionBoundary('start');
1565
- if (redirectToElement) {
1566
- redirectToElement.focus(options);
1567
- }
1568
- return !!redirectToElement;
1569
- }
1570
- /**
1571
- * Focuses the last tabbable element within the focus trap region.
1572
- * @returns Whether focus was moved successfully.
1573
- */
1574
- focusLastTabbableElement(options) {
1575
- const redirectToElement = this._getRegionBoundary('end');
1576
- if (redirectToElement) {
1577
- redirectToElement.focus(options);
1578
- }
1579
- return !!redirectToElement;
1580
- }
1581
- /**
1582
- * Checks whether the focus trap has successfully been attached.
1583
- */
1584
- hasAttached() {
1585
- return this._hasAttached;
1586
- }
1587
- /** Get the first tabbable element from a DOM subtree (inclusive). */
1588
- _getFirstTabbableElement(root) {
1589
- if (this._checker.isFocusable(root) && this._checker.isTabbable(root)) {
1590
- return root;
1591
- }
1592
- const children = root.children;
1593
- for (let i = 0; i < children.length; i++) {
1594
- const tabbableChild = children[i].nodeType === this._document.ELEMENT_NODE
1595
- ? this._getFirstTabbableElement(children[i])
1596
- : null;
1597
- if (tabbableChild) {
1598
- return tabbableChild;
1599
- }
1600
- }
1601
- return null;
1602
- }
1603
- /** Get the last tabbable element from a DOM subtree (inclusive). */
1604
- _getLastTabbableElement(root) {
1605
- if (this._checker.isFocusable(root) && this._checker.isTabbable(root)) {
1606
- return root;
1607
- }
1608
- // Iterate in reverse DOM order.
1609
- const children = root.children;
1610
- for (let i = children.length - 1; i >= 0; i--) {
1611
- const tabbableChild = children[i].nodeType === this._document.ELEMENT_NODE
1612
- ? this._getLastTabbableElement(children[i])
1613
- : null;
1614
- if (tabbableChild) {
1615
- return tabbableChild;
1616
- }
1617
- }
1618
- return null;
1619
- }
1620
- /** Creates an anchor element. */
1621
- _createAnchor() {
1622
- const anchor = this._document.createElement('div');
1623
- this._toggleAnchorTabIndex(this._enabled, anchor);
1624
- anchor.classList.add('cdk-visually-hidden');
1625
- anchor.classList.add('cdk-focus-trap-anchor');
1626
- anchor.setAttribute('aria-hidden', 'true');
1627
- return anchor;
1628
- }
1629
- /**
1630
- * Toggles the `tabindex` of an anchor, based on the enabled state of the focus trap.
1631
- * @param isEnabled Whether the focus trap is enabled.
1632
- * @param anchor Anchor on which to toggle the tabindex.
1633
- */
1634
- _toggleAnchorTabIndex(isEnabled, anchor) {
1635
- // Remove the tabindex completely, rather than setting it to -1, because if the
1636
- // element has a tabindex, the user might still hit it when navigating with the arrow keys.
1637
- isEnabled ? anchor.setAttribute('tabindex', '0') : anchor.removeAttribute('tabindex');
1638
- }
1639
- /**
1640
- * Toggles the`tabindex` of both anchors to either trap Tab focus or allow it to escape.
1641
- * @param enabled: Whether the anchors should trap Tab.
1642
- */
1643
- toggleAnchors(enabled) {
1644
- if (this._startAnchor && this._endAnchor) {
1645
- this._toggleAnchorTabIndex(enabled, this._startAnchor);
1646
- this._toggleAnchorTabIndex(enabled, this._endAnchor);
1647
- }
1648
- }
1649
- /** Executes a function when the zone is stable. */
1650
- _executeOnStable(fn) {
1651
- // TODO: remove this conditional when injector is required in the constructor.
1652
- if (this._injector) {
1653
- afterNextRender(fn, { injector: this._injector });
1654
- }
1655
- else {
1656
- setTimeout(fn);
1657
- }
1658
- }
1659
- }
1660
- /**
1661
- * Factory that allows easy instantiation of focus traps.
1662
- */
1663
- class FocusTrapFactory {
1664
- _checker = inject(InteractivityChecker);
1665
- _ngZone = inject(NgZone);
1666
- _document = inject(DOCUMENT);
1667
- _injector = inject(Injector);
1668
- constructor() {
1669
- inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader);
1670
- }
1671
- /**
1672
- * Creates a focus-trapped region around the given element.
1673
- * @param element The element around which focus will be trapped.
1674
- * @param deferCaptureElements Defers the creation of focus-capturing elements to be done
1675
- * manually by the user.
1676
- * @returns The created focus trap instance.
1677
- */
1678
- create(element, deferCaptureElements = false) {
1679
- return new FocusTrap(element, this._checker, this._ngZone, this._document, deferCaptureElements, this._injector);
1680
- }
1681
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: FocusTrapFactory, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1682
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: FocusTrapFactory, providedIn: 'root' });
1683
- }
1684
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: FocusTrapFactory, decorators: [{
1685
- type: Injectable,
1686
- args: [{ providedIn: 'root' }]
1687
- }], ctorParameters: () => [] });
1688
- /** Directive for trapping focus within a region. */
1689
- class CdkTrapFocus {
1690
- _elementRef = inject(ElementRef);
1691
- _focusTrapFactory = inject(FocusTrapFactory);
1692
- /** Underlying FocusTrap instance. */
1693
- focusTrap;
1694
- /** Previously focused element to restore focus to upon destroy when using autoCapture. */
1695
- _previouslyFocusedElement = null;
1696
- /** Whether the focus trap is active. */
1697
- get enabled() {
1698
- return this.focusTrap?.enabled || false;
1699
- }
1700
- set enabled(value) {
1701
- if (this.focusTrap) {
1702
- this.focusTrap.enabled = value;
1703
- }
1704
- }
1705
- /**
1706
- * Whether the directive should automatically move focus into the trapped region upon
1707
- * initialization and return focus to the previous activeElement upon destruction.
1708
- */
1709
- autoCapture;
1710
- constructor() {
1711
- const platform = inject(Platform);
1712
- if (platform.isBrowser) {
1713
- this.focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement, true);
1714
- }
1715
- }
1716
- ngOnDestroy() {
1717
- this.focusTrap?.destroy();
1718
- // If we stored a previously focused element when using autoCapture, return focus to that
1719
- // element now that the trapped region is being destroyed.
1720
- if (this._previouslyFocusedElement) {
1721
- this._previouslyFocusedElement.focus();
1722
- this._previouslyFocusedElement = null;
1723
- }
1724
- }
1725
- ngAfterContentInit() {
1726
- this.focusTrap?.attachAnchors();
1727
- if (this.autoCapture) {
1728
- this._captureFocus();
1729
- }
1730
- }
1731
- ngDoCheck() {
1732
- if (this.focusTrap && !this.focusTrap.hasAttached()) {
1733
- this.focusTrap.attachAnchors();
1734
- }
1735
- }
1736
- ngOnChanges(changes) {
1737
- const autoCaptureChange = changes['autoCapture'];
1738
- if (autoCaptureChange &&
1739
- !autoCaptureChange.firstChange &&
1740
- this.autoCapture &&
1741
- this.focusTrap?.hasAttached()) {
1742
- this._captureFocus();
1743
- }
1744
- }
1745
- _captureFocus() {
1746
- this._previouslyFocusedElement = _getFocusedElementPierceShadowDom();
1747
- this.focusTrap?.focusInitialElementWhenReady();
1748
- }
1749
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: CdkTrapFocus, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1750
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "16.1.0", version: "19.2.0", type: CdkTrapFocus, isStandalone: true, selector: "[cdkTrapFocus]", inputs: { enabled: ["cdkTrapFocus", "enabled", booleanAttribute], autoCapture: ["cdkTrapFocusAutoCapture", "autoCapture", booleanAttribute] }, exportAs: ["cdkTrapFocus"], usesOnChanges: true, ngImport: i0 });
1751
- }
1752
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: CdkTrapFocus, decorators: [{
1753
- type: Directive,
1754
- args: [{
1755
- selector: '[cdkTrapFocus]',
1756
- exportAs: 'cdkTrapFocus',
1757
- }]
1758
- }], ctorParameters: () => [], propDecorators: { enabled: [{
1759
- type: Input,
1760
- args: [{ alias: 'cdkTrapFocus', transform: booleanAttribute }]
1761
- }], autoCapture: [{
1762
- type: Input,
1763
- args: [{ alias: 'cdkTrapFocusAutoCapture', transform: booleanAttribute }]
1764
- }] } });
1765
-
1766
- /**
1767
- * Class that allows for trapping focus within a DOM element.
1768
- *
1769
- * This class uses a strategy pattern that determines how it traps focus.
1770
- * See FocusTrapInertStrategy.
1771
- */
1772
- class ConfigurableFocusTrap extends FocusTrap {
1773
- _focusTrapManager;
1774
- _inertStrategy;
1775
- /** Whether the FocusTrap is enabled. */
1776
- get enabled() {
1777
- return this._enabled;
371
+ class ConfigurableFocusTrap extends FocusTrap {
372
+ _focusTrapManager;
373
+ _inertStrategy;
374
+ /** Whether the FocusTrap is enabled. */
375
+ get enabled() {
376
+ return this._enabled;
1778
377
  }
1779
378
  set enabled(value) {
1780
379
  this._enabled = value;
@@ -1897,10 +496,10 @@ class FocusTrapManager {
1897
496
  }
1898
497
  }
1899
498
  }
1900
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: FocusTrapManager, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1901
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: FocusTrapManager, providedIn: 'root' });
499
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.0.0-next.1", ngImport: i0, type: FocusTrapManager, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
500
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.0.0-next.1", ngImport: i0, type: FocusTrapManager, providedIn: 'root' });
1902
501
  }
1903
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: FocusTrapManager, decorators: [{
502
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.0.0-next.1", ngImport: i0, type: FocusTrapManager, decorators: [{
1904
503
  type: Injectable,
1905
504
  args: [{ providedIn: 'root' }]
1906
505
  }] });
@@ -1928,1010 +527,13 @@ class ConfigurableFocusTrapFactory {
1928
527
  }
1929
528
  return new ConfigurableFocusTrap(element, this._checker, this._ngZone, this._document, this._focusTrapManager, this._inertStrategy, configObject, this._injector);
1930
529
  }
1931
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ConfigurableFocusTrapFactory, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1932
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ConfigurableFocusTrapFactory, providedIn: 'root' });
1933
- }
1934
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ConfigurableFocusTrapFactory, decorators: [{
1935
- type: Injectable,
1936
- args: [{ providedIn: 'root' }]
1937
- }], ctorParameters: () => [] });
1938
-
1939
- /** Gets whether an event could be a faked `mousedown` event dispatched by a screen reader. */
1940
- function isFakeMousedownFromScreenReader(event) {
1941
- // Some screen readers will dispatch a fake `mousedown` event when pressing enter or space on
1942
- // a clickable element. We can distinguish these events when `event.buttons` is zero, or
1943
- // `event.detail` is zero depending on the browser:
1944
- // - `event.buttons` works on Firefox, but fails on Chrome.
1945
- // - `detail` works on Chrome, but fails on Firefox.
1946
- return event.buttons === 0 || event.detail === 0;
1947
- }
1948
- /** Gets whether an event could be a faked `touchstart` event dispatched by a screen reader. */
1949
- function isFakeTouchstartFromScreenReader(event) {
1950
- const touch = (event.touches && event.touches[0]) || (event.changedTouches && event.changedTouches[0]);
1951
- // A fake `touchstart` can be distinguished from a real one by looking at the `identifier`
1952
- // which is typically >= 0 on a real device versus -1 from a screen reader. Just to be safe,
1953
- // we can also look at `radiusX` and `radiusY`. This behavior was observed against a Windows 10
1954
- // device with a touch screen running NVDA v2020.4 and Firefox 85 or Chrome 88.
1955
- return (!!touch &&
1956
- touch.identifier === -1 &&
1957
- (touch.radiusX == null || touch.radiusX === 1) &&
1958
- (touch.radiusY == null || touch.radiusY === 1));
1959
- }
1960
-
1961
- /**
1962
- * Injectable options for the InputModalityDetector. These are shallowly merged with the default
1963
- * options.
1964
- */
1965
- const INPUT_MODALITY_DETECTOR_OPTIONS = new InjectionToken('cdk-input-modality-detector-options');
1966
- /**
1967
- * Default options for the InputModalityDetector.
1968
- *
1969
- * Modifier keys are ignored by default (i.e. when pressed won't cause the service to detect
1970
- * keyboard input modality) for two reasons:
1971
- *
1972
- * 1. Modifier keys are commonly used with mouse to perform actions such as 'right click' or 'open
1973
- * in new tab', and are thus less representative of actual keyboard interaction.
1974
- * 2. VoiceOver triggers some keyboard events when linearly navigating with Control + Option (but
1975
- * confusingly not with Caps Lock). Thus, to have parity with other screen readers, we ignore
1976
- * these keys so as to not update the input modality.
1977
- *
1978
- * Note that we do not by default ignore the right Meta key on Safari because it has the same key
1979
- * code as the ContextMenu key on other browsers. When we switch to using event.key, we can
1980
- * distinguish between the two.
1981
- */
1982
- const INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS = {
1983
- ignoreKeys: [ALT, CONTROL, MAC_META, META, SHIFT],
1984
- };
1985
- /**
1986
- * The amount of time needed to pass after a touchstart event in order for a subsequent mousedown
1987
- * event to be attributed as mouse and not touch.
1988
- *
1989
- * This is the value used by AngularJS Material. Through trial and error (on iPhone 6S) they found
1990
- * that a value of around 650ms seems appropriate.
1991
- */
1992
- const TOUCH_BUFFER_MS = 650;
1993
- /**
1994
- * Event listener options that enable capturing and also mark the listener as passive if the browser
1995
- * supports it.
1996
- */
1997
- const modalityEventListenerOptions = {
1998
- passive: true,
1999
- capture: true,
2000
- };
2001
- /**
2002
- * Service that detects the user's input modality.
2003
- *
2004
- * This service does not update the input modality when a user navigates with a screen reader
2005
- * (e.g. linear navigation with VoiceOver, object navigation / browse mode with NVDA, virtual PC
2006
- * cursor mode with JAWS). This is in part due to technical limitations (i.e. keyboard events do not
2007
- * fire as expected in these modes) but is also arguably the correct behavior. Navigating with a
2008
- * screen reader is akin to visually scanning a page, and should not be interpreted as actual user
2009
- * input interaction.
2010
- *
2011
- * When a user is not navigating but *interacting* with a screen reader, this service attempts to
2012
- * update the input modality to keyboard, but in general this service's behavior is largely
2013
- * undefined.
2014
- */
2015
- class InputModalityDetector {
2016
- _platform = inject(Platform);
2017
- _listenerCleanups;
2018
- /** Emits whenever an input modality is detected. */
2019
- modalityDetected;
2020
- /** Emits when the input modality changes. */
2021
- modalityChanged;
2022
- /** The most recently detected input modality. */
2023
- get mostRecentModality() {
2024
- return this._modality.value;
2025
- }
2026
- /**
2027
- * The most recently detected input modality event target. Is null if no input modality has been
2028
- * detected or if the associated event target is null for some unknown reason.
2029
- */
2030
- _mostRecentTarget = null;
2031
- /** The underlying BehaviorSubject that emits whenever an input modality is detected. */
2032
- _modality = new BehaviorSubject(null);
2033
- /** Options for this InputModalityDetector. */
2034
- _options;
2035
- /**
2036
- * The timestamp of the last touch input modality. Used to determine whether mousedown events
2037
- * should be attributed to mouse or touch.
2038
- */
2039
- _lastTouchMs = 0;
2040
- /**
2041
- * Handles keydown events. Must be an arrow function in order to preserve the context when it gets
2042
- * bound.
2043
- */
2044
- _onKeydown = (event) => {
2045
- // If this is one of the keys we should ignore, then ignore it and don't update the input
2046
- // modality to keyboard.
2047
- if (this._options?.ignoreKeys?.some(keyCode => keyCode === event.keyCode)) {
2048
- return;
2049
- }
2050
- this._modality.next('keyboard');
2051
- this._mostRecentTarget = _getEventTarget(event);
2052
- };
2053
- /**
2054
- * Handles mousedown events. Must be an arrow function in order to preserve the context when it
2055
- * gets bound.
2056
- */
2057
- _onMousedown = (event) => {
2058
- // Touches trigger both touch and mouse events, so we need to distinguish between mouse events
2059
- // that were triggered via mouse vs touch. To do so, check if the mouse event occurs closely
2060
- // after the previous touch event.
2061
- if (Date.now() - this._lastTouchMs < TOUCH_BUFFER_MS) {
2062
- return;
2063
- }
2064
- // Fake mousedown events are fired by some screen readers when controls are activated by the
2065
- // screen reader. Attribute them to keyboard input modality.
2066
- this._modality.next(isFakeMousedownFromScreenReader(event) ? 'keyboard' : 'mouse');
2067
- this._mostRecentTarget = _getEventTarget(event);
2068
- };
2069
- /**
2070
- * Handles touchstart events. Must be an arrow function in order to preserve the context when it
2071
- * gets bound.
2072
- */
2073
- _onTouchstart = (event) => {
2074
- // Same scenario as mentioned in _onMousedown, but on touch screen devices, fake touchstart
2075
- // events are fired. Again, attribute to keyboard input modality.
2076
- if (isFakeTouchstartFromScreenReader(event)) {
2077
- this._modality.next('keyboard');
2078
- return;
2079
- }
2080
- // Store the timestamp of this touch event, as it's used to distinguish between mouse events
2081
- // triggered via mouse vs touch.
2082
- this._lastTouchMs = Date.now();
2083
- this._modality.next('touch');
2084
- this._mostRecentTarget = _getEventTarget(event);
2085
- };
2086
- constructor() {
2087
- const ngZone = inject(NgZone);
2088
- const document = inject(DOCUMENT);
2089
- const options = inject(INPUT_MODALITY_DETECTOR_OPTIONS, { optional: true });
2090
- this._options = {
2091
- ...INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS,
2092
- ...options,
2093
- };
2094
- // Skip the first emission as it's null.
2095
- this.modalityDetected = this._modality.pipe(skip(1));
2096
- this.modalityChanged = this.modalityDetected.pipe(distinctUntilChanged());
2097
- // If we're not in a browser, this service should do nothing, as there's no relevant input
2098
- // modality to detect.
2099
- if (this._platform.isBrowser) {
2100
- const renderer = inject(RendererFactory2).createRenderer(null, null);
2101
- this._listenerCleanups = ngZone.runOutsideAngular(() => {
2102
- return [
2103
- _bindEventWithOptions(renderer, document, 'keydown', this._onKeydown, modalityEventListenerOptions),
2104
- _bindEventWithOptions(renderer, document, 'mousedown', this._onMousedown, modalityEventListenerOptions),
2105
- _bindEventWithOptions(renderer, document, 'touchstart', this._onTouchstart, modalityEventListenerOptions),
2106
- ];
2107
- });
2108
- }
2109
- }
2110
- ngOnDestroy() {
2111
- this._modality.complete();
2112
- this._listenerCleanups?.forEach(cleanup => cleanup());
2113
- }
2114
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: InputModalityDetector, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
2115
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: InputModalityDetector, providedIn: 'root' });
2116
- }
2117
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: InputModalityDetector, decorators: [{
2118
- type: Injectable,
2119
- args: [{ providedIn: 'root' }]
2120
- }], ctorParameters: () => [] });
2121
-
2122
- const LIVE_ANNOUNCER_ELEMENT_TOKEN = new InjectionToken('liveAnnouncerElement', {
2123
- providedIn: 'root',
2124
- factory: LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY,
2125
- });
2126
- /** @docs-private */
2127
- function LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY() {
2128
- return null;
2129
- }
2130
- /** Injection token that can be used to configure the default options for the LiveAnnouncer. */
2131
- const LIVE_ANNOUNCER_DEFAULT_OPTIONS = new InjectionToken('LIVE_ANNOUNCER_DEFAULT_OPTIONS');
2132
-
2133
- let uniqueIds = 0;
2134
- class LiveAnnouncer {
2135
- _ngZone = inject(NgZone);
2136
- _defaultOptions = inject(LIVE_ANNOUNCER_DEFAULT_OPTIONS, {
2137
- optional: true,
2138
- });
2139
- _liveElement;
2140
- _document = inject(DOCUMENT);
2141
- _previousTimeout;
2142
- _currentPromise;
2143
- _currentResolve;
2144
- constructor() {
2145
- const elementToken = inject(LIVE_ANNOUNCER_ELEMENT_TOKEN, { optional: true });
2146
- this._liveElement = elementToken || this._createLiveElement();
2147
- }
2148
- announce(message, ...args) {
2149
- const defaultOptions = this._defaultOptions;
2150
- let politeness;
2151
- let duration;
2152
- if (args.length === 1 && typeof args[0] === 'number') {
2153
- duration = args[0];
2154
- }
2155
- else {
2156
- [politeness, duration] = args;
2157
- }
2158
- this.clear();
2159
- clearTimeout(this._previousTimeout);
2160
- if (!politeness) {
2161
- politeness =
2162
- defaultOptions && defaultOptions.politeness ? defaultOptions.politeness : 'polite';
2163
- }
2164
- if (duration == null && defaultOptions) {
2165
- duration = defaultOptions.duration;
2166
- }
2167
- // TODO: ensure changing the politeness works on all environments we support.
2168
- this._liveElement.setAttribute('aria-live', politeness);
2169
- if (this._liveElement.id) {
2170
- this._exposeAnnouncerToModals(this._liveElement.id);
2171
- }
2172
- // This 100ms timeout is necessary for some browser + screen-reader combinations:
2173
- // - Both JAWS and NVDA over IE11 will not announce anything without a non-zero timeout.
2174
- // - With Chrome and IE11 with NVDA or JAWS, a repeated (identical) message won't be read a
2175
- // second time without clearing and then using a non-zero delay.
2176
- // (using JAWS 17 at time of this writing).
2177
- return this._ngZone.runOutsideAngular(() => {
2178
- if (!this._currentPromise) {
2179
- this._currentPromise = new Promise(resolve => (this._currentResolve = resolve));
2180
- }
2181
- clearTimeout(this._previousTimeout);
2182
- this._previousTimeout = setTimeout(() => {
2183
- this._liveElement.textContent = message;
2184
- if (typeof duration === 'number') {
2185
- this._previousTimeout = setTimeout(() => this.clear(), duration);
2186
- }
2187
- // For some reason in tests this can be undefined
2188
- // Probably related to ZoneJS and every other thing that patches browser APIs in tests
2189
- this._currentResolve?.();
2190
- this._currentPromise = this._currentResolve = undefined;
2191
- }, 100);
2192
- return this._currentPromise;
2193
- });
2194
- }
2195
- /**
2196
- * Clears the current text from the announcer element. Can be used to prevent
2197
- * screen readers from reading the text out again while the user is going
2198
- * through the page landmarks.
2199
- */
2200
- clear() {
2201
- if (this._liveElement) {
2202
- this._liveElement.textContent = '';
2203
- }
2204
- }
2205
- ngOnDestroy() {
2206
- clearTimeout(this._previousTimeout);
2207
- this._liveElement?.remove();
2208
- this._liveElement = null;
2209
- this._currentResolve?.();
2210
- this._currentPromise = this._currentResolve = undefined;
2211
- }
2212
- _createLiveElement() {
2213
- const elementClass = 'cdk-live-announcer-element';
2214
- const previousElements = this._document.getElementsByClassName(elementClass);
2215
- const liveEl = this._document.createElement('div');
2216
- // Remove any old containers. This can happen when coming in from a server-side-rendered page.
2217
- for (let i = 0; i < previousElements.length; i++) {
2218
- previousElements[i].remove();
2219
- }
2220
- liveEl.classList.add(elementClass);
2221
- liveEl.classList.add('cdk-visually-hidden');
2222
- liveEl.setAttribute('aria-atomic', 'true');
2223
- liveEl.setAttribute('aria-live', 'polite');
2224
- liveEl.id = `cdk-live-announcer-${uniqueIds++}`;
2225
- this._document.body.appendChild(liveEl);
2226
- return liveEl;
2227
- }
2228
- /**
2229
- * Some browsers won't expose the accessibility node of the live announcer element if there is an
2230
- * `aria-modal` and the live announcer is outside of it. This method works around the issue by
2231
- * pointing the `aria-owns` of all modals to the live announcer element.
2232
- */
2233
- _exposeAnnouncerToModals(id) {
2234
- // TODO(http://github.com/angular/components/issues/26853): consider de-duplicating this with
2235
- // the `SnakBarContainer` and other usages.
2236
- //
2237
- // Note that the selector here is limited to CDK overlays at the moment in order to reduce the
2238
- // section of the DOM we need to look through. This should cover all the cases we support, but
2239
- // the selector can be expanded if it turns out to be too narrow.
2240
- const modals = this._document.querySelectorAll('body > .cdk-overlay-container [aria-modal="true"]');
2241
- for (let i = 0; i < modals.length; i++) {
2242
- const modal = modals[i];
2243
- const ariaOwns = modal.getAttribute('aria-owns');
2244
- if (!ariaOwns) {
2245
- modal.setAttribute('aria-owns', id);
2246
- }
2247
- else if (ariaOwns.indexOf(id) === -1) {
2248
- modal.setAttribute('aria-owns', ariaOwns + ' ' + id);
2249
- }
2250
- }
2251
- }
2252
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: LiveAnnouncer, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
2253
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: LiveAnnouncer, providedIn: 'root' });
2254
- }
2255
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: LiveAnnouncer, decorators: [{
2256
- type: Injectable,
2257
- args: [{ providedIn: 'root' }]
2258
- }], ctorParameters: () => [] });
2259
- /**
2260
- * A directive that works similarly to aria-live, but uses the LiveAnnouncer to ensure compatibility
2261
- * with a wider range of browsers and screen readers.
2262
- */
2263
- class CdkAriaLive {
2264
- _elementRef = inject(ElementRef);
2265
- _liveAnnouncer = inject(LiveAnnouncer);
2266
- _contentObserver = inject(ContentObserver);
2267
- _ngZone = inject(NgZone);
2268
- /** The aria-live politeness level to use when announcing messages. */
2269
- get politeness() {
2270
- return this._politeness;
2271
- }
2272
- set politeness(value) {
2273
- this._politeness = value === 'off' || value === 'assertive' ? value : 'polite';
2274
- if (this._politeness === 'off') {
2275
- if (this._subscription) {
2276
- this._subscription.unsubscribe();
2277
- this._subscription = null;
2278
- }
2279
- }
2280
- else if (!this._subscription) {
2281
- this._subscription = this._ngZone.runOutsideAngular(() => {
2282
- return this._contentObserver.observe(this._elementRef).subscribe(() => {
2283
- // Note that we use textContent here, rather than innerText, in order to avoid a reflow.
2284
- const elementText = this._elementRef.nativeElement.textContent;
2285
- // The `MutationObserver` fires also for attribute
2286
- // changes which we don't want to announce.
2287
- if (elementText !== this._previousAnnouncedText) {
2288
- this._liveAnnouncer.announce(elementText, this._politeness, this.duration);
2289
- this._previousAnnouncedText = elementText;
2290
- }
2291
- });
2292
- });
2293
- }
2294
- }
2295
- _politeness = 'polite';
2296
- /** Time in milliseconds after which to clear out the announcer element. */
2297
- duration;
2298
- _previousAnnouncedText;
2299
- _subscription;
2300
- constructor() {
2301
- inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader);
2302
- }
2303
- ngOnDestroy() {
2304
- if (this._subscription) {
2305
- this._subscription.unsubscribe();
2306
- }
2307
- }
2308
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: CdkAriaLive, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2309
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.2.0", type: CdkAriaLive, isStandalone: true, selector: "[cdkAriaLive]", inputs: { politeness: ["cdkAriaLive", "politeness"], duration: ["cdkAriaLiveDuration", "duration"] }, exportAs: ["cdkAriaLive"], ngImport: i0 });
2310
- }
2311
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: CdkAriaLive, decorators: [{
2312
- type: Directive,
2313
- args: [{
2314
- selector: '[cdkAriaLive]',
2315
- exportAs: 'cdkAriaLive',
2316
- }]
2317
- }], ctorParameters: () => [], propDecorators: { politeness: [{
2318
- type: Input,
2319
- args: ['cdkAriaLive']
2320
- }], duration: [{
2321
- type: Input,
2322
- args: ['cdkAriaLiveDuration']
2323
- }] } });
2324
-
2325
- /** Detection mode used for attributing the origin of a focus event. */
2326
- var FocusMonitorDetectionMode;
2327
- (function (FocusMonitorDetectionMode) {
2328
- /**
2329
- * Any mousedown, keydown, or touchstart event that happened in the previous
2330
- * tick or the current tick will be used to assign a focus event's origin (to
2331
- * either mouse, keyboard, or touch). This is the default option.
2332
- */
2333
- FocusMonitorDetectionMode[FocusMonitorDetectionMode["IMMEDIATE"] = 0] = "IMMEDIATE";
2334
- /**
2335
- * A focus event's origin is always attributed to the last corresponding
2336
- * mousedown, keydown, or touchstart event, no matter how long ago it occurred.
2337
- */
2338
- FocusMonitorDetectionMode[FocusMonitorDetectionMode["EVENTUAL"] = 1] = "EVENTUAL";
2339
- })(FocusMonitorDetectionMode || (FocusMonitorDetectionMode = {}));
2340
- /** InjectionToken for FocusMonitorOptions. */
2341
- const FOCUS_MONITOR_DEFAULT_OPTIONS = new InjectionToken('cdk-focus-monitor-default-options');
2342
- /**
2343
- * Event listener options that enable capturing and also
2344
- * mark the listener as passive if the browser supports it.
2345
- */
2346
- const captureEventListenerOptions = normalizePassiveListenerOptions({
2347
- passive: true,
2348
- capture: true,
2349
- });
2350
- /** Monitors mouse and keyboard events to determine the cause of focus events. */
2351
- class FocusMonitor {
2352
- _ngZone = inject(NgZone);
2353
- _platform = inject(Platform);
2354
- _inputModalityDetector = inject(InputModalityDetector);
2355
- /** The focus origin that the next focus event is a result of. */
2356
- _origin = null;
2357
- /** The FocusOrigin of the last focus event tracked by the FocusMonitor. */
2358
- _lastFocusOrigin;
2359
- /** Whether the window has just been focused. */
2360
- _windowFocused = false;
2361
- /** The timeout id of the window focus timeout. */
2362
- _windowFocusTimeoutId;
2363
- /** The timeout id of the origin clearing timeout. */
2364
- _originTimeoutId;
2365
- /**
2366
- * Whether the origin was determined via a touch interaction. Necessary as properly attributing
2367
- * focus events to touch interactions requires special logic.
2368
- */
2369
- _originFromTouchInteraction = false;
2370
- /** Map of elements being monitored to their info. */
2371
- _elementInfo = new Map();
2372
- /** The number of elements currently being monitored. */
2373
- _monitoredElementCount = 0;
2374
- /**
2375
- * Keeps track of the root nodes to which we've currently bound a focus/blur handler,
2376
- * as well as the number of monitored elements that they contain. We have to treat focus/blur
2377
- * handlers differently from the rest of the events, because the browser won't emit events
2378
- * to the document when focus moves inside of a shadow root.
2379
- */
2380
- _rootNodeFocusListenerCount = new Map();
2381
- /**
2382
- * The specified detection mode, used for attributing the origin of a focus
2383
- * event.
2384
- */
2385
- _detectionMode;
2386
- /**
2387
- * Event listener for `focus` events on the window.
2388
- * Needs to be an arrow function in order to preserve the context when it gets bound.
2389
- */
2390
- _windowFocusListener = () => {
2391
- // Make a note of when the window regains focus, so we can
2392
- // restore the origin info for the focused element.
2393
- this._windowFocused = true;
2394
- this._windowFocusTimeoutId = setTimeout(() => (this._windowFocused = false));
2395
- };
2396
- /** Used to reference correct document/window */
2397
- _document = inject(DOCUMENT, { optional: true });
2398
- /** Subject for stopping our InputModalityDetector subscription. */
2399
- _stopInputModalityDetector = new Subject();
2400
- constructor() {
2401
- const options = inject(FOCUS_MONITOR_DEFAULT_OPTIONS, {
2402
- optional: true,
2403
- });
2404
- this._detectionMode = options?.detectionMode || FocusMonitorDetectionMode.IMMEDIATE;
2405
- }
2406
- /**
2407
- * Event listener for `focus` and 'blur' events on the document.
2408
- * Needs to be an arrow function in order to preserve the context when it gets bound.
2409
- */
2410
- _rootNodeFocusAndBlurListener = (event) => {
2411
- const target = _getEventTarget(event);
2412
- // We need to walk up the ancestor chain in order to support `checkChildren`.
2413
- for (let element = target; element; element = element.parentElement) {
2414
- if (event.type === 'focus') {
2415
- this._onFocus(event, element);
2416
- }
2417
- else {
2418
- this._onBlur(event, element);
2419
- }
2420
- }
2421
- };
2422
- monitor(element, checkChildren = false) {
2423
- const nativeElement = coerceElement(element);
2424
- // Do nothing if we're not on the browser platform or the passed in node isn't an element.
2425
- if (!this._platform.isBrowser || nativeElement.nodeType !== 1) {
2426
- // Note: we don't want the observable to emit at all so we don't pass any parameters.
2427
- return of();
2428
- }
2429
- // If the element is inside the shadow DOM, we need to bind our focus/blur listeners to
2430
- // the shadow root, rather than the `document`, because the browser won't emit focus events
2431
- // to the `document`, if focus is moving within the same shadow root.
2432
- const rootNode = _getShadowRoot(nativeElement) || this._getDocument();
2433
- const cachedInfo = this._elementInfo.get(nativeElement);
2434
- // Check if we're already monitoring this element.
2435
- if (cachedInfo) {
2436
- if (checkChildren) {
2437
- // TODO(COMP-318): this can be problematic, because it'll turn all non-checkChildren
2438
- // observers into ones that behave as if `checkChildren` was turned on. We need a more
2439
- // robust solution.
2440
- cachedInfo.checkChildren = true;
2441
- }
2442
- return cachedInfo.subject;
2443
- }
2444
- // Create monitored element info.
2445
- const info = {
2446
- checkChildren: checkChildren,
2447
- subject: new Subject(),
2448
- rootNode,
2449
- };
2450
- this._elementInfo.set(nativeElement, info);
2451
- this._registerGlobalListeners(info);
2452
- return info.subject;
2453
- }
2454
- stopMonitoring(element) {
2455
- const nativeElement = coerceElement(element);
2456
- const elementInfo = this._elementInfo.get(nativeElement);
2457
- if (elementInfo) {
2458
- elementInfo.subject.complete();
2459
- this._setClasses(nativeElement);
2460
- this._elementInfo.delete(nativeElement);
2461
- this._removeGlobalListeners(elementInfo);
2462
- }
2463
- }
2464
- focusVia(element, origin, options) {
2465
- const nativeElement = coerceElement(element);
2466
- const focusedElement = this._getDocument().activeElement;
2467
- // If the element is focused already, calling `focus` again won't trigger the event listener
2468
- // which means that the focus classes won't be updated. If that's the case, update the classes
2469
- // directly without waiting for an event.
2470
- if (nativeElement === focusedElement) {
2471
- this._getClosestElementsInfo(nativeElement).forEach(([currentElement, info]) => this._originChanged(currentElement, origin, info));
2472
- }
2473
- else {
2474
- this._setOrigin(origin);
2475
- // `focus` isn't available on the server
2476
- if (typeof nativeElement.focus === 'function') {
2477
- nativeElement.focus(options);
2478
- }
2479
- }
2480
- }
2481
- ngOnDestroy() {
2482
- this._elementInfo.forEach((_info, element) => this.stopMonitoring(element));
2483
- }
2484
- /** Access injected document if available or fallback to global document reference */
2485
- _getDocument() {
2486
- return this._document || document;
2487
- }
2488
- /** Use defaultView of injected document if available or fallback to global window reference */
2489
- _getWindow() {
2490
- const doc = this._getDocument();
2491
- return doc.defaultView || window;
2492
- }
2493
- _getFocusOrigin(focusEventTarget) {
2494
- if (this._origin) {
2495
- // If the origin was realized via a touch interaction, we need to perform additional checks
2496
- // to determine whether the focus origin should be attributed to touch or program.
2497
- if (this._originFromTouchInteraction) {
2498
- return this._shouldBeAttributedToTouch(focusEventTarget) ? 'touch' : 'program';
2499
- }
2500
- else {
2501
- return this._origin;
2502
- }
2503
- }
2504
- // If the window has just regained focus, we can restore the most recent origin from before the
2505
- // window blurred. Otherwise, we've reached the point where we can't identify the source of the
2506
- // focus. This typically means one of two things happened:
2507
- //
2508
- // 1) The element was programmatically focused, or
2509
- // 2) The element was focused via screen reader navigation (which generally doesn't fire
2510
- // events).
2511
- //
2512
- // Because we can't distinguish between these two cases, we default to setting `program`.
2513
- if (this._windowFocused && this._lastFocusOrigin) {
2514
- return this._lastFocusOrigin;
2515
- }
2516
- // If the interaction is coming from an input label, we consider it a mouse interactions.
2517
- // This is a special case where focus moves on `click`, rather than `mousedown` which breaks
2518
- // our detection, because all our assumptions are for `mousedown`. We need to handle this
2519
- // special case, because it's very common for checkboxes and radio buttons.
2520
- if (focusEventTarget && this._isLastInteractionFromInputLabel(focusEventTarget)) {
2521
- return 'mouse';
2522
- }
2523
- return 'program';
2524
- }
2525
- /**
2526
- * Returns whether the focus event should be attributed to touch. Recall that in IMMEDIATE mode, a
2527
- * touch origin isn't immediately reset at the next tick (see _setOrigin). This means that when we
2528
- * handle a focus event following a touch interaction, we need to determine whether (1) the focus
2529
- * event was directly caused by the touch interaction or (2) the focus event was caused by a
2530
- * subsequent programmatic focus call triggered by the touch interaction.
2531
- * @param focusEventTarget The target of the focus event under examination.
2532
- */
2533
- _shouldBeAttributedToTouch(focusEventTarget) {
2534
- // Please note that this check is not perfect. Consider the following edge case:
2535
- //
2536
- // <div #parent tabindex="0">
2537
- // <div #child tabindex="0" (click)="#parent.focus()"></div>
2538
- // </div>
2539
- //
2540
- // Suppose there is a FocusMonitor in IMMEDIATE mode attached to #parent. When the user touches
2541
- // #child, #parent is programmatically focused. This code will attribute the focus to touch
2542
- // instead of program. This is a relatively minor edge-case that can be worked around by using
2543
- // focusVia(parent, 'program') to focus #parent.
2544
- return (this._detectionMode === FocusMonitorDetectionMode.EVENTUAL ||
2545
- !!focusEventTarget?.contains(this._inputModalityDetector._mostRecentTarget));
2546
- }
2547
- /**
2548
- * Sets the focus classes on the element based on the given focus origin.
2549
- * @param element The element to update the classes on.
2550
- * @param origin The focus origin.
2551
- */
2552
- _setClasses(element, origin) {
2553
- element.classList.toggle('cdk-focused', !!origin);
2554
- element.classList.toggle('cdk-touch-focused', origin === 'touch');
2555
- element.classList.toggle('cdk-keyboard-focused', origin === 'keyboard');
2556
- element.classList.toggle('cdk-mouse-focused', origin === 'mouse');
2557
- element.classList.toggle('cdk-program-focused', origin === 'program');
2558
- }
2559
- /**
2560
- * Updates the focus origin. If we're using immediate detection mode, we schedule an async
2561
- * function to clear the origin at the end of a timeout. The duration of the timeout depends on
2562
- * the origin being set.
2563
- * @param origin The origin to set.
2564
- * @param isFromInteraction Whether we are setting the origin from an interaction event.
2565
- */
2566
- _setOrigin(origin, isFromInteraction = false) {
2567
- this._ngZone.runOutsideAngular(() => {
2568
- this._origin = origin;
2569
- this._originFromTouchInteraction = origin === 'touch' && isFromInteraction;
2570
- // If we're in IMMEDIATE mode, reset the origin at the next tick (or in `TOUCH_BUFFER_MS` ms
2571
- // for a touch event). We reset the origin at the next tick because Firefox focuses one tick
2572
- // after the interaction event. We wait `TOUCH_BUFFER_MS` ms before resetting the origin for
2573
- // a touch event because when a touch event is fired, the associated focus event isn't yet in
2574
- // the event queue. Before doing so, clear any pending timeouts.
2575
- if (this._detectionMode === FocusMonitorDetectionMode.IMMEDIATE) {
2576
- clearTimeout(this._originTimeoutId);
2577
- const ms = this._originFromTouchInteraction ? TOUCH_BUFFER_MS : 1;
2578
- this._originTimeoutId = setTimeout(() => (this._origin = null), ms);
2579
- }
2580
- });
2581
- }
2582
- /**
2583
- * Handles focus events on a registered element.
2584
- * @param event The focus event.
2585
- * @param element The monitored element.
2586
- */
2587
- _onFocus(event, element) {
2588
- // NOTE(mmalerba): We currently set the classes based on the focus origin of the most recent
2589
- // focus event affecting the monitored element. If we want to use the origin of the first event
2590
- // instead we should check for the cdk-focused class here and return if the element already has
2591
- // it. (This only matters for elements that have includesChildren = true).
2592
- // If we are not counting child-element-focus as focused, make sure that the event target is the
2593
- // monitored element itself.
2594
- const elementInfo = this._elementInfo.get(element);
2595
- const focusEventTarget = _getEventTarget(event);
2596
- if (!elementInfo || (!elementInfo.checkChildren && element !== focusEventTarget)) {
2597
- return;
2598
- }
2599
- this._originChanged(element, this._getFocusOrigin(focusEventTarget), elementInfo);
2600
- }
2601
- /**
2602
- * Handles blur events on a registered element.
2603
- * @param event The blur event.
2604
- * @param element The monitored element.
2605
- */
2606
- _onBlur(event, element) {
2607
- // If we are counting child-element-focus as focused, make sure that we aren't just blurring in
2608
- // order to focus another child of the monitored element.
2609
- const elementInfo = this._elementInfo.get(element);
2610
- if (!elementInfo ||
2611
- (elementInfo.checkChildren &&
2612
- event.relatedTarget instanceof Node &&
2613
- element.contains(event.relatedTarget))) {
2614
- return;
2615
- }
2616
- this._setClasses(element);
2617
- this._emitOrigin(elementInfo, null);
2618
- }
2619
- _emitOrigin(info, origin) {
2620
- if (info.subject.observers.length) {
2621
- this._ngZone.run(() => info.subject.next(origin));
2622
- }
2623
- }
2624
- _registerGlobalListeners(elementInfo) {
2625
- if (!this._platform.isBrowser) {
2626
- return;
2627
- }
2628
- const rootNode = elementInfo.rootNode;
2629
- const rootNodeFocusListeners = this._rootNodeFocusListenerCount.get(rootNode) || 0;
2630
- if (!rootNodeFocusListeners) {
2631
- this._ngZone.runOutsideAngular(() => {
2632
- rootNode.addEventListener('focus', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
2633
- rootNode.addEventListener('blur', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
2634
- });
2635
- }
2636
- this._rootNodeFocusListenerCount.set(rootNode, rootNodeFocusListeners + 1);
2637
- // Register global listeners when first element is monitored.
2638
- if (++this._monitoredElementCount === 1) {
2639
- // Note: we listen to events in the capture phase so we
2640
- // can detect them even if the user stops propagation.
2641
- this._ngZone.runOutsideAngular(() => {
2642
- const window = this._getWindow();
2643
- window.addEventListener('focus', this._windowFocusListener);
2644
- });
2645
- // The InputModalityDetector is also just a collection of global listeners.
2646
- this._inputModalityDetector.modalityDetected
2647
- .pipe(takeUntil(this._stopInputModalityDetector))
2648
- .subscribe(modality => {
2649
- this._setOrigin(modality, true /* isFromInteraction */);
2650
- });
2651
- }
2652
- }
2653
- _removeGlobalListeners(elementInfo) {
2654
- const rootNode = elementInfo.rootNode;
2655
- if (this._rootNodeFocusListenerCount.has(rootNode)) {
2656
- const rootNodeFocusListeners = this._rootNodeFocusListenerCount.get(rootNode);
2657
- if (rootNodeFocusListeners > 1) {
2658
- this._rootNodeFocusListenerCount.set(rootNode, rootNodeFocusListeners - 1);
2659
- }
2660
- else {
2661
- rootNode.removeEventListener('focus', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
2662
- rootNode.removeEventListener('blur', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);
2663
- this._rootNodeFocusListenerCount.delete(rootNode);
2664
- }
2665
- }
2666
- // Unregister global listeners when last element is unmonitored.
2667
- if (!--this._monitoredElementCount) {
2668
- const window = this._getWindow();
2669
- window.removeEventListener('focus', this._windowFocusListener);
2670
- // Equivalently, stop our InputModalityDetector subscription.
2671
- this._stopInputModalityDetector.next();
2672
- // Clear timeouts for all potentially pending timeouts to prevent the leaks.
2673
- clearTimeout(this._windowFocusTimeoutId);
2674
- clearTimeout(this._originTimeoutId);
2675
- }
2676
- }
2677
- /** Updates all the state on an element once its focus origin has changed. */
2678
- _originChanged(element, origin, elementInfo) {
2679
- this._setClasses(element, origin);
2680
- this._emitOrigin(elementInfo, origin);
2681
- this._lastFocusOrigin = origin;
2682
- }
2683
- /**
2684
- * Collects the `MonitoredElementInfo` of a particular element and
2685
- * all of its ancestors that have enabled `checkChildren`.
2686
- * @param element Element from which to start the search.
2687
- */
2688
- _getClosestElementsInfo(element) {
2689
- const results = [];
2690
- this._elementInfo.forEach((info, currentElement) => {
2691
- if (currentElement === element || (info.checkChildren && currentElement.contains(element))) {
2692
- results.push([currentElement, info]);
2693
- }
2694
- });
2695
- return results;
2696
- }
2697
- /**
2698
- * Returns whether an interaction is likely to have come from the user clicking the `label` of
2699
- * an `input` or `textarea` in order to focus it.
2700
- * @param focusEventTarget Target currently receiving focus.
2701
- */
2702
- _isLastInteractionFromInputLabel(focusEventTarget) {
2703
- const { _mostRecentTarget: mostRecentTarget, mostRecentModality } = this._inputModalityDetector;
2704
- // If the last interaction used the mouse on an element contained by one of the labels
2705
- // of an `input`/`textarea` that is currently focused, it is very likely that the
2706
- // user redirected focus using the label.
2707
- if (mostRecentModality !== 'mouse' ||
2708
- !mostRecentTarget ||
2709
- mostRecentTarget === focusEventTarget ||
2710
- (focusEventTarget.nodeName !== 'INPUT' && focusEventTarget.nodeName !== 'TEXTAREA') ||
2711
- focusEventTarget.disabled) {
2712
- return false;
2713
- }
2714
- const labels = focusEventTarget.labels;
2715
- if (labels) {
2716
- for (let i = 0; i < labels.length; i++) {
2717
- if (labels[i].contains(mostRecentTarget)) {
2718
- return true;
2719
- }
2720
- }
2721
- }
2722
- return false;
2723
- }
2724
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: FocusMonitor, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
2725
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: FocusMonitor, providedIn: 'root' });
530
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.0.0-next.1", ngImport: i0, type: ConfigurableFocusTrapFactory, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
531
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.0.0-next.1", ngImport: i0, type: ConfigurableFocusTrapFactory, providedIn: 'root' });
2726
532
  }
2727
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: FocusMonitor, decorators: [{
533
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.0.0-next.1", ngImport: i0, type: ConfigurableFocusTrapFactory, decorators: [{
2728
534
  type: Injectable,
2729
535
  args: [{ providedIn: 'root' }]
2730
536
  }], ctorParameters: () => [] });
2731
- /**
2732
- * Directive that determines how a particular element was focused (via keyboard, mouse, touch, or
2733
- * programmatically) and adds corresponding classes to the element.
2734
- *
2735
- * There are two variants of this directive:
2736
- * 1) cdkMonitorElementFocus: does not consider an element to be focused if one of its children is
2737
- * focused.
2738
- * 2) cdkMonitorSubtreeFocus: considers an element focused if it or any of its children are focused.
2739
- */
2740
- class CdkMonitorFocus {
2741
- _elementRef = inject(ElementRef);
2742
- _focusMonitor = inject(FocusMonitor);
2743
- _monitorSubscription;
2744
- _focusOrigin = null;
2745
- cdkFocusChange = new EventEmitter();
2746
- constructor() { }
2747
- get focusOrigin() {
2748
- return this._focusOrigin;
2749
- }
2750
- ngAfterViewInit() {
2751
- const element = this._elementRef.nativeElement;
2752
- this._monitorSubscription = this._focusMonitor
2753
- .monitor(element, element.nodeType === 1 && element.hasAttribute('cdkMonitorSubtreeFocus'))
2754
- .subscribe(origin => {
2755
- this._focusOrigin = origin;
2756
- this.cdkFocusChange.emit(origin);
2757
- });
2758
- }
2759
- ngOnDestroy() {
2760
- this._focusMonitor.stopMonitoring(this._elementRef);
2761
- if (this._monitorSubscription) {
2762
- this._monitorSubscription.unsubscribe();
2763
- }
2764
- }
2765
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: CdkMonitorFocus, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2766
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.2.0", type: CdkMonitorFocus, isStandalone: true, selector: "[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]", outputs: { cdkFocusChange: "cdkFocusChange" }, exportAs: ["cdkMonitorFocus"], ngImport: i0 });
2767
- }
2768
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: CdkMonitorFocus, decorators: [{
2769
- type: Directive,
2770
- args: [{
2771
- selector: '[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]',
2772
- exportAs: 'cdkMonitorFocus',
2773
- }]
2774
- }], ctorParameters: () => [], propDecorators: { cdkFocusChange: [{
2775
- type: Output
2776
- }] } });
2777
-
2778
- /** Set of possible high-contrast mode backgrounds. */
2779
- var HighContrastMode;
2780
- (function (HighContrastMode) {
2781
- HighContrastMode[HighContrastMode["NONE"] = 0] = "NONE";
2782
- HighContrastMode[HighContrastMode["BLACK_ON_WHITE"] = 1] = "BLACK_ON_WHITE";
2783
- HighContrastMode[HighContrastMode["WHITE_ON_BLACK"] = 2] = "WHITE_ON_BLACK";
2784
- })(HighContrastMode || (HighContrastMode = {}));
2785
- /** CSS class applied to the document body when in black-on-white high-contrast mode. */
2786
- const BLACK_ON_WHITE_CSS_CLASS = 'cdk-high-contrast-black-on-white';
2787
- /** CSS class applied to the document body when in white-on-black high-contrast mode. */
2788
- const WHITE_ON_BLACK_CSS_CLASS = 'cdk-high-contrast-white-on-black';
2789
- /** CSS class applied to the document body when in high-contrast mode. */
2790
- const HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS = 'cdk-high-contrast-active';
2791
- /**
2792
- * Service to determine whether the browser is currently in a high-contrast-mode environment.
2793
- *
2794
- * Microsoft Windows supports an accessibility feature called "High Contrast Mode". This mode
2795
- * changes the appearance of all applications, including web applications, to dramatically increase
2796
- * contrast.
2797
- *
2798
- * IE, Edge, and Firefox currently support this mode. Chrome does not support Windows High Contrast
2799
- * Mode. This service does not detect high-contrast mode as added by the Chrome "High Contrast"
2800
- * browser extension.
2801
- */
2802
- class HighContrastModeDetector {
2803
- _platform = inject(Platform);
2804
- /**
2805
- * Figuring out the high contrast mode and adding the body classes can cause
2806
- * some expensive layouts. This flag is used to ensure that we only do it once.
2807
- */
2808
- _hasCheckedHighContrastMode;
2809
- _document = inject(DOCUMENT);
2810
- _breakpointSubscription;
2811
- constructor() {
2812
- this._breakpointSubscription = inject(BreakpointObserver)
2813
- .observe('(forced-colors: active)')
2814
- .subscribe(() => {
2815
- if (this._hasCheckedHighContrastMode) {
2816
- this._hasCheckedHighContrastMode = false;
2817
- this._applyBodyHighContrastModeCssClasses();
2818
- }
2819
- });
2820
- }
2821
- /** Gets the current high-contrast-mode for the page. */
2822
- getHighContrastMode() {
2823
- if (!this._platform.isBrowser) {
2824
- return HighContrastMode.NONE;
2825
- }
2826
- // Create a test element with an arbitrary background-color that is neither black nor
2827
- // white; high-contrast mode will coerce the color to either black or white. Also ensure that
2828
- // appending the test element to the DOM does not affect layout by absolutely positioning it
2829
- const testElement = this._document.createElement('div');
2830
- testElement.style.backgroundColor = 'rgb(1,2,3)';
2831
- testElement.style.position = 'absolute';
2832
- this._document.body.appendChild(testElement);
2833
- // Get the computed style for the background color, collapsing spaces to normalize between
2834
- // browsers. Once we get this color, we no longer need the test element. Access the `window`
2835
- // via the document so we can fake it in tests. Note that we have extra null checks, because
2836
- // this logic will likely run during app bootstrap and throwing can break the entire app.
2837
- const documentWindow = this._document.defaultView || window;
2838
- const computedStyle = documentWindow && documentWindow.getComputedStyle
2839
- ? documentWindow.getComputedStyle(testElement)
2840
- : null;
2841
- const computedColor = ((computedStyle && computedStyle.backgroundColor) || '').replace(/ /g, '');
2842
- testElement.remove();
2843
- switch (computedColor) {
2844
- // Pre Windows 11 dark theme.
2845
- case 'rgb(0,0,0)':
2846
- // Windows 11 dark themes.
2847
- case 'rgb(45,50,54)':
2848
- case 'rgb(32,32,32)':
2849
- return HighContrastMode.WHITE_ON_BLACK;
2850
- // Pre Windows 11 light theme.
2851
- case 'rgb(255,255,255)':
2852
- // Windows 11 light theme.
2853
- case 'rgb(255,250,239)':
2854
- return HighContrastMode.BLACK_ON_WHITE;
2855
- }
2856
- return HighContrastMode.NONE;
2857
- }
2858
- ngOnDestroy() {
2859
- this._breakpointSubscription.unsubscribe();
2860
- }
2861
- /** Applies CSS classes indicating high-contrast mode to document body (browser-only). */
2862
- _applyBodyHighContrastModeCssClasses() {
2863
- if (!this._hasCheckedHighContrastMode && this._platform.isBrowser && this._document.body) {
2864
- const bodyClasses = this._document.body.classList;
2865
- bodyClasses.remove(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS, BLACK_ON_WHITE_CSS_CLASS, WHITE_ON_BLACK_CSS_CLASS);
2866
- this._hasCheckedHighContrastMode = true;
2867
- const mode = this.getHighContrastMode();
2868
- if (mode === HighContrastMode.BLACK_ON_WHITE) {
2869
- bodyClasses.add(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS, BLACK_ON_WHITE_CSS_CLASS);
2870
- }
2871
- else if (mode === HighContrastMode.WHITE_ON_BLACK) {
2872
- bodyClasses.add(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS, WHITE_ON_BLACK_CSS_CLASS);
2873
- }
2874
- }
2875
- }
2876
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: HighContrastModeDetector, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
2877
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: HighContrastModeDetector, providedIn: 'root' });
2878
- }
2879
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: HighContrastModeDetector, decorators: [{
2880
- type: Injectable,
2881
- args: [{ providedIn: 'root' }]
2882
- }], ctorParameters: () => [] });
2883
-
2884
- class A11yModule {
2885
- constructor() {
2886
- inject(HighContrastModeDetector)._applyBodyHighContrastModeCssClasses();
2887
- }
2888
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: A11yModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2889
- static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.0", ngImport: i0, type: A11yModule, imports: [ObserversModule, CdkAriaLive, CdkTrapFocus, CdkMonitorFocus], exports: [CdkAriaLive, CdkTrapFocus, CdkMonitorFocus] });
2890
- static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: A11yModule, imports: [ObserversModule] });
2891
- }
2892
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: A11yModule, decorators: [{
2893
- type: NgModule,
2894
- args: [{
2895
- imports: [ObserversModule, CdkAriaLive, CdkTrapFocus, CdkMonitorFocus],
2896
- exports: [CdkAriaLive, CdkTrapFocus, CdkMonitorFocus],
2897
- }]
2898
- }], ctorParameters: () => [] });
2899
-
2900
- /**
2901
- * Keeps track of the ID count per prefix. This helps us make the IDs a bit more deterministic
2902
- * like they were before the service was introduced. Note that ideally we wouldn't have to do
2903
- * this, but there are some internal tests that rely on the IDs.
2904
- */
2905
- const counters = {};
2906
- /** Service that generates unique IDs for DOM nodes. */
2907
- class _IdGenerator {
2908
- _appId = inject(APP_ID);
2909
- /**
2910
- * Generates a unique ID with a specific prefix.
2911
- * @param prefix Prefix to add to the ID.
2912
- */
2913
- getId(prefix) {
2914
- // Omit the app ID if it's the default `ng`. Since the vast majority of pages have one
2915
- // Angular app on them, we can reduce the amount of breakages by not adding it.
2916
- if (this._appId !== 'ng') {
2917
- prefix += this._appId;
2918
- }
2919
- if (!counters.hasOwnProperty(prefix)) {
2920
- counters[prefix] = 0;
2921
- }
2922
- return `${prefix}${counters[prefix]++}`;
2923
- }
2924
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: _IdGenerator, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
2925
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: _IdGenerator, providedIn: 'root' });
2926
- }
2927
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: _IdGenerator, decorators: [{
2928
- type: Injectable,
2929
- args: [{ providedIn: 'root' }]
2930
- }] });
2931
-
2932
- /**
2933
- * Generated bundle index. Do not edit.
2934
- */
2935
537
 
2936
- export { A11yModule, ActiveDescendantKeyManager, AriaDescriber, CDK_DESCRIBEDBY_HOST_ATTRIBUTE, CDK_DESCRIBEDBY_ID_PREFIX, CdkAriaLive, CdkMonitorFocus, CdkTrapFocus, ConfigurableFocusTrap, ConfigurableFocusTrapFactory, EventListenerFocusTrapInertStrategy, FOCUS_MONITOR_DEFAULT_OPTIONS, FOCUS_TRAP_INERT_STRATEGY, FocusKeyManager, FocusMonitor, FocusMonitorDetectionMode, FocusTrap, FocusTrapFactory, HighContrastMode, 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, NOOP_TREE_KEY_MANAGER_FACTORY, NOOP_TREE_KEY_MANAGER_FACTORY_PROVIDER, NoopTreeKeyManager, TREE_KEY_MANAGER, TREE_KEY_MANAGER_FACTORY, TREE_KEY_MANAGER_FACTORY_PROVIDER, TreeKeyManager, _IdGenerator, addAriaReferencedId, getAriaReferenceIds, isFakeMousedownFromScreenReader, isFakeTouchstartFromScreenReader, removeAriaReferencedId };
538
+ export { AriaDescriber, CDK_DESCRIBEDBY_HOST_ATTRIBUTE, CDK_DESCRIBEDBY_ID_PREFIX, ConfigurableFocusTrap, ConfigurableFocusTrapFactory, EventListenerFocusTrapInertStrategy, FOCUS_TRAP_INERT_STRATEGY, MESSAGES_CONTAINER_ID, NOOP_TREE_KEY_MANAGER_FACTORY, NOOP_TREE_KEY_MANAGER_FACTORY_PROVIDER, NoopTreeKeyManager, addAriaReferencedId, getAriaReferenceIds, removeAriaReferencedId };
2937
539
  //# sourceMappingURL=a11y.mjs.map