1
+ function getTabs ( el : TabContainerElement ) : HTMLElement [ ] {
2
+ return Array . from ( el . querySelectorAll < HTMLElement > ( '[role="tablist"] [role="tab"]' ) ) . filter (
3
+ tab => tab instanceof HTMLElement && tab . closest ( el . tagName ) === el
4
+ )
5
+ }
6
+
1
7
export default class TabContainerElement extends HTMLElement {
2
8
constructor ( ) {
3
9
super ( )
@@ -7,7 +13,7 @@ export default class TabContainerElement extends HTMLElement {
7
13
if ( ! ( target instanceof HTMLElement ) ) return
8
14
if ( target . closest ( this . tagName ) !== this ) return
9
15
if ( target . getAttribute ( 'role' ) !== 'tab' && ! target . closest ( '[role="tablist"]' ) ) return
10
- const tabs = Array . from ( this . querySelectorAll ( '[role="tablist"] [role="tab"]' ) )
16
+ const tabs = getTabs ( this )
11
17
const currentIndex = tabs . indexOf ( tabs . find ( tab => tab . matches ( '[aria-selected="true"]' ) ) ! )
12
18
13
19
if ( event . code === 'ArrowRight' ) {
@@ -28,21 +34,21 @@ export default class TabContainerElement extends HTMLElement {
28
34
} )
29
35
30
36
this . addEventListener ( 'click' , ( event : MouseEvent ) => {
31
- const tabs = Array . from ( this . querySelectorAll ( '[role="tablist"] [role="tab"]' ) )
37
+ const tabs = getTabs ( this )
32
38
33
39
if ( ! ( event . target instanceof Element ) ) return
34
40
if ( event . target . closest ( this . tagName ) !== this ) return
35
41
36
42
const tab = event . target . closest ( '[role="tab"]' )
37
- if ( ! tab || ! tab . closest ( '[role="tablist"]' ) ) return
43
+ if ( ! ( tab instanceof HTMLElement ) || ! tab . closest ( '[role="tablist"]' ) ) return
38
44
39
45
const index = tabs . indexOf ( tab )
40
46
selectTab ( this , index )
41
47
} )
42
48
}
43
49
44
50
connectedCallback ( ) : void {
45
- for ( const tab of this . querySelectorAll ( '[role="tablist"] [role="tab"]' ) ) {
51
+ for ( const tab of getTabs ( this ) ) {
46
52
if ( ! tab . hasAttribute ( 'aria-selected' ) ) {
47
53
tab . setAttribute ( 'aria-selected' , 'false' )
48
54
}
@@ -58,8 +64,10 @@ export default class TabContainerElement extends HTMLElement {
58
64
}
59
65
60
66
function selectTab ( tabContainer : TabContainerElement , index : number ) {
61
- const tabs = tabContainer . querySelectorAll < HTMLElement > ( '[role="tablist"] [role="tab"]' )
62
- const panels = tabContainer . querySelectorAll < HTMLElement > ( '[role="tabpanel"]' )
67
+ const tabs = getTabs ( tabContainer )
68
+ const panels = Array . from ( tabContainer . querySelectorAll < HTMLElement > ( '[role="tabpanel"]' ) ) . filter (
69
+ panel => panel . closest ( tabContainer . tagName ) === tabContainer
70
+ )
63
71
64
72
const selectedTab = tabs [ index ]
65
73
const selectedPanel = panels [ index ]
0 commit comments