@angular/cdk 21.0.0-next.9 → 21.0.0-rc.0

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 (123) hide show
  1. package/_adev_assets/cdk_drag_drop.json +13 -12
  2. package/_adev_assets/cdk_testing.json +9 -9
  3. package/_adev_assets/cdk_testing_protractor.json +1 -1
  4. package/_adev_assets/cdk_testing_selenium_webdriver.json +1 -1
  5. package/_adev_assets/cdk_testing_testbed.json +1 -1
  6. package/fesm2022/_a11y-module-chunk.mjs +755 -869
  7. package/fesm2022/_a11y-module-chunk.mjs.map +1 -1
  8. package/fesm2022/_activedescendant-key-manager-chunk.mjs +8 -8
  9. package/fesm2022/_activedescendant-key-manager-chunk.mjs.map +1 -1
  10. package/fesm2022/_array-chunk.mjs +1 -1
  11. package/fesm2022/_array-chunk.mjs.map +1 -1
  12. package/fesm2022/_breakpoints-observer-chunk.mjs +149 -152
  13. package/fesm2022/_breakpoints-observer-chunk.mjs.map +1 -1
  14. package/fesm2022/_css-pixel-value-chunk.mjs +4 -5
  15. package/fesm2022/_css-pixel-value-chunk.mjs.map +1 -1
  16. package/fesm2022/_data-source-chunk.mjs +2 -8
  17. package/fesm2022/_data-source-chunk.mjs.map +1 -1
  18. package/fesm2022/_directionality-chunk.mjs +54 -54
  19. package/fesm2022/_directionality-chunk.mjs.map +1 -1
  20. package/fesm2022/_dispose-view-repeater-strategy-chunk.mjs +25 -36
  21. package/fesm2022/_dispose-view-repeater-strategy-chunk.mjs.map +1 -1
  22. package/fesm2022/_element-chunk.mjs +6 -17
  23. package/fesm2022/_element-chunk.mjs.map +1 -1
  24. package/fesm2022/_fake-event-detection-chunk.mjs +3 -17
  25. package/fesm2022/_fake-event-detection-chunk.mjs.map +1 -1
  26. package/fesm2022/_focus-key-manager-chunk.mjs +10 -14
  27. package/fesm2022/_focus-key-manager-chunk.mjs.map +1 -1
  28. package/fesm2022/_focus-monitor-chunk.mjs +376 -566
  29. package/fesm2022/_focus-monitor-chunk.mjs.map +1 -1
  30. package/fesm2022/_id-generator-chunk.mjs +36 -27
  31. package/fesm2022/_id-generator-chunk.mjs.map +1 -1
  32. package/fesm2022/_keycodes-chunk.mjs +9 -9
  33. package/fesm2022/_keycodes-chunk.mjs.map +1 -1
  34. package/fesm2022/_list-key-manager-chunk.mjs +248 -336
  35. package/fesm2022/_list-key-manager-chunk.mjs.map +1 -1
  36. package/fesm2022/_overlay-module-chunk.mjs +2534 -2948
  37. package/fesm2022/_overlay-module-chunk.mjs.map +1 -1
  38. package/fesm2022/_passive-listeners-chunk.mjs +10 -22
  39. package/fesm2022/_passive-listeners-chunk.mjs.map +1 -1
  40. package/fesm2022/_platform-chunk.mjs +42 -65
  41. package/fesm2022/_platform-chunk.mjs.map +1 -1
  42. package/fesm2022/_recycle-view-repeater-strategy-chunk.mjs +78 -134
  43. package/fesm2022/_recycle-view-repeater-strategy-chunk.mjs.map +1 -1
  44. package/fesm2022/_scrolling-chunk.mjs +44 -85
  45. package/fesm2022/_scrolling-chunk.mjs.map +1 -1
  46. package/fesm2022/_selection-model-chunk.mjs +138 -209
  47. package/fesm2022/_selection-model-chunk.mjs.map +1 -1
  48. package/fesm2022/_shadow-dom-chunk.mjs +21 -35
  49. package/fesm2022/_shadow-dom-chunk.mjs.map +1 -1
  50. package/fesm2022/_style-loader-chunk.mjs +50 -37
  51. package/fesm2022/_style-loader-chunk.mjs.map +1 -1
  52. package/fesm2022/_test-environment-chunk.mjs +2 -14
  53. package/fesm2022/_test-environment-chunk.mjs.map +1 -1
  54. package/fesm2022/_tree-key-manager-chunk.mjs +229 -308
  55. package/fesm2022/_tree-key-manager-chunk.mjs.map +1 -1
  56. package/fesm2022/_typeahead-chunk.mjs +52 -74
  57. package/fesm2022/_typeahead-chunk.mjs.map +1 -1
  58. package/fesm2022/_unique-selection-dispatcher-chunk.mjs +43 -40
  59. package/fesm2022/_unique-selection-dispatcher-chunk.mjs.map +1 -1
  60. package/fesm2022/a11y.mjs +351 -449
  61. package/fesm2022/a11y.mjs.map +1 -1
  62. package/fesm2022/accordion.mjs +254 -192
  63. package/fesm2022/accordion.mjs.map +1 -1
  64. package/fesm2022/bidi.mjs +121 -64
  65. package/fesm2022/bidi.mjs.map +1 -1
  66. package/fesm2022/cdk.mjs +1 -2
  67. package/fesm2022/cdk.mjs.map +1 -1
  68. package/fesm2022/clipboard.mjs +208 -186
  69. package/fesm2022/clipboard.mjs.map +1 -1
  70. package/fesm2022/coercion-private.mjs +4 -8
  71. package/fesm2022/coercion-private.mjs.map +1 -1
  72. package/fesm2022/coercion.mjs +11 -29
  73. package/fesm2022/coercion.mjs.map +1 -1
  74. package/fesm2022/dialog.mjs +660 -808
  75. package/fesm2022/dialog.mjs.map +1 -1
  76. package/fesm2022/drag-drop.mjs +3347 -4286
  77. package/fesm2022/drag-drop.mjs.map +1 -1
  78. package/fesm2022/keycodes.mjs +4 -8
  79. package/fesm2022/keycodes.mjs.map +1 -1
  80. package/fesm2022/layout.mjs +44 -26
  81. package/fesm2022/layout.mjs.map +1 -1
  82. package/fesm2022/listbox.mjs +841 -895
  83. package/fesm2022/listbox.mjs.map +1 -1
  84. package/fesm2022/menu.mjs +1942 -1858
  85. package/fesm2022/menu.mjs.map +1 -1
  86. package/fesm2022/observers-private.mjs +88 -106
  87. package/fesm2022/observers-private.mjs.map +1 -1
  88. package/fesm2022/observers.mjs +262 -184
  89. package/fesm2022/observers.mjs.map +1 -1
  90. package/fesm2022/overlay.mjs +72 -68
  91. package/fesm2022/overlay.mjs.map +1 -1
  92. package/fesm2022/platform.mjs +43 -54
  93. package/fesm2022/platform.mjs.map +1 -1
  94. package/fesm2022/portal.mjs +402 -560
  95. package/fesm2022/portal.mjs.map +1 -1
  96. package/fesm2022/private.mjs +38 -10
  97. package/fesm2022/private.mjs.map +1 -1
  98. package/fesm2022/scrolling.mjs +1323 -1400
  99. package/fesm2022/scrolling.mjs.map +1 -1
  100. package/fesm2022/stepper.mjs +758 -590
  101. package/fesm2022/stepper.mjs.map +1 -1
  102. package/fesm2022/table.mjs +2327 -2319
  103. package/fesm2022/table.mjs.map +1 -1
  104. package/fesm2022/testing-selenium-webdriver.mjs +252 -325
  105. package/fesm2022/testing-selenium-webdriver.mjs.map +1 -1
  106. package/fesm2022/testing-testbed.mjs +592 -709
  107. package/fesm2022/testing-testbed.mjs.map +1 -1
  108. package/fesm2022/testing.mjs +368 -889
  109. package/fesm2022/testing.mjs.map +1 -1
  110. package/fesm2022/text-field.mjs +459 -388
  111. package/fesm2022/text-field.mjs.map +1 -1
  112. package/fesm2022/tree.mjs +1483 -1731
  113. package/fesm2022/tree.mjs.map +1 -1
  114. package/overlay/_index.scss +28 -0
  115. package/overlay-prebuilt.css +1 -1
  116. package/package.json +1 -1
  117. package/schematics/ng-add/index.js +1 -1
  118. package/types/_overlay-module-chunk.d.ts +59 -7
  119. package/types/_portal-directives-chunk.d.ts +2 -18
  120. package/types/accordion.d.ts +3 -1
  121. package/types/dialog.d.ts +1 -1
  122. package/types/overlay.d.ts +6 -2
  123. package/types/portal.d.ts +1 -1
@@ -1,949 +1,428 @@
1
1
  import { BehaviorSubject } from 'rxjs';
2
2
 
3
- /** Subject used to dispatch and listen for changes to the auto change detection status . */
4
3
  const autoChangeDetectionSubject = new BehaviorSubject({
5
- isDisabled: false,
4
+ isDisabled: false
6
5
  });
7
- /** The current subscription to `autoChangeDetectionSubject`. */
8
6
  let autoChangeDetectionSubscription;
9
- /**
10
- * The default handler for auto change detection status changes. This handler will be used if the
11
- * specific environment does not install its own.
12
- * @param status The new auto change detection status.
13
- */
14
7
  function defaultAutoChangeDetectionHandler(status) {
15
- status.onDetectChangesNow?.();
8
+ status.onDetectChangesNow?.();
16
9
  }
17
- /**
18
- * Allows a test `HarnessEnvironment` to install its own handler for auto change detection status
19
- * changes.
20
- * @param handler The handler for the auto change detection status.
21
- */
22
10
  function handleAutoChangeDetectionStatus(handler) {
23
- stopHandlingAutoChangeDetectionStatus();
24
- autoChangeDetectionSubscription = autoChangeDetectionSubject.subscribe(handler);
11
+ stopHandlingAutoChangeDetectionStatus();
12
+ autoChangeDetectionSubscription = autoChangeDetectionSubject.subscribe(handler);
25
13
  }
26
- /** Allows a `HarnessEnvironment` to stop handling auto change detection status changes. */
27
14
  function stopHandlingAutoChangeDetectionStatus() {
28
- autoChangeDetectionSubscription?.unsubscribe();
29
- autoChangeDetectionSubscription = null;
15
+ autoChangeDetectionSubscription?.unsubscribe();
16
+ autoChangeDetectionSubscription = null;
30
17
  }
31
- /**
32
- * Batches together triggering of change detection over the duration of the given function.
33
- * @param fn The function to call with batched change detection.
34
- * @param triggerBeforeAndAfter Optionally trigger change detection once before and after the batch
35
- * operation. If false, change detection will not be triggered.
36
- * @return The result of the given function.
37
- */
38
18
  async function batchChangeDetection(fn, triggerBeforeAndAfter) {
39
- // If change detection batching is already in progress, just run the function.
40
- if (autoChangeDetectionSubject.getValue().isDisabled) {
41
- return await fn();
42
- }
43
- // If nothing is handling change detection batching, install the default handler.
44
- if (!autoChangeDetectionSubscription) {
45
- handleAutoChangeDetectionStatus(defaultAutoChangeDetectionHandler);
46
- }
47
- if (triggerBeforeAndAfter) {
48
- await new Promise(resolve => autoChangeDetectionSubject.next({
49
- isDisabled: true,
50
- onDetectChangesNow: resolve,
51
- }));
52
- // The function passed in may throw (e.g. if the user wants to make an expectation of an error
53
- // being thrown. If this happens, we need to make sure we still re-enable change detection, so
54
- // we wrap it in a `finally` block.
55
- try {
56
- return await fn();
57
- }
58
- finally {
59
- await new Promise(resolve => autoChangeDetectionSubject.next({
60
- isDisabled: false,
61
- onDetectChangesNow: resolve,
62
- }));
63
- }
64
- }
65
- else {
66
- autoChangeDetectionSubject.next({ isDisabled: true });
67
- // The function passed in may throw (e.g. if the user wants to make an expectation of an error
68
- // being thrown. If this happens, we need to make sure we still re-enable change detection, so
69
- // we wrap it in a `finally` block.
70
- try {
71
- return await fn();
72
- }
73
- finally {
74
- autoChangeDetectionSubject.next({ isDisabled: false });
75
- }
19
+ if (autoChangeDetectionSubject.getValue().isDisabled) {
20
+ return await fn();
21
+ }
22
+ if (!autoChangeDetectionSubscription) {
23
+ handleAutoChangeDetectionStatus(defaultAutoChangeDetectionHandler);
24
+ }
25
+ if (triggerBeforeAndAfter) {
26
+ await new Promise(resolve => autoChangeDetectionSubject.next({
27
+ isDisabled: true,
28
+ onDetectChangesNow: resolve
29
+ }));
30
+ try {
31
+ return await fn();
32
+ } finally {
33
+ await new Promise(resolve => autoChangeDetectionSubject.next({
34
+ isDisabled: false,
35
+ onDetectChangesNow: resolve
36
+ }));
37
+ }
38
+ } else {
39
+ autoChangeDetectionSubject.next({
40
+ isDisabled: true
41
+ });
42
+ try {
43
+ return await fn();
44
+ } finally {
45
+ autoChangeDetectionSubject.next({
46
+ isDisabled: false
47
+ });
76
48
  }
49
+ }
77
50
  }
78
- /**
79
- * Disables the harness system's auto change detection for the duration of the given function.
80
- * @param fn The function to disable auto change detection for.
81
- * @return The result of the given function.
82
- */
83
51
  async function manualChangeDetection(fn) {
84
- return batchChangeDetection(fn, false);
52
+ return batchChangeDetection(fn, false);
85
53
  }
86
- /**
87
- * Resolves the given list of async values in parallel (i.e. via Promise.all) while batching change
88
- * detection over the entire operation such that change detection occurs exactly once before
89
- * resolving the values and once after.
90
- * @param values A getter for the async values to resolve in parallel with batched change detection.
91
- * @return The resolved values.
92
- */
93
54
  async function parallel(values) {
94
- return batchChangeDetection(() => Promise.all(values()), true);
55
+ return batchChangeDetection(() => Promise.all(values()), true);
95
56
  }
96
57
 
97
- /**
98
- * Base class for component test harnesses that all component harness authors should extend. This
99
- * base component harness provides the basic ability to locate element and sub-component harnesses.
100
- */
101
58
  class ComponentHarness {
102
- locatorFactory;
103
- constructor(locatorFactory) {
104
- this.locatorFactory = locatorFactory;
105
- }
106
- /** Gets a `Promise` for the `TestElement` representing the host element of the component. */
107
- async host() {
108
- return this.locatorFactory.rootElement;
109
- }
110
- /**
111
- * Gets a `LocatorFactory` for the document root element. This factory can be used to create
112
- * locators for elements that a component creates outside of its own root element. (e.g. by
113
- * appending to document.body).
114
- */
115
- documentRootLocatorFactory() {
116
- return this.locatorFactory.documentRootLocatorFactory();
117
- }
118
- /**
119
- * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
120
- * or element under the host element of this `ComponentHarness`.
121
- *
122
- * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'`
123
- *
124
- * ```html
125
- * <div id="d1"></div><div id="d2"></div>
126
- * ```
127
- *
128
- * then we expect:
129
- *
130
- * ```ts
131
- * await ch.locatorFor(DivHarness, 'div')() // Gets a `DivHarness` instance for #d1
132
- * await ch.locatorFor('div', DivHarness)() // Gets a `TestElement` instance for #d1
133
- * await ch.locatorFor('span')() // Throws because the `Promise` rejects
134
- * ```
135
- *
136
- * @param queries A list of queries specifying which harnesses and elements to search for:
137
- * - A `string` searches for elements matching the CSS selector specified by the string.
138
- * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
139
- * given class.
140
- * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
141
- * predicate.
142
- * @return An asynchronous locator function that searches for and returns a `Promise` for the
143
- * first element or harness matching the given search criteria. Matches are ordered first by
144
- * order in the DOM, and second by order in the queries list. If no matches are found, the
145
- * `Promise` rejects. The type that the `Promise` resolves to is a union of all result types for
146
- * each query.
147
- */
148
- locatorFor(...queries) {
149
- return this.locatorFactory.locatorFor(...queries);
150
- }
151
- /**
152
- * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
153
- * or element under the host element of this `ComponentHarness`.
154
- *
155
- * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'`
156
- *
157
- * ```html
158
- * <div id="d1"></div><div id="d2"></div>
159
- * ```
160
- *
161
- * then we expect:
162
- *
163
- * ```ts
164
- * await ch.locatorForOptional(DivHarness, 'div')() // Gets a `DivHarness` instance for #d1
165
- * await ch.locatorForOptional('div', DivHarness)() // Gets a `TestElement` instance for #d1
166
- * await ch.locatorForOptional('span')() // Gets `null`
167
- * ```
168
- *
169
- * @param queries A list of queries specifying which harnesses and elements to search for:
170
- * - A `string` searches for elements matching the CSS selector specified by the string.
171
- * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
172
- * given class.
173
- * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
174
- * predicate.
175
- * @return An asynchronous locator function that searches for and returns a `Promise` for the
176
- * first element or harness matching the given search criteria. Matches are ordered first by
177
- * order in the DOM, and second by order in the queries list. If no matches are found, the
178
- * `Promise` is resolved with `null`. The type that the `Promise` resolves to is a union of all
179
- * result types for each query or null.
180
- */
181
- locatorForOptional(...queries) {
182
- return this.locatorFactory.locatorForOptional(...queries);
183
- }
184
- /**
185
- * Creates an asynchronous locator function that can be used to find `ComponentHarness` instances
186
- * or elements under the host element of this `ComponentHarness`.
187
- *
188
- * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'` and
189
- * `IdIsD1Harness.hostSelector` is `'#d1'`
190
- *
191
- * ```html
192
- * <div id="d1"></div><div id="d2"></div>
193
- * ```
194
- *
195
- * then we expect:
196
- *
197
- * ```ts
198
- * // Gets [DivHarness for #d1, TestElement for #d1, DivHarness for #d2, TestElement for #d2]
199
- * await ch.locatorForAll(DivHarness, 'div')()
200
- * // Gets [TestElement for #d1, TestElement for #d2]
201
- * await ch.locatorForAll('div', '#d1')()
202
- * // Gets [DivHarness for #d1, IdIsD1Harness for #d1, DivHarness for #d2]
203
- * await ch.locatorForAll(DivHarness, IdIsD1Harness)()
204
- * // Gets []
205
- * await ch.locatorForAll('span')()
206
- * ```
207
- *
208
- * @param queries A list of queries specifying which harnesses and elements to search for:
209
- * - A `string` searches for elements matching the CSS selector specified by the string.
210
- * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
211
- * given class.
212
- * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
213
- * predicate.
214
- * @return An asynchronous locator function that searches for and returns a `Promise` for all
215
- * elements and harnesses matching the given search criteria. Matches are ordered first by
216
- * order in the DOM, and second by order in the queries list. If an element matches more than
217
- * one `ComponentHarness` class, the locator gets an instance of each for the same element. If
218
- * an element matches multiple `string` selectors, only one `TestElement` instance is returned
219
- * for that element. The type that the `Promise` resolves to is an array where each element is
220
- * the union of all result types for each query.
221
- */
222
- locatorForAll(...queries) {
223
- return this.locatorFactory.locatorForAll(...queries);
224
- }
225
- /**
226
- * Flushes change detection and async tasks in the Angular zone.
227
- * In most cases it should not be necessary to call this manually. However, there may be some edge
228
- * cases where it is needed to fully flush animation events.
229
- */
230
- async forceStabilize() {
231
- return this.locatorFactory.forceStabilize();
232
- }
233
- /**
234
- * Waits for all scheduled or running async tasks to complete. This allows harness
235
- * authors to wait for async tasks outside of the Angular zone.
236
- */
237
- async waitForTasksOutsideAngular() {
238
- return this.locatorFactory.waitForTasksOutsideAngular();
239
- }
59
+ locatorFactory;
60
+ constructor(locatorFactory) {
61
+ this.locatorFactory = locatorFactory;
62
+ }
63
+ async host() {
64
+ return this.locatorFactory.rootElement;
65
+ }
66
+ documentRootLocatorFactory() {
67
+ return this.locatorFactory.documentRootLocatorFactory();
68
+ }
69
+ locatorFor(...queries) {
70
+ return this.locatorFactory.locatorFor(...queries);
71
+ }
72
+ locatorForOptional(...queries) {
73
+ return this.locatorFactory.locatorForOptional(...queries);
74
+ }
75
+ locatorForAll(...queries) {
76
+ return this.locatorFactory.locatorForAll(...queries);
77
+ }
78
+ async forceStabilize() {
79
+ return this.locatorFactory.forceStabilize();
80
+ }
81
+ async waitForTasksOutsideAngular() {
82
+ return this.locatorFactory.waitForTasksOutsideAngular();
83
+ }
240
84
  }
241
- /**
242
- * Base class for component harnesses that authors should extend if they anticipate that consumers
243
- * of the harness may want to access other harnesses within the `<ng-content>` of the component.
244
- */
245
85
  class ContentContainerComponentHarness extends ComponentHarness {
246
- /**
247
- * Gets a `HarnessLoader` that searches for harnesses under the first element matching the given
248
- * selector within the current harness's content.
249
- * @param selector The selector for an element in the component's content.
250
- * @returns A `HarnessLoader` that searches for harnesses under the given selector.
251
- */
252
- async getChildLoader(selector) {
253
- return (await this.getRootHarnessLoader()).getChildLoader(selector);
254
- }
255
- /**
256
- * Gets a list of `HarnessLoader` for each element matching the given selector under the current
257
- * harness's cotnent that searches for harnesses under that element.
258
- * @param selector The selector for elements in the component's content.
259
- * @returns A list of `HarnessLoader` for each element matching the given selector.
260
- */
261
- async getAllChildLoaders(selector) {
262
- return (await this.getRootHarnessLoader()).getAllChildLoaders(selector);
263
- }
264
- /**
265
- * Gets the first matching harness for the given query within the current harness's content.
266
- * @param query The harness query to search for.
267
- * @returns The first harness matching the given query.
268
- * @throws If no matching harness is found.
269
- */
270
- async getHarness(query) {
271
- return (await this.getRootHarnessLoader()).getHarness(query);
272
- }
273
- /**
274
- * Gets the first matching harness for the given query within the current harness's content.
275
- * @param query The harness query to search for.
276
- * @returns The first harness matching the given query, or null if none is found.
277
- */
278
- async getHarnessOrNull(query) {
279
- return (await this.getRootHarnessLoader()).getHarnessOrNull(query);
280
- }
281
- /**
282
- * Gets a matching harness for the given query and index within the current harness's content.
283
- * @param query The harness query to search for.
284
- * @param index The zero-indexed offset of the component to find.
285
- * @returns The first harness matching the given query.
286
- * @throws If no matching harness is found.
287
- */
288
- async getHarnessAtIndex(query, index) {
289
- return (await this.getRootHarnessLoader()).getHarnessAtIndex(query, index);
290
- }
291
- /**
292
- * Gets all matching harnesses for the given query within the current harness's content.
293
- * @param query The harness query to search for.
294
- * @returns The list of harness matching the given query.
295
- */
296
- async getAllHarnesses(query) {
297
- return (await this.getRootHarnessLoader()).getAllHarnesses(query);
298
- }
299
- /**
300
- * Returns the number of matching harnesses for the given query within the current harness's
301
- * content.
302
- *
303
- * @param query The harness query to search for.
304
- * @returns The number of matching harnesses for the given query.
305
- */
306
- async countHarnesses(query) {
307
- return (await this.getRootHarnessLoader()).countHarnesses(query);
308
- }
309
- /**
310
- * Checks whether there is a matching harnesses for the given query within the current harness's
311
- * content.
312
- *
313
- * @param query The harness query to search for.
314
- * @returns Whether there is matching harnesses for the given query.
315
- */
316
- async hasHarness(query) {
317
- return (await this.getRootHarnessLoader()).hasHarness(query);
318
- }
319
- /**
320
- * Gets the root harness loader from which to start
321
- * searching for content contained by this harness.
322
- */
323
- async getRootHarnessLoader() {
324
- return this.locatorFactory.rootHarnessLoader();
325
- }
86
+ async getChildLoader(selector) {
87
+ return (await this.getRootHarnessLoader()).getChildLoader(selector);
88
+ }
89
+ async getAllChildLoaders(selector) {
90
+ return (await this.getRootHarnessLoader()).getAllChildLoaders(selector);
91
+ }
92
+ async getHarness(query) {
93
+ return (await this.getRootHarnessLoader()).getHarness(query);
94
+ }
95
+ async getHarnessOrNull(query) {
96
+ return (await this.getRootHarnessLoader()).getHarnessOrNull(query);
97
+ }
98
+ async getHarnessAtIndex(query, index) {
99
+ return (await this.getRootHarnessLoader()).getHarnessAtIndex(query, index);
100
+ }
101
+ async getAllHarnesses(query) {
102
+ return (await this.getRootHarnessLoader()).getAllHarnesses(query);
103
+ }
104
+ async countHarnesses(query) {
105
+ return (await this.getRootHarnessLoader()).countHarnesses(query);
106
+ }
107
+ async hasHarness(query) {
108
+ return (await this.getRootHarnessLoader()).hasHarness(query);
109
+ }
110
+ async getRootHarnessLoader() {
111
+ return this.locatorFactory.rootHarnessLoader();
112
+ }
326
113
  }
327
- /**
328
- * A class used to associate a ComponentHarness class with predicate functions that can be used to
329
- * filter instances of the class to be matched.
330
- */
331
114
  class HarnessPredicate {
332
- harnessType;
333
- _predicates = [];
334
- _descriptions = [];
335
- _ancestor;
336
- constructor(harnessType, options) {
337
- this.harnessType = harnessType;
338
- this._addBaseOptions(options);
339
- }
340
- /**
341
- * Checks if the specified nullable string value matches the given pattern.
342
- * @param value The nullable string value to check, or a Promise resolving to the
343
- * nullable string value.
344
- * @param pattern The pattern the value is expected to match. If `pattern` is a string,
345
- * `value` is expected to match exactly. If `pattern` is a regex, a partial match is
346
- * allowed. If `pattern` is `null`, the value is expected to be `null`.
347
- * @return Whether the value matches the pattern.
348
- */
349
- static async stringMatches(value, pattern) {
350
- value = await value;
351
- if (pattern === null) {
352
- return value === null;
353
- }
354
- else if (value === null) {
355
- return false;
356
- }
357
- return typeof pattern === 'string' ? value === pattern : pattern.test(value);
358
- }
359
- /**
360
- * Adds a predicate function to be run against candidate harnesses.
361
- * @param description A description of this predicate that may be used in error messages.
362
- * @param predicate An async predicate function.
363
- * @return this (for method chaining).
364
- */
365
- add(description, predicate) {
366
- this._descriptions.push(description);
367
- this._predicates.push(predicate);
368
- return this;
369
- }
370
- /**
371
- * Adds a predicate function that depends on an option value to be run against candidate
372
- * harnesses. If the option value is undefined, the predicate will be ignored.
373
- * @param name The name of the option (may be used in error messages).
374
- * @param option The option value.
375
- * @param predicate The predicate function to run if the option value is not undefined.
376
- * @return this (for method chaining).
377
- */
378
- addOption(name, option, predicate) {
379
- if (option !== undefined) {
380
- this.add(`${name} = ${_valueAsString(option)}`, item => predicate(item, option));
381
- }
382
- return this;
383
- }
384
- /**
385
- * Filters a list of harnesses on this predicate.
386
- * @param harnesses The list of harnesses to filter.
387
- * @return A list of harnesses that satisfy this predicate.
388
- */
389
- async filter(harnesses) {
390
- if (harnesses.length === 0) {
391
- return [];
392
- }
393
- const results = await parallel(() => harnesses.map(h => this.evaluate(h)));
394
- return harnesses.filter((_, i) => results[i]);
395
- }
396
- /**
397
- * Evaluates whether the given harness satisfies this predicate.
398
- * @param harness The harness to check
399
- * @return A promise that resolves to true if the harness satisfies this predicate,
400
- * and resolves to false otherwise.
401
- */
402
- async evaluate(harness) {
403
- const results = await parallel(() => this._predicates.map(p => p(harness)));
404
- return results.reduce((combined, current) => combined && current, true);
405
- }
406
- /** Gets a description of this predicate for use in error messages. */
407
- getDescription() {
408
- return this._descriptions.join(', ');
409
- }
410
- /** Gets the selector used to find candidate elements. */
411
- getSelector() {
412
- // We don't have to go through the extra trouble if there are no ancestors.
413
- if (!this._ancestor) {
414
- return (this.harnessType.hostSelector || '').trim();
415
- }
416
- const [ancestors, ancestorPlaceholders] = _splitAndEscapeSelector(this._ancestor);
417
- const [selectors, selectorPlaceholders] = _splitAndEscapeSelector(this.harnessType.hostSelector || '');
418
- const result = [];
419
- // We have to add the ancestor to each part of the host compound selector, otherwise we can get
420
- // incorrect results. E.g. `.ancestor .a, .ancestor .b` vs `.ancestor .a, .b`.
421
- ancestors.forEach(escapedAncestor => {
422
- const ancestor = _restoreSelector(escapedAncestor, ancestorPlaceholders);
423
- return selectors.forEach(escapedSelector => result.push(`${ancestor} ${_restoreSelector(escapedSelector, selectorPlaceholders)}`));
424
- });
425
- return result.join(', ');
426
- }
427
- /** Adds base options common to all harness types. */
428
- _addBaseOptions(options) {
429
- this._ancestor = options.ancestor || '';
430
- if (this._ancestor) {
431
- this._descriptions.push(`has ancestor matching selector "${this._ancestor}"`);
432
- }
433
- const selector = options.selector;
434
- if (selector !== undefined) {
435
- this.add(`host matches selector "${selector}"`, async (item) => {
436
- return (await item.host()).matchesSelector(selector);
437
- });
438
- }
439
- }
115
+ harnessType;
116
+ _predicates = [];
117
+ _descriptions = [];
118
+ _ancestor;
119
+ constructor(harnessType, options) {
120
+ this.harnessType = harnessType;
121
+ this._addBaseOptions(options);
122
+ }
123
+ static async stringMatches(value, pattern) {
124
+ value = await value;
125
+ if (pattern === null) {
126
+ return value === null;
127
+ } else if (value === null) {
128
+ return false;
129
+ }
130
+ return typeof pattern === 'string' ? value === pattern : pattern.test(value);
131
+ }
132
+ add(description, predicate) {
133
+ this._descriptions.push(description);
134
+ this._predicates.push(predicate);
135
+ return this;
136
+ }
137
+ addOption(name, option, predicate) {
138
+ if (option !== undefined) {
139
+ this.add(`${name} = ${_valueAsString(option)}`, item => predicate(item, option));
140
+ }
141
+ return this;
142
+ }
143
+ async filter(harnesses) {
144
+ if (harnesses.length === 0) {
145
+ return [];
146
+ }
147
+ const results = await parallel(() => harnesses.map(h => this.evaluate(h)));
148
+ return harnesses.filter((_, i) => results[i]);
149
+ }
150
+ async evaluate(harness) {
151
+ const results = await parallel(() => this._predicates.map(p => p(harness)));
152
+ return results.reduce((combined, current) => combined && current, true);
153
+ }
154
+ getDescription() {
155
+ return this._descriptions.join(', ');
156
+ }
157
+ getSelector() {
158
+ if (!this._ancestor) {
159
+ return (this.harnessType.hostSelector || '').trim();
160
+ }
161
+ const [ancestors, ancestorPlaceholders] = _splitAndEscapeSelector(this._ancestor);
162
+ const [selectors, selectorPlaceholders] = _splitAndEscapeSelector(this.harnessType.hostSelector || '');
163
+ const result = [];
164
+ ancestors.forEach(escapedAncestor => {
165
+ const ancestor = _restoreSelector(escapedAncestor, ancestorPlaceholders);
166
+ return selectors.forEach(escapedSelector => result.push(`${ancestor} ${_restoreSelector(escapedSelector, selectorPlaceholders)}`));
167
+ });
168
+ return result.join(', ');
169
+ }
170
+ _addBaseOptions(options) {
171
+ this._ancestor = options.ancestor || '';
172
+ if (this._ancestor) {
173
+ this._descriptions.push(`has ancestor matching selector "${this._ancestor}"`);
174
+ }
175
+ const selector = options.selector;
176
+ if (selector !== undefined) {
177
+ this.add(`host matches selector "${selector}"`, async item => {
178
+ return (await item.host()).matchesSelector(selector);
179
+ });
180
+ }
181
+ }
440
182
  }
441
- /** Represent a value as a string for the purpose of logging. */
442
183
  function _valueAsString(value) {
443
- if (value === undefined) {
444
- return 'undefined';
445
- }
446
- try {
447
- // `JSON.stringify` doesn't handle RegExp properly, so we need a custom replacer.
448
- // Use a character that is unlikely to appear in real strings to denote the start and end of
449
- // the regex. This allows us to strip out the extra quotes around the value added by
450
- // `JSON.stringify`. Also do custom escaping on `"` characters to prevent `JSON.stringify`
451
- // from escaping them as if they were part of a string.
452
- const stringifiedValue = JSON.stringify(value, (_, v) => v instanceof RegExp
453
- ? `◬MAT_RE_ESCAPE◬${v.toString().replace(/"/g, '◬MAT_RE_ESCAPE◬')}◬MAT_RE_ESCAPE◬`
454
- : v);
455
- // Strip out the extra quotes around regexes and put back the manually escaped `"` characters.
456
- return stringifiedValue
457
- .replace(/"◬MAT_RE_ESCAPE◬|◬MAT_RE_ESCAPE◬"/g, '')
458
- .replace(/◬MAT_RE_ESCAPE◬/g, '"');
459
- }
460
- catch {
461
- // `JSON.stringify` will throw if the object is cyclical,
462
- // in this case the best we can do is report the value as `{...}`.
463
- return '{...}';
464
- }
184
+ if (value === undefined) {
185
+ return 'undefined';
186
+ }
187
+ try {
188
+ const stringifiedValue = JSON.stringify(value, (_, v) => v instanceof RegExp ? `◬MAT_RE_ESCAPE◬${v.toString().replace(/"/g, '◬MAT_RE_ESCAPE◬')}◬MAT_RE_ESCAPE◬` : v);
189
+ return stringifiedValue.replace(/"◬MAT_RE_ESCAPE◬|◬MAT_RE_ESCAPE◬"/g, '').replace(/◬MAT_RE_ESCAPE◬/g, '"');
190
+ } catch {
191
+ return '{...}';
192
+ }
465
193
  }
466
- /**
467
- * Splits up a compound selector into its parts and escapes any quoted content. The quoted content
468
- * has to be escaped, because it can contain commas which will throw throw us off when trying to
469
- * split it.
470
- * @param selector Selector to be split.
471
- * @returns The escaped string where any quoted content is replaced with a placeholder. E.g.
472
- * `[foo="bar"]` turns into `[foo=__cdkPlaceholder-0__]`. Use `_restoreSelector` to restore
473
- * the placeholders.
474
- */
475
194
  function _splitAndEscapeSelector(selector) {
476
- const placeholders = [];
477
- // Note that the regex doesn't account for nested quotes so something like `"ab'cd'e"` will be
478
- // considered as two blocks. It's a bit of an edge case, but if we find that it's a problem,
479
- // we can make it a bit smarter using a loop. Use this for now since it's more readable and
480
- // compact. More complete implementation:
481
- // https://github.com/angular/angular/blob/bd34bc9e89f18a/packages/compiler/src/shadow_css.ts#L655
482
- const result = selector.replace(/(["'][^["']*["'])/g, (_, keep) => {
483
- const replaceBy = `__cdkPlaceholder-${placeholders.length}__`;
484
- placeholders.push(keep);
485
- return replaceBy;
486
- });
487
- return [result.split(',').map(part => part.trim()), placeholders];
195
+ const placeholders = [];
196
+ const result = selector.replace(/(["'][^["']*["'])/g, (_, keep) => {
197
+ const replaceBy = `__cdkPlaceholder-${placeholders.length}__`;
198
+ placeholders.push(keep);
199
+ return replaceBy;
200
+ });
201
+ return [result.split(',').map(part => part.trim()), placeholders];
488
202
  }
489
- /** Restores a selector whose content was escaped in `_splitAndEscapeSelector`. */
490
203
  function _restoreSelector(selector, placeholders) {
491
- return selector.replace(/__cdkPlaceholder-(\d+)__/g, (_, index) => placeholders[+index]);
204
+ return selector.replace(/__cdkPlaceholder-(\d+)__/g, (_, index) => placeholders[+index]);
492
205
  }
493
206
 
494
- /**
495
- * Base harness environment class that can be extended to allow `ComponentHarness`es to be used in
496
- * different test environments (e.g. testbed, protractor, etc.). This class implements the
497
- * functionality of both a `HarnessLoader` and `LocatorFactory`. This class is generic on the raw
498
- * element type, `E`, used by the particular test environment.
499
- */
500
207
  class HarnessEnvironment {
501
- rawRootElement;
502
- /** The root element of this `HarnessEnvironment` as a `TestElement`. */
503
- get rootElement() {
504
- this._rootElement = this._rootElement || this.createTestElement(this.rawRootElement);
505
- return this._rootElement;
506
- }
507
- set rootElement(element) {
508
- this._rootElement = element;
509
- }
510
- _rootElement;
511
- constructor(
512
- /** The native root element of this `HarnessEnvironment`. */
513
- rawRootElement) {
514
- this.rawRootElement = rawRootElement;
515
- }
516
- /** Gets a locator factory rooted at the document root. */
517
- documentRootLocatorFactory() {
518
- return this.createEnvironment(this.getDocumentRoot());
519
- }
520
- /**
521
- * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
522
- * or element under the root element of this `HarnessEnvironment`.
523
- *
524
- * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'`
525
- *
526
- * ```html
527
- * <div id="d1"></div><div id="d2"></div>
528
- * ```
529
- *
530
- * then we expect:
531
- *
532
- * ```ts
533
- * await lf.locatorFor(DivHarness, 'div')() // Gets a `DivHarness` instance for #d1
534
- * await lf.locatorFor('div', DivHarness)() // Gets a `TestElement` instance for #d1
535
- * await lf.locatorFor('span')() // Throws because the `Promise` rejects
536
- * ```
537
- *
538
- * @param queries A list of queries specifying which harnesses and elements to search for:
539
- * - A `string` searches for elements matching the CSS selector specified by the string.
540
- * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
541
- * given class.
542
- * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
543
- * predicate.
544
- * @return An asynchronous locator function that searches for and returns a `Promise` for the
545
- * first element or harness matching the given search criteria. Matches are ordered first by
546
- * order in the DOM, and second by order in the queries list. If no matches are found, the
547
- * `Promise` rejects. The type that the `Promise` resolves to is a union of all result types for
548
- * each query.
549
- */
550
- locatorFor(...queries) {
551
- return () => _assertResultFound(this._getAllHarnessesAndTestElements(queries), _getDescriptionForLocatorForQueries(queries));
552
- }
553
- /**
554
- * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
555
- * or element under the root element of this `HarnessEnvironmnet`.
556
- *
557
- * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'`
558
- *
559
- * ```html
560
- * <div id="d1"></div><div id="d2"></div>
561
- * ```
562
- *
563
- * then we expect:
564
- *
565
- * ```ts
566
- * await lf.locatorForOptional(DivHarness, 'div')() // Gets a `DivHarness` instance for #d1
567
- * await lf.locatorForOptional('div', DivHarness)() // Gets a `TestElement` instance for #d1
568
- * await lf.locatorForOptional('span')() // Gets `null`
569
- * ```
570
- *
571
- * @param queries A list of queries specifying which harnesses and elements to search for:
572
- * - A `string` searches for elements matching the CSS selector specified by the string.
573
- * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
574
- * given class.
575
- * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
576
- * predicate.
577
- * @return An asynchronous locator function that searches for and returns a `Promise` for the
578
- * first element or harness matching the given search criteria. Matches are ordered first by
579
- * order in the DOM, and second by order in the queries list. If no matches are found, the
580
- * `Promise` is resolved with `null`. The type that the `Promise` resolves to is a union of all
581
- * result types for each query or null.
582
- */
583
- locatorForOptional(...queries) {
584
- return async () => (await this._getAllHarnessesAndTestElements(queries))[0] || null;
585
- }
586
- /**
587
- * Creates an asynchronous locator function that can be used to find `ComponentHarness` instances
588
- * or elements under the root element of this `HarnessEnvironment`.
589
- *
590
- * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'` and
591
- * `IdIsD1Harness.hostSelector` is `'#d1'`
592
- *
593
- * ```html
594
- * <div id="d1"></div><div id="d2"></div>
595
- * ```
596
- *
597
- * then we expect:
598
- *
599
- * ```ts
600
- * // Gets [DivHarness for #d1, TestElement for #d1, DivHarness for #d2, TestElement for #d2]
601
- * await lf.locatorForAll(DivHarness, 'div')()
602
- * // Gets [TestElement for #d1, TestElement for #d2]
603
- * await lf.locatorForAll('div', '#d1')()
604
- * // Gets [DivHarness for #d1, IdIsD1Harness for #d1, DivHarness for #d2]
605
- * await lf.locatorForAll(DivHarness, IdIsD1Harness)()
606
- * // Gets []
607
- * await lf.locatorForAll('span')()
608
- * ```
609
- *
610
- * @param queries A list of queries specifying which harnesses and elements to search for:
611
- * - A `string` searches for elements matching the CSS selector specified by the string.
612
- * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
613
- * given class.
614
- * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
615
- * predicate.
616
- * @return An asynchronous locator function that searches for and returns a `Promise` for all
617
- * elements and harnesses matching the given search criteria. Matches are ordered first by
618
- * order in the DOM, and second by order in the queries list. If an element matches more than
619
- * one `ComponentHarness` class, the locator gets an instance of each for the same element. If
620
- * an element matches multiple `string` selectors, only one `TestElement` instance is returned
621
- * for that element. The type that the `Promise` resolves to is an array where each element is
622
- * the union of all result types for each query.
623
- */
624
- locatorForAll(...queries) {
625
- return () => this._getAllHarnessesAndTestElements(queries);
626
- }
627
- /** @return A `HarnessLoader` rooted at the root element of this `HarnessEnvironment`. */
628
- async rootHarnessLoader() {
629
- return this;
630
- }
631
- /**
632
- * Gets a `HarnessLoader` instance for an element under the root of this `HarnessEnvironment`.
633
- * @param selector The selector for the root element.
634
- * @return A `HarnessLoader` rooted at the first element matching the given selector.
635
- * @throws If no matching element is found for the given selector.
636
- */
637
- async harnessLoaderFor(selector) {
638
- return this.createEnvironment(await _assertResultFound(this.getAllRawElements(selector), [
639
- _getDescriptionForHarnessLoaderQuery(selector),
640
- ]));
641
- }
642
- /**
643
- * Gets a `HarnessLoader` instance for an element under the root of this `HarnessEnvironment`.
644
- * @param selector The selector for the root element.
645
- * @return A `HarnessLoader` rooted at the first element matching the given selector, or null if
646
- * no matching element is found.
647
- */
648
- async harnessLoaderForOptional(selector) {
649
- const elements = await this.getAllRawElements(selector);
650
- return elements[0] ? this.createEnvironment(elements[0]) : null;
651
- }
652
- /**
653
- * Gets a list of `HarnessLoader` instances, one for each matching element.
654
- * @param selector The selector for the root element.
655
- * @return A list of `HarnessLoader`, one rooted at each element matching the given selector.
656
- */
657
- async harnessLoaderForAll(selector) {
658
- const elements = await this.getAllRawElements(selector);
659
- return elements.map(element => this.createEnvironment(element));
660
- }
661
- /**
662
- * Searches for an instance of the component corresponding to the given harness type under the
663
- * `HarnessEnvironment`'s root element, and returns a `ComponentHarness` for that instance. If
664
- * multiple matching components are found, a harness for the first one is returned. If no matching
665
- * component is found, an error is thrown.
666
- * @param query A query for a harness to create
667
- * @return An instance of the given harness type
668
- * @throws If a matching component instance can't be found.
669
- */
670
- getHarness(query) {
671
- return this.locatorFor(query)();
672
- }
673
- /**
674
- * Searches for an instance of the component corresponding to the given harness type under the
675
- * `HarnessEnvironment`'s root element, and returns a `ComponentHarness` for that instance. If
676
- * multiple matching components are found, a harness for the first one is returned. If no matching
677
- * component is found, null is returned.
678
- * @param query A query for a harness to create
679
- * @return An instance of the given harness type (or null if not found).
680
- */
681
- getHarnessOrNull(query) {
682
- return this.locatorForOptional(query)();
683
- }
684
- /**
685
- * Searches for an instance of the component corresponding to the given harness type and index
686
- * under the `HarnessEnvironment`'s root element, and returns a `ComponentHarness` for that
687
- * instance. The index specifies the offset of the component to find. If no matching
688
- * component is found at that index, an error is thrown.
689
- * @param query A query for a harness to create
690
- * @param index The zero-indexed offset of the component to find
691
- * @return An instance of the given harness type
692
- * @throws If a matching component instance can't be found.
693
- */
694
- async getHarnessAtIndex(query, offset) {
695
- if (offset < 0) {
696
- throw Error('Index must not be negative');
697
- }
698
- const harnesses = await this.locatorForAll(query)();
699
- if (offset >= harnesses.length) {
700
- throw Error(`No harness was located at index ${offset}`);
701
- }
702
- return harnesses[offset];
703
- }
704
- /**
705
- * Searches for all instances of the component corresponding to the given harness type under the
706
- * `HarnessEnvironment`'s root element, and returns a list `ComponentHarness` for each instance.
707
- * @param query A query for a harness to create
708
- * @return A list instances of the given harness type.
709
- */
710
- getAllHarnesses(query) {
711
- return this.locatorForAll(query)();
712
- }
713
- /**
714
- * Searches for all instance of the component corresponding to the given harness type under the
715
- * `HarnessEnvironment`'s root element, and returns the number that were found.
716
- * @param query A query for a harness to create
717
- * @return The number of instances that were found.
718
- */
719
- async countHarnesses(query) {
720
- return (await this.locatorForAll(query)()).length;
721
- }
722
- /**
723
- * Searches for an instance of the component corresponding to the given harness type under the
724
- * `HarnessEnvironment`'s root element, and returns a boolean indicating if any were found.
725
- * @param query A query for a harness to create
726
- * @return A boolean indicating if an instance was found.
727
- */
728
- async hasHarness(query) {
729
- return (await this.locatorForOptional(query)()) !== null;
730
- }
731
- /**
732
- * Searches for an element with the given selector under the evironment's root element,
733
- * and returns a `HarnessLoader` rooted at the matching element. If multiple elements match the
734
- * selector, the first is used. If no elements match, an error is thrown.
735
- * @param selector The selector for the root element of the new `HarnessLoader`
736
- * @return A `HarnessLoader` rooted at the element matching the given selector.
737
- * @throws If a matching element can't be found.
738
- */
739
- async getChildLoader(selector) {
740
- return this.createEnvironment(await _assertResultFound(this.getAllRawElements(selector), [
741
- _getDescriptionForHarnessLoaderQuery(selector),
742
- ]));
743
- }
744
- /**
745
- * Searches for all elements with the given selector under the environment's root element,
746
- * and returns an array of `HarnessLoader`s, one for each matching element, rooted at that
747
- * element.
748
- * @param selector The selector for the root element of the new `HarnessLoader`
749
- * @return A list of `HarnessLoader`s, one for each matching element, rooted at that element.
750
- */
751
- async getAllChildLoaders(selector) {
752
- return (await this.getAllRawElements(selector)).map(e => this.createEnvironment(e));
753
- }
754
- /** Creates a `ComponentHarness` for the given harness type with the given raw host element. */
755
- createComponentHarness(harnessType, element) {
756
- return new harnessType(this.createEnvironment(element));
757
- }
758
- /**
759
- * Matches the given raw elements with the given list of element and harness queries to produce a
760
- * list of matched harnesses and test elements.
761
- */
762
- async _getAllHarnessesAndTestElements(queries) {
763
- if (!queries.length) {
764
- throw Error('CDK Component harness query must contain at least one element.');
765
- }
766
- const { allQueries, harnessQueries, elementQueries, harnessTypes } = _parseQueries(queries);
767
- // Combine all of the queries into one large comma-delimited selector and use it to get all raw
768
- // elements matching any of the individual queries.
769
- const rawElements = await this.getAllRawElements([...elementQueries, ...harnessQueries.map(predicate => predicate.getSelector())].join(','));
770
- // If every query is searching for the same harness subclass, we know every result corresponds
771
- // to an instance of that subclass. Likewise, if every query is for a `TestElement`, we know
772
- // every result corresponds to a `TestElement`. Otherwise we need to verify which result was
773
- // found by which selector so it can be matched to the appropriate instance.
774
- const skipSelectorCheck = (elementQueries.length === 0 && harnessTypes.size === 1) || harnessQueries.length === 0;
775
- const perElementMatches = await parallel(() => rawElements.map(async (rawElement) => {
776
- const testElement = this.createTestElement(rawElement);
777
- const allResultsForElement = await parallel(
778
- // For each query, get `null` if it doesn't match, or a `TestElement` or
779
- // `ComponentHarness` as appropriate if it does match. This gives us everything that
780
- // matches the current raw element, but it may contain duplicate entries (e.g.
781
- // multiple `TestElement` or multiple `ComponentHarness` of the same type).
782
- () => allQueries.map(query => this._getQueryResultForElement(query, rawElement, testElement, skipSelectorCheck)));
783
- return _removeDuplicateQueryResults(allResultsForElement);
784
- }));
785
- return [].concat(...perElementMatches);
786
- }
787
- /**
788
- * Check whether the given query matches the given element, if it does return the matched
789
- * `TestElement` or `ComponentHarness`, if it does not, return null. In cases where the caller
790
- * knows for sure that the query matches the element's selector, `skipSelectorCheck` can be used
791
- * to skip verification and optimize performance.
792
- */
793
- async _getQueryResultForElement(query, rawElement, testElement, skipSelectorCheck = false) {
794
- if (typeof query === 'string') {
795
- return skipSelectorCheck || (await testElement.matchesSelector(query)) ? testElement : null;
796
- }
797
- if (skipSelectorCheck || (await testElement.matchesSelector(query.getSelector()))) {
798
- const harness = this.createComponentHarness(query.harnessType, rawElement);
799
- return (await query.evaluate(harness)) ? harness : null;
800
- }
801
- return null;
802
- }
208
+ rawRootElement;
209
+ get rootElement() {
210
+ this._rootElement = this._rootElement || this.createTestElement(this.rawRootElement);
211
+ return this._rootElement;
212
+ }
213
+ set rootElement(element) {
214
+ this._rootElement = element;
215
+ }
216
+ _rootElement;
217
+ constructor(rawRootElement) {
218
+ this.rawRootElement = rawRootElement;
219
+ }
220
+ documentRootLocatorFactory() {
221
+ return this.createEnvironment(this.getDocumentRoot());
222
+ }
223
+ locatorFor(...queries) {
224
+ return () => _assertResultFound(this._getAllHarnessesAndTestElements(queries), _getDescriptionForLocatorForQueries(queries));
225
+ }
226
+ locatorForOptional(...queries) {
227
+ return async () => (await this._getAllHarnessesAndTestElements(queries))[0] || null;
228
+ }
229
+ locatorForAll(...queries) {
230
+ return () => this._getAllHarnessesAndTestElements(queries);
231
+ }
232
+ async rootHarnessLoader() {
233
+ return this;
234
+ }
235
+ async harnessLoaderFor(selector) {
236
+ return this.createEnvironment(await _assertResultFound(this.getAllRawElements(selector), [_getDescriptionForHarnessLoaderQuery(selector)]));
237
+ }
238
+ async harnessLoaderForOptional(selector) {
239
+ const elements = await this.getAllRawElements(selector);
240
+ return elements[0] ? this.createEnvironment(elements[0]) : null;
241
+ }
242
+ async harnessLoaderForAll(selector) {
243
+ const elements = await this.getAllRawElements(selector);
244
+ return elements.map(element => this.createEnvironment(element));
245
+ }
246
+ getHarness(query) {
247
+ return this.locatorFor(query)();
248
+ }
249
+ getHarnessOrNull(query) {
250
+ return this.locatorForOptional(query)();
251
+ }
252
+ async getHarnessAtIndex(query, offset) {
253
+ if (offset < 0) {
254
+ throw Error('Index must not be negative');
255
+ }
256
+ const harnesses = await this.locatorForAll(query)();
257
+ if (offset >= harnesses.length) {
258
+ throw Error(`No harness was located at index ${offset}`);
259
+ }
260
+ return harnesses[offset];
261
+ }
262
+ getAllHarnesses(query) {
263
+ return this.locatorForAll(query)();
264
+ }
265
+ async countHarnesses(query) {
266
+ return (await this.locatorForAll(query)()).length;
267
+ }
268
+ async hasHarness(query) {
269
+ return (await this.locatorForOptional(query)()) !== null;
270
+ }
271
+ async getChildLoader(selector) {
272
+ return this.createEnvironment(await _assertResultFound(this.getAllRawElements(selector), [_getDescriptionForHarnessLoaderQuery(selector)]));
273
+ }
274
+ async getAllChildLoaders(selector) {
275
+ return (await this.getAllRawElements(selector)).map(e => this.createEnvironment(e));
276
+ }
277
+ createComponentHarness(harnessType, element) {
278
+ return new harnessType(this.createEnvironment(element));
279
+ }
280
+ async _getAllHarnessesAndTestElements(queries) {
281
+ if (!queries.length) {
282
+ throw Error('CDK Component harness query must contain at least one element.');
283
+ }
284
+ const {
285
+ allQueries,
286
+ harnessQueries,
287
+ elementQueries,
288
+ harnessTypes
289
+ } = _parseQueries(queries);
290
+ const rawElements = await this.getAllRawElements([...elementQueries, ...harnessQueries.map(predicate => predicate.getSelector())].join(','));
291
+ const skipSelectorCheck = elementQueries.length === 0 && harnessTypes.size === 1 || harnessQueries.length === 0;
292
+ const perElementMatches = await parallel(() => rawElements.map(async rawElement => {
293
+ const testElement = this.createTestElement(rawElement);
294
+ const allResultsForElement = await parallel(() => allQueries.map(query => this._getQueryResultForElement(query, rawElement, testElement, skipSelectorCheck)));
295
+ return _removeDuplicateQueryResults(allResultsForElement);
296
+ }));
297
+ return [].concat(...perElementMatches);
298
+ }
299
+ async _getQueryResultForElement(query, rawElement, testElement, skipSelectorCheck = false) {
300
+ if (typeof query === 'string') {
301
+ return skipSelectorCheck || (await testElement.matchesSelector(query)) ? testElement : null;
302
+ }
303
+ if (skipSelectorCheck || (await testElement.matchesSelector(query.getSelector()))) {
304
+ const harness = this.createComponentHarness(query.harnessType, rawElement);
305
+ return (await query.evaluate(harness)) ? harness : null;
306
+ }
307
+ return null;
308
+ }
803
309
  }
804
- /**
805
- * Parses a list of queries in the format accepted by the `locatorFor*` methods into an easier to
806
- * work with format.
807
- */
808
310
  function _parseQueries(queries) {
809
- const allQueries = [];
810
- const harnessQueries = [];
811
- const elementQueries = [];
812
- const harnessTypes = new Set();
813
- for (const query of queries) {
814
- if (typeof query === 'string') {
815
- allQueries.push(query);
816
- elementQueries.push(query);
817
- }
818
- else {
819
- const predicate = query instanceof HarnessPredicate ? query : new HarnessPredicate(query, {});
820
- allQueries.push(predicate);
821
- harnessQueries.push(predicate);
822
- harnessTypes.add(predicate.harnessType);
823
- }
824
- }
825
- return { allQueries, harnessQueries, elementQueries, harnessTypes };
311
+ const allQueries = [];
312
+ const harnessQueries = [];
313
+ const elementQueries = [];
314
+ const harnessTypes = new Set();
315
+ for (const query of queries) {
316
+ if (typeof query === 'string') {
317
+ allQueries.push(query);
318
+ elementQueries.push(query);
319
+ } else {
320
+ const predicate = query instanceof HarnessPredicate ? query : new HarnessPredicate(query, {});
321
+ allQueries.push(predicate);
322
+ harnessQueries.push(predicate);
323
+ harnessTypes.add(predicate.harnessType);
324
+ }
325
+ }
326
+ return {
327
+ allQueries,
328
+ harnessQueries,
329
+ elementQueries,
330
+ harnessTypes
331
+ };
826
332
  }
827
- /**
828
- * Removes duplicate query results for a particular element. (e.g. multiple `TestElement`
829
- * instances or multiple instances of the same `ComponentHarness` class.
830
- */
831
333
  async function _removeDuplicateQueryResults(results) {
832
- let testElementMatched = false;
833
- let matchedHarnessTypes = new Set();
834
- const dedupedMatches = [];
835
- for (const result of results) {
836
- if (!result) {
837
- continue;
838
- }
839
- if (result instanceof ComponentHarness) {
840
- if (!matchedHarnessTypes.has(result.constructor)) {
841
- matchedHarnessTypes.add(result.constructor);
842
- dedupedMatches.push(result);
843
- }
844
- }
845
- else if (!testElementMatched) {
846
- testElementMatched = true;
847
- dedupedMatches.push(result);
848
- }
849
- }
850
- return dedupedMatches;
334
+ let testElementMatched = false;
335
+ let matchedHarnessTypes = new Set();
336
+ const dedupedMatches = [];
337
+ for (const result of results) {
338
+ if (!result) {
339
+ continue;
340
+ }
341
+ if (result instanceof ComponentHarness) {
342
+ if (!matchedHarnessTypes.has(result.constructor)) {
343
+ matchedHarnessTypes.add(result.constructor);
344
+ dedupedMatches.push(result);
345
+ }
346
+ } else if (!testElementMatched) {
347
+ testElementMatched = true;
348
+ dedupedMatches.push(result);
349
+ }
350
+ }
351
+ return dedupedMatches;
851
352
  }
852
- /** Verifies that there is at least one result in an array. */
853
353
  async function _assertResultFound(results, queryDescriptions) {
854
- const result = (await results)[0];
855
- if (result == undefined) {
856
- throw Error(`Failed to find element matching one of the following queries:\n` +
857
- queryDescriptions.map(desc => `(${desc})`).join(',\n'));
858
- }
859
- return result;
354
+ const result = (await results)[0];
355
+ if (result == undefined) {
356
+ throw Error(`Failed to find element matching one of the following queries:\n` + queryDescriptions.map(desc => `(${desc})`).join(',\n'));
357
+ }
358
+ return result;
860
359
  }
861
- /** Gets a list of description strings from a list of queries. */
862
360
  function _getDescriptionForLocatorForQueries(queries) {
863
- return queries.map(query => typeof query === 'string'
864
- ? _getDescriptionForTestElementQuery(query)
865
- : _getDescriptionForComponentHarnessQuery(query));
361
+ return queries.map(query => typeof query === 'string' ? _getDescriptionForTestElementQuery(query) : _getDescriptionForComponentHarnessQuery(query));
866
362
  }
867
- /** Gets a description string for a `ComponentHarness` query. */
868
363
  function _getDescriptionForComponentHarnessQuery(query) {
869
- const harnessPredicate = query instanceof HarnessPredicate ? query : new HarnessPredicate(query, {});
870
- const { name, hostSelector } = harnessPredicate.harnessType;
871
- const description = `${name} with host element matching selector: "${hostSelector}"`;
872
- const constraints = harnessPredicate.getDescription();
873
- return (description +
874
- (constraints ? ` satisfying the constraints: ${harnessPredicate.getDescription()}` : ''));
364
+ const harnessPredicate = query instanceof HarnessPredicate ? query : new HarnessPredicate(query, {});
365
+ const {
366
+ name,
367
+ hostSelector
368
+ } = harnessPredicate.harnessType;
369
+ const description = `${name} with host element matching selector: "${hostSelector}"`;
370
+ const constraints = harnessPredicate.getDescription();
371
+ return description + (constraints ? ` satisfying the constraints: ${harnessPredicate.getDescription()}` : '');
875
372
  }
876
- /** Gets a description string for a `TestElement` query. */
877
373
  function _getDescriptionForTestElementQuery(selector) {
878
- return `TestElement for element matching selector: "${selector}"`;
374
+ return `TestElement for element matching selector: "${selector}"`;
879
375
  }
880
- /** Gets a description string for a `HarnessLoader` query. */
881
376
  function _getDescriptionForHarnessLoaderQuery(selector) {
882
- return `HarnessLoader for element matching selector: "${selector}"`;
377
+ return `HarnessLoader for element matching selector: "${selector}"`;
883
378
  }
884
379
 
885
- /** An enum of non-text keys that can be used with the `sendKeys` method. */
886
- // NOTE: This is a separate enum from `@angular/cdk/keycodes` because we don't necessarily want to
887
- // support every possible keyCode. We also can't rely on Protractor's `Key` because we don't want a
888
- // dependency on any particular testing framework here. Instead we'll just maintain this supported
889
- // list of keys and let individual concrete `HarnessEnvironment` classes map them to whatever key
890
- // representation is used in its respective testing framework.
891
- // tslint:disable-next-line:prefer-const-enum Seems like this causes some issues with System.js
892
380
  var TestKey;
893
381
  (function (TestKey) {
894
- TestKey[TestKey["BACKSPACE"] = 0] = "BACKSPACE";
895
- TestKey[TestKey["TAB"] = 1] = "TAB";
896
- TestKey[TestKey["ENTER"] = 2] = "ENTER";
897
- TestKey[TestKey["SHIFT"] = 3] = "SHIFT";
898
- TestKey[TestKey["CONTROL"] = 4] = "CONTROL";
899
- TestKey[TestKey["ALT"] = 5] = "ALT";
900
- TestKey[TestKey["ESCAPE"] = 6] = "ESCAPE";
901
- TestKey[TestKey["PAGE_UP"] = 7] = "PAGE_UP";
902
- TestKey[TestKey["PAGE_DOWN"] = 8] = "PAGE_DOWN";
903
- TestKey[TestKey["END"] = 9] = "END";
904
- TestKey[TestKey["HOME"] = 10] = "HOME";
905
- TestKey[TestKey["LEFT_ARROW"] = 11] = "LEFT_ARROW";
906
- TestKey[TestKey["UP_ARROW"] = 12] = "UP_ARROW";
907
- TestKey[TestKey["RIGHT_ARROW"] = 13] = "RIGHT_ARROW";
908
- TestKey[TestKey["DOWN_ARROW"] = 14] = "DOWN_ARROW";
909
- TestKey[TestKey["INSERT"] = 15] = "INSERT";
910
- TestKey[TestKey["DELETE"] = 16] = "DELETE";
911
- TestKey[TestKey["F1"] = 17] = "F1";
912
- TestKey[TestKey["F2"] = 18] = "F2";
913
- TestKey[TestKey["F3"] = 19] = "F3";
914
- TestKey[TestKey["F4"] = 20] = "F4";
915
- TestKey[TestKey["F5"] = 21] = "F5";
916
- TestKey[TestKey["F6"] = 22] = "F6";
917
- TestKey[TestKey["F7"] = 23] = "F7";
918
- TestKey[TestKey["F8"] = 24] = "F8";
919
- TestKey[TestKey["F9"] = 25] = "F9";
920
- TestKey[TestKey["F10"] = 26] = "F10";
921
- TestKey[TestKey["F11"] = 27] = "F11";
922
- TestKey[TestKey["F12"] = 28] = "F12";
923
- TestKey[TestKey["META"] = 29] = "META";
924
- TestKey[TestKey["COMMA"] = 30] = "COMMA";
382
+ TestKey[TestKey["BACKSPACE"] = 0] = "BACKSPACE";
383
+ TestKey[TestKey["TAB"] = 1] = "TAB";
384
+ TestKey[TestKey["ENTER"] = 2] = "ENTER";
385
+ TestKey[TestKey["SHIFT"] = 3] = "SHIFT";
386
+ TestKey[TestKey["CONTROL"] = 4] = "CONTROL";
387
+ TestKey[TestKey["ALT"] = 5] = "ALT";
388
+ TestKey[TestKey["ESCAPE"] = 6] = "ESCAPE";
389
+ TestKey[TestKey["PAGE_UP"] = 7] = "PAGE_UP";
390
+ TestKey[TestKey["PAGE_DOWN"] = 8] = "PAGE_DOWN";
391
+ TestKey[TestKey["END"] = 9] = "END";
392
+ TestKey[TestKey["HOME"] = 10] = "HOME";
393
+ TestKey[TestKey["LEFT_ARROW"] = 11] = "LEFT_ARROW";
394
+ TestKey[TestKey["UP_ARROW"] = 12] = "UP_ARROW";
395
+ TestKey[TestKey["RIGHT_ARROW"] = 13] = "RIGHT_ARROW";
396
+ TestKey[TestKey["DOWN_ARROW"] = 14] = "DOWN_ARROW";
397
+ TestKey[TestKey["INSERT"] = 15] = "INSERT";
398
+ TestKey[TestKey["DELETE"] = 16] = "DELETE";
399
+ TestKey[TestKey["F1"] = 17] = "F1";
400
+ TestKey[TestKey["F2"] = 18] = "F2";
401
+ TestKey[TestKey["F3"] = 19] = "F3";
402
+ TestKey[TestKey["F4"] = 20] = "F4";
403
+ TestKey[TestKey["F5"] = 21] = "F5";
404
+ TestKey[TestKey["F6"] = 22] = "F6";
405
+ TestKey[TestKey["F7"] = 23] = "F7";
406
+ TestKey[TestKey["F8"] = 24] = "F8";
407
+ TestKey[TestKey["F9"] = 25] = "F9";
408
+ TestKey[TestKey["F10"] = 26] = "F10";
409
+ TestKey[TestKey["F11"] = 27] = "F11";
410
+ TestKey[TestKey["F12"] = 28] = "F12";
411
+ TestKey[TestKey["META"] = 29] = "META";
412
+ TestKey[TestKey["COMMA"] = 30] = "COMMA";
925
413
  })(TestKey || (TestKey = {}));
926
414
 
927
- /**
928
- * Returns an error which reports that no keys have been specified.
929
- * @docs-private
930
- */
931
415
  function getNoKeysSpecifiedError() {
932
- return Error('No keys have been specified.');
416
+ return Error('No keys have been specified.');
933
417
  }
934
418
 
935
- /**
936
- * Gets text of element excluding certain selectors within the element.
937
- * @param element Element to get text from,
938
- * @param excludeSelector Selector identifying which elements to exclude,
939
- */
940
419
  function _getTextWithExcludedElements(element, excludeSelector) {
941
- const clone = element.cloneNode(true);
942
- const exclusions = clone.querySelectorAll(excludeSelector);
943
- for (let i = 0; i < exclusions.length; i++) {
944
- exclusions[i].remove();
945
- }
946
- return (clone.textContent || '').trim();
420
+ const clone = element.cloneNode(true);
421
+ const exclusions = clone.querySelectorAll(excludeSelector);
422
+ for (let i = 0; i < exclusions.length; i++) {
423
+ exclusions[i].remove();
424
+ }
425
+ return (clone.textContent || '').trim();
947
426
  }
948
427
 
949
428
  export { ComponentHarness, ContentContainerComponentHarness, HarnessEnvironment, HarnessPredicate, TestKey, _getTextWithExcludedElements, getNoKeysSpecifiedError, handleAutoChangeDetectionStatus, manualChangeDetection, parallel, stopHandlingAutoChangeDetectionStatus };