/
a11y.js
1715 lines (1689 loc) · 61.1 KB
/
a11y.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
import { A, DOWN_ARROW, NINE, TAB, UP_ARROW, Z, ZERO } from '@angular/cdk/keycodes';
import { debounceTime } from 'rxjs/operators/debounceTime';
import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';
import { tap } from 'rxjs/operators/tap';
import { Directive, ElementRef, EventEmitter, Inject, Injectable, InjectionToken, Input, NgModule, NgZone, Optional, Output, Renderer2, SkipSelf } from '@angular/core';
import { Platform, PlatformModule, supportsPassiveEventListeners } from '@angular/cdk/platform';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { first } from 'rxjs/operators/first';
import { of } from 'rxjs/observable/of';
import { CommonModule } from '@angular/common';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* This interface is for items that can be passed to a ListKeyManager.
* @record
*/
/**
* This class manages keyboard events for selectable lists. If you pass it a query list
* of items, it will set the active item correctly when arrow events occur.
*/
class ListKeyManager {
/**
* @param {?} _items
*/
constructor(_items) {
this._items = _items;
this._activeItemIndex = -1;
this._wrap = false;
this._letterKeyStream = new Subject();
this._typeaheadSubscription = Subscription.EMPTY;
this._pressedLetters = [];
/**
* Stream that emits any time the TAB key is pressed, so components can react
* when focus is shifted off of the list.
*/
this.tabOut = new Subject();
/**
* Stream that emits whenever the active item of the list manager changes.
*/
this.change = new Subject();
}
/**
* Turns on wrapping mode, which ensures that the active item will wrap to
* the other end of list when there are no more items in the given direction.
* @return {?}
*/
withWrap() {
this._wrap = true;
return this;
}
/**
* Turns on typeahead mode which allows users to set the active item by typing.
* @param {?=} debounceInterval Time to wait after the last keystroke before setting the active item.
* @return {?}
*/
withTypeAhead(debounceInterval = 200) {
if (this._items.length && this._items.some(item => typeof item.getLabel !== 'function')) {
throw Error('ListKeyManager items in typeahead mode must implement the `getLabel` method.');
}
this._typeaheadSubscription.unsubscribe();
// Debounce the presses of non-navigational keys, collect the ones that correspond to letters
// and convert those letters back into a string. Afterwards find the first item that starts
// with that string and select it.
this._typeaheadSubscription = this._letterKeyStream.pipe(tap(keyCode => this._pressedLetters.push(keyCode)), debounceTime(debounceInterval), filter(() => this._pressedLetters.length > 0), map(() => this._pressedLetters.join(''))).subscribe(inputString => {
const /** @type {?} */ items = this._items.toArray();
// Start at 1 because we want to start searching at the item immediately
// following the current active item.
for (let /** @type {?} */ i = 1; i < items.length + 1; i++) {
const /** @type {?} */ index = (this._activeItemIndex + i) % items.length;
const /** @type {?} */ item = items[index];
if (!item.disabled && /** @type {?} */ ((item.getLabel))().toUpperCase().trim().indexOf(inputString) === 0) {
this.setActiveItem(index);
break;
}
}
this._pressedLetters = [];
});
return this;
}
/**
* Sets the active item to the item at the index specified.
* @param {?} index The index of the item to be set as active.
* @return {?}
*/
setActiveItem(index) {
const /** @type {?} */ previousIndex = this._activeItemIndex;
this._activeItemIndex = index;
this._activeItem = this._items.toArray()[index];
if (this._activeItemIndex !== previousIndex) {
this.change.next(index);
}
}
/**
* Sets the active item depending on the key event passed in.
* @param {?} event Keyboard event to be used for determining which element should be active.
* @return {?}
*/
onKeydown(event) {
switch (event.keyCode) {
case DOWN_ARROW:
this.setNextItemActive();
break;
case UP_ARROW:
this.setPreviousItemActive();
break;
case TAB:
this.tabOut.next();
return;
default:
const /** @type {?} */ keyCode = event.keyCode;
// Attempt to use the `event.key` which also maps it to the user's keyboard language,
// otherwise fall back to resolving alphanumeric characters via the keyCode.
if (event.key && event.key.length === 1) {
this._letterKeyStream.next(event.key.toLocaleUpperCase());
}
else if ((keyCode >= A && keyCode <= Z) || (keyCode >= ZERO && keyCode <= NINE)) {
this._letterKeyStream.next(String.fromCharCode(keyCode));
}
// Note that we return here, in order to avoid preventing
// the default action of non-navigational keys.
return;
}
this._pressedLetters = [];
event.preventDefault();
}
/**
* Index of the currently active item.
* @return {?}
*/
get activeItemIndex() {
return this._activeItemIndex;
}
/**
* The active item.
* @return {?}
*/
get activeItem() {
return this._activeItem;
}
/**
* Sets the active item to the first enabled item in the list.
* @return {?}
*/
setFirstItemActive() {
this._setActiveItemByIndex(0, 1);
}
/**
* Sets the active item to the last enabled item in the list.
* @return {?}
*/
setLastItemActive() {
this._setActiveItemByIndex(this._items.length - 1, -1);
}
/**
* Sets the active item to the next enabled item in the list.
* @return {?}
*/
setNextItemActive() {
this._activeItemIndex < 0 ? this.setFirstItemActive() : this._setActiveItemByDelta(1);
}
/**
* Sets the active item to a previous enabled item in the list.
* @return {?}
*/
setPreviousItemActive() {
this._activeItemIndex < 0 && this._wrap ? this.setLastItemActive()
: this._setActiveItemByDelta(-1);
}
/**
* Allows setting of the activeItemIndex without any other effects.
* @param {?} index The new activeItemIndex.
* @return {?}
*/
updateActiveItemIndex(index) {
this._activeItemIndex = index;
}
/**
* This method sets the active item, given a list of items and the delta between the
* currently active item and the new active item. It will calculate differently
* depending on whether wrap mode is turned on.
* @param {?} delta
* @param {?=} items
* @return {?}
*/
_setActiveItemByDelta(delta, items = this._items.toArray()) {
this._wrap ? this._setActiveInWrapMode(delta, items)
: this._setActiveInDefaultMode(delta, items);
}
/**
* Sets the active item properly given "wrap" mode. In other words, it will continue to move
* down the list until it finds an item that is not disabled, and it will wrap if it
* encounters either end of the list.
* @param {?} delta
* @param {?} items
* @return {?}
*/
_setActiveInWrapMode(delta, items) {
// when active item would leave menu, wrap to beginning or end
this._activeItemIndex =
(this._activeItemIndex + delta + items.length) % items.length;
// skip all disabled menu items recursively until an enabled one is reached
if (items[this._activeItemIndex].disabled) {
this._setActiveInWrapMode(delta, items);
}
else {
this.setActiveItem(this._activeItemIndex);
}
}
/**
* Sets the active item properly given the default mode. In other words, it will
* continue to move down the list until it finds an item that is not disabled. If
* it encounters either end of the list, it will stop and not wrap.
* @param {?} delta
* @param {?} items
* @return {?}
*/
_setActiveInDefaultMode(delta, items) {
this._setActiveItemByIndex(this._activeItemIndex + delta, delta, items);
}
/**
* Sets the active item to the first enabled item starting at the index specified. If the
* item is disabled, it will move in the fallbackDelta direction until it either
* finds an enabled item or encounters the end of the list.
* @param {?} index
* @param {?} fallbackDelta
* @param {?=} items
* @return {?}
*/
_setActiveItemByIndex(index, fallbackDelta, items = this._items.toArray()) {
if (!items[index]) {
return;
}
while (items[index].disabled) {
index += fallbackDelta;
if (!items[index]) {
return;
}
}
this.setActiveItem(index);
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* This is the interface for highlightable items (used by the ActiveDescendantKeyManager).
* Each item must know how to style itself as active or inactive and whether or not it is
* currently disabled.
* @record
*/
class ActiveDescendantKeyManager extends ListKeyManager {
/**
* This method sets the active item to the item at the specified index.
* It also adds active styles to the newly active item and removes active
* styles from the previously active item.
* @param {?} index
* @return {?}
*/
setActiveItem(index) {
if (this.activeItem) {
this.activeItem.setInactiveStyles();
}
super.setActiveItem(index);
if (this.activeItem) {
this.activeItem.setActiveStyles();
}
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* IDs are deliminated by an empty space, as per the spec.
*/
const ID_DELIMINATOR = ' ';
/**
* Adds the given ID to the specified ARIA attribute on an element.
* Used for attributes such as aria-labelledby, aria-owns, etc.
* @param {?} el
* @param {?} attr
* @param {?} id
* @return {?}
*/
function addAriaReferencedId(el, attr, id) {
const /** @type {?} */ ids = getAriaReferenceIds(el, attr);
if (ids.some(existingId => existingId.trim() == id.trim())) {
return;
}
ids.push(id.trim());
el.setAttribute(attr, ids.join(ID_DELIMINATOR));
}
/**
* Removes the given ID from the specified ARIA attribute on an element.
* Used for attributes such as aria-labelledby, aria-owns, etc.
* @param {?} el
* @param {?} attr
* @param {?} id
* @return {?}
*/
function removeAriaReferencedId(el, attr, id) {
const /** @type {?} */ ids = getAriaReferenceIds(el, attr);
const /** @type {?} */ filteredIds = ids.filter(val => val != id.trim());
el.setAttribute(attr, filteredIds.join(ID_DELIMINATOR));
}
/**
* Gets the list of IDs referenced by the given ARIA attribute on an element.
* Used for attributes such as aria-labelledby, aria-owns, etc.
* @param {?} el
* @param {?} attr
* @return {?}
*/
function getAriaReferenceIds(el, attr) {
// Get string array of all individual ids (whitespace deliminated) in the attribute value
return (el.getAttribute(attr) || '').match(/\S+/g) || [];
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Interface used to register message elements and keep a count of how many registrations have
* the same message and the reference to the message element used for the aria-describedby.
* @record
*/
/**
* ID used for the body container where all messages are appended.
*/
const MESSAGES_CONTAINER_ID = 'cdk-describedby-message-container';
/**
* ID prefix used for each created message element.
*/
const CDK_DESCRIBEDBY_ID_PREFIX = 'cdk-describedby-message';
/**
* Attribute given to each host element that is described by a message element.
*/
const CDK_DESCRIBEDBY_HOST_ATTRIBUTE = 'cdk-describedby-host';
/**
* Global incremental identifier for each registered message element.
*/
let nextId = 0;
/**
* Global map of all registered message elements that have been placed into the document.
*/
const messageRegistry = new Map();
/**
* Container for all registered messages.
*/
let messagesContainer = null;
/**
* Utility that creates visually hidden elements with a message content. Useful for elements that
* want to use aria-describedby to further describe themselves without adding additional visual
* content.
* \@docs-private
*/
class AriaDescriber {
/**
* @param {?} _platform
*/
constructor(_platform) {
this._platform = _platform;
}
/**
* Adds to the host element an aria-describedby reference to a hidden element that contains
* the message. If the same message has already been registered, then it will reuse the created
* message element.
* @param {?} hostElement
* @param {?} message
* @return {?}
*/
describe(hostElement, message) {
if (!this._platform.isBrowser || !message.trim()) {
return;
}
if (!messageRegistry.has(message)) {
createMessageElement(message);
}
if (!isElementDescribedByMessage(hostElement, message)) {
addMessageReference(hostElement, message);
}
}
/**
* Removes the host element's aria-describedby reference to the message element.
* @param {?} hostElement
* @param {?} message
* @return {?}
*/
removeDescription(hostElement, message) {
if (!this._platform.isBrowser || !message.trim()) {
return;
}
if (isElementDescribedByMessage(hostElement, message)) {
removeMessageReference(hostElement, message);
}
const /** @type {?} */ registeredMessage = messageRegistry.get(message);
if (registeredMessage && registeredMessage.referenceCount === 0) {
deleteMessageElement(message);
}
if (messagesContainer && messagesContainer.childNodes.length === 0) {
deleteMessagesContainer();
}
}
/**
* Unregisters all created message elements and removes the message container.
* @return {?}
*/
ngOnDestroy() {
if (!this._platform.isBrowser) {
return;
}
const /** @type {?} */ describedElements = document.querySelectorAll(`[${CDK_DESCRIBEDBY_HOST_ATTRIBUTE}]`);
for (let /** @type {?} */ i = 0; i < describedElements.length; i++) {
removeCdkDescribedByReferenceIds(describedElements[i]);
describedElements[i].removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);
}
if (messagesContainer) {
deleteMessagesContainer();
}
messageRegistry.clear();
}
}
AriaDescriber.decorators = [
{ type: Injectable },
];
/** @nocollapse */
AriaDescriber.ctorParameters = () => [
{ type: Platform, },
];
/**
* Creates a new element in the visually hidden message container element with the message
* as its content and adds it to the message registry.
* @param {?} message
* @return {?}
*/
function createMessageElement(message) {
const /** @type {?} */ messageElement = document.createElement('div');
messageElement.setAttribute('id', `${CDK_DESCRIBEDBY_ID_PREFIX}-${nextId++}`);
messageElement.appendChild(/** @type {?} */ ((document.createTextNode(message))));
if (!messagesContainer) {
createMessagesContainer();
} /** @type {?} */
((messagesContainer)).appendChild(messageElement);
messageRegistry.set(message, { messageElement, referenceCount: 0 });
}
/**
* Deletes the message element from the global messages container.
* @param {?} message
* @return {?}
*/
function deleteMessageElement(message) {
const /** @type {?} */ registeredMessage = messageRegistry.get(message);
const /** @type {?} */ messageElement = registeredMessage && registeredMessage.messageElement;
if (messagesContainer && messageElement) {
messagesContainer.removeChild(messageElement);
}
messageRegistry.delete(message);
}
/**
* Creates the global container for all aria-describedby messages.
* @return {?}
*/
function createMessagesContainer() {
messagesContainer = document.createElement('div');
messagesContainer.setAttribute('id', MESSAGES_CONTAINER_ID);
messagesContainer.setAttribute('aria-hidden', 'true');
messagesContainer.style.display = 'none';
document.body.appendChild(messagesContainer);
}
/**
* Deletes the global messages container.
* @return {?}
*/
function deleteMessagesContainer() {
document.body.removeChild(/** @type {?} */ ((messagesContainer)));
messagesContainer = null;
}
/**
* Removes all cdk-describedby messages that are hosted through the element.
* @param {?} element
* @return {?}
*/
function removeCdkDescribedByReferenceIds(element) {
// Remove all aria-describedby reference IDs that are prefixed by CDK_DESCRIBEDBY_ID_PREFIX
const /** @type {?} */ originalReferenceIds = getAriaReferenceIds(element, 'aria-describedby')
.filter(id => id.indexOf(CDK_DESCRIBEDBY_ID_PREFIX) != 0);
element.setAttribute('aria-describedby', originalReferenceIds.join(' '));
}
/**
* Adds a message reference to the element using aria-describedby and increments the registered
* message's reference count.
* @param {?} element
* @param {?} message
* @return {?}
*/
function addMessageReference(element, message) {
const /** @type {?} */ registeredMessage = /** @type {?} */ ((messageRegistry.get(message)));
// Add the aria-describedby reference and set the describedby_host attribute to mark the element.
addAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);
element.setAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE, '');
registeredMessage.referenceCount++;
}
/**
* Removes a message reference from the element using aria-describedby and decrements the registered
* message's reference count.
* @param {?} element
* @param {?} message
* @return {?}
*/
function removeMessageReference(element, message) {
const /** @type {?} */ registeredMessage = /** @type {?} */ ((messageRegistry.get(message)));
registeredMessage.referenceCount--;
removeAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);
element.removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);
}
/**
* Returns true if the element has been described by the provided message ID.
* @param {?} element
* @param {?} message
* @return {?}
*/
function isElementDescribedByMessage(element, message) {
const /** @type {?} */ referenceIds = getAriaReferenceIds(element, 'aria-describedby');
const /** @type {?} */ registeredMessage = messageRegistry.get(message);
const /** @type {?} */ messageId = registeredMessage && registeredMessage.messageElement.id;
return !!messageId && referenceIds.indexOf(messageId) != -1;
}
/**
* \@docs-private
* @param {?} parentDispatcher
* @param {?} platform
* @return {?}
*/
function ARIA_DESCRIBER_PROVIDER_FACTORY(parentDispatcher, platform) {
return parentDispatcher || new AriaDescriber(platform);
}
/**
* \@docs-private
*/
const ARIA_DESCRIBER_PROVIDER = {
// If there is already an AriaDescriber available, use that. Otherwise, provide a new one.
provide: AriaDescriber,
deps: [
[new Optional(), new SkipSelf(), AriaDescriber],
Platform
],
useFactory: ARIA_DESCRIBER_PROVIDER_FACTORY
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Screenreaders will often fire fake mousedown events when a focusable element
* is activated using the keyboard. We can typically distinguish between these faked
* mousedown events and real mousedown events using the "buttons" property. While
* real mousedowns will indicate the mouse button that was pressed (e.g. "1" for
* the left mouse button), faked mousedowns will usually set the property value to 0.
* @param {?} event
* @return {?}
*/
function isFakeMousedownFromScreenReader(event) {
return event.buttons === 0;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* This is the interface for focusable items (used by the FocusKeyManager).
* Each item must know how to focus itself, whether or not it is currently disabled
* and be able to supply it's label.
* @record
*/
class FocusKeyManager extends ListKeyManager {
/**
* This method sets the active item to the item at the specified index.
* It also adds focuses the newly active item.
* @param {?} index
* @return {?}
*/
setActiveItem(index) {
super.setActiveItem(index);
if (this.activeItem) {
this.activeItem.focus();
}
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Utility for checking the interactivity of an element, such as whether is is focusable or
* tabbable.
*/
class InteractivityChecker {
/**
* @param {?} _platform
*/
constructor(_platform) {
this._platform = _platform;
}
/**
* Gets whether an element is disabled.
*
* @param {?} element Element to be checked.
* @return {?} Whether the element is disabled.
*/
isDisabled(element) {
// This does not capture some cases, such as a non-form control with a disabled attribute or
// a form control inside of a disabled form, but should capture the most common cases.
return element.hasAttribute('disabled');
}
/**
* Gets whether an element is visible for the purposes of interactivity.
*
* This will capture states like `display: none` and `visibility: hidden`, but not things like
* being clipped by an `overflow: hidden` parent or being outside the viewport.
*
* @param {?} element
* @return {?} Whether the element is visible.
*/
isVisible(element) {
return hasGeometry(element) && getComputedStyle(element).visibility === 'visible';
}
/**
* Gets whether an element can be reached via Tab key.
* Assumes that the element has already been checked with isFocusable.
*
* @param {?} element Element to be checked.
* @return {?} Whether the element is tabbable.
*/
isTabbable(element) {
// Nothing is tabbable on the the server 😎
if (!this._platform.isBrowser) {
return false;
}
let /** @type {?} */ frameElement = /** @type {?} */ (getWindow(element).frameElement);
if (frameElement) {
let /** @type {?} */ frameType = frameElement && frameElement.nodeName.toLowerCase();
// Frame elements inherit their tabindex onto all child elements.
if (getTabIndexValue(frameElement) === -1) {
return false;
}
// Webkit and Blink consider anything inside of an <object> element as non-tabbable.
if ((this._platform.BLINK || this._platform.WEBKIT) && frameType === 'object') {
return false;
}
// Webkit and Blink disable tabbing to an element inside of an invisible frame.
if ((this._platform.BLINK || this._platform.WEBKIT) && !this.isVisible(frameElement)) {
return false;
}
}
let /** @type {?} */ nodeName = element.nodeName.toLowerCase();
let /** @type {?} */ tabIndexValue = getTabIndexValue(element);
if (element.hasAttribute('contenteditable')) {
return tabIndexValue !== -1;
}
if (nodeName === 'iframe') {
// The frames may be tabbable depending on content, but it's not possibly to reliably
// investigate the content of the frames.
return false;
}
if (nodeName === 'audio') {
if (!element.hasAttribute('controls')) {
// By default an <audio> element without the controls enabled is not tabbable.
return false;
}
else if (this._platform.BLINK) {
// In Blink <audio controls> elements are always tabbable.
return true;
}
}
if (nodeName === 'video') {
if (!element.hasAttribute('controls') && this._platform.TRIDENT) {
// In Trident a <video> element without the controls enabled is not tabbable.
return false;
}
else if (this._platform.BLINK || this._platform.FIREFOX) {
// In Chrome and Firefox <video controls> elements are always tabbable.
return true;
}
}
if (nodeName === 'object' && (this._platform.BLINK || this._platform.WEBKIT)) {
// In all Blink and WebKit based browsers <object> elements are never tabbable.
return false;
}
// In iOS the browser only considers some specific elements as tabbable.
if (this._platform.WEBKIT && this._platform.IOS && !isPotentiallyTabbableIOS(element)) {
return false;
}
return element.tabIndex >= 0;
}
/**
* Gets whether an element can be focused by the user.
*
* @param {?} element Element to be checked.
* @return {?} Whether the element is focusable.
*/
isFocusable(element) {
// Perform checks in order of left to most expensive.
// Again, naive approach that does not capture many edge cases and browser quirks.
return isPotentiallyFocusable(element) && !this.isDisabled(element) && this.isVisible(element);
}
}
InteractivityChecker.decorators = [
{ type: Injectable },
];
/** @nocollapse */
InteractivityChecker.ctorParameters = () => [
{ type: Platform, },
];
/**
* Checks whether the specified element has any geometry / rectangles.
* @param {?} element
* @return {?}
*/
function hasGeometry(element) {
// Use logic from jQuery to check for an invisible element.
// See https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js#L12
return !!(element.offsetWidth || element.offsetHeight ||
(typeof element.getClientRects === 'function' && element.getClientRects().length));
}
/**
* Gets whether an element's
* @param {?} element
* @return {?}
*/
function isNativeFormElement(element) {
let /** @type {?} */ nodeName = element.nodeName.toLowerCase();
return nodeName === 'input' ||
nodeName === 'select' ||
nodeName === 'button' ||
nodeName === 'textarea';
}
/**
* Gets whether an element is an <input type="hidden">.
* @param {?} element
* @return {?}
*/
function isHiddenInput(element) {
return isInputElement(element) && element.type == 'hidden';
}
/**
* Gets whether an element is an anchor that has an href attribute.
* @param {?} element
* @return {?}
*/
function isAnchorWithHref(element) {
return isAnchorElement(element) && element.hasAttribute('href');
}
/**
* Gets whether an element is an input element.
* @param {?} element
* @return {?}
*/
function isInputElement(element) {
return element.nodeName.toLowerCase() == 'input';
}
/**
* Gets whether an element is an anchor element.
* @param {?} element
* @return {?}
*/
function isAnchorElement(element) {
return element.nodeName.toLowerCase() == 'a';
}
/**
* Gets whether an element has a valid tabindex.
* @param {?} element
* @return {?}
*/
function hasValidTabIndex(element) {
if (!element.hasAttribute('tabindex') || element.tabIndex === undefined) {
return false;
}
let /** @type {?} */ tabIndex = element.getAttribute('tabindex');
// IE11 parses tabindex="" as the value "-32768"
if (tabIndex == '-32768') {
return false;
}
return !!(tabIndex && !isNaN(parseInt(tabIndex, 10)));
}
/**
* Returns the parsed tabindex from the element attributes instead of returning the
* evaluated tabindex from the browsers defaults.
* @param {?} element
* @return {?}
*/
function getTabIndexValue(element) {
if (!hasValidTabIndex(element)) {
return null;
}
// See browser issue in Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=1128054
const /** @type {?} */ tabIndex = parseInt(element.getAttribute('tabindex') || '', 10);
return isNaN(tabIndex) ? -1 : tabIndex;
}
/**
* Checks whether the specified element is potentially tabbable on iOS
* @param {?} element
* @return {?}
*/
function isPotentiallyTabbableIOS(element) {
let /** @type {?} */ nodeName = element.nodeName.toLowerCase();
let /** @type {?} */ inputType = nodeName === 'input' && (/** @type {?} */ (element)).type;
return inputType === 'text'
|| inputType === 'password'
|| nodeName === 'select'
|| nodeName === 'textarea';
}
/**
* Gets whether an element is potentially focusable without taking current visible/disabled state
* into account.
* @param {?} element
* @return {?}
*/
function isPotentiallyFocusable(element) {
// Inputs are potentially focusable *unless* they're type="hidden".
if (isHiddenInput(element)) {
return false;
}
return isNativeFormElement(element) ||
isAnchorWithHref(element) ||
element.hasAttribute('contenteditable') ||
hasValidTabIndex(element);
}
/**
* Gets the parent window of a DOM node with regards of being inside of an iframe.
* @param {?} node
* @return {?}
*/
function getWindow(node) {
return node.ownerDocument.defaultView || window;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Class that allows for trapping focus within a DOM element.
*
* This class currently uses a relatively simple approach to focus trapping.
* It assumes that the tab order is the same as DOM order, which is not necessarily true.
* Things like tabIndex > 0, flex `order`, and shadow roots can cause to two to misalign.
*/
class FocusTrap {
/**
* @param {?} _element
* @param {?} _platform
* @param {?} _checker
* @param {?} _ngZone
* @param {?=} deferAnchors
*/
constructor(_element, _platform, _checker, _ngZone, deferAnchors = false) {
this._element = _element;
this._platform = _platform;
this._checker = _checker;
this._ngZone = _ngZone;
this._enabled = true;
if (!deferAnchors) {
this.attachAnchors();
}
}
/**
* Whether the focus trap is active.
* @return {?}
*/
get enabled() { return this._enabled; }
/**
* @param {?} val
* @return {?}
*/
set enabled(val) {
this._enabled = val;
if (this._startAnchor && this._endAnchor) {
this._startAnchor.tabIndex = this._endAnchor.tabIndex = this._enabled ? 0 : -1;
}
}
/**
* Destroys the focus trap by cleaning up the anchors.
* @return {?}
*/
destroy() {
if (this._startAnchor && this._startAnchor.parentNode) {
this._startAnchor.parentNode.removeChild(this._startAnchor);
}
if (this._endAnchor && this._endAnchor.parentNode) {
this._endAnchor.parentNode.removeChild(this._endAnchor);
}
this._startAnchor = this._endAnchor = null;
}
/**
* Inserts the anchors into the DOM. This is usually done automatically
* in the constructor, but can be deferred for cases like directives with `*ngIf`.
* @return {?}
*/
attachAnchors() {
// If we're not on the browser, there can be no focus to trap.
if (!this._platform.isBrowser) {
return;
}
if (!this._startAnchor) {
this._startAnchor = this._createAnchor();
}
if (!this._endAnchor) {
this._endAnchor = this._createAnchor();
}
this._ngZone.runOutsideAngular(() => {
/** @type {?} */ ((this._startAnchor)).addEventListener('focus', () => {
this.focusLastTabbableElement();
}); /** @type {?} */
((this._endAnchor)).addEventListener('focus', () => {
this.focusFirstTabbableElement();
});
if (this._element.parentNode) {
this._element.parentNode.insertBefore(/** @type {?} */ ((this._startAnchor)), this._element);
this._element.parentNode.insertBefore(/** @type {?} */ ((this._endAnchor)), this._element.nextSibling);
}
});
}
/**
* Waits for the zone to stabilize, then either focuses the first element that the
* user specified, or the first tabbable element.
* @return {?} Returns a promise that resolves with a boolean, depending
* on whether focus was moved successfuly.
*/
focusInitialElementWhenReady() {
return new Promise(resolve => {
this._executeOnStable(() => resolve(this.focusInitialElement()));
});
}
/**
* Waits for the zone to stabilize, then focuses
* the first tabbable element within the focus trap region.
* @return {?} Returns a promise that resolves with a boolean, depending
* on whether focus was moved successfuly.
*/
focusFirstTabbableElementWhenReady() {
return new Promise(resolve => {
this._executeOnStable(() => resolve(this.focusFirstTabbableElement()));
});
}
/**
* Waits for the zone to stabilize, then focuses
* the last tabbable element within the focus trap region.
* @return {?} Returns a promise that resolves with a boolean, depending
* on whether focus was moved successfuly.
*/
focusLastTabbableElementWhenReady() {
return new Promise(resolve => {
this._executeOnStable(() => resolve(this.focusLastTabbableElement()));
});
}
/**
* Get the specified boundary element of the trapped region.
* @param {?} bound The boundary to get (start or end of trapped region).
* @return {?} The boundary element.
*/
_getRegionBoundary(bound) {
if (!this._platform.isBrowser) {
return null;
}
// Contains the deprecated version of selector, for temporary backwards comparability.
let /** @type {?} */ markers = /** @type {?} */ (this._element.querySelectorAll(`[cdk-focus-region-${bound}], ` +
`[cdkFocusRegion${bound}], ` +
`[cdk-focus-${bound}]`));
for (let /** @type {?} */ i = 0; i < markers.length; i++) {
if (markers[i].hasAttribute(`cdk-focus-${bound}`)) {
console.warn(`Found use of deprecated attribute 'cdk-focus-${bound}',` +
` use 'cdkFocusRegion${bound}' instead.`, markers[i]);