Skip to content

Commit

Permalink
add default-tab attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
keithamus committed Feb 19, 2024
1 parent e329880 commit df9d585
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import '@github/tab-container-element'
</tab-container>
```

If none of the tabs have `aria-selected=true`, then the first tab will be selected automatically. You can also add the `default-tab=N` attribute to avoid having to set `aria-selected=true` on the desired tab.

### Events

- `tab-container-change` (bubbles, cancelable): fired on `<tab-container>` before a new tab is selected and visibility is updated. `event.tab` is the tab that will be focused and `tab.panel` is the panel that will be shown if the event isn't cancelled.
Expand Down
3 changes: 2 additions & 1 deletion src/tab-container-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,8 @@ export class TabContainerElement extends HTMLElement {
this.#beforeTabsSlot.assign(...beforeSlotted)
this.#afterTabsSlot.assign(...afterTabSlotted)
this.#afterPanelsSlot.assign(...afterSlotted)
const defaultIndex = this.#tabs.findIndex(el => el.matches('[aria-selected=true]'))
const defaultTab = Number(this.getAttribute('default-tab') || -1)
const defaultIndex = defaultTab >= 0 ? defaultTab : this.#tabs.findIndex(el => el.matches('[aria-selected=true]'))
index = index >= 0 ? index : Math.max(0, defaultIndex)
}

Expand Down
32 changes: 32 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,38 @@ describe('tab-container', function () {
})
})

describe('after tree insertion with default-tab', function () {
beforeEach(function () {
document.body.innerHTML = `
<tab-container default-tab=1>
<button type="button" role="tab">Tab one</button>
<button type="button" role="tab">Tab two</button>
<button type="button" role="tab">Tab three</button>
<div role="tabpanel" hidden>
Panel 1
</div>
<div role="tabpanel">
Panel 2
</div>
<div role="tabpanel" hidden data-tab-container-no-tabstop>
Panel 3
</div>
</tab-container>
`
tabs = Array.from(document.querySelectorAll('button'))
panels = Array.from(document.querySelectorAll('[role="tabpanel"]'))
})

afterEach(function () {
document.body.innerHTML = ''
})

it('the second tab is still selected', function () {
assert.deepStrictEqual(tabs.map(isSelected), [false, true, false], 'Second tab is selected')
assert.deepStrictEqual(panels.map(isHidden), [true, false, true], 'Second panel is visible')
})
})

describe('after tree insertion', function () {
beforeEach(function () {
document.body.innerHTML = `
Expand Down

0 comments on commit df9d585

Please sign in to comment.