Skip to content
Brok UI

Loading…

No results

Select

Open source Core

Pick a value from a list — the native select, a custom listbox, a filterable combobox or a scrolling wheel.

Version
v1.4.3
Stability
stable
License
MIT
Related
Native Select
Combobox
Wheel Picker

Advanced Select — Custom listbox select with keyboard navigation, type-ahead, rich options (secondary meta) and a hidden form value.

Preview

Apple
Banana
Blueberry
Grapes
Pineapple
previews.components.select-advanced.default.blade.php Blade
<div class="w-full max-w-xs">
    <x-ui.select-advanced name="fruit" :placeholder="__('Select a fruit')">
        <x-ui.select-advanced.option value="apple">{{ __('Apple') }}</x-ui.select-advanced.option>
        <x-ui.select-advanced.option value="banana">{{ __('Banana') }}</x-ui.select-advanced.option>
        <x-ui.select-advanced.option value="blueberry">{{ __('Blueberry') }}</x-ui.select-advanced.option>
        <x-ui.select-advanced.option value="grapes">{{ __('Grapes') }}</x-ui.select-advanced.option>
        <x-ui.select-advanced.option value="pineapple">{{ __('Pineapple') }}</x-ui.select-advanced.option>
    </x-ui.select-advanced>
</div>

Installation

terminal
php artisan ui:add select-advanced

Note

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

resources/js/ui/index.js JS
import './select-advanced.js';

Registry contract

php artisan ui:add select-advanced 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/select-advanced.blade.php
  • blade resources/views/components/ui/select-advanced/option.blade.php
  • js resources/js/ui/select-advanced.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.

select-advanced.md
# Brok UI: Advanced Select (`select-advanced`)

Custom listbox select with keyboard navigation, type-ahead, rich options (secondary meta) and a hidden form value.

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

## Install

```bash
php artisan ui:add select-advanced
```

## Usage

```blade
<div class="w-full max-w-xs">
    <x-ui.select-advanced name="fruit" :placeholder="__('Select a fruit')">
        <x-ui.select-advanced.option value="apple">{{ __('Apple') }}</x-ui.select-advanced.option>
        <x-ui.select-advanced.option value="banana">{{ __('Banana') }}</x-ui.select-advanced.option>
        <x-ui.select-advanced.option value="blueberry">{{ __('Blueberry') }}</x-ui.select-advanced.option>
        <x-ui.select-advanced.option value="grapes">{{ __('Grapes') }}</x-ui.select-advanced.option>
        <x-ui.select-advanced.option value="pineapple">{{ __('Pineapple') }}</x-ui.select-advanced.option>
    </x-ui.select-advanced>
</div>
```

## Props

- `name` (string|null, default `null`) — Hidden input name for the selected value.
- `value` (mixed, default ``) — On <x-ui.select-advanced.option>: the value submitted and matched when this option is chosen.
- `label` (mixed|null, default ``) — On <x-ui.select-advanced.option>: primary text; defaults to the slot content and drives type-ahead matching.
- `placeholder` (string, default `Select an option`) — Trigger label before selection.
- `description` (mixed|null, default `null`) — Declared by @props in the registry Blade source.
- `meta` (mixed|null, default `null`) — Declared by @props in the registry Blade source.

## Use when

- Use when users choose among a bounded set and space efficiency matters more than always-visible comparison.
- Needing full keyboard support (arrow keys, type-ahead, Home/End) and rich options with a secondary description or trailing meta.
- Styling the trigger and option list beyond what a native <select> allows.

## Avoid when

- Do not use for tiny lists or when users benefit from seeing all options at once.
- A plain, short option list where native <select> semantics and mobile picker UI are preferred; use select instead.
- The user should be able to filter by typing; use combobox instead.

## Anti-patterns

- Hiding tiny or high-frequency option sets

## Rules

- Use the `<brok:select-advanced>` tag (or `<x-ui.select-advanced>`) 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/select-advanced
- Registry JSON (files, props, contract): https://brokui.dev/r/open/select-advanced.json

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

Examples

rich.blade.php Blade
{{-- Rich options: a primary label, a secondary meta line, and a trailing
     meta adornment (here a price). Generic — any "thing with a subtitle". --}}
<div class="w-full max-w-sm">
    <x-ui.select-advanced name="plan" value="pro" :label="__('Pro')" :placeholder="__('Select a plan')">
        <x-ui.select-advanced.option
            value="starter"
            :label="__('Starter')"
            :description="__('For individuals getting started')"
            :meta="__('$0/mo')"
        />
        <x-ui.select-advanced.option
            value="pro"
            :label="__('Pro')"
            :description="__('For small teams shipping fast')"
            :meta="__('$29/mo')"
        />
        <x-ui.select-advanced.option
            value="business"
            :label="__('Business')"
            :description="__('Advanced controls and SSO')"
            :meta="__('$99/mo')"
        />
        <x-ui.select-advanced.option
            value="enterprise"
            :label="__('Enterprise')"
            :description="__('Custom limits and support')"
            :meta="__('Contact us')"
        />
    </x-ui.select-advanced>
</div>

API

manifest knowledge + registry-derived coverage

Props

Props accepted by this component: name, type, default value and description.
Prop Type Default Description
name string | null null Hidden input name for the selected value.
value mixed On <x-ui.select-advanced.option>: the value submitted and matched when this option is chosen.
label mixed | null On <x-ui.select-advanced.option>: primary text; defaults to the slot content and drives type-ahead matching.
placeholder string Select an option Trigger label before selection.
description mixed | null null Declared by @props in the registry Blade source.
meta mixed | null null Declared by @props in the registry Blade source.

Slots

  • default — The <x-ui.select-advanced.option> list rendered inside the listbox.
  • icon — On <x-ui.select-advanced.option>: a leading icon for that option.
  • x-ui.select-advanced.option — Installed subcomponent from the registry item.

Data slots

Stable hooks for CSS overrides and browser tests.

select-advanced select-content select-option select-trigger

Behavior

  • ArrowUp/Down/Home/End move the active option, type-ahead jumps to a matching option, Enter or Space chooses it, Escape closes and refocuses the trigger.
  • The chosen value mirrors to a hidden input for form submission; the trigger shows the active option's label.
  • Binds wire:model (Livewire) or x-model (Alpine) to the selected value through x-modelable; an inbound value refreshes the trigger label.
  • 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.
  • Needing full keyboard support (arrow keys, type-ahead, Home/End) and rich options with a secondary description or trailing meta.
  • Styling the trigger and option list beyond what a native <select> allows.

Avoid when

  • Do not use for tiny lists or when users benefit from seeing all options at once.
  • A plain, short option list where native <select> semantics and mobile picker UI are preferred; use select instead.
  • The user should be able to filter by typing; use combobox instead.

Use instead

  • Radio or checkbox for visible comparison

Anti-patterns

  • Hiding tiny or high-frequency option sets
Anatomy
root select-option select-trigger select-content
Theming hooks
field-trigger

Accessibility

WCAG 2.2 AA Keyboard focus-visible RTL-ready Localized labels Dark mode
Keyboard
Enter Space Escape
Focus
managed
  • The trigger carries role="combobox" with aria-expanded and aria-activedescendant so a screen reader tracks the active option without moving focus off the trigger.
  • A rich option's label, description and meta are joined into one aria-label so the whole row reads as a coherent phrase.
  • 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="select-advanced-{{ $record->id }}">
    <div class="w-full max-w-xs">
        <x-ui.select-advanced name="fruit" :placeholder="__('Select a fruit')">
            <x-ui.select-advanced.option value="apple">{{ __('Apple') }}</x-ui.select-advanced.option>
            <x-ui.select-advanced.option value="banana">{{ __('Banana') }}</x-ui.select-advanced.option>
            <x-ui.select-advanced.option value="blueberry">{{ __('Blueberry') }}</x-ui.select-advanced.option>
            <x-ui.select-advanced.option value="grapes">{{ __('Grapes') }}</x-ui.select-advanced.option>
            <x-ui.select-advanced.option value="pineapple">{{ __('Pineapple') }}</x-ui.select-advanced.option>
        </x-ui.select-advanced>
    </div>
</div>

Validation

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

livewire-form.blade.php Blade
<form wire:submit="save" class="space-y-2">
    <brok:select-advanced
        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/select-advanced.blade.php Blade
{{-- A wrapping <x-ui.field name="…"> shares its name down via @aware so this
     composite self-wires old()/aria-invalid/aria-describedby off the shared
     $errors bag. Inert with no field ancestor and no own `name` —
     fully backward-compatible. --}}
@aware([
    'name' => null,
])

@props([
    'name' => null,
    'value' => '',
    'label' => '',
    'placeholder' => 'Select an option',
])

@php
    $styles = require base_path(config('ui.component_path', 'resources/views/components/ui').'/_styles.php');
    $trigger = $styles['field-trigger'];
    $awareName = $name ?? null;
    $fieldName = $awareName ?? $attributes->get('name');

    $bag = ($errors ?? null) instanceof \Illuminate\Support\ViewErrorBag ? $errors : null;
    $hasBagError = $bag && filled($fieldName) && $bag->has($fieldName);

    // old() repopulates the chosen value after a failed redirect-back.
    $resolvedValue = filled($fieldName) ? old($fieldName, $value) : $value;

    $describedBy = (filled($awareName) && $hasBagError) ? $fieldName.'-error' : null;
@endphp

{{--
    Advanced Select (spec §17 + §19). A custom listbox-based select with full
    keyboard support: ArrowUp/Down/Home/End to move, type-ahead to jump,
    Enter/Space to choose, Escape to close. Single value, mirrored to a hidden
    input for forms. For a plain native control use <x-ui.select> instead.
--}}
<div
    x-data="uiSelect({ value: @js($resolvedValue), label: @js($label) })"
    {{-- 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"
    x-id="['select-list']"
    data-slot="select-advanced"
    @if ($hasBagError) data-invalid="true" @endif
    @keydown.escape="if (open) { $event.stopPropagation(); closeAndFocus() }"
    @click.outside="close()"
    {{ $attributes->except(['name'])->merge(['class' => 'relative w-full']) }}
>
    @if (filled($fieldName))
        <input type="hidden" name="{{ $fieldName }}" :value="value" />
    @endif

    <button
        type="button"
        data-slot="select-trigger"
        x-ref="trigger"
        role="combobox"
        aria-haspopup="listbox"
        x-bind:aria-label="label || @js($placeholder) || @js(__('Select option'))"
        :aria-expanded="open"
        x-bind:aria-controls="$id('select-list')"
        x-bind:aria-activedescendant="activeId()"
        @if ($hasBagError) aria-invalid="true" @endif
        @if (filled($describedBy)) aria-describedby="{{ $describedBy }}" @endif
        @click="toggle()"
        @keydown.down.prevent="open ? move(1) : show()"
        @keydown.up.prevent="open ? move(-1) : show()"
        @keydown.enter.prevent="open ? choose() : show()"
        @keydown.space.prevent="open ? choose() : show()"
        @keydown="typeahead($event)"
        class="{{ $trigger['base'] }} {{ $trigger['sizes']['md'] }} {{ $trigger['states'][$hasBagError ? 'invalid' : 'default'] }}"
    >
        <span class="truncate" :class="label ? 'text-foreground' : 'text-muted-foreground'" x-text="label || @js($placeholder)"></span>
        <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="size-4 shrink-0 text-muted-foreground">
            <path d="m6 9 6 6 6-6" />
        </svg>
    </button>

    <div
        data-slot="select-content"
        role="listbox"
        x-ref="list"
        x-bind:id="$id('select-list')"
        x-show="open"
        x-cloak
        x-transition:enter="motion-safe:transition motion-safe:duration-100 motion-safe:ease-out"
        x-transition:enter-start="opacity-0 motion-safe:scale-[0.97]"
        x-transition:enter-end="opacity-100 motion-safe:scale-100"
        x-transition:leave="motion-safe:transition motion-safe:duration-75 motion-safe:ease-in"
        x-transition:leave-start="opacity-100 motion-safe:scale-100"
        x-transition:leave-end="opacity-0 motion-safe:scale-[0.97]"
        class="absolute z-dropdown mt-1 max-h-60 w-full origin-top overflow-y-auto rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md motion-reduce:transition-none"
    >
        {{ $slot }}
    </div>
</div>
resources/views/components/ui/select-advanced/option.blade.php Blade
@props([
    'value',
    'label' => null,
    'description' => null,
    'meta' => null,
])

@php
    // Primary label drives type-ahead matching; the slot holds the visible
    // primary text (or the explicit `label` prop when given).
    $primary = $label ?? trim($slot);

    // A rich option carries a secondary line and/or a trailing meta adornment
    // (or a leading icon slot). Screen readers get the whole row as one phrase
    // via aria-label so label + description + meta read coherently.
    $isRich = filled($description) || filled($meta) || isset($icon);
    $ariaLabel = collect([$primary, $description, $meta])->filter()->implode(', ');
@endphp

<div
    data-slot="select-option"
    role="option"
    data-value="{{ $value }}"
    data-label="{{ $primary }}"
    x-bind:id="$id('select-list') + '-option-' + encodeId(@js($value))"
    @if ($isRich) aria-label="{{ $ariaLabel }}" @endif
    :aria-selected="value === @js($value)"
    :data-active="active === @js($value)"
    @click="select(@js($value), @js($primary))"
    @mousemove="active = @js($value)"
    {{ $attributes->merge(['class' => 'flex cursor-pointer items-center justify-between gap-2 rounded-sm px-2 py-2 text-sm text-popover-foreground outline-none transition-colors data-[active=true]:bg-accent data-[active=true]:text-accent-foreground']) }}
>
    <span class="flex min-w-0 items-center gap-2">
        @isset($icon)
            <span class="grid shrink-0 place-items-center text-muted-foreground" aria-hidden="true">{{ $icon }}</span>
        @endisset
        @if ($isRich)
            <span class="flex min-w-0 flex-col">
                <span class="truncate">{{ $primary }}</span>
                @if (filled($description))
                    <span class="truncate text-xs text-muted-foreground">{{ $description }}</span>
                @endif
            </span>
        @else
            <span class="truncate">{{ $slot }}</span>
        @endif
    </span>
    <span class="flex shrink-0 items-center gap-2">
        @if (filled($meta))
            <span class="text-xs text-muted-foreground">{{ $meta }}</span>
        @endif
        <svg x-show="value === @js($value)" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="size-4 text-primary">
            <path d="M20 6 9 17l-5-5" />
        </svg>
    </span>
</div>
resources/js/ui/select-advanced.js JS
/**
 * Advanced Select behavior (spec §17 + §19): a custom listbox select.
 *
 * Supports ArrowUp/Down/Home/End navigation, type-ahead (jump to the option
 * whose label starts with the typed characters), Enter/Space to choose, and
 * Escape to close. The selection mirrors to a hidden input for forms.
 */
document.addEventListener('alpine:init', () => {
    window.Alpine.data('uiSelect', (config = {}) => ({
        open: false,
        value: config.value ?? '',
        label: config.label ?? '',
        active: null,
        typed: '',
        typedTimer: null,

        /**
         * Modelable value (`x-modelable="model"` on the root). An inbound value
         * (Livewire, `x-model`) also refreshes the trigger label from the
         * matching option's markup.
         */
        get model() {
            return this.value;
        },
        set model(v) {
            const next = v == null ? '' : String(v);
            if (next === String(this.value)) return;
            this.value = next;
            const option = this.options().find((el) => el.dataset.value === next);
            this.label = option ? option.dataset.label || option.textContent.trim() : '';
        },

        options() {
            const list = this.$refs.list;
            if (!list) {
                return [];
            }
            return Array.from(list.querySelectorAll('[data-slot="select-option"]'));
        },

        values() {
            return this.options().map((el) => el.dataset.value);
        },

        toggle() {
            this.open ? this.close() : this.show();
        },

        show() {
            this.open = true;
            this.active = this.value || this.values()[0] || null;
            this.scrollActiveIntoView();
        },

        close() {
            this.open = false;
        },

        closeAndFocus() {
            if (!this.open) {
                return;
            }
            this.open = false;
            this.$nextTick(() => this.$refs.trigger?.focus());
        },

        move(direction) {
            const values = this.values();
            if (values.length === 0) {
                return;
            }
            const current = values.indexOf(this.active);
            const next = current === -1
                ? (direction > 0 ? 0 : values.length - 1)
                : (current + direction + values.length) % values.length;
            this.active = values[next];
            this.scrollActiveIntoView();
        },

        scrollActiveIntoView() {
            this.$nextTick(() => {
                this.$refs.list
                    ?.querySelector(`[data-slot="select-option"][data-value="${CSS.escape(this.active)}"]`)
                    ?.scrollIntoView({ block: 'nearest' });
            });
        },

        /**
         * Stable DOM id for the active option, so the trigger can point
         * `aria-activedescendant` at it. Returns null when nothing is active.
         */
        activeId() {
            return this.active == null
                ? null
                : `${this.$id('select-list')}-option-${this.encodeId(this.active)}`;
        },

        /** Turn an arbitrary option value into an id-safe suffix. */
        encodeId(value) {
            return String(value).replace(/[^a-zA-Z0-9_-]/g, '-');
        },

        typeahead(event) {
            // Only printable single characters; ignore navigation/modifier keys.
            if (event.key.length !== 1 || event.metaKey || event.ctrlKey || event.altKey) {
                return;
            }
            if (!this.open) {
                this.show();
            }
            clearTimeout(this.typedTimer);
            this.typed += event.key.toLowerCase();
            this.typedTimer = setTimeout(() => (this.typed = ''), 600);

            const match = this.options().find((el) =>
                (el.dataset.label || '').toLowerCase().startsWith(this.typed)
            );
            if (match) {
                this.active = match.dataset.value;
                this.scrollActiveIntoView();
            }
        },

        choose() {
            if (this.active == null) {
                return;
            }
            this.$refs.list
                ?.querySelector(`[data-slot="select-option"][data-value="${CSS.escape(this.active)}"]`)
                ?.click();
        },

        select(value, label) {
            this.value = value;
            this.label = label;
            this.open = false;
            this.$dispatch('change', { value });
            this.$nextTick(() => this.$refs.trigger?.focus());
        },

        destroy() {
            // Clear the pending type-ahead reset so the timer cannot fire after teardown.
            clearTimeout(this.typedTimer);
        },
    }));
});

Ownership & lifecycle

Owner, release state, review evidence and adoption for this item.
Owner
Platform UI (@JoshJML)
Current version
1.4.3
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