Skip to content
Brok UI

Loading…

No results

Toggle Group

Open source

A set of two-state buttons with single or multiple selection.

Version
v1.2.4
Stability
stable
License
MIT
Related
Toggle
Radio Tabs
Segmented Nav

Preview

Variant
Size
previews.components.toggle-group.default.blade.php Blade
<div class="flex flex-col gap-6">
    <x-ui.toggle-group type="single" name="align" value="center" aria-label="{{ __('Text alignment') }}">
        <x-ui.toggle-group.item value="left">{{ __('Left') }}</x-ui.toggle-group.item>
        <x-ui.toggle-group.item value="center">{{ __('Center') }}</x-ui.toggle-group.item>
        <x-ui.toggle-group.item value="right">{{ __('Right') }}</x-ui.toggle-group.item>
    </x-ui.toggle-group>

    <x-ui.toggle-group type="multiple" name="format" aria-label="{{ __('Text formatting') }}">
        <x-ui.toggle-group.item value="bold"><strong>{{ __('Bold') }}</strong></x-ui.toggle-group.item>
        <x-ui.toggle-group.item value="italic"><em>{{ __('Italic') }}</em></x-ui.toggle-group.item>
        <x-ui.toggle-group.item value="underline"><span class="underline">{{ __('Underline') }}</span></x-ui.toggle-group.item>
    </x-ui.toggle-group>
</div>

Variant options

Default Current
Outline Current

Size options

Sm Current
Md Current
Lg Current

Installation

terminal
php artisan ui:add toggle-group

Note

This component ships an Alpine behavior module at resources/js/ui/toggle-group.js. Import it once from your bundle so it registers on alpine:init:

resources/js/ui/index.js JS
import './toggle-group.js';

Registry contract

php artisan ui:add toggle-group writes only the files below. The CLI validates each file hash before writing and asks before it replaces a local change, unless you pass --force.

  • blade resources/views/components/ui/toggle-group.blade.php
  • blade resources/views/components/ui/toggle-group/item.blade.php
  • js resources/js/ui/toggle-group.js
Registry dependencies
None — installs on its own.
Packages
composer: jml/brok:^0.2
npm: alpinejs

Use with AI

A brief for your coding agent: install command, usage, props, guidance and the rules. Copy it, or open a prompt about this component in an assistant.

toggle-group.md
# Brok UI: Toggle Group (`toggle-group`)

A set of two-state buttons with single or multiple selection.

Brok UI is a Laravel Blade component registry. Installed components are plain Blade files the app owns.

## Install

```bash
php artisan ui:add toggle-group
```

## Usage

```blade
<div class="flex flex-col gap-6">
    <x-ui.toggle-group type="single" name="align" value="center" aria-label="{{ __('Text alignment') }}">
        <x-ui.toggle-group.item value="left">{{ __('Left') }}</x-ui.toggle-group.item>
        <x-ui.toggle-group.item value="center">{{ __('Center') }}</x-ui.toggle-group.item>
        <x-ui.toggle-group.item value="right">{{ __('Right') }}</x-ui.toggle-group.item>
    </x-ui.toggle-group>

    <x-ui.toggle-group type="multiple" name="format" aria-label="{{ __('Text formatting') }}">
        <x-ui.toggle-group.item value="bold"><strong>{{ __('Bold') }}</strong></x-ui.toggle-group.item>
        <x-ui.toggle-group.item value="italic"><em>{{ __('Italic') }}</em></x-ui.toggle-group.item>
        <x-ui.toggle-group.item value="underline"><span class="underline">{{ __('Underline') }}</span></x-ui.toggle-group.item>
    </x-ui.toggle-group>
</div>
```

## Props

- `type` (string, default `single`) — Declared by @props in the shipped Blade source.
- `name` (mixed|null, default `null`) — Declared by @props in the shipped Blade source.
- `value` (mixed, default `null`) — This item's value, matched against the group's current selection.
- `variant` (string, default `default`) — Declared by @props in the shipped Blade source.
- `size` (string, default `md`) — Declared by @props in the shipped Blade source.

## Use when

- Use when users choose among a bounded set and space efficiency matters more than always-visible comparison.
- Grouping related two-state buttons, such as text alignment or formatting toggles, that share roving keyboard focus.
- Needing single or multiple selection among a row of pressed/unpressed buttons.

## Avoid when

- Do not use for tiny lists or when users benefit from seeing all options at once.
- Only one standalone toggle is needed; use toggle by itself.
- The choice must submit a single mutually exclusive value with native radio semantics; use radio or radio-tabs.

## Anti-patterns

- Hiding tiny or high-frequency option sets

## Rules

- Use the `<brok:toggle-group>` tag (or `<x-ui.toggle-group>`) in Blade; do not rewrite the component.
- Prefer the documented props and variants over utility-class overrides; when a utility must win, use the `!` important modifier.
- Use semantic design tokens (`bg-primary`, `text-muted-foreground`), never raw colour utilities.
- Keep the `data-slot` attributes; they are the styling and test hooks.

## Links

- Docs: https://brokui.dev/docs/components/toggle-group
- Registry JSON (files, props, contract): https://brokui.dev/r/open/toggle-group.json

Working in Claude Code, Cursor or Codex? Give the agent the whole registry through the MCP server or the Brok UI skill.

API

manifest knowledge + registry-derived coverage

Props

Props accepted by this component: name, type, default value and description.
Prop Type Default Description
type string single Declared by @props in the shipped Blade source.
name mixed | null null Declared by @props in the shipped Blade source.
value mixed null This item's value, matched against the group's current selection.
variant string default Declared by @props in the shipped Blade source.
size string md Declared by @props in the shipped Blade source.

Slots

  • default — toggle-group.item elements composing the group.
  • x-ui.toggle-group.item — Installed subcomponent from the registry item.

Data slots

Stable hooks for CSS overrides and browser tests.

toggle-group toggle-group-item

Behavior

  • type="single" keeps at most one item pressed; type="multiple" allows several items pressed at once.
  • Arrow keys move a roving tabindex between items so only one item is tab-stoppable at a time.
  • The root is modelable via x-model or wire:model, and with a name prop mirrors the selection into a hidden input for plain form submission.
  • Installs a JavaScript behavior module when the registry item includes resources/js/ui files.
  • Declares registry capability flags: a11y, interactive, responsive, rtl, darkMode, localized.

Guidance

Bounded compact selection

Choose from a bounded option set in limited space.

Use when

  • Use when users choose among a bounded set and space efficiency matters more than always-visible comparison.
  • Grouping related two-state buttons, such as text alignment or formatting toggles, that share roving keyboard focus.
  • Needing single or multiple selection among a row of pressed/unpressed buttons.

Avoid when

  • Do not use for tiny lists or when users benefit from seeing all options at once.
  • Only one standalone toggle is needed; use toggle by itself.
  • The choice must submit a single mutually exclusive value with native radio semantics; use radio or radio-tabs.

Use instead

  • Radio or checkbox for visible comparison

Anti-patterns

  • Hiding tiny or high-frequency option sets
Anatomy
root toggle-group-item
Theming hooks
toggle

Accessibility

WCAG 2.2 AA Keyboard focus-visible RTL-ready Localized labels Dark mode
Keyboard
ArrowUp ArrowDown ArrowLeft ArrowRight Home End
Focus
managed
  • The root has role="group" and each item is a real button with a live aria-pressed attribute.
  • Roving tabindex means arrow-key navigation moves focus between items while Tab moves past the whole group in one stop.
  • Semantic HTML and a stable data-slot attribute for styling and scripting hooks.
  • Focus-visible rings use the ring token, so keyboard focus is always visible.
  • Disabled and invalid states are conveyed to assistive tech, not by color alone.
  • Targets WCAG 2.2 AA; verify contrast in light, dark, admin and customer surfaces in the preview.
  • Labels go through __() and layout uses logical properties (ms-*, text-start), so it mirrors under dir="rtl" — flip the preview to RTL to confirm.
  • Dark mode uses the same semantic tokens under the dark class; high contrast follows forced-color system tokens.

Livewire

Needs wire:key

Add a stable wire:key when Livewire can reorder this interactive component.

livewire-component.blade.php Blade
<div wire:key="toggle-group-{{ $record->id }}">
    <div class="flex flex-col gap-6">
        <x-ui.toggle-group type="single" name="align" value="center" aria-label="{{ __('Text alignment') }}">
            <x-ui.toggle-group.item value="left">{{ __('Left') }}</x-ui.toggle-group.item>
            <x-ui.toggle-group.item value="center">{{ __('Center') }}</x-ui.toggle-group.item>
            <x-ui.toggle-group.item value="right">{{ __('Right') }}</x-ui.toggle-group.item>
        </x-ui.toggle-group>
    
        <x-ui.toggle-group type="multiple" name="format" aria-label="{{ __('Text formatting') }}">
            <x-ui.toggle-group.item value="bold"><strong>{{ __('Bold') }}</strong></x-ui.toggle-group.item>
            <x-ui.toggle-group.item value="italic"><em>{{ __('Italic') }}</em></x-ui.toggle-group.item>
            <x-ui.toggle-group.item value="underline"><span class="underline">{{ __('Underline') }}</span></x-ui.toggle-group.item>
        </x-ui.toggle-group>
    </div>
</div>

Validation

Validation support: native. Keep the error message connected with aria-describedby.

livewire-form.blade.php Blade
<form wire:submit="save" class="space-y-2">
    <brok:toggle-group
        wire:model="value"
        :aria-invalid="$errors->has('value') ? 'true' : 'false'"
        aria-describedby="value-error"
    />

    @error('value')
        <p id="value-error" role="alert">{{ $message }}</p>
    @enderror

    <brok:button type="submit" wire:loading.attr="disabled">
        <span wire:loading.remove>Save</span>
        <span wire:loading>Saving…</span>
    </brok:button>
</form>

Source

The exact, editable files ui:add writes into your app. Previews render this same code; there are no preview-only components.

resources/views/components/ui/toggle-group.blade.php Blade
@props([
    'type' => 'single',
    'name' => null,
    'value' => null,
    // Item look, read by every toggle-group.item through @aware: toggle's
    // default | outline variants and sm | md | lg control tiers.
    'variant' => 'default',
    'size' => 'md',
])
@php
    $styles = require base_path(config('ui.component_path', 'resources/views/components/ui').'/_styles.php');
    $variant = $styles['normalizeVariant']($variant);
    $variant = in_array($variant, ['default', 'outline'], true) ? $variant : 'default';
    $size = in_array($size, ['sm', 'md', 'lg'], true) ? $size : 'md';
@endphp
<div
    x-data="uiToggleGroup({ type: @js($type), value: @js($value) })"
    {{-- Modelable: `x-model` (Alpine) and `wire:model` (Livewire binds through
         the same x-model contract) attach to the root. Inert without either. --}}
    x-modelable="model"
    data-slot="toggle-group"
    data-type="{{ $type }}"
    data-variant="{{ $variant }}"
    data-size="{{ $size }}"
    role="group"
    @keydown="onKey($event)"
    {{ $attributes->merge(['class' => 'inline-flex items-center gap-1 rounded-md']) }}
>
    {{ $slot }}
    @if ($name)
        <input type="hidden" name="{{ $name }}" :value="Array.isArray(value) ? value.join(',') : (value ?? '')" />
    @endif
</div>
resources/views/components/ui/toggle-group/item.blade.php Blade
@aware([
    'variant' => 'default',
    'size' => 'md',
])

@props(['value'])

@php
    $styles = require base_path(config('ui.component_path', 'resources/views/components/ui').'/_styles.php');
    $variant = $styles['normalizeVariant']($variant);
    // One item is a toggle: same recipe, same control tiers, so a group reads
    // as a row of the standalone control. The group owns the pressed state.
    $recipe = $styles['toggle'];
    // The group keeps the accent pressed fill; an older _styles.php carries it in base.
    $pressed = $recipe['tones']['accent'] ?? '';
    $classes = trim($recipe['base'].' '.$pressed.' '.($recipe['variants'][$variant] ?? $recipe['variants']['default']).' '.($recipe['sizes'][$size] ?? $recipe['sizes']['md']));
@endphp

<button
    type="button"
    data-slot="toggle-group-item"
    data-value="{{ $value }}"
    data-variant="{{ $variant }}"
    data-size="{{ $size }}"
    :data-state="isOn(@js($value)) ? 'on' : 'off'"
    :aria-pressed="isOn(@js($value))"
    :tabindex="rovingTabindex($el)"
    @click="toggle(@js($value))"
    {{ $attributes->merge(['class' => $classes]) }}
>{{ $slot }}</button>
resources/js/ui/toggle-group.js JS
/**
 * Toggle group behavior (spec §19 behavior layer).
 *
 * A set of two-state buttons that support "single" (one active value) or
 * "multiple" (an array of active values) selection. Selection state lives on
 * the root so each instance — and any hidden form input — stays independent.
 *
 * Focus uses the roving-tabindex pattern: only one item is in the tab order,
 * and ArrowLeft/Right/Up/Down/Home/End move focus within the group. Horizontal
 * arrows respect the resolved text direction, so they are swapped under RTL.
 *
 * Self-registers on `alpine:init` so import order does not matter — import this
 * file once from your bundle (e.g. resources/js/ui/index.js).
 */
document.addEventListener('alpine:init', () => {
    window.Alpine.data('uiToggleGroup', (config = {}) => ({
        type: config.type ?? 'single',
        value:
            (config.type ?? 'single') === 'multiple'
                ? config.value ?? []
                : config.value ?? null,

        /**
         * Modelable value (`x-modelable="model"` on the root): the pressed value
         * (single) or the array of pressed values (multiple).
         */
        get model() {
            return this.value;
        },
        set model(v) {
            if (this.type === 'multiple') {
                this.value = Array.isArray(v) ? [...v] : (v == null || v === '' ? [] : [v]);
            } else {
                this.value = v == null || v === '' ? null : v;
            }
        },

        isOn(v) {
            return this.type === 'multiple' ? this.value.includes(v) : this.value === v;
        },

        toggle(v) {
            if (this.type === 'multiple') {
                this.value = this.isOn(v)
                    ? this.value.filter((x) => x !== v)
                    : [...this.value, v];
            } else {
                this.value = this.value === v ? null : v;
            }
        },

        /** Items that participate in roving focus (enabled items only). */
        _items() {
            return Array.from(
                this.$el.querySelectorAll('[data-slot="toggle-group-item"]:not(:disabled)')
            );
        },

        /** Only the first "on" item (or the first item) is tabbable. */
        rovingTabindex(el) {
            const items = this._items();
            const active = items.find((i) => i.getAttribute('data-state') === 'on') || items[0];
            return el === active ? 0 : -1;
        },

        /** Roving keyboard navigation, direction-aware for horizontal arrows. */
        onKey(event) {
            const items = this._items();
            const cur = items.indexOf(event.target);
            if (cur === -1) {
                return;
            }

            const rtl = getComputedStyle(this.$el).direction === 'rtl';
            let key = event.key;
            if (rtl) {
                if (key === 'ArrowRight') {
                    key = 'ArrowLeft';
                } else if (key === 'ArrowLeft') {
                    key = 'ArrowRight';
                }
            }

            let next;
            switch (key) {
                case 'ArrowRight':
                case 'ArrowDown':
                    next = (cur + 1) % items.length;
                    break;
                case 'ArrowLeft':
                case 'ArrowUp':
                    next = (cur - 1 + items.length) % items.length;
                    break;
                case 'Home':
                    next = 0;
                    break;
                case 'End':
                    next = items.length - 1;
                    break;
                default:
                    return;
            }

            event.preventDefault();
            items[next].focus();
        },
    }));
});

Ownership & lifecycle

Owner, release state, review evidence and adoption for this item.
Owner
Platform UI (@JoshJML)
Current version
1.2.4
Status
Stable
License
open
Accessibility reviewed
No review date recorded
Last breaking change
No date recorded
Deprecation
Not deprecated
Contract
v6
Foundation
≥ 1.0.0