# Tabs

A card's panels switched by the locked segmented control: the picked pill slides to the next tab with its words changing color as it passes, and counts sit after the words.

Tier: free. Type: component. Category: navigation. Tags: motion, keyboard, run.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/tabs.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/tabs.tsx`.

## Preview

Live preview: https://pixilui.com/components/tabs

Knobs:

- `size`: `md`, `lg`

Signature: Click Cost and the pill slides across Trace and Logs, each word turning dark exactly as the pill passes under it.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/tabs.tsx, quiet https://pixilui.com/r/standalone/tabs.quiet.tsx.

## Code

`components/pixilui/tabs.tsx`

```tsx
"use client";

import { createContext, forwardRef, useContext, useId, useLayoutEffect, useState, type ComponentPropsWithoutRef, type ReactNode } from "react";
import { cn } from "./lib/utils";
import { SegmentedControlCore, type SegmentedOption, type SegmentedPickBy } from "./segmented-control";

/*
  Tabs (B7, locked 1 Dec 2026): the locked segmented control as a tab list. Its options name panels, so it is role
  tablist with aria-selected and aria-controls, and each panel is role tabpanel, focusable, hidden unless picked
  (segmented.js with data-panel). The pill slides on a click and jumps on arrows, Home and End.
*/

type TabsContext = { value: string; pick: (value: string, by: SegmentedPickBy) => void; id: string; setFirst: (value: string) => void };
const Context = createContext<TabsContext | null>(null);
const useTabs = (part: string) => {
  const c = useContext(Context);
  if (!c) throw new Error(`${part} must be inside <Tabs>`);
  return c;
};
const panelId = (id: string, value: string) => `${id}-p-${value}`;
const tabId = (id: string, value: string) => `${id}-t-${value}`;

export type TabsProps = Omit<ComponentPropsWithoutRef<"div">, "defaultValue" | "onChange"> & {
  /** The open tab, controlled. Pair with onValueChange. */
  value?: string;
  /** The tab open at first when uncontrolled. Defaults to the first option of the list. */
  defaultValue?: string;
  /** Runs when a tab is picked, with how: pointer or key. */
  onValueChange?: (value: string, details: { by: SegmentedPickBy }) => void | Promise<void>;
  /** The list and its panels. */
  children?: ReactNode;
};

/** A card's panels switched by the locked segmented control: the picked pill slides to the next tab. */
export const Tabs = forwardRef<HTMLDivElement, TabsProps>(function Tabs({ value: valueProp, defaultValue, onValueChange, children, ...rest }, ref) {
  const id = useId().replace(/:/g, "");
  const [inner, setInner] = useState(defaultValue ?? "");
  // with no value yet, the list's first tab is open
  const [first, setFirst] = useState("");
  const value = valueProp ?? (inner || first);
  const pick = (next: string, by: SegmentedPickBy) => {
    if (valueProp === undefined) setInner(next);
    void onValueChange?.(next, { by });
  };
  return (
    <Context.Provider value={{ value, pick, id, setFirst }}>
      <div ref={ref} {...rest}>
        {children}
      </div>
    </Context.Provider>
  );
});

export type TabsListProps = Omit<ComponentPropsWithoutRef<"div">, "defaultValue" | "onChange" | "children"> & {
  /** The tabs, in order. A string is both the value and the words; add count for "Trace 7". */
  options: readonly SegmentedOption[];
  /** md is 32 tall in all, lg 36. */
  size?: "md" | "lg";
  /** Icon-only tabs: one tooltip travels along the row. */
  tipGroup?: boolean;
  /** What the panels belong to, for screen readers ("Run"). */
  "aria-label": string;
};

/** The tab list: the locked segmented control, role tablist. */
export const TabsList = forwardRef<HTMLDivElement, TabsListProps>(function TabsList({ options, ...rest }, ref) {
  const tabs = useTabs("TabsList");
  const first = (typeof options[0] === "string" ? options[0] : options[0]?.value) ?? "";
  const { setFirst } = tabs;
  useLayoutEffect(() => setFirst(first), [setFirst, first]);
  return (
    <SegmentedControlCore
      ref={ref}
      options={options}
      value={tabs.value || first}
      onValueChange={(v, d) => tabs.pick(v, d.by)}
      panels={(v) => panelId(tabs.id, v)}
      optionId={(v) => tabId(tabs.id, v)}
      {...rest}
    />
  );
});

export type TabsPanelProps = ComponentPropsWithoutRef<"div"> & {
  /** The option of the list this panel belongs to. */
  value: string;
  /** Keep the panel in the page while hidden (it is hidden either way). On by default, as the locked page does. */
  keepMounted?: boolean;
};

/** One panel: shown while its tab is picked, focusable so the keyboard can reach long content. */
export const TabsPanel = forwardRef<HTMLDivElement, TabsPanelProps>(function TabsPanel({ value, keepMounted = true, className, children, ...rest }, ref) {
  const tabs = useTabs("TabsPanel");
  const open = tabs.value === value;
  return (
    <div
      ref={ref}
      role="tabpanel"
      id={panelId(tabs.id, value)}
      aria-labelledby={tabId(tabs.id, value)}
      tabIndex={0}
      hidden={!open}
      className={cn(className)}
      {...rest}
    >
      {open || keepMounted ? children : null}
    </div>
  );
});
```

## Usage

When to use:

- Switching the panels of one card: a run's Overview, Trace, Logs and Cost; an agent's General, Tools, Permissions and Memory.
- Two to five short tab names, with a count where it helps (Trace 7).

When not to use:

- Picking a value that changes the same view: use the segmented control.
- Moving between pages: use links in the navigation.
- More than five panels: use a list that opens each one.

```tsx
import { Tabs, TabsList, TabsPanel } from "@/components/pixilui/tabs";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  size: ["md", "lg"],
} as const;

const steps = [
  ["0:00", "Read the ticket from Lena Ortiz"],
  ["0:06", "Looked up two charges in Billing"],
  ["0:19", "Matched the duplicate charge of $214.00"],
  ["0:24", "Asked Maya Rao to approve the refund"],
  ["1:31", "Refunded $214.00 to Visa ending 4242"],
  ["1:39", "Added a note to her account"],
  ["1:48", "Replied to Lena"],
];
const facts = [
  ["Outcome", "Refunded $214.00 to Visa ending 4242"],
  ["Approved by", "Maya Rao, 9:47 AM"],
  ["Took", "1m 48s, 3 tools, $4.20"],
];
const logs = [
  ["0:00", "run 4f9a started by Maya Rao"],
  ["0:02", "stripe.charges.list customer=cus_R82kd0"],
  ["0:03", "2 charges found for Nov 14"],
  ["0:05", "duplicate ch_3Pq81x $214.00"],
  ["0:41", "approval requested from Maya Rao"],
  ["1:02", "approved"],
  ["1:04", "stripe.refunds.create ch_3Pq81x"],
  ["1:06", "refund re_3Pq9Ad pending"],
  ["1:21", "zendesk.tickets.update 88214"],
  ["1:30", "email queued to lena.ortiz"],
  ["1:39", "note added to the account"],
  ["2:14", "run 4f9a finished"],
];

const costs = [
  ["Model", "$2.86"],
  ["Billing lookups", "$0.94"],
  ["Refund API", "$0.40"],
];

/** A finished run's card: Overview, Trace with its 7 steps, its 12 Logs and Cost, as the lock shows it. */
export default function TabsDemo({ size = "md" }: KnobValues<typeof knobs>) {
  return (
    <Tabs defaultValue="trace" className="flex w-full max-w-xl flex-col gap-4 rounded-panel bg-surface p-6 elevation-raised">
      <div className="flex flex-col">
        <span className="type-label font-medium text-foreground">Refund for Lena Ortiz</span>
        <span className="type-caption text-muted">Run 4f9a, finished 2 minutes ago</span>
      </div>
      <div>
        <TabsList
          aria-label="Run"
          size={size}
          options={[
            { value: "overview", label: "Overview" },
            { value: "trace", label: "Trace", count: 7 },
            { value: "logs", label: "Logs", count: 12 },
            { value: "cost", label: "Cost" },
          ]}
        />
      </div>
      <div className="h-72 overflow-auto">
        <TabsPanel value="overview">
          <dl className="flex flex-col gap-2.5">
            {facts.map(([k, v]) => (
              <div key={k} className="flex justify-between gap-4 type-label">
                <dt className="text-muted">{k}</dt>
                <dd className="text-end text-foreground tabular-nums">{v}</dd>
              </div>
            ))}
          </dl>
        </TabsPanel>
        <TabsPanel value="trace">
          <ol className="flex flex-col">
            {steps.map(([t, s]) => (
              <li key={t} className="grid grid-cols-[52px_1fr] gap-3 py-1.5 type-label">
                <span className="type-caption text-muted tabular-nums">{t}</span>
                <span className="text-foreground">{s}</span>
              </li>
            ))}
          </ol>
        </TabsPanel>
        <TabsPanel value="logs">
          <ol className="flex flex-col">
            {logs.map(([t, line]) => (
              <li key={t} className="grid grid-cols-[52px_1fr] gap-3 py-1 type-caption">
                <span className="text-muted tabular-nums">{t}</span>
                <span className="font-mono text-secondary">{line}</span>
              </li>
            ))}
          </ol>
        </TabsPanel>
        <TabsPanel value="cost">
          <dl className="flex flex-col gap-2.5">
            {costs.map(([k, v]) => (
              <div key={k} className="flex justify-between gap-4 type-label">
                <dt className="text-muted">{k}</dt>
                <dd className="text-foreground tabular-nums">{v}</dd>
              </div>
            ))}
            <div className="flex justify-between gap-4 border-t border-divider pt-2.5 type-label font-medium">
              <dt className="text-foreground">This run</dt>
              <dd className="text-foreground tabular-nums">$4.20</dd>
            </div>
          </dl>
        </TabsPanel>
      </div>
    </Tabs>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode` |  | The list and its panels. |
| `value` | `string` |  | The open tab, controlled. Pair with onValueChange. |
| `defaultValue` | `string` |  | The tab open at first when uncontrolled. Defaults to the first option of the list. |
| `onValueChange` | `(value: string, details: { by: SegmentedPickBy }) => void \| Promise<void>` |  | Runs when a tab is picked, with how: pointer or key. |

Also accepts every native `<div>` attribute except `defaultValue`, `onChange`, and a ref to it.

## Keyboard

- `Tab`: Moves focus to the open tab, then into its panel.
- `ArrowLeft` + `ArrowRight`: Opens the previous or next tab at once, wrapping.
- `Home` + `End`: Opens the first or last tab.

## Accessibility

- A tablist of tabs with aria-selected and aria-controls; each panel is role tabpanel, named by its tab, focusable so long content can be scrolled by keyboard.
- One tab stop in the list: the open tab. Hidden panels are hidden.
- The pill and the clipped copy of the words are aria-hidden.

## Motion

- A click slides the pill to the new tab and resizes it, 240ms on ease-in-out, interruptibly; the words in the picked color move with it.
- Keyboard picks jump. A list inside a panel that was hidden places itself at once when it shows.
- Reduced motion: everything at once.

## Responsive

- The list is as wide as its tabs. Keep tab names short so it fits at 375 wide; panels fill their container.

## Performance

- The list is the segmented control: CSS in the foundation (section 8), four custom properties per pick.

## Notes for AI

- <Tabs defaultValue="trace"><TabsList aria-label="Run" options={[{ value: "overview", label: "Overview" }, { value: "trace", label: "Trace", count: 7 }]} /><TabsPanel value="overview">...</TabsPanel><TabsPanel value="trace">...</TabsPanel></Tabs>.
- Controlled with value and onValueChange(value, { by }). With no value, the first tab is open.
- Panels stay in the page while hidden (keepMounted); pass keepMounted={false} to drop a heavy panel's content when it hides.
- Per-style rule: quiet wears the locked quiet group (foundation.css section 8), as the segmented control does.

## Related

- [Segmented control](https://pixilui.com/components/segmented-control/markdown): One choice from two to five on a grey track: the picked pill slides to your next pick, its words changing color as it passes, and a time-boxed option says when it ends and switches back.
- [Dropdown menu](https://pixilui.com/components/dropdown-menu/markdown): The base for every menu, select and picker: it grows out of its trigger, a highlight glides between rows, and rows can be actions, choices that say what they cost, checkboxes, switches or submenus.
