# Toggle Component

Two-state buttons that stay pressed, like Bold in an editor or a star on a repository, plus toggle groups: formatting toolbars, rows of outline toggles and segmented controls with a sliding indicator. One dependency-free Stimulus controller handles all of them. Free component.

## Features

- Standalone toggles and groups from one controller (`toggle-button`)
- State lives in `aria-pressed`: screen readers announce it and Tailwind's `aria-pressed:` variants style it
- Single-select, multi-select (`multiple`) and always-one-selected groups. Always-one-selected groups (alignment, segmented controls) are radio groups: `role="radio"` items with `aria-checked`, announced as "radio button, 2 of 3, checked"
- A group is one tab stop: arrow keys, Home and End move focus (RTL aware), Space and Enter press. In a radio group the arrows also select, like native radios
- Segmented controls with an indicator that slides and resizes to segments of any width, stays aligned on resize, and jumps instantly for keyboard presses and reduced motion
- Optional hidden input so toggles submit with a form: `1`/`0` standalone, comma-separated values for groups
- `toggle-button:change` event with the item, its value and every pressed value in the group
- Stays in sync with Turbo morphs, Turbo Streams that add or remove items, and scripts that set `aria-pressed` directly: the group rules still apply
- `press(value)` / `release(value)` API for your own controllers
- CSS-only examples on native checkboxes and radios for forms (with `collection_check_boxes` / `collection_radio_buttons`), filter chips and view switchers
- Pressed state stays visible in Windows High Contrast (forced colors) mode
- Console warnings for common setup mistakes: missing labels, items without a value, an unpositioned indicator, `multiple` with an indicator

## Implementation Options

| Option | Best for | Files |
|--------|----------|-------|
| ViewComponent | Ruby API: variants, sizes, items as slots, ARIA and Stimulus wiring written for you | `app/components/toggle/` |
| Shared partials | Same options and markup as the ViewComponents, for apps without `view_component` | `app/views/shared/components/toggle/` |
| Plain ERB | Full markup control and the special examples (favorite buttons, filter chips, view switcher, forms) | `app/views/components/toggle/` |

All need `app/javascript/controllers/toggle_button_controller.js`, except the native-input examples (View Switcher, Filter Chips, Toggles in a Form), which need no JavaScript.

## Installation

1. Copy `toggle_button_controller.js` to `app/javascript/controllers/`. With importmap and `eagerLoadControllersFrom` / `pin_all_from` it registers itself as `toggle-button`.
2. For the ViewComponents, copy `app/components/toggle/` (needs the `view_component` gem, 4.x).
3. Tailwind CSS v4.

## ViewComponent

### Standalone Toggle

```erb
<%# Icon only: `label:` is the accessible name and makes the button square %>
<%= render Toggle::Component.new(label: "Bold") do %>
  <svg …></svg>
<% end %>

<%# With text, bordered, pressed on the server %>
<%= render Toggle::Component.new(variant: :outline, pressed: current_user.watching?(@project)) do %>
  <svg class="size-4 group-aria-pressed/toggle:fill-current" …></svg>
  Watch
<% end %>
```

### Toggle Group

```erb
<%= render Toggle::GroupComponent.new(label: "Text alignment", required: true) do |group| %>
  <% group.with_item(value: "left", label: "Align left", pressed: true) do %><svg …></svg><% end %>
  <% group.with_item(value: "center", label: "Align center") do %><svg …></svg><% end %>
<% end %>

<%= render Toggle::GroupComponent.new(label: "Time range", variant: :segmented, name: "range") do |group| %>
  <% group.with_item(value: "week", pressed: true).with_content("Week") %>
  <% group.with_item(value: "month").with_content("Month") %>
<% end %>
```

### `Toggle::Component` Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `label` | String | `nil` | `aria-label`. Required for icon-only toggles; leave it out when the content has visible text |
| `pressed` | Boolean | `false` | Initial state, rendered as `aria-pressed` |
| `variant` | Symbol | `:ghost` | `:ghost` (no border) or `:outline` (bordered, pressed state sits in) |
| `size` | Symbol | `:md` | `:sm` (32px, 40px tall hit area), `:md` (36px), `:lg` (44px, touch) |
| `icon_only` | Boolean | `label.present?` | Square shape for an icon |
| `value` | String | `nil` | Reported in `event.detail.value` |
| `name` | String | `nil` | Renders a hidden input inside the button that submits `"1"` or `"0"` |
| `disabled` | Boolean | `false` | Disables the button; it keeps showing its state |
| `classes` | String | `nil` | Extra classes for the button |
| `html` | Hash | `{}` | Extra attributes. A `data: { action: }` is added after `toggle-button#toggle`, not instead of it |

Icons without a `size-*` class are sized to match the toggle.

### `Toggle::GroupComponent` Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `label` | String | required | `aria-label` for the group |
| `variant` | Symbol | `:toolbar` | `:toolbar` (ghost items in a bordered bar), `:outline` (separate bordered toggles), `:segmented` (sliding indicator). Required single-select groups (every `:segmented` group by default) render `role="radiogroup"` with `role="radio"` items; others render `role="toolbar"` |
| `size` | Symbol | `:md` | `:sm`, `:md` or `:lg`. Toolbar and outline items are 32/36/44px. A segmented group is 32/36/44px tall; its items are 28/32/40px so they sit inside the track |
| `multiple` | Boolean | `false` | Several items can be pressed. Not available for `:segmented` |
| `required` | Boolean | `true` for `:segmented`, else `false` | Keeps one item selected. With single-select, the group becomes a radio group: style item content with `group-aria-checked/toggle:` instead of `group-aria-pressed/toggle:` |
| `name` | String | `nil` | Renders a hidden input with the pressed values, comma-separated |
| `classes` | String | `nil` | Extra classes for the group |
| `html` | Hash | `{}` | Extra attributes for the group, e.g. `data: { action: "toggle-button:change->editor#format" }` |

### Item Options (`with_item`)

`value:` (required, unique in the group), `label:`, `pressed:`, `icon_only:`, `disabled:`, `classes:`, `html:`. Pass content as a block or with `.with_content("Week")`. Unknown options raise `ArgumentError`.

## Shared Partials

For apps without `view_component`. Same options, same markup, same errors as the ViewComponents (a spec keeps them identical):

```erb
<%= render "shared/components/toggle/toggle", label: "Bold", content: bold_icon %>
<%= render "shared/components/toggle/toggle", variant: :outline, name: "watch", pressed: true do %>Watch<% end %>

<%= render "shared/components/toggle/toggle_group", label: "Time range", variant: :segmented, name: "range", items: [
  { value: "week", content: "Week", pressed: true },
  { value: "month", content: "Month" }
] %>
```

Group items are hashes with the item options above plus `content:` (text, or HTML from `capture`).

## Plain ERB

```erb
<%# Standalone %>
<button type="button" aria-label="Bold" aria-pressed="false"
        data-controller="toggle-button" data-action="toggle-button#toggle"
        class="… aria-pressed:bg-neutral-200/80 aria-pressed:text-neutral-950">…</button>

<%# Group: the controller goes on the wrapper, every button is an item with a value %>
<div role="toolbar" aria-label="Text style" data-controller="toggle-button" data-toggle-button-multiple-value="true">
  <button type="button" value="bold" aria-label="Bold" aria-pressed="true"
          data-toggle-button-target="item" data-action="toggle-button#toggle">…</button>
</div>

<%# One item always selected: a radio group. Items use role="radio" and aria-checked (style with aria-checked:) %>
<div role="radiogroup" aria-label="Text alignment" data-controller="toggle-button">
  <button type="button" role="radio" value="left" aria-label="Align left" aria-checked="true"
          data-toggle-button-target="item" data-action="toggle-button#toggle"
          class="… aria-checked:bg-neutral-200/80 aria-checked:text-neutral-950">…</button>
</div>
```

Use `role="toolbar"` for toolbars and rows of toggles (it tells screen reader users that arrow keys work). When one item is always selected (alignment, segmented controls), use `role="radiogroup"` with `role="radio"` / `aria-checked` items: the controller treats it as required, and the arrow keys select as they move. For a segmented control, add `<span data-toggle-button-target="indicator" aria-hidden="true" class="pointer-events-none absolute top-0 left-0 …">` as the first child of a `relative` group, and give the items `relative` so they sit above it.

## Stimulus Controller

### Values

| Value | Type | Default | Description |
|-------|------|---------|-------------|
| `multiple` | Boolean | `false` | Groups only. Several items can be pressed at once |
| `required` | Boolean | `false` | Groups only. Keeps at least one item pressed. Implied by `role="radiogroup"` |

### Targets

| Target | Description |
|--------|-------------|
| `item` | A button in a group, with a `value` and `aria-pressed` (or `role="radio"` and `aria-checked` in a radio group). Without item targets, the controller element is a standalone toggle |
| `indicator` | Optional. Absolutely positioned element moved and sized under the pressed item of a single-select group |
| `input` | Optional hidden input kept in sync: `1`/`0` standalone (put it inside the button), comma-separated values for a group |

### Actions and Events

| Name | Type | Description |
|------|------|-------------|
| `toggle-button#toggle` | Action | Presses or releases the clicked button. Put it on the standalone button or on every item |
| `toggle-button#press` / `toggle-button#release` | Action | Press or release the item named by `data-toggle-button-value-param` (from an element inside the controller). Counts as a user change |
| `toggle-button:change` | Event | After each user change (click, key, radio arrow, action): `event.detail` has `item`, `pressed`, `value` and `values` (all pressed values). Bubbles |

The hidden input also fires a bubbling `change` event, so a form with `data-controller="autosubmit" data-action="change->autosubmit#submit"` saves on every press.

### Keyboard

| Key | Action |
|-----|--------|
| Tab | Moves into the group (to the pressed item, or the first one) and out of it |
| Arrow keys | Move focus between enabled items, wrapping around; left and right flip in RTL. In a radio group they also select. With Alt, Ctrl or Cmd held they do nothing, so browser shortcuts keep working |
| Home / End | First / last enabled item |
| Space / Enter | Press or release the focused item |

### Setting State From Outside

From another Stimulus controller, call the public API. It follows the group rules (a single-select group releases the other items, a required group keeps its last item) and updates the indicator and the hidden input:

```js
const toggle = this.application.getControllerForElementAndIdentifier(this.rangeTarget, "toggle-button")
toggle.press("month")   // a group item, by value
toggle.release("bold")
toggle.press()          // a standalone toggle: no value
```

You can also set `aria-pressed` (`aria-checked` on radios) on an item from anywhere, or let a Turbo morph do it: in a single-select group the other items are released for you. None of these dispatch `toggle-button:change`, because the user did not change anything (like setting `checkbox.checked` from JavaScript).

## Styling Hooks

- `aria-pressed:` on the button for its pressed look (`aria-checked:` on the `role="radio"` items of a radio group).
- `group-aria-pressed/toggle:` on content inside a toggle (the button has `group/toggle`, in the ViewComponent, the partials and the ERB examples). Use `group-aria-checked/toggle:` inside radio group items.
- `group-has-[[value=center][aria-pressed=true]]/name:` on a nearby element to react to a group without JavaScript. Always use a named group (`group/name`) so the selector can't match an unrelated `.group` ancestor.
- `disabled:` for disabled toggles; they keep showing their state.

## Accessibility

- Toggles are `<button type="button">` with `aria-pressed`. Icon-only toggles need an `aria-label`.
- When one item is always selected, the group is a `radiogroup` of `role="radio"` items with `aria-checked`. A pressed toggle that can't be released would be misleading: screen readers announce "radio button, 2 of 3, checked" instead, which also says the arrow keys move between the options.
- Keep the label the same in both states: "Save" with `aria-pressed="true"` reads as "Save, toggle button, pressed". A label that also changes ("Saved") is announced as a different button, so the Favorite example hides its swapped label with `aria-hidden`.
- Every group needs an `aria-label`. Toolbars and rows use `role="toolbar"`, always-one-selected groups `role="radiogroup"`.
- Text segments use their visible text as the name ("1D") so voice control users can say what they see; put the long form in `title` ("1 day") instead of an `aria-label` that hides the visible text.
- In forced colors mode (Windows High Contrast) background colors are replaced, so pressed items switch to the system `Highlight` / `HighlightText` colors with `forced-colors:aria-pressed:` (and `forced-colors:aria-checked:`) classes. Keep them when you restyle a toggle.
- Motion (sliding indicator, icon pops, rolling counts) is skipped under `prefers-reduced-motion`.

## Toggle, Switch, Checkbox or Tabs?

- **Toggle**: a pressed/not-pressed button for a mode or formatting (Bold, Star, Grid view).
- **Switch**: an on/off setting that takes effect immediately (Notifications).
- **Checkbox**: a choice inside a form that applies when it is submitted.
- **Tabs**: when the control shows and hides panels of content. A segmented control does not manage panels; use Tabs for that.

## Browser Support

All current browsers. The CSS-only examples use `:has()` (Chrome 105+, Safari 15.4+, Firefox 121+); in older browsers their indicator and check marks stay put, but the inputs still work and submit.

## Forms

Prefer the form builder when the values belong to a record. Native inputs submit without JavaScript and Rails adds the hidden empty value that clears a multi-select:

```erb
<%= form_with model: @digest_setting do |form| %>
  <%= form.collection_check_boxes :days, [["mon", "Monday"], ["tue", "Tuesday"]], :first, :last do |day| %>
    <label class="relative cursor-pointer">
      <%= day.check_box(class: "peer sr-only") %>
      <span class="… peer-checked:bg-neutral-900 peer-checked:text-white peer-focus-visible:outline-2"><%= day.text %></span>
    </label>
  <% end %>
<% end %>
```

Use `collection_radio_buttons` the same way for a single choice. Use the Stimulus toggle with `name:` when you need `aria-pressed` buttons rather than inputs; it submits `1`/`0` or comma-separated values.

## Troubleshooting

- **A `[toggle-button]` warning in the console**: it names the element and the fix. Warnings are for setup mistakes only and never stop the toggle from working.
- **Nothing happens on click**: the action is missing. Standalone: `data-action="toggle-button#toggle"` on the same button as `data-controller`. Group: on every item.
- **Several items in a group are tab stops**: the items are missing `data-toggle-button-target="item"`.
- **Indicator is misplaced**: the group must be `relative`, the indicator `absolute top-0 left-0`, and items `relative`.
- **All filter chips show a check mark**: an unnamed `group` class is matching an outer `.group`. Use a named group (`group/chip`).
- **Two view switchers affect each other**: radios with the same `name` form one group across the page. Give each switcher its own name.
- **A checked chip turns grey or loses its text on hover**: a plain `hover:bg-*` is emitted after `peer-checked:bg-*`, so it overrides the checked background. Scope the hover to unchecked inputs with `peer-not-checked:hover:bg-*` (and `dark:peer-not-checked:hover:bg-*`), and use `peer-checked:hover:bg-*` for the checked hover.

---

## AI Instructions

### Choose An Implementation

- **ViewComponent**: Default when the app has `view_component`. Use `Toggle::Component` for one toggle and `Toggle::GroupComponent` for toolbars, rows and segmented controls.
- **Shared partials**: Default when the app has no `view_component`: `shared/components/toggle/toggle` and `toggle_group` take the same options as locals.
- **Plain ERB**: Use when you need markup the ViewComponents don't cover (favorite buttons with animations, filter chips, view switchers); copy the closest file from `app/views/components/toggle/`.
- **Native inputs (no JavaScript)**: Use checkboxes or radios styled as toggles when the values belong to a form model, as in Filter Chips and Toggles in a Form.

### Quick Reference

- **Vanilla examples**: `app/views/components/toggle/`
- **ViewComponent**: `render Toggle::Component.new(label: "Bold") { svg }`
- **Group ViewComponent**: `render Toggle::GroupComponent.new(label: "Alignment", required: true) { |group| group.with_item(value: "left", label: "Align left", pressed: true) { svg } }`
- **ViewComponent files**: `app/components/toggle/`
- **Shared partials**: `render "shared/components/toggle/toggle", label: "Bold", content: icon` and `render "shared/components/toggle/toggle_group", label: "Alignment", required: true, items: [{ value: "left", label: "Align left", pressed: true, content: icon }]` (`app/views/shared/components/toggle/`)
- **Stimulus controller**: `app/javascript/controllers/toggle_button_controller.js` (identifier `toggle-button`)

### Implementation Checklist

- Render the initial state on the server: `pressed:` (ViewComponent) or `aria-pressed="true"` (ERB).
- Give icon-only toggles a `label:` / `aria-label`, and every group a `label:` / `aria-label`. Use `role="toolbar"` for toolbars in plain ERB, and `role="radiogroup"` with `role="radio"` / `aria-checked` items when one item is always selected.
- To change the state from code, call `press(value)` / `release(value)` on the controller (or set `aria-pressed` / `aria-checked`); never toggle classes by hand.
- Keep the `forced-colors:` classes when restyling a toggle; without them the pressed state disappears in Windows High Contrast.
- For form fields bound to a model, use `form.collection_check_boxes` / `form.collection_radio_buttons` with `class: "peer sr-only"` inputs, as in Toggles in a Form.
- Give every group item a unique `value`.
- In plain ERB groups, the controller goes on the wrapper and each button gets `data-toggle-button-target="item"` and `data-action="toggle-button#toggle"`.
- Use named Tailwind groups (`group/align`) for any `group-has-*` or `group-aria-pressed` selector.
- Persist changes with `toggle-button:change` (fetch or Turbo), or with `name:` inside a form that has `data-controller="autosubmit" data-action="change->autosubmit#submit"`.
- For counts that change with the state (stars, likes), render both numbers from the server: the count without and with the current user's vote.

### Common Patterns

- Editor toolbar: `GroupComponent` with `multiple: true` for Bold/Italic/Underline, another with `required: true` for alignment.
- Chart range or calendar view: `variant: :segmented`.
- Star, like or bookmark: copy the Favorite Toggles example and wire `toggle-button:change` to your endpoint.
- Search filters in a form: Filter Chips (native checkboxes, `name="amenities[]"`).

### Common Mistakes

- Do not use a toggle for a setting that applies immediately; use a Switch.
- Do not use a segmented control to show and hide content panels; use Tabs.
- Do not change the button label with its state; `aria-pressed` already says it.
- Do not put `data-controller="toggle-button"` on every item of a group; only on the wrapper.
- Do not use `aria-pressed` on the items of a `role="radiogroup"`, or `aria-pressed:` classes on radio items; radios use `aria-checked`.
- Do not use physical `left-*` / `ml-*` / `pr-*` on indicators and spacing; use `start-*` / `ms-*` / `pe-*` so RTL layouts work.
- Do not use an unnamed `group` class with `group-has-*`; it leaks to outer `.group` elements.
- Do not pair a plain `hover:bg-*` with `peer-checked:bg-*` on an input-backed toggle; use `peer-not-checked:hover:bg-*` so hover never overrides the checked state.
- Do not reuse a radio `name` for two view switchers on one page.
- Do not invent options (`style:`, `color:`, `variant: :primary`, `size: :xl`); unknown options raise `ArgumentError`.
- Do not pass `name:` to a group item; pass it to `Toggle::GroupComponent`.