# Toggle

A two-state button (WAI-ARIA Button pattern, toggle variant). The pressed state flips optimistically and the button carries `data-pending` while `pressedChangeAction` runs.

## Anatomy

```tsx
import { Toggle } from "@funstack/ui/toggle";

<Toggle pressedChangeAction={setFavorite}>Favorite</Toggle>
```

One plain component, no parts. It renders `<button type="button" aria-pressed>`.

```tsx title="ToggleFavorite.tsx"
"use client";
import { Toggle } from "@funstack/ui/toggle";
import { fakeSave } from "./fake-api.js";

// Uncontrolled Toggle with an async action. The star flips at once (optimistic), the button
// carries data-pending for the 800 ms the save takes, and a second click while pending wins.
export function ToggleFavorite() {
  return (
    <Toggle className="demo-toggle" pressedChangeAction={(next) => fakeSave(`favorite=${next}`)}>
      {({ pressed, pending }) => (
        <>
          {pending ? (
            <span className="demo-spinner" aria-hidden />
          ) : (
            <span aria-hidden>{pressed ? "★" : "☆"}</span>
          )}
          Favorite
        </>
      )}
    </Toggle>
  );
}
```

```css title="toggle.css"
/* Toggle: data attributes carry library state; :hover / :focus-visible come from the platform. */
.demo-toggle {
  display: inline-flex;
  align-items: center;
  gap: 0.4em;
  padding: 0.4em 0.9em;
  border: 1px solid var(--color-border);
  border-radius: 999px;
  background: var(--color-bg);
  color: var(--color-text);
  font: inherit;
  cursor: pointer;
  /* The optimistic flip is a sync commit, so it animates with a plain CSS transition. */
  transition:
    background-color 120ms,
    color 120ms,
    border-color 120ms;
}

.demo-toggle[data-pressed] {
  background: var(--color-primary);
  border-color: var(--color-primary);
  color: var(--color-on-primary);
}

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

.demo-toggle[data-disabled] {
  opacity: 0.5;
  cursor: not-allowed;
}

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

@media (prefers-reduced-motion: reduce) {
  .demo-toggle {
    transition: none;
  }
}
```

## Props

| Prop | Type | Default | Description |
| - | - | - | - |
| `pressed` | `boolean` | – | Controlled pressed state. undefined means uncontrolled. |
| `defaultPressed` | `boolean` | `false` | Initial pressed state in uncontrolled mode. |
| `pressedChangeAction` | `ChangeAction<boolean, TogglePressedChangeDetails>` | – | Called with the next pressed state on every user-initiated change. Runs inside the Toggle's transition; may be sync or async. Rejections reach the nearest Error Boundary. `details` carries `reason`, always `"activate"` (a button has no platform path; every change details type has the field), and `event` (the native click event; keyboard activation also arrives as a click). |
| `disabled` | `boolean` | `false` | Never dispatches. Native `disabled` on a `<button>`; with a link or component `render`, `aria-disabled="true"` instead (the element stays focusable). Inside a Toolbar `aria-disabled="true"` on every element, so the Toggle stays in the arrow sequence. 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: ToggleState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ToggleState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: ToggleState) => ReactNode)` | – | Rendered from optimistic state; must not suspend. |
| `render` | `ReactElement \| ((props, state: ToggleState) => ReactNode)` | – | Replace the default \<button> (element form) or take over rendering (function form). |

- **State**: `ToggleState` is `{ pressed, pending, disabled }`; `pressed` is optimistic.
- **Owned**: `aria-pressed`, `disabled`, `aria-disabled` (inside a Toolbar, or a link or component `render`), `onClick`, `data-pressed`, `data-pending`, `data-disabled`.

Every other `<button>` prop passes through; `type` defaults to `"button"` and a `render` element's own `type` wins. No `transition` prop: everything a Toggle renders is optimistic (see Optimistic and pending). No `readOnly` either: a Toggle is not a form control and the `button` role has no read-only state; a toggle the user may not change is `disabled` (focusable inside a Toolbar).

## Data attributes

| Attribute | On | Meaning |
| - | - | - |
| `data-pressed` | Toggle | Optimistically pressed. |
| `aria-pressed` | Toggle | `"true"` or `"false"`, optimistic. |
| `data-pending` | Toggle | `pressedChangeAction` is in flight. |
| `data-disabled` | Toggle | The `disabled` prop (also matches `:disabled`, except inside a Toolbar, where the button is `aria-disabled`). |

## Keyboard and ARIA

| Key | Behaviour |
| - | - |
| Enter / Space / Click | Toggles (native button activation). |
| Tab | Focusable unless disabled (inside a Toolbar a disabled Toggle stays focusable). |

- `aria-pressed` is always `"true"` or `"false"`, never `"mixed"`, and follows the optimistic state.
- Keep the accessible name stable: the label should not change with the pressed state (swap an icon, not the text).
- The button is not disabled while pending. A second click while pending reverses the first, and the latest click wins.

## Transition types

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

`fsui-toggle` plus `fsui-toggle-press` or `fsui-toggle-release`.

## Optimistic and pending

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

`aria-pressed` and `data-pressed` follow the optimistic state; `data-pending` is on the Toggle while `pressedChangeAction` is in flight. Animate the pressed flip with a CSS transition on `[data-pressed]`. The Toggle has no `transition` prop; to animate the commit that ends the action (for example a spinner turning back into an icon), wrap the content in your own `<ViewTransition>` keyed on the `fsui-toggle` types.

### Walkthrough

1. Click: `aria-pressed` and `data-pressed` flip at once, `data-pending` appears, `pressedChangeAction(true, details)` runs.
2. Resolve: in uncontrolled mode the value is committed; `data-pending` goes. In controlled mode the parent's `pressed` decides.
3. Reject: the pressed state rolls back and the error reaches the nearest Error Boundary.
4. Click again while pending: the next value is the opposite of the _optimistic_ value, so the second click undoes the first. Only the latest dispatch commits.

```tsx title="ToggleErrors.tsx"
"use client";
import { startTransition, useRef, useState } from "react";
import { Toggle } from "@funstack/ui/toggle";
import { DemoErrorBoundary } from "./DemoErrorBoundary.js";
import { fakeSave } from "./fake-api.js";

// Two ways to handle a failing action.
export function ToggleErrors() {
  return (
    <div className="demo-row">
      <ControlledWithInlineError />
      <DemoErrorBoundary>
        <Toggle
          className="demo-toggle"
          pressedChangeAction={(next) => fakeSave(`notify=${next}`, { fail: true })}
        >
          {({ pending }) => (
            <>{pending && <span className="demo-spinner" aria-hidden />}Notify me</>
          )}
        </Toggle>
      </DemoErrorBoundary>
    </div>
  );
}

// Controlled, "update on success": the parent adopts the value only after the save succeeds.
// Every second save fails; the error is caught inside the action, so the Toggle snaps back.
function ControlledWithInlineError() {
  const [pinned, setPinned] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const saves = useRef(0);
  return (
    <span>
      <Toggle
        className="demo-toggle"
        pressed={pinned}
        pressedChangeAction={async (next) => {
          setError(null); // sync prefix: already a Transition update
          try {
            await fakeSave(`pinned=${next}`, { fail: ++saves.current % 2 === 0 });
            // After an await, wrap state updates in startTransition yourself.
            startTransition(() => setPinned(next));
          } catch (e) {
            startTransition(() => setError(e instanceof Error ? e.message : String(e)));
          }
        }}
      >
        {({ pending }) => <>{pending && <span className="demo-spinner" aria-hidden />}Pin</>}
      </Toggle>
      {error && <span className="demo-inline-error"> {error}</span>}
    </span>
  );
}
```

The left Toggle catches its errors inline; the right one lets them reach a boundary.

## Suspense

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

No content region. The `children` function renders optimistic state and must not suspend.

## Browser-owned state

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

None: the pressed state is library-owned.

## Before hydration

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

Markup and ARIA. Pressing needs JavaScript.

## Recipes

Several toggles that share one value (text styles, an alignment choice) are a [ToggleGroup](toggle-group.md): one Tab stop, arrow keys between the items, and a set value with `added` / `removed` in the action's details.

### Controlled, local state

```tsx
const [muted, setMuted] = useState(false);

<Toggle pressed={muted} pressedChangeAction={(next) => { setMuted(next); }}>
  Mute
</Toggle>
```

### A Server Function, from a Server Component

```tsx
<Toggle defaultPressed={post.favorited} pressedChangeAction={setFavorite.bind(null, post.id)}>
  Favorite
</Toggle>
```

> **Disabling while pending**
>
> The library does not do it (native `disabled` would drop keyboard focus). Use `.toggle[data-pending] { pointer-events: none }`, or add `aria-busy` yourself.
