Tabs
A set of layered sections of content, known as tab panels, that display one panel of content at a time.
Demo
Automatic Activation (Default)
Tabs are activated automatically when focused with arrow keys.
This is the overview panel content. It provides a general introduction to the product or service.
Keyboard navigation support, ARIA compliant, Automatic and manual activation modes.
Pricing information would be displayed here.
Manual Activation
Tabs require Enter or Space to activate after focusing.
Content for tab one. Press Enter or Space to activate tabs.
Content for tab two.
Content for tab three.
Vertical Orientation
Tabs arranged vertically with Up/Down arrow navigation.
Configure your application settings here.
Manage your profile information.
Set your notification preferences.
Accessibility Features
WAI-ARIA Roles
| Role | Target Element | Description |
|---|---|---|
tablist | Container | Container for tab elements |
tab | Each tab | Individual tab element |
tabpanel | Panel | Content area for each tab |
WAI-ARIA tablist role (opens in new tab)
WAI-ARIA Properties
| Attribute | Target | Values | Required | Configuration |
|---|---|---|---|---|
aria-orientation | tablist | "horizontal" | "vertical" | No | orientation prop |
aria-controls | tab | ID reference to associated panel | Yes | Auto-generated |
aria-labelledby | tabpanel | ID reference to associated tab | Yes | Auto-generated |
WAI-ARIA States
aria-selected
Indicates the currently active tab.
| Target | tab element |
| Values | true | false |
| Required | Yes |
| Change Trigger | Tab click, Arrow keys (automatic), Enter/Space (manual) |
| Reference | aria-selected (opens in new tab) |
Keyboard Support
| Key | Action |
|---|---|
| Tab | Move focus into/out of the tablist |
| Arrow Right / Arrow Left | Navigate between tabs (horizontal) |
| Arrow Down / Arrow Up | Navigate between tabs (vertical) |
| Home | Move focus to first tab |
| End | Move focus to last tab |
| Enter / Space | Activate tab (manual mode only) |
Source Code
Tabs.svelte
<script lang="ts">
import { onMount } from 'svelte';
export interface TabItem {
id: string;
label: string;
content?: string;
disabled?: boolean;
}
interface TabsProps {
tabs: TabItem[];
defaultSelectedId?: string;
orientation?: 'horizontal' | 'vertical';
activationMode?: 'automatic' | 'manual';
label?: string;
onSelectionChange?: (tabId: string) => void;
}
let {
tabs = [],
defaultSelectedId = undefined,
orientation = 'horizontal',
activationMode = 'automatic',
label = undefined,
onSelectionChange = () => {},
}: TabsProps = $props();
let selectedId = $state('');
let focusedIndex = $state(0);
let tablistElement: HTMLElement;
let tabRefs: Record<string, HTMLButtonElement> = {};
let tablistId = $state('');
onMount(() => {
tablistId = `tabs-${Math.random().toString(36).substr(2, 9)}`;
});
// Initialize selected tab
$effect(() => {
if (tabs.length > 0 && !selectedId) {
const initialTab = defaultSelectedId
? tabs.find(tab => tab.id === defaultSelectedId && !tab.disabled)
: tabs.find(tab => !tab.disabled);
selectedId = initialTab?.id || tabs[0]?.id;
}
});
// Derived values
let availableTabs = $derived(tabs.filter(tab => !tab.disabled));
let containerClass = $derived(
`apg-tabs ${orientation === 'vertical' ? 'apg-tabs--vertical' : 'apg-tabs--horizontal'}`
);
let tablistClass = $derived(
`apg-tablist ${orientation === 'vertical' ? 'apg-tablist--vertical' : 'apg-tablist--horizontal'}`
);
function getTabClass(tab: TabItem): string {
const classes = ['apg-tab'];
classes.push(orientation === 'vertical' ? 'apg-tab--vertical' : 'apg-tab--horizontal');
if (tab.id === selectedId) classes.push('apg-tab--selected');
if (tab.disabled) classes.push('apg-tab--disabled');
return classes.join(' ');
}
function getPanelClass(tab: TabItem): string {
return `apg-tabpanel ${tab.id === selectedId ? 'apg-tabpanel--active' : 'apg-tabpanel--inactive'}`;
}
function handleTabSelection(tabId: string) {
selectedId = tabId;
onSelectionChange(tabId);
}
function handleTabFocus(index: number) {
focusedIndex = index;
const tab = availableTabs[index];
if (tab && tabRefs[tab.id]) {
tabRefs[tab.id].focus();
}
}
function handleKeyDown(event: KeyboardEvent) {
const target = event.target;
if (!tablistElement || !(target instanceof Node) || !tablistElement.contains(target)) {
return;
}
let newIndex = focusedIndex;
let shouldPreventDefault = false;
switch (event.key) {
case 'ArrowRight':
case 'ArrowDown':
newIndex = (focusedIndex + 1) % availableTabs.length;
shouldPreventDefault = true;
break;
case 'ArrowLeft':
case 'ArrowUp':
newIndex = (focusedIndex - 1 + availableTabs.length) % availableTabs.length;
shouldPreventDefault = true;
break;
case 'Home':
newIndex = 0;
shouldPreventDefault = true;
break;
case 'End':
newIndex = availableTabs.length - 1;
shouldPreventDefault = true;
break;
case 'Enter':
case ' ':
if (activationMode === 'manual') {
const focusedTab = availableTabs[focusedIndex];
if (focusedTab) {
handleTabSelection(focusedTab.id);
}
}
shouldPreventDefault = true;
break;
}
if (shouldPreventDefault) {
event.preventDefault();
if (newIndex !== focusedIndex) {
handleTabFocus(newIndex);
if (activationMode === 'automatic') {
const newTab = availableTabs[newIndex];
if (newTab) {
handleTabSelection(newTab.id);
}
}
}
}
}
// Update focused index when selected tab changes
$effect(() => {
const selectedIndex = availableTabs.findIndex(tab => tab.id === selectedId);
if (selectedIndex >= 0) {
focusedIndex = selectedIndex;
}
});
</script>
<div class={containerClass}>
<div
bind:this={tablistElement}
role="tablist"
aria-orientation={orientation}
class={tablistClass}
onkeydown={handleKeyDown}
>
{#each tabs as tab}
{@const isSelected = tab.id === selectedId}
{@const tabIndex = tab.disabled ? -1 : (isSelected ? 0 : -1)}
<button
bind:this={tabRefs[tab.id]}
role="tab"
type="button"
id="{tablistId}-tab-{tab.id}"
aria-selected={isSelected}
aria-controls={isSelected ? `${tablistId}-panel-${tab.id}` : undefined}
tabindex={tabIndex}
disabled={tab.disabled}
class={getTabClass(tab)}
onclick={() => !tab.disabled && handleTabSelection(tab.id)}
>
<span class="apg-tab-label">{tab.label}</span>
</button>
{/each}
</div>
<div class="apg-tabpanels">
{#each tabs as tab}
{@const isSelected = tab.id === selectedId}
<div
role="tabpanel"
id="{tablistId}-panel-{tab.id}"
aria-labelledby="{tablistId}-tab-{tab.id}"
hidden={!isSelected}
class={getPanelClass(tab)}
tabindex={isSelected ? 0 : -1}
>
{#if tab.content}
{@html tab.content}
{/if}
</div>
{/each}
</div>
</div> Usage
Example
<script>
import Tabs from './Tabs.svelte';
const tabs = [
{ id: 'tab1', label: 'First', content: 'First panel content' },
{ id: 'tab2', label: 'Second', content: 'Second panel content' },
{ id: 'tab3', label: 'Third', content: 'Third panel content' }
];
function handleTabChange(event) {
console.log('Tab changed:', event.detail);
}
</script>
<Tabs
{tabs}
label="My tabs"
ontabchange={handleTabChange}
/> API
Props
| Prop | Type | Default | Description |
|---|---|---|---|
tabs | TabItem[] | required | Array of tab items with id, label, content |
label | string | - | Accessible label for the tablist |
defaultTab | string | first tab | ID of the initially selected tab |
orientation | 'horizontal' | 'vertical' | 'horizontal' | Tab layout direction |
activationMode | 'automatic' | 'manual' | 'automatic' | How tabs are activated |
Events
| Event | Detail | Description |
|---|---|---|
tabchange | string | Dispatched when the active tab changes |
TabItem Interface
Types
interface TabItem {
id: string;
label: string;
content: string;
disabled?: boolean;
} Testing
Tests verify APG compliance across keyboard interaction, ARIA attributes, and accessibility requirements.
Test Categories
High Priority: APG Keyboard Interaction
| Test | Description |
|---|---|
ArrowRight/Left | Moves focus between tabs (horizontal) |
ArrowDown/Up | Moves focus between tabs (vertical orientation) |
Home/End | Moves focus to first/last tab |
Loop navigation | Arrow keys loop from last to first and vice versa |
Disabled skip | Skips disabled tabs during navigation |
Automatic activation | Tab panel changes on focus (default mode) |
Manual activation | Enter/Space required to activate tab |
High Priority: APG ARIA Attributes
| Test | Description |
|---|---|
role="tablist" | Container has tablist role |
role="tab" | Each tab button has tab role |
role="tabpanel" | Content panel has tabpanel role |
aria-selected | Selected tab has aria-selected="true" |
aria-controls | Tab references its panel via aria-controls |
aria-labelledby | Panel references its tab via aria-labelledby |
aria-orientation | Reflects horizontal/vertical orientation |
High Priority: Focus Management (Roving Tabindex)
| Test | Description |
|---|---|
tabIndex=0 | Selected tab has tabIndex=0 |
tabIndex=-1 | Non-selected tabs have tabIndex=-1 |
Tab to panel | Tab key moves focus from tablist to panel |
Panel focusable | Panel has tabIndex=0 for focus |
Medium Priority: Accessibility
| Test | Description |
|---|---|
axe violations | No WCAG 2.1 AA violations (via jest-axe) |
Testing Tools
- Vitest (opens in new tab) - Test runner
- Testing Library (opens in new tab) - Framework-specific testing utilities
- jest-axe (opens in new tab) - Automated accessibility testing
See testing-strategy.md (opens in new tab) for full documentation.
Tabs.test.svelte.ts
import { render, screen } from "@testing-library/svelte";
import userEvent from "@testing-library/user-event";
import { axe } from "jest-axe";
import { describe, expect, it, vi } from "vitest";
import Tabs from "./Tabs.svelte";
import type { TabItem } from "./Tabs.svelte";
// ใในใ็จใฎใฟใใใผใฟ
const defaultTabs: TabItem[] = [
{ id: "tab1", label: "Tab 1", content: "Content 1" },
{ id: "tab2", label: "Tab 2", content: "Content 2" },
{ id: "tab3", label: "Tab 3", content: "Content 3" },
];
const tabsWithDisabled: TabItem[] = [
{ id: "tab1", label: "Tab 1", content: "Content 1" },
{ id: "tab2", label: "Tab 2", content: "Content 2", disabled: true },
{ id: "tab3", label: "Tab 3", content: "Content 3" },
];
describe("Tabs (Svelte)", () => {
// ๐ด High Priority: APG ๆบๆ ใฎๆ ธๅฟ
describe("APG: ใญใผใใผใๆไฝ (Horizontal)", () => {
describe("Automatic Activation", () => {
it("ArrowRight ใงๆฌกใฎใฟใใซ็งปๅใป้ธๆใใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: defaultTabs } });
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
tab1.focus();
await user.keyboard("{ArrowRight}");
const tab2 = screen.getByRole("tab", { name: "Tab 2" });
expect(tab2).toHaveFocus();
expect(tab2).toHaveAttribute("aria-selected", "true");
expect(screen.getByRole("tabpanel")).toHaveTextContent("Content 2");
});
it("ArrowLeft ใงๅใฎใฟใใซ็งปๅใป้ธๆใใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: defaultTabs, defaultSelectedId: "tab2" } });
const tab2 = screen.getByRole("tab", { name: "Tab 2" });
tab2.focus();
await user.keyboard("{ArrowLeft}");
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
expect(tab1).toHaveFocus();
expect(tab1).toHaveAttribute("aria-selected", "true");
});
it("ArrowRight ใงๆๅพใใๆๅใซใซใผใใใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: defaultTabs, defaultSelectedId: "tab3" } });
const tab3 = screen.getByRole("tab", { name: "Tab 3" });
tab3.focus();
await user.keyboard("{ArrowRight}");
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
expect(tab1).toHaveFocus();
expect(tab1).toHaveAttribute("aria-selected", "true");
});
it("ArrowLeft ใงๆๅใใๆๅพใซใซใผใใใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: defaultTabs } });
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
tab1.focus();
await user.keyboard("{ArrowLeft}");
const tab3 = screen.getByRole("tab", { name: "Tab 3" });
expect(tab3).toHaveFocus();
expect(tab3).toHaveAttribute("aria-selected", "true");
});
it("Home ใงๆๅใฎใฟใใซ็งปๅใป้ธๆใใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: defaultTabs, defaultSelectedId: "tab3" } });
const tab3 = screen.getByRole("tab", { name: "Tab 3" });
tab3.focus();
await user.keyboard("{Home}");
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
expect(tab1).toHaveFocus();
expect(tab1).toHaveAttribute("aria-selected", "true");
});
it("End ใงๆๅพใฎใฟใใซ็งปๅใป้ธๆใใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: defaultTabs } });
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
tab1.focus();
await user.keyboard("{End}");
const tab3 = screen.getByRole("tab", { name: "Tab 3" });
expect(tab3).toHaveFocus();
expect(tab3).toHaveAttribute("aria-selected", "true");
});
it("disabled ใฟใใในใญใใใใฆๆฌกใฎๆๅนใชใฟใใซ็งปๅใใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: tabsWithDisabled } });
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
tab1.focus();
await user.keyboard("{ArrowRight}");
const tab3 = screen.getByRole("tab", { name: "Tab 3" });
expect(tab3).toHaveFocus();
expect(tab3).toHaveAttribute("aria-selected", "true");
});
});
describe("Manual Activation", () => {
it("็ขๅฐใญใผใงใใฉใผใซใน็งปๅใใใใใใซใฏๅใๆฟใใใชใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: defaultTabs, activationMode: "manual" } });
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
tab1.focus();
await user.keyboard("{ArrowRight}");
const tab2 = screen.getByRole("tab", { name: "Tab 2" });
expect(tab2).toHaveFocus();
expect(tab1).toHaveAttribute("aria-selected", "true");
expect(tab2).toHaveAttribute("aria-selected", "false");
expect(screen.getByRole("tabpanel")).toHaveTextContent("Content 1");
});
it("Enter ใงใใฉใผใซในไธญใฎใฟใใ้ธๆใใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: defaultTabs, activationMode: "manual" } });
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
tab1.focus();
await user.keyboard("{ArrowRight}");
await user.keyboard("{Enter}");
const tab2 = screen.getByRole("tab", { name: "Tab 2" });
expect(tab2).toHaveAttribute("aria-selected", "true");
expect(screen.getByRole("tabpanel")).toHaveTextContent("Content 2");
});
it("Space ใงใใฉใผใซในไธญใฎใฟใใ้ธๆใใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: defaultTabs, activationMode: "manual" } });
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
tab1.focus();
await user.keyboard("{ArrowRight}");
await user.keyboard(" ");
const tab2 = screen.getByRole("tab", { name: "Tab 2" });
expect(tab2).toHaveAttribute("aria-selected", "true");
expect(screen.getByRole("tabpanel")).toHaveTextContent("Content 2");
});
});
});
describe("APG: ใญใผใใผใๆไฝ (Vertical)", () => {
it("ArrowDown ใงๆฌกใฎใฟใใซ็งปๅใป้ธๆใใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: defaultTabs, orientation: "vertical" } });
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
tab1.focus();
await user.keyboard("{ArrowDown}");
const tab2 = screen.getByRole("tab", { name: "Tab 2" });
expect(tab2).toHaveFocus();
expect(tab2).toHaveAttribute("aria-selected", "true");
});
it("ArrowUp ใงๅใฎใฟใใซ็งปๅใป้ธๆใใ", async () => {
const user = userEvent.setup();
render(Tabs, {
props: { tabs: defaultTabs, orientation: "vertical", defaultSelectedId: "tab2" },
});
const tab2 = screen.getByRole("tab", { name: "Tab 2" });
tab2.focus();
await user.keyboard("{ArrowUp}");
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
expect(tab1).toHaveFocus();
expect(tab1).toHaveAttribute("aria-selected", "true");
});
it("ArrowDown/Up ใงใซใผใใใ", async () => {
const user = userEvent.setup();
render(Tabs, {
props: { tabs: defaultTabs, orientation: "vertical", defaultSelectedId: "tab3" },
});
const tab3 = screen.getByRole("tab", { name: "Tab 3" });
tab3.focus();
await user.keyboard("{ArrowDown}");
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
expect(tab1).toHaveFocus();
});
});
describe("APG: ARIA ๅฑๆง", () => {
it('tablist ใ role="tablist" ใๆใค', () => {
render(Tabs, { props: { tabs: defaultTabs } });
expect(screen.getByRole("tablist")).toBeInTheDocument();
});
it('ๅใฟใใ role="tab" ใๆใค', () => {
render(Tabs, { props: { tabs: defaultTabs } });
const tabs = screen.getAllByRole("tab");
expect(tabs).toHaveLength(3);
});
it('ๅใใใซใ role="tabpanel" ใๆใค', () => {
render(Tabs, { props: { tabs: defaultTabs } });
expect(screen.getByRole("tabpanel")).toBeInTheDocument();
});
it('้ธๆไธญใฟใใ aria-selected="true"ใ้้ธๆใ "false"', () => {
render(Tabs, { props: { tabs: defaultTabs } });
const tabs = screen.getAllByRole("tab");
expect(tabs[0]).toHaveAttribute("aria-selected", "true");
expect(tabs[1]).toHaveAttribute("aria-selected", "false");
expect(tabs[2]).toHaveAttribute("aria-selected", "false");
});
it("้ธๆไธญใฟใใฎ aria-controls ใใใใซ id ใจไธ่ด", () => {
render(Tabs, { props: { tabs: defaultTabs } });
const selectedTab = screen.getByRole("tab", { name: "Tab 1" });
const tabpanel = screen.getByRole("tabpanel");
const ariaControls = selectedTab.getAttribute("aria-controls");
expect(ariaControls).toBe(tabpanel.id);
});
it("ใใใซใฎ aria-labelledby ใใฟใ id ใจไธ่ด", () => {
render(Tabs, { props: { tabs: defaultTabs } });
const selectedTab = screen.getByRole("tab", { name: "Tab 1" });
const tabpanel = screen.getByRole("tabpanel");
const ariaLabelledby = tabpanel.getAttribute("aria-labelledby");
expect(ariaLabelledby).toBe(selectedTab.id);
});
it("aria-orientation ใ orientation prop ใๅๆ ใใ", () => {
render(Tabs, { props: { tabs: defaultTabs } });
expect(screen.getByRole("tablist")).toHaveAttribute(
"aria-orientation",
"horizontal"
);
});
});
describe("APG: ใใฉใผใซใน็ฎก็ (Roving Tabindex)", () => {
it("Automatic: ้ธๆไธญใฟใใฎใฟ tabIndex=0", () => {
render(Tabs, { props: { tabs: defaultTabs } });
const tabs = screen.getAllByRole("tab");
expect(tabs[0]).toHaveAttribute("tabIndex", "0");
expect(tabs[1]).toHaveAttribute("tabIndex", "-1");
expect(tabs[2]).toHaveAttribute("tabIndex", "-1");
});
it("Tab ใญใผใง tabpanel ใซ็งปๅใงใใ", async () => {
const user = userEvent.setup();
render(Tabs, { props: { tabs: defaultTabs } });
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
tab1.focus();
await user.tab();
expect(screen.getByRole("tabpanel")).toHaveFocus();
});
it("tabpanel ใ tabIndex=0 ใงใใฉใผใซในๅฏ่ฝ", () => {
render(Tabs, { props: { tabs: defaultTabs } });
const tabpanel = screen.getByRole("tabpanel");
expect(tabpanel).toHaveAttribute("tabIndex", "0");
});
});
// ๐ก Medium Priority: ใขใฏใปใทใใชใใฃๆค่จผ
describe("ใขใฏใปใทใใชใใฃ", () => {
it("axe ใซใใ WCAG 2.1 AA ้ๅใใชใ", async () => {
const { container } = render(Tabs, { props: { tabs: defaultTabs } });
const results = await axe(container);
expect(results).toHaveNoViolations();
});
});
describe("Props", () => {
it("defaultSelectedId ใงๅๆ้ธๆใฟใใๆๅฎใงใใ", () => {
render(Tabs, { props: { tabs: defaultTabs, defaultSelectedId: "tab2" } });
const tab2 = screen.getByRole("tab", { name: "Tab 2" });
expect(tab2).toHaveAttribute("aria-selected", "true");
expect(screen.getByRole("tabpanel")).toHaveTextContent("Content 2");
});
it("onSelectionChange ใใฟใ้ธๆๆใซๅผใณๅบใใใ", async () => {
const handleSelectionChange = vi.fn();
const user = userEvent.setup();
render(Tabs, {
props: { tabs: defaultTabs, onSelectionChange: handleSelectionChange },
});
await user.click(screen.getByRole("tab", { name: "Tab 2" }));
expect(handleSelectionChange).toHaveBeenCalledWith("tab2");
});
});
describe("็ฐๅธธ็ณป", () => {
it("defaultSelectedId ใๅญๅจใใชใๅ ดๅใๆๅใฎใฟใใ้ธๆใใใ", () => {
render(Tabs, { props: { tabs: defaultTabs, defaultSelectedId: "nonexistent" } });
const tab1 = screen.getByRole("tab", { name: "Tab 1" });
expect(tab1).toHaveAttribute("aria-selected", "true");
});
});
});