Refactor the tab component
This commit is contained in:
@@ -4,40 +4,24 @@
|
||||
export let tabs = [];
|
||||
|
||||
let tabbedContent = null;
|
||||
let activeIndex = 0;
|
||||
|
||||
const selectTab = (event) => {
|
||||
const tab = event.target;
|
||||
const panel = tabbedContent.querySelector(
|
||||
`#${tab.getAttribute('aria-controls')}`,
|
||||
);
|
||||
|
||||
tabbedContent.querySelectorAll('[role="tab"]').forEach((t) => {
|
||||
t.setAttribute('aria-selected', 'false');
|
||||
t.setAttribute('tabindex', '-1');
|
||||
});
|
||||
|
||||
tab.setAttribute('aria-selected', 'true');
|
||||
tab.setAttribute('tabindex', '0');
|
||||
|
||||
tabbedContent.querySelectorAll('[role="tabpanel"]').forEach((p) => {
|
||||
p.hidden = true;
|
||||
});
|
||||
|
||||
panel.hidden = false;
|
||||
};
|
||||
const isSelected = (index) => index === activeIndex;
|
||||
const getTabIndex = (index) => (isSelected(index) ? 0 : -1);
|
||||
</script>
|
||||
|
||||
<section bind:this={tabbedContent}>
|
||||
<div role="tablist">
|
||||
{#each tabs as tab, i}
|
||||
{@const tabId = tab.id || i}
|
||||
{@const id = tab.id || i}
|
||||
{@const selected = i === activeIndex}
|
||||
<button
|
||||
role="tab"
|
||||
id="tab-{tabId}"
|
||||
aria-controls="panel-{tabId}"
|
||||
aria-selected="false"
|
||||
tabindex="-1"
|
||||
on:click={selectTab}
|
||||
id="tab-{id}"
|
||||
aria-controls="panel-{id}"
|
||||
aria-selected={selected}
|
||||
tabindex={selected ? 0 : -1}
|
||||
on:click={() => (activeIndex = i)}
|
||||
>
|
||||
{tab.title}
|
||||
</button>
|
||||
@@ -45,8 +29,7 @@
|
||||
</div>
|
||||
|
||||
{#each tabs as tab, i}
|
||||
{@const tabId = tab.id || i}
|
||||
<div role="tabpanel" id="panel-{tabId}" hidden>
|
||||
<div role="tabpanel" id="panel-{tab.id || i}" hidden={i !== activeIndex}>
|
||||
<p>{tab.content}</p>
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
Reference in New Issue
Block a user