Skip to content

Commit b11dd53

Browse files
authored
Merge pull request #74 from github/refactor-gettabs-into-private-getters
Refactor gettabs into private getters
2 parents 46c139c + 72afa63 commit b11dd53

1 file changed

Lines changed: 14 additions & 10 deletions

File tree

src/tab-container-element.ts

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,5 @@
11
const HTMLElement = globalThis.HTMLElement || (null as unknown as (typeof window)['HTMLElement'])
22

3-
function getTabs(el: TabContainerElement): HTMLElement[] {
4-
return Array.from(el.querySelectorAll<HTMLElement>('[role="tablist"] [role="tab"]')).filter(
5-
tab => tab instanceof HTMLElement && tab.closest(el.tagName) === el,
6-
)
7-
}
8-
93
export class TabContainerChangeEvent extends Event {
104
constructor(type: string, {tab, panel, ...init}: EventInit & {tab?: Element; panel?: Element}) {
115
super(type, init)
@@ -72,10 +66,20 @@ export class TabContainerElement extends HTMLElement {
7266
}
7367
}
7468

69+
get #tabList() {
70+
return this.querySelector<HTMLElement>('[role=tablist]')
71+
}
72+
73+
get #tabs() {
74+
return Array.from(this.#tabList?.querySelectorAll<HTMLElement>('[role="tab"]') || []).filter(
75+
tab => tab instanceof HTMLElement && tab.closest(this.tagName) === this,
76+
)
77+
}
78+
7579
connectedCallback(): void {
7680
this.addEventListener('keydown', this)
7781
this.addEventListener('click', this)
78-
for (const tab of getTabs(this)) {
82+
for (const tab of this.#tabs) {
7983
if (!tab.hasAttribute('aria-selected')) {
8084
tab.setAttribute('aria-selected', 'false')
8185
}
@@ -97,7 +101,7 @@ export class TabContainerElement extends HTMLElement {
97101
#handleKeydown(event: KeyboardEvent) {
98102
const tab = (event.target as HTMLElement)?.closest?.('[role="tab"]')
99103
if (!tab) return
100-
const tabs = getTabs(this)
104+
const tabs = this.#tabs
101105
if (!tabs.includes(tab as HTMLElement)) return
102106

103107
const currentIndex = tabs.indexOf(tabs.find(e => e.matches('[aria-selected="true"]'))!)
@@ -125,13 +129,13 @@ export class TabContainerElement extends HTMLElement {
125129
#handleClick(event: MouseEvent) {
126130
const tab = (event.target as HTMLElement)?.closest?.('[role=tab]')
127131
if (!tab) return
128-
const tabs = getTabs(this)
132+
const tabs = this.#tabs
129133
const index = tabs.indexOf(tab as HTMLElement)
130134
if (index >= 0) this.selectTab(index)
131135
}
132136

133137
selectTab(index: number): void {
134-
const tabs = getTabs(this)
138+
const tabs = this.#tabs
135139
const panels = Array.from(this.querySelectorAll<HTMLElement>('[role="tabpanel"]')).filter(
136140
panel => panel.closest(this.tagName) === this,
137141
)

0 commit comments

Comments
 (0)