# Tabs

The WAI-ARIA Tabs pattern. Tabs and the indicator show the optimistic selection; panels show the committed one, so a panel that suspends keeps the current panel on screen while the selected tab shows `data-pending`.

## Anatomy

```tsx
import { Tabs } from "@funstack/ui/tabs";

<Tabs.Root defaultValue="general">          {/* div: state, transition, ids */}
  <Tabs.List aria-label="Settings">         {/* div[role=tablist]: arrow keys */}
    <Tabs.Tab value="general">General</Tabs.Tab>   {/* button[role=tab] */}
    <Tabs.Tab value="billing">Billing</Tabs.Tab>
    <Tabs.Indicator />                      {/* span: optional marker, after the Tabs */}
  </Tabs.List>
  <Tabs.Panel value="general">...</Tabs.Panel>     {/* div[role=tabpanel] */}
  <Tabs.Panel value="billing">...</Tabs.Panel>
</Tabs.Root>
```

The Indicator ships no styles and is an empty span. The library sets its `position-anchor` to the selected Tab; your CSS positions it against that Tab with CSS Anchor Positioning. The least CSS for an underline (class names are yours):

```css
.list { position: relative; display: flex; }
.indicator { position: absolute; bottom: 0; left: anchor(left); width: anchor-size(width);
             height: 3px; background: royalblue; }
```

Ids and `aria-controls` / `aria-labelledby` are wired from `value`; Tabs and Panels do not need to be registered or kept in the same order. A Tab names its Panel in `aria-controls` only while that Panel is mounted: an unselected Panel is not rendered by default, and during a pending switch the newly selected Tab names its Panel from the commit that mounts it. Give the List an accessible name (`aria-label` or `aria-labelledby`).

```tsx title="TabsSuspending.tsx"
"use client";
import { Suspense, use, useState } from "react";
import { Tabs } from "@funstack/ui/tabs";
import { sleep } from "./fake-api.js";

// Cache the promises so `use()` sees the same one on every render.
const cache = new Map<string, Promise<string[]>>();
function loadOrders(status: string): Promise<string[]> {
  let promise = cache.get(status);
  if (promise === undefined) {
    promise = sleep(1200).then(() => [1, 2, 3].map((n) => `${status} order #${n}0${n}`));
    cache.set(status, promise);
  }
  return promise;
}

function Orders({ status }: { status: string }) {
  const orders = use(loadOrders(status));
  return (
    <ul>
      {orders.map((order) => (
        <li key={order}>{order}</li>
      ))}
    </ul>
  );
}

const statuses = ["Open", "Shipped", "Returned"];
const tabs = ["Summary", ...statuses];

// Panels suspend while their data loads. The Suspense boundary sits above Tabs.Root, yet its
// fallback never replaces a loaded panel: selection is a transition, so the old panel stays
// (dimmed through .demo-tabs[data-pending]) and the selected tab shows a spinner.
export function TabsSuspending() {
  const [generation, setGeneration] = useState(0);
  return (
    <>
      <Suspense key={generation} fallback={<p>Loading orders…</p>}>
        <Tabs.Root className="demo-tabs" defaultValue="Summary">
          <Tabs.List className="demo-tabs-list" aria-label="Orders">
            {tabs.map((status) => (
              <Tabs.Tab key={status} value={status} className="demo-tab">
                {({ pending }) => (
                  <>
                    {status}
                    {pending && <span className="demo-spinner" aria-hidden />}
                  </>
                )}
              </Tabs.Tab>
            ))}
            <Tabs.Indicator className="demo-tabs-indicator" />
          </Tabs.List>
          {/* The first panel needs no data, so the server-rendered HTML is complete. */}
          <Tabs.Panel value="Summary" className="demo-tab-panel">
            <p>Pick a status. Each list takes 1.2 s to load the first time.</p>
          </Tabs.Panel>
          {statuses.map((status) => (
            <Tabs.Panel key={status} value={status} className="demo-tab-panel">
              <Orders status={status} />
            </Tabs.Panel>
          ))}
        </Tabs.Root>
      </Suspense>
      <button
        type="button"
        className="demo-button"
        onClick={() => {
          cache.clear();
          setGeneration((g) => g + 1);
        }}
      >
        Clear the cache and start over
      </button>
    </>
  );
}
```

```css title="tabs.css"
/* Tabs: optimistic selection on tabs and the indicator, committed selection on panels. */
.demo-tabs-list {
  /* The Indicator is absolutely positioned against the Tabs (its anchors) inside the list. */
  position: relative;
  display: flex;
  gap: 4px;
  border-bottom: 1px solid var(--color-border);
}

.demo-tab {
  display: inline-flex;
  align-items: center;
  gap: 0.4em;
  padding: 0.5em 0.9em;
  border: none;
  background: none;
  color: var(--color-text-secondary);
  font: inherit;
  cursor: pointer;
  transition: color 120ms;
}

.demo-tab[data-selected] {
  color: var(--color-primary);
}

.demo-tab[data-pending] {
  cursor: progress;
}

.demo-tab[aria-disabled="true"] {
  opacity: 0.4;
  cursor: not-allowed;
}

.demo-tab:focus-visible {
  outline: 2px solid var(--color-primary);
  outline-offset: -2px;
}

/* CSS Anchor Positioning places the indicator under the optimistic tab; a CSS transition
   slides it. */
.demo-tabs-indicator {
  position: absolute;
  bottom: -1px;
  left: anchor(left);
  width: anchor-size(width);
  height: 3px;
  border-radius: 2px;
  background: var(--color-primary);
  transition:
    left 200ms ease-out,
    width 200ms ease-out;
}

.demo-tab-panel {
  padding: 12px 4px 0;
}

.demo-tab-panel :is(p, ul) {
  margin: 0 0 12px;
}

/* The old panel stays while the next one loads; dim it after a short delay. */
.demo-tabs[data-pending] .demo-tab-panel {
  opacity: 0.5;
  transition: opacity 150ms 150ms;
}

/* ViewTransition classes used by the `transition` prop on Tabs.Panel. */
::view-transition-old(.demo-slide-next) {
  animation: 180ms ease-in both demo-out-left;
}
::view-transition-new(.demo-slide-next) {
  animation: 180ms ease-out both demo-in-right;
}
::view-transition-old(.demo-slide-prev) {
  animation: 180ms ease-in both demo-out-right;
}
::view-transition-new(.demo-slide-prev) {
  animation: 180ms ease-out both demo-in-left;
}

@keyframes demo-out-left {
  to {
    opacity: 0;
    translate: -2rem 0;
  }
}
@keyframes demo-in-right {
  from {
    opacity: 0;
    translate: 2rem 0;
  }
}
@keyframes demo-out-right {
  to {
    opacity: 0;
    translate: 2rem 0;
  }
}
@keyframes demo-in-left {
  from {
    opacity: 0;
    translate: -2rem 0;
  }
}

@media (prefers-reduced-motion: reduce) {
  ::view-transition-group(*),
  ::view-transition-old(*),
  ::view-transition-new(*) {
    animation: none !important;
  }
  .demo-tabs-indicator,
  .demo-tab {
    transition: none;
  }
}
```

## Props

### `Tabs.Root`

| Prop | Type | Default | Description |
| - | - | - | - |
| `value` | `V \| null` | – | Controlled selected value. null selects nothing; undefined means uncontrolled. `V` is the item value type: a declared union you pass is kept, a literal is `string` ([Typed values](../concepts/action-props.md#typed-values)). |
| `defaultValue` | `V \| null` | `null` | Initial value in uncontrolled mode. A development warning fires when neither value nor defaultValue is passed; pass defaultValue={null} to start empty on purpose. |
| `valueChangeAction` | `ChangeAction<V, TabsValueChangeDetails>` | – | Runs inside the Root's transition whenever a tab is selected. Sync or async; rejections reach the nearest Error Boundary and roll the selection back. `details.reason` (a `ChangeReason`) is `"activate"` (click, Enter/Space, or focus in automatic mode) or `"platform"` (find-in-page revealed a `keepMounted="until-found"` panel; `event` is the `beforematch` event). |
| `orientation` | `"horizontal" \| "vertical"` | `"horizontal"` | Layout and arrow-key axis. |
| `activationMode` | `"automatic" \| "manual"` | `"automatic"` | automatic: selection follows focus. manual: arrow keys only move focus; Enter, Space or click selects. |
| `loop` | `boolean` | `true` | Whether arrow keys wrap from the last tab to the first. |
| `disabled` | `boolean` | `false` | Disables every Tab (still focusable, never dispatches). A click on a disabled control runs no `onClick`, a `render` element's included ([unavailable parts](../concepts/render.md#unavailable)). |
| `className` | `string \| ((state: TabsRootState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: TabsRootState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: TabsRootState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: TabsRootState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `TabsRootState` is `{ value, pending, orientation, disabled }`; `value` is the optimistic selection.
- **Owned**: `data-pending`, `data-orientation`, `data-disabled`.

### `Tabs.List`

| Prop | Type | Default | Description |
| - | - | - | - |
| `experimental_focusGroup` | `boolean` | `false` | Renders `focusgroup="tablist … nomemory"` and `focusgroupstart` on the selected tab; where the browser implements it (Chromium), the browser handles arrow keys, Home and End, and unselected tabs drop `tabindex="-1"` after hydration (Chromium leaves negative-tabindex elements out of the focusgroup). The JS path stays active elsewhere. |
| `className` | `string \| ((state: TabsListState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: TabsListState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: TabsListState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: TabsListState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `TabsListState` is `{ orientation, disabled }`.
- **Owned**: `role` (`"tablist"`), `aria-orientation`, `tabIndex`, `onKeyDown`, `onFocus`, `focusgroup` (the token list with the flag, removed otherwise), `data-orientation`, `data-disabled`.

### `Tabs.Tab`

| Prop | Type | Default | Description |
| - | - | - | - |
| `value` | `V` | – | Required. The value this tab selects; unique within the Root. `V` is `string` unless you pass a type argument, which checks the value ([Typed values](../concepts/action-props.md#typed-values)). |
| `disabled` | `boolean` | `false` | Focusable but inert: aria-disabled="true", never dispatches. A click runs no `onClick`, a `render` element's included, and is cancelled; a `render` element's `disabled` disables the part too ([unavailable parts](../concepts/render.md#unavailable)). |
| `className` | `string \| ((state: TabsTabState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: TabsTabState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: TabsTabState) => ReactNode)` | – | Rendered from optimistic state; must not suspend. |
| `render` | `ReactElement \| ((props, state: TabsTabState) => ReactNode)` | – | Replace the default \<button> (element form) or take over rendering (function form). |

- **State**: `TabsTabState` is `{ value, selected, pending, disabled, orientation }`.
- **Owned**: `role` (`"tab"`), `type` (on a `<button>`), `id`, `aria-selected`, `aria-controls` (token-merged; the Panel id only while a Panel with that `value` is mounted), `aria-disabled`, `tabIndex`, `focusgroupstart` (on the selected Tab with the flag, removed otherwise), `onClick`, `onKeyDown`, `onFocus`, `data-selected`, `data-pending`, `data-disabled`, `data-orientation`, and `anchor-name` in `style` for the Indicator (your `style` wins).

No `transition` prop: everything a Tab renders is optimistic. Animate the selection with a CSS `transition` on `[data-selected]`; to animate a tab's content when the action settles, wrap it in your own `<ViewTransition>` keyed on `fsui-tabs`.

### `Tabs.Panel`

| Prop | Type | Default | Description |
| - | - | - | - |
| `value` | `V` | – | Required. The tab this panel belongs to. `V` is `string` unless you pass a type argument, which checks the value ([Typed values](../concepts/action-props.md#typed-values)). |
| `keepMounted` | `boolean \| "until-found"` | `false` | `false`: hidden panels are not rendered. `true`: rendered inside `<Activity mode="hidden">` (DOM and state kept, effects stopped, not in server HTML); a popup open inside leaves the screen with the panel, still open and with no `onOpenChange`, and is shown again without moving focus when the tab is selected again (a modal Dialog takes focus). `"until-found"`: rendered with `hidden="until-found"` (in the server HTML as plain `hidden`, upgraded after hydration; effects live); find-in-page or a text fragment selects the tab. A popup open inside leaves the screen and comes back with the panel in both modes. |
| `transition` | `ViewTransitionClass` | – | The class of the Panel's `<ViewTransition>`; without it no boundary is rendered. A string animates this Tabs' own switches and the Panel's own mount, unmount and `<Activity>` reveal (whatever caused them; [only as the top of what is inserted or removed](../concepts/transitions.md#mount-unmount)); not another Tabs, not an unrelated transition, not content that changes inside. A controlled `value` you change in your own transition needs a map keyed on `fsui-tabs` plus `addTransitionType("fsui-tabs")` ([recipe](../concepts/transitions.md#controlled)) for a `keepMounted="until-found"` Panel. A type map is React's: it names every Panel that has it and that a commit with its types reaches, and each plays the class; end it with `default: "none"` ([Type maps](../concepts/transitions.md#type-maps)). |
| `className` | `string \| ((state: TabsPanelState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: TabsPanelState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: TabsPanelState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: TabsPanelState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `TabsPanelState` is `{ value, selected, orientation, disabled }`; `selected` is committed, `disabled` is the Root's.
- **Owned**: `role` (`"tabpanel"`), `id`, `aria-labelledby` (token-merged), `hidden`, `data-selected`, `data-orientation`, `data-disabled`.

Panels get `tabIndex={0}` by default (APG); pass `tabIndex={-1}` when the panel starts with focusable content.

### `Tabs.Indicator`

| Prop | Type | Default | Description |
| - | - | - | - |
| `className` | `string \| ((state: TabsIndicatorState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: TabsIndicatorState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: TabsIndicatorState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: TabsIndicatorState) => ReactNode)` | – | Replace the default \<span> (element form) or take over rendering (function form). |

- **State**: `TabsIndicatorState` is `{ value, selected, pending, orientation }`; `selected` is `value !== null`.
- **Owned**: `aria-hidden`, `hidden`, `data-selected`, `data-pending`, `data-orientation`, and `position-anchor` in `style`.

A decorative span that follows the optimistic tab. Give it `position: absolute` and `anchor()` insets in CSS, and a CSS `transition` on them to slide. It must come after the Tabs inside the List.

## Data attributes

| Attribute | On | Meaning |
| - | - | - |
| `data-pending` | Root | A selection is in flight (including a suspending panel's wait). |
| `data-pending` | Tab | This tab is the one the user is waiting on. |
| `data-pending` | Indicator | Mirrors the Root. |
| `data-selected` | Tab, Indicator | Optimistic selection (immediate). |
| `data-selected` | Panel | Committed selection (relevant with `keepMounted`). |
| `data-disabled` | Root, List, Tab, Panel | Disabled by prop or by the Root. |
| `data-orientation` | every part | `"horizontal"` or `"vertical"`. |
| `aria-selected` | Tab | Optimistic selection. |
| `aria-disabled` | Tab | `"true"` when disabled (still focusable). |

```css
.tab[data-selected] { color: var(--accent); }
.tab[aria-disabled="true"] { opacity: 0.4; }
.tabs[data-pending] .panel { opacity: 0.6; transition: opacity 150ms 150ms; }
.indicator { position: absolute; left: anchor(left); width: anchor-size(width); transition: left 200ms, width 200ms; }
```

## Keyboard and ARIA

| Key | Where | Behaviour |
| - | - | - |
| ArrowRight / ArrowLeft | Tab, horizontal list | Next / previous Tab (swapped under `direction: rtl`); wraps if `loop`. |
| ArrowDown / ArrowUp | Tab, vertical list | Next / previous Tab; wraps if `loop`. |
| Home / End | Tab | First / last Tab, disabled or not. |
| Any of these with Alt, Ctrl or Meta, or already default-prevented | Tab | Not handled: the key is the browser's. |
| Enter / Space | Tab | Selects the focused Tab (the only way to select by keyboard in manual mode). |
| Tab | Tab | Leaves the list: the selected Tab is the only Tab stop (roving `tabindex`), and the Panel is next. |

- In automatic mode, moving focus between tabs selects. Focus entering the list from outside never selects.
- Disabled tabs are focusable with arrow keys (`aria-disabled`), but never selected.
- With no selection (`null`, or a value that matches no tab), the List itself is the Tab stop and hands focus to the first enabled tab.
- `aria-selected` follows the optimistic selection. `aria-orientation` is always set on the List.
- Key presses with Alt, Ctrl or Meta are left to the browser, and so is a key your own `onKeyDown` on a Tab prevented.

## Transition types

Concept: [Transitions & ViewTransition](../concepts/transitions.md#transition-types)

`fsui-tabs` plus `fsui-tabs-next` or `fsui-tabs-prev`: the DOM order of the new tab relative to the committed one. Only `fsui-tabs` when the order cannot be determined (no committed tab, or a value with no rendered Tab). These types are public API: key a `transition` map on them, and add them with `addTransitionType` for a controlled change ([Transitions](../concepts/transitions.md#controlled)). A string `transition` is keyed on an internal per-instance type instead, which this component's own dispatch adds.

## Optimistic and pending

Concept: [Pending & optimistic state](../concepts/pending-and-optimistic.md)

Tab and Indicator show the optimistic selection (`aria-selected`, `data-selected`); Panels show the committed one. `data-pending` is on the Root, on the Tab that is the optimistic selection, and mirrored on the Indicator; never on a Panel.

### Walkthrough

```tsx title="TabsSaved.tsx"
"use client";
import { Tabs } from "@funstack/ui/tabs";
import { DemoErrorBoundary } from "./DemoErrorBoundary.js";
import { fakeSave } from "./fake-api.js";

let saves = 0;

// Manual activation with an awaited save: arrow keys only move focus, Enter / Space / click
// select. The panel switches when the save resolves; every third save rejects, the selection
// rolls back and the error reaches the Error Boundary. Panels slide by DOM direction through
// the library's fsui-tabs-next / fsui-tabs-prev transition types.
export function TabsSaved() {
  return (
    <DemoErrorBoundary>
      <Tabs.Root
        className="demo-tabs"
        defaultValue="profile"
        activationMode="manual"
        valueChangeAction={async (next) => {
          await fakeSave(`tab "${next}"`, { fail: ++saves % 3 === 0 });
        }}
      >
        <Tabs.List className="demo-tabs-list" aria-label="Account settings">
          <Tabs.Tab value="profile" className="demo-tab">
            Profile
          </Tabs.Tab>
          <Tabs.Tab value="billing" className="demo-tab">
            Billing
          </Tabs.Tab>
          <Tabs.Tab value="danger" className="demo-tab" disabled>
            Danger zone
          </Tabs.Tab>
          <Tabs.Tab value="team" className="demo-tab">
            Team
          </Tabs.Tab>
          <Tabs.Indicator className="demo-tabs-indicator" />
        </Tabs.List>
        {["profile", "billing", "danger", "team"].map((value) => (
          <Tabs.Panel
            key={value}
            value={value}
            className="demo-tab-panel"
            transition={{
              "fsui-tabs-next": "demo-slide-next",
              "fsui-tabs-prev": "demo-slide-prev",
              default: "none",
            }}
          >
            <p>The {value} settings.</p>
          </Tabs.Panel>
        ))}
      </Tabs.Root>
    </DemoErrorBoundary>
  );
}
```

`tabs.css`: the same file as above.

1. Select Billing: the tab and indicator move immediately, the Root and the Billing tab get `data-pending`, the Profile panel stays.
2. The save resolves: the Billing panel replaces Profile in one commit, sliding by the `fsui-tabs-next` type.
3. The save rejects: the selection rolls back to the committed tab and the error reaches the Error Boundary.
4. Selecting another tab while one is pending replaces the intent; clicking the committed tab again is a real dispatch that cancels the pending switch.

> **Automatic activation and slow actions**
>
> With `activationMode="automatic"`, every arrow key press dispatches. Prefer `"manual"` when the action awaits a server round trip, or do not return the promise (`(next) => { void save(next); }`).

Without a `valueChangeAction` (uncontrolled), a switch does not wait for an action pending elsewhere in the app: the Tab moves at once and the Panel follows in a deferred render, which still keeps the old Panel while the new one suspends. With a `valueChangeAction`, or controlled, a switch also waits for any other action pending in the app: the Tab moves at once, the Root shows `data-pending`, and the Panel switches when that action settles. See [Pending actions hold other transitions](../concepts/action-props.md#pending-actions-hold-transitions).

## Suspense

Concept: [Suspense](../concepts/suspense.md)

A newly selected Panel that suspends keeps the current Panel on screen until it is ready, while the new Tab is already selected and pending. A `<Suspense>` inside the Panel shows its fallback instead. Tab content must not suspend.

## Browser-owned state

Concept: [Browser-owned state](../concepts/browser-owned-state.md)

Selection is library-owned. With `keepMounted="until-found"`, find-in-page or a text fragment can reveal a hidden panel; that is dispatched with `reason: "platform"`, and if a controlled parent refuses, the panel is hidden again once the action settles.

## Before hydration

Concept: [Server Components](../concepts/server-components.md#before-hydration)

Markup and ARIA. With `keepMounted="until-found"`, hidden panels are in the HTML (as plain `hidden`; find-in-page reaches them after hydration). Switching tabs needs JavaScript.

## Recipes

### <a id="router"></a>Controlled by a router

```tsx
// `section` comes from the URL; navigating is the state update.
<Tabs.Root value={section} valueChangeAction={(next) => navigate(`/settings/${next}`)}>
  ...
</Tabs.Root>
```

A controlled `value` that matches no tab is allowed (a sub-route without a tab): nothing is selected and a development warning explains it.

Whether the Panel's `transition` animates a switch, and whether a pending action holds it, depends on how the router renders a navigation. A router that keeps its state in an external store (TanStack Router) renders every navigation urgently: the Tab switches in a synchronous commit and the Panel in the deferred render that follows, and nothing holds either. The deferred commit starts a view transition around the Panel switch, but its types are not reliable: none for Back and Forward, and for a click only sometimes the direction. A class on the map's `default` animates every switch; a map keyed on the direction types alone animates nothing dependable. With such a router, use a `default` class, leave `transition` off the Panels, or mirror the value into React state ([Worked example: TanStack Router](../concepts/transitions.md#tanstack-router)).

React Router 8 hands a navigation's new route to React in `startTransition` unless the router has `useTransitions={false}` ([React Router](../concepts/react-router.md#use-transitions)). With the prop left out or `true`, the Tab shows the new value at once with `data-pending`, and the Panel switches when the new route renders, which a save pending elsewhere holds.

### Tabs as links

```tsx
<Tabs.Tab value="docs" render={<a href="/docs" />}>Docs</Tabs.Tab>
```

### Preserved panels and find-in-page

```tsx
{/* The draft survives switching tabs. */}
<Tabs.Panel value="editor" keepMounted>
  <DraftEditor />
</Tabs.Panel>

{/* In the server HTML and found by Ctrl+F; finding text selects the tab. */}
<Tabs.Panel value="changelog" keepMounted="until-found">
  <Changelog />
</Tabs.Panel>
```
