Skip to content

Commit d0cd9a5

Browse files
committed
refactor: hoist tab query&filter into function
1 parent d485ea9 commit d0cd9a5

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

src/index.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
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+
17
export default class TabContainerElement extends HTMLElement {
28
constructor() {
39
super()
@@ -7,9 +13,7 @@ export default class TabContainerElement extends HTMLElement {
713
if (!(target instanceof HTMLElement)) return
814
if (target.closest(this.tagName) !== this) return
915
if (target.getAttribute('role') !== 'tab' && !target.closest('[role="tablist"]')) return
10-
const tabs = Array.from(this.querySelectorAll('[role="tablist"] [role="tab"]')).filter(
11-
tab => tab.closest(this.tagName) === this
12-
)
16+
const tabs = getTabs(this)
1317
const currentIndex = tabs.indexOf(tabs.find(tab => tab.matches('[aria-selected="true"]'))!)
1418

1519
if (event.code === 'ArrowRight') {
@@ -30,21 +34,21 @@ export default class TabContainerElement extends HTMLElement {
3034
})
3135

3236
this.addEventListener('click', (event: MouseEvent) => {
33-
const tabs = Array.from(this.querySelectorAll('[role="tablist"] [role="tab"]'))
37+
const tabs = getTabs(this)
3438

3539
if (!(event.target instanceof Element)) return
3640
if (event.target.closest(this.tagName) !== this) return
3741

3842
const tab = event.target.closest('[role="tab"]')
39-
if (!tab || !tab.closest('[role="tablist"]')) return
43+
if (!(tab instanceof HTMLElement) || !tab.closest('[role="tablist"]')) return
4044

4145
const index = tabs.indexOf(tab)
4246
selectTab(this, index)
4347
})
4448
}
4549

4650
connectedCallback(): void {
47-
for (const tab of this.querySelectorAll('[role="tablist"] [role="tab"]')) {
51+
for (const tab of getTabs(this)) {
4852
if (!tab.hasAttribute('aria-selected')) {
4953
tab.setAttribute('aria-selected', 'false')
5054
}
@@ -60,9 +64,7 @@ export default class TabContainerElement extends HTMLElement {
6064
}
6165

6266
function selectTab(tabContainer: TabContainerElement, index: number) {
63-
const tabs = Array.from(tabContainer.querySelectorAll<HTMLElement>('[role="tablist"] [role="tab"]')).filter(
64-
tab => tab.closest(tabContainer.tagName) === tabContainer
65-
)
67+
const tabs = getTabs(tabContainer)
6668
const panels = Array.from(tabContainer.querySelectorAll<HTMLElement>('[role="tabpanel"]')).filter(
6769
panel => panel.closest(tabContainer.tagName) === tabContainer
6870
)

0 commit comments

Comments
 (0)