# Tabs
Panels shown one at a time, switched by a person or an agent.
Source page: https://dinachi.dev/docs/components/tabs

## Installation
```bash
npx @dinachi/cli@latest add tabs
```
Adds to your project:
- `components/ui/tabs/tabs.tsx`
- `components/ui/tabs/index.ts`
Installs:
- `@base-ui/react` ^1.9.0

## Usage
```tsx
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"

export function AccountTabs() {
  return (
    <Tabs defaultValue="account">
      <TabsList>
        <TabsTrigger value="account">Account</TabsTrigger>
        <TabsTrigger value="password">Password</TabsTrigger>
      </TabsList>
      <TabsContent value="account">Manage your account.</TabsContent>
      <TabsContent value="password">Change your password.</TabsContent>
    </Tabs>
  )
}
```

## Anatomy
```tsx
<Tabs>
  <TabsList>
    <TabsTrigger />
    <TabsIndicator />
  </TabsList>
  <TabsContent />
</Tabs>
```
- `Tabs`: Holds the active tab.
- `TabsList`: The row of tabs.
- `TabsTrigger`: One tab.
- `TabsContent`: The panel for one tab.
- `TabsIndicator`: Slides to the active tab. Needs a `relative` `TabsList`.

## Examples

### Default
Three panels, one showing at a time.
```tsx
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';

export function Example() {
  return (
    <Tabs defaultValue="account" className="w-full max-w-md">
      <TabsList>
        <TabsTrigger value="account">Account</TabsTrigger>
        <TabsTrigger value="password">Password</TabsTrigger>
        <TabsTrigger value="settings">Settings</TabsTrigger>
      </TabsList>
      <TabsContent value="account" className="space-y-2 pt-4">
        <h3 className="text-sm font-medium">Account</h3>
        <p className="text-sm text-muted-foreground">
          Manage your account settings and preferences.
        </p>
      </TabsContent>
      <TabsContent value="password" className="space-y-2 pt-4">
        <h3 className="text-sm font-medium">Password</h3>
        <p className="text-sm text-muted-foreground">
          Change your password and security settings.
        </p>
      </TabsContent>
      <TabsContent value="settings" className="space-y-2 pt-4">
        <h3 className="text-sm font-medium">Settings</h3>
        <p className="text-sm text-muted-foreground">
          Configure your application preferences.
        </p>
      </TabsContent>
    </Tabs>
  );
}
```

### Controlled
Hold the active tab in state to read or set it.
```tsx
import React from 'react';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';

export function Example() {
  const [activeTab, setActiveTab] = React.useState('overview');

  return (
    <div className="w-full max-w-md space-y-2">
      <Tabs value={activeTab} onValueChange={(val) => setActiveTab(val)}>
        <TabsList>
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="analytics">Analytics</TabsTrigger>
          <TabsTrigger value="reports">Reports</TabsTrigger>
        </TabsList>
        <TabsContent value="overview" className="pt-4">
          <div className="rounded-md border p-4">
            <p className="text-sm">Overview content for your dashboard.</p>
          </div>
        </TabsContent>
        <TabsContent value="analytics" className="pt-4">
          <div className="rounded-md border p-4">
            <p className="text-sm">Analytics data and charts.</p>
          </div>
        </TabsContent>
        <TabsContent value="reports" className="pt-4">
          <div className="rounded-md border p-4">
            <p className="text-sm">Generated reports and exports.</p>
          </div>
        </TabsContent>
      </Tabs>
      <p className="text-xs text-muted-foreground">Active tab: {activeTab}</p>
    </div>
  );
}
```

### With indicator
A bar that slides to the active tab.
```tsx
import { Tabs, TabsList, TabsTrigger, TabsContent, TabsIndicator } from '@/components/ui/tabs';

export function Example() {
  return (
    <Tabs defaultValue="music" className="w-full max-w-md">
      <TabsList className="relative">
        <TabsTrigger value="music">Music</TabsTrigger>
        <TabsTrigger value="podcasts">Podcasts</TabsTrigger>
        <TabsTrigger value="audiobooks">Audiobooks</TabsTrigger>
        <TabsIndicator />
      </TabsList>
      <TabsContent value="music" className="pt-4">
        <p className="text-sm text-muted-foreground">Browse your music library.</p>
      </TabsContent>
      <TabsContent value="podcasts" className="pt-4">
        <p className="text-sm text-muted-foreground">Discover new podcasts.</p>
      </TabsContent>
      <TabsContent value="audiobooks" className="pt-4">
        <p className="text-sm text-muted-foreground">Listen to audiobooks.</p>
      </TabsContent>
    </Tabs>
  );
}
```

### Disabled tab
Keep a tab visible but out of reach, for people and agents.
```tsx
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';

export function Example() {
  return (
    <Tabs defaultValue="active" className="w-full max-w-md">
      <TabsList>
        <TabsTrigger value="active">Active</TabsTrigger>
        <TabsTrigger value="disabled" disabled>Disabled</TabsTrigger>
        <TabsTrigger value="archived">Archived</TabsTrigger>
      </TabsList>
      <TabsContent value="active" className="pt-4">
        <p className="text-sm text-muted-foreground">Active content is visible here.</p>
      </TabsContent>
      <TabsContent value="archived" className="pt-4">
        <p className="text-sm text-muted-foreground">Archived items are shown here.</p>
      </TabsContent>
    </Tabs>
  );
}
```

## Notes

### Automatic changes
Uncontrolled Tabs pick a fallback when the active tab is missing or disabled, calling `onValueChange` with `details.reason` `"initial"`, `"missing"` or `"disabled"`. These cannot be cancelled.

## API reference
Props marked **agent** change what an agent reads or may do.

### Tabs
Holds the active tab.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `Value` | - | Controlled active tab. `null` shows none. |
| `defaultValue` | `Value` | `0` | Starting tab when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `orientation` | `"horizontal" \| "vertical"` | `"horizontal"` | Which arrow keys move between tabs. |
| `aria-label` **agent** | `string` | - | Names the tabs for the agent. Defaults to `tabs`. |

### TabsList
The row of tabs.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `activateOnFocus` | `boolean` | `false` | Selects a tab on arrow focus, not on Enter or Space. |
| `loopFocus` | `boolean` | `true` | Wraps arrow keys from last tab to first. |

### TabsTrigger
One tab.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `Value` | - | Matches its `TabsContent`. Also what `onValueChange` receives. |
| `children` **agent** | `ReactNode` | - | The tab's text; the agent selects by it. |
| `disabled` **agent** | `boolean` | `false` | Focusable but not selectable. Refused for agents. |

### TabsContent
The panel for one tab.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `Value` | - | The `TabsTrigger` value it belongs to. |
| `keepMounted` | `boolean` | `false` | Keeps the panel in the DOM while hidden. |

### TabsIndicator
Slides to the active tab. Needs a `relative` `TabsList`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `renderBeforeHydration` | `boolean` | `false` | Places the bar before hydration, so it shows sooner after SSR. |

## Agent
Inside an `AgentProvider`, Tabs appears in `agent.snapshot()` as `tabs`.
Reads:
- `label`: The Tabs' aria-label, or `tabs`.
- `value`: The active tab's label.
- `items`: Every tab's label, in order.
- `disabled`: True when every tab is disabled.
Actions:
- `select("Password")`: Selects by label, then value. A miss lists the tabs; disabled tabs are refused.
An agent's choice clicks the tab and reaches `onValueChange` with the agent's details. `isAgentChange(details)` is true for it; `details.cancel()` refuses it and the agent is told. Disabled tabs refuse on their own.
```ts
await agent.act({
  steps: [{ ref: "tabs", action: "select", args: ["Password"] }],
})
```

## Accessibility
- Tablist, tabs with `aria-selected`, and tabpanels labelled by their tab.
- With several tab sets on a page, give each an aria-label.
- Disabled tabs stay focusable and announced.
- Hidden panels leave the DOM unless `keepMounted` is set.
### Keyboard
| Keys | Does |
| --- | --- |
| `←` / `→` | Moves focus between tabs. ↑ and ↓ when vertical |
| `Home` / `End` | Moves focus to the first or last tab |
| `Space` / `Enter` | Selects the focused tab |
| `Tab` | Moves focus from the tab list into the open panel |

## Source
`components/ui/tabs/tabs.tsx`
```tsx
import * as React from "react";
import { Tabs as BaseTabs } from "@base-ui/react/tabs";
import { cn } from "@/lib/utils";
import {
  agentChoicesOf,
  changeAsAgent,
  matchAgentChoice,
  useAgentControl,
  useAgentItem,
  useHasAgent,
  useMergedRef,
  type AgentItems,
} from "@/components/ui/agent";

type Details = BaseTabs.Root.ChangeEventDetails;

const TabsAgentContext = React.createContext<AgentItems | null>(null);

/**
 * Base UI keeps the value, so its fallbacks for a missing or disabled tab still apply.
 * The agent selects a tab by clicking it, and the app sees that change with the agent's
 * details, which it can cancel.
 */
const Tabs = React.forwardRef<
  React.ComponentRef<typeof BaseTabs.Root>,
  React.ComponentProps<typeof BaseTabs.Root>
>(({ className, onValueChange, ...props }, ref) => {
  const element = React.useRef<HTMLDivElement | null>(null);
  const [items] = React.useState<AgentItems>(() => new Map());
  const pending = React.useRef<Details | null>(null);

  const change = (value: unknown, details: Details) => {
    const agent = pending.current;
    pending.current = null;
    onValueChange?.(value, agent ?? details);
    if (agent?.isCanceled) details.cancel();
  };

  useAgentControl(() => {
    const choices = agentChoicesOf(items);
    const active = [...items].find(([el]) => el.getAttribute("aria-selected") === "true")?.[1];
    const select = (wanted: unknown) => {
      const match = matchAgentChoice(choices, wanted);
      if (typeof match === "string") return match;
      const tab = [...items].find(([, v]) => v === match.value)?.[0];
      return changeAsAgent<unknown, Details>((_, details) => {
        pending.current = details;
        tab?.click();
        pending.current = null;
      }, match.value);
    };
    return {
      kind: "tabs",
      element: choices.length ? element.current : null,
      value: choices.find((c) => c.value === active)?.label ?? "",
      items: choices.map((c) => c.label),
      disabled: choices.length > 0 && choices.every((c) => c.disabled),
      actions: { select },
    };
  });

  return (
    <TabsAgentContext.Provider value={useHasAgent() ? items : null}>
      <BaseTabs.Root
        ref={useMergedRef(ref, element)}
        className={cn("w-full", className)}
        onValueChange={change}
        data-slot="tabs"
        {...props}
      />
    </TabsAgentContext.Provider>
  );
});
Tabs.displayName = "Tabs";

const TabsList = React.forwardRef<
  React.ComponentRef<typeof BaseTabs.List>,
  React.ComponentProps<typeof BaseTabs.List>
>(({ className, ...props }, ref) => (
  <BaseTabs.List
    ref={ref}
    className={cn(
      "inline-flex h-10 items-center justify-center rounded-md p-1 text-muted-foreground z-0",
      className
    )}
    data-slot="tabs-list"
    {...props}
  />
));
TabsList.displayName = "TabsList";

const TabsTrigger = React.forwardRef<
  React.ComponentRef<typeof BaseTabs.Tab>,
  React.ComponentProps<typeof BaseTabs.Tab>
>(({ className, ...props }, ref) => {
  const items = React.useContext(TabsAgentContext);
  const element = React.useRef<HTMLButtonElement | null>(null);
  useAgentItem(items, element, props.value);
  return (
  <BaseTabs.Tab
    ref={useMergedRef(ref, element)}
    data-agent-part={items ? "" : undefined}
    className={cn(
      "inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background",
      "transition-[color,background-color,box-shadow] duration-[var(--motion-duration-fast,150ms)]",
      "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
      "data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      "data-[active]:bg-muted data-[active]:text-foreground data-[active]:shadow-sm",
      "hover:text-foreground",
      className
    )}
    data-slot="tabs-trigger"
    {...props}
  />
  );
});
TabsTrigger.displayName = "TabsTrigger";

const TabsContent = React.forwardRef<
  React.ComponentRef<typeof BaseTabs.Panel>,
  React.ComponentProps<typeof BaseTabs.Panel>
>(({ className, ...props }, ref) => (
  <BaseTabs.Panel
    ref={ref}
    className={cn(
      "mt-2 ring-offset-background",
      "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
      className
    )}
    data-slot="tabs-content"
    {...props}
  />
));
TabsContent.displayName = "TabsContent";

const TabsIndicator = React.forwardRef<
  React.ComponentRef<typeof BaseTabs.Indicator>,
  React.ComponentProps<typeof BaseTabs.Indicator>
>(({ className, ...props }, ref) => (
  <BaseTabs.Indicator
    ref={ref}
    className={cn(
      "absolute bottom-0 left-0 z-10 h-1 w-[var(--active-tab-width)] -translate-y-1/2 translate-x-[var(--active-tab-left)] rounded-sm bg-muted-foreground",
      // The indicator moves between two on-screen positions rather than entering, so it
      // takes the in-out curve. Width is a layout property, but the indicator is
      // absolutely positioned and therefore out of flow, so animating it reflows only
      // itself. Naming the three properties keeps `all` from animating its colour and
      // shadow on every tab change as well.
      "transition-[transform,translate,width] duration-[var(--motion-duration-base,200ms)] ease-[var(--motion-ease-in-out,cubic-bezier(0.77,0,0.175,1))]",
      "motion-reduce:transition-none",
      className
    )}
    data-slot="tabs-indicator"
    {...props}
  />
));
TabsIndicator.displayName = "TabsIndicator";

export type TabsProps = React.ComponentProps<typeof BaseTabs.Root>;
export type TabsListProps = React.ComponentProps<typeof BaseTabs.List>;
export type TabsTriggerProps = React.ComponentProps<typeof BaseTabs.Tab>;
export type TabsContentProps = React.ComponentProps<typeof BaseTabs.Panel>;
export type TabsIndicatorProps = React.ComponentProps<typeof BaseTabs.Indicator>;

export {
  Tabs,
  TabsList,
  TabsTrigger,
  TabsContent,
  TabsIndicator,
};
```
