Skip to content

Commit

Permalink
Merge pull request #97 from github/ensure_tabs_available
Browse files Browse the repository at this point in the history
Ensure tabs are available before selecting
  • Loading branch information
camertron authored Jun 19, 2024
2 parents b294c24 + a947f7d commit 98f5d77
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 8 deletions.
1 change: 1 addition & 0 deletions .tool-versions
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
nodejs 22.3.0
3 changes: 3 additions & 0 deletions custom-elements.json
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,9 @@
"kind": "field",
"name": "#tabList",
"privacy": "private",
"type": {
"text": "HTMLElement"
},
"readonly": true
},
{
Expand Down
19 changes: 16 additions & 3 deletions src/tab-container-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export class TabContainerElement extends HTMLElement {

static observedAttributes = ['vertical']

get #tabList() {
get #tabList(): HTMLElement {
const wrapper = this.querySelector('[slot=tablist-wrapper]')
if (wrapper?.closest(this.tagName) === this) {
return wrapper.querySelector('[role=tablist]') as HTMLElement
Expand Down Expand Up @@ -221,7 +221,18 @@ export class TabContainerElement extends HTMLElement {
this.addEventListener('click', this)

this.selectTab(-1)
this.#setupComplete = true

if (!this.#setupComplete) {
const mutationObserver = new MutationObserver(() => {
this.selectTab(-1)

if (this.#setupComplete) {
mutationObserver.disconnect()
}
})

mutationObserver.observe(this, {childList: true, subtree: true})
}
}

attributeChangedCallback(name: string) {
Expand Down Expand Up @@ -356,7 +367,7 @@ export class TabContainerElement extends HTMLElement {
* Out of bounds index
*/
if (index > tabs.length - 1) {
throw new RangeError(`Index "${index}" out of bounds`)
return
}

const selectedTab = tabs[index]
Expand Down Expand Up @@ -401,5 +412,7 @@ export class TabContainerElement extends HTMLElement {
}),
)
}

this.#setupComplete = true
}
}
8 changes: 3 additions & 5 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -339,11 +339,9 @@ describe('tab-container', function () {
})

it('result in noop, when selectTab receives out of bounds index', function () {
assert.throws(() => tabContainer.selectTab(3), 'Index "3" out of bounds')

tabContainer.selectTab(2)
assert.deepStrictEqual(tabs.map(isSelected), [false, false, true], 'Third tab is selected')
assert.deepStrictEqual(panels.map(isHidden), [true, true, false], 'Third panel is visible')
tabContainer.selectTab(3)
assert.deepStrictEqual(tabs.map(isSelected), [true, false, false], 'First tab is selected')
assert.deepStrictEqual(panels.map(isHidden), [false, true, true], 'First panel is visible')
})
})

Expand Down

0 comments on commit 98f5d77

Please sign in to comment.