Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

16.8 KB
Raw Blame
@props([
    'id' => null,
    'htmlId' => null,
    'label' => null,
    'helper' => null,
    'required' => false,
    'options' => [], // list of ['value' => ..., 'label' => ..., 'description' => ?string, 'disabled' => bool, 'dot' => ?string, 'state' => ?string]
    'placeholder' => 'Select…',
    'emptyText' => 'No options available.',
    'live' => false,
    'onChange' => null, // optional $wire method to call after a selection
    'onChangeArgs' => null, // optional arguments followed by the selected value
    'wire' => true, // false = purely client-side value (no Livewire binding)
    'value' => null, // initial value when wire=false
    'disabled' => false,
    'tooltip' => true,
    'portal' => false,
    'preserveValue' => false,
    'canGate' => null,
    'canResource' => null,
    'autoDisable' => true,
    'multiple' => false, // true = the bound value is an array of option values
    'searchable' => false, // true = a search field filters the options
    'searchPlaceholder' => 'Search…',
    'searchEmptyText' => 'No matching options',
    'allowCustom' => false, // true (with searchable) = the search text can be chosen as a custom value
])

@php
    if ($canGate && $canResource && $autoDisable && ! Illuminate\Support\Facades\Gate::allows($canGate, $canResource)) {
        $disabled = true;
    }

    $triggerId = ($htmlId ?? $id).'-trigger';
    $panelId = ($htmlId ?? $id).'-panel';

    // A multiple listbox also shows item errors, for example a rule on `ids.*`.
    $errorMessage = $wire && $id && isset($errors)
        ? ($errors->first($id) ?: ($multiple ? $errors->first($id.'.*') : null))
        : null;

    if ($multiple) {
        // Server-rendered trigger text; Alpine keeps it current after init.
        if (! $wire) {
            $value = is_array($value) ? array_values($value) : [];
        }
        $selectedValues = $wire ? data_get($__livewire ?? null, $id) : $value;
        $selectedValues = is_array($selectedValues) ? array_map('strval', $selectedValues) : [];
        $selectedLabels = collect($options)
            ->filter(fn ($option) => empty($option['header']) && in_array((string) $option['value'], $selectedValues, true))
            ->pluck('label');
        $multipleLabel = match (true) {
            $selectedLabels->isEmpty() => $placeholder,
            $selectedLabels->count() <= 2 => $selectedLabels->implode(', '),
            default => $selectedLabels->count().' selected',
        };
    }
@endphp

<div class="w-full min-w-0">
    @if ($label)
        {{--
            Keep helper outside the label so taps do not open the listbox trigger.
            Margin lives only on this wrapper (mb-0 on the label) so spacing matches
            plain text labels and is not doubled by .application-settings-form label rules.
        --}}
        {{-- Fixed h-4 matches the helper icon so side-by-side fields align with or without a helper. --}}
        <div class="mb-1.5 flex h-4 w-full items-center gap-1.5">
            <label for="{{ $triggerId }}" class="mb-0! flex items-center gap-1.5 leading-4">
                {{ $label }}
                @if ($required)
                    <x-highlighted text="*" />
                @endif
            </label>
            @if ($helper)
                <x-helper :helper="$helper" />
            @endif
        </div>
    @endif
    <div class="relative min-w-0" x-data="{
        open: false,
        positioned: false,
        panelPosition: {},
        saving: false,
        options: @js(array_values($options)),
        @if ($searchable)
        query: '',
        init() {
            this.$watch('open', (open) => open ? this.$nextTick(() => this.$refs.search?.focus()) : this.query = '');
        },
        get visibleOptions() {
            const query = this.query.toLowerCase().trim();
            if (query === '') return this.options;
            return this.options.filter((option) => !option.header && [option.label, option.value, option.description, option.state]
                .some((text) => String(text ?? '').toLowerCase().includes(query)));
        },
        get customOption() {
            const query = this.query.trim();
            if (!@js($allowCustom) || query === '' || this.options.some((option) => !option.header && String(option.value) === query)) return null;
            return { value: query, label: query };
        },
        chooseOnlyMatch() {
            const matches = this.visibleOptions.filter((option) => !option.disabled);
            if (matches.length === 1) this.choose(matches[0]);
            else if (this.customOption) this.choose(this.customOption);
        },
        @else
        get visibleOptions() {
            return this.options;
        },
        @endif
        get selectedOption() {
            @if ($multiple)
                return null;
            @else
                return this.options.find((option) => String(option.value) === String(this.value)) ?? null;
            @endif
        },
        dotClass(dot) {
            return {
                success: 'bg-success',
                warning: 'bg-warning',
                error: 'bg-error',
                neutral: 'bg-neutral-400',
            }[dot] ?? '';
        },
        value: @if (!$wire) @js($value) @elseif ($live && ! $onChange) @entangle($id).live @else @entangle($id) @endif,
        @if ($multiple)
        get selected() {
            return Array.isArray(this.value) ? this.value : [];
        },
        isSelected(option) {
            return this.selected.some((value) => String(value) === String(option.value));
        },
        get selectedLabels() {
            return this.options.filter((option) => !option.header && this.isSelected(option)).map((option) => option.label);
        },
        get current() {
            const labels = this.selectedLabels;
            if (labels.length === 0) return @js($placeholder);
            return labels.length <= 2 ? labels.join(', ') : `${labels.length} selected`;
        },
        get title() {
            return this.selectedLabels.join(', ') || @js($placeholder);
        },
        @else
        isSelected(option) {
            return String(option.value) === String(this.value);
        },
        get current() {
            const found = this.options.find((option) => String(option.value) === String(this.value));
            if (found) return found.label;
            return @js($allowCustom) && this.value ? String(this.value) : @js($placeholder);
        },
        get title() {
            return this.current;
        },
        @endif
        async choose(option) {
            if (option.header || option.disabled || this.saving) return;
            @if ($multiple)
                {{-- Replace the whole array: an in-place splice makes Livewire send two updates for one click. --}}
                const next = this.isSelected(option)
                    ? this.selected.filter((value) => String(value) !== String(option.value))
                    : [...this.selected, option.value];
            @else
                this.open = false;
                if (String(option.value) === String(this.value)) return;
                const next = option.value;
            @endif
            this.value = next;
            this.$dispatch('listbox-change', { value: next });
            @if ($onChange && is_array($onChangeArgs))
                this.saving = true;
                try {
                    await this.$wire.{{ $onChange }}(...@js($onChangeArgs), next);
                } finally {
                    this.saving = false;
                }
            @elseif ($onChange)
                this.saving = true;
                try {
                    await this.$wire.{{ $onChange }}();
                } finally {
                    this.saving = false;
                }
            @endif
        },
        toggle() {
            this.open = !this.open;
            this.positioned = false;
        },
        positionPanel(panel = null) {
            const trigger = this.$refs.trigger;
            panel ??= this.$refs.panel;
            if (!trigger || !panel) return;

            const gap = 4;
            const edge = 12;
            const triggerRect = trigger.getBoundingClientRect();
            panel.style.width = 'max-content';
            panel.style.minWidth = `${triggerRect.width}px`;
            panel.style.maxWidth = `${window.innerWidth - (edge * 2)}px`;
            const panelWidth = Math.min(
                Math.max(triggerRect.width, panel.offsetWidth),
                window.innerWidth - (edge * 2),
            );
            const panelHeight = Math.min(panel.scrollHeight, 256);
            const fitsBelow = window.innerHeight - triggerRect.bottom - gap >= panelHeight;
            const top = fitsBelow
                ? triggerRect.bottom + gap
                : Math.max(edge, triggerRect.top - gap - panelHeight);
            const left = Math.min(
                Math.max(edge, triggerRect.left),
                window.innerWidth - panelWidth - edge,
            );

            // Kept in state for the :style binding, because a Livewire morph resets the inline style.
            // minWidth and maxWidth too: a fixed panel resolves the CSS min-width: 100% against the viewport.
            this.panelPosition = {
                top: `${top}px`,
                left: `${left}px`,
                width: `${panelWidth}px`,
                minWidth: panel.style.minWidth,
                maxWidth: panel.style.maxWidth,
            };
            this.positioned = true;
        },
    }" x-modelable="value" :class="{ 'pointer-events-none opacity-70': saving }"
        {{-- Livewire morphs this attribute in place, so new options arrive without closing an open panel. --}}
        data-options="{{ json_encode(array_values($options)) }}"
        x-init="new MutationObserver(() => options = JSON.parse($el.dataset.options)).observe($el, { attributeFilter: ['data-options'] })"
        {{ $attributes->whereStartsWith('x-model') }}
        {{ $attributes->whereStartsWith('x-effect') }}
        @if ($preserveValue) wire:ignore @endif
        @click.outside="$refs.panel?.contains($event.target) || (open = false)" @keydown.escape="open = false" @resize.window="open && positionPanel()"
        @scroll.window.capture="open && positionPanel()">
        <button x-ref="trigger" id="{{ $triggerId }}" type="button" class="listbox-trigger" @click="toggle()"
            @disabled($disabled) {{ $attributes->whereStartsWith('x-bind:disabled') }} aria-haspopup="listbox"
            :aria-expanded="open" @if ($tooltip) :title="title" @endif>
            <span class="listbox-trigger-label flex items-center gap-2">
                <span x-show="selectedOption?.dot" class="size-1.5 shrink-0 rounded-full" :class="dotClass(selectedOption?.dot)"></span>
                <span class="min-w-0 truncate" x-text="current">{{ $multiple ? $multipleLabel : '' }}</span>
                <span x-show="selectedOption?.state" class="shrink-0 text-xs text-neutral-500 dark:text-fg-dim" x-text="selectedOption?.state"></span>
            </span>
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2"
                stroke="currentColor" class="size-3.5 shrink-0 opacity-60">
                <path stroke-linecap="round" stroke-linejoin="round" d="m8 9 4-4 4 4m0 6-4 4-4-4" />
            </svg>
        </button>
        {{-- Fixed positioning lets the panel escape overflow containers such as modal bodies and tables.
             portal also moves it to <body>, for an ancestor with a transform or filter. --}}
        @if ($portal)
            <template x-teleport="body">
        @endif
            <div x-ref="panel" id="{{ $panelId }}" class="listbox-panel{{ $searchable ? ' searchable-listbox-panel' : '' }}"
                style="position: fixed; z-index: 9999; visibility: hidden" x-show="open"
                x-cloak :style="{ visibility: positioned ? 'visible' : 'hidden', ...panelPosition }"
                x-transition:enter="transition ease-out duration-100"
                x-transition:enter-start="opacity-0 -translate-y-1 scale-[0.98]"
                x-transition:enter-end="opacity-100 translate-y-0 scale-100"
                x-transition:leave="transition ease-in duration-75"
                x-transition:leave-start="opacity-100 translate-y-0 scale-100"
                x-transition:leave-end="opacity-0 -translate-y-1 scale-[0.98]"
                x-effect="if (open) requestAnimationFrame(() => positionPanel($el))" role="listbox"
                @if ($multiple) aria-multiselectable="true" @endif>
                @if ($searchable)
                    <div class="searchable-listbox-search">
                        <x-reicon name="search"
                            class="pointer-events-none absolute top-1/2 left-3 size-3 -translate-y-1/2 text-neutral-400 dark:text-fg-faint" />
                        <input x-ref="search" type="search" x-model="query" autocomplete="off"
                            placeholder="{{ $searchPlaceholder }}" class="searchable-listbox-search-input"
                            @keydown.enter.prevent="chooseOnlyMatch()" @keydown.escape.stop="open = false" />
                    </div>
                    <div class="searchable-listbox-options">
                @endif
                <div x-show="visibleOptions.length === 0{{ $searchable && $allowCustom ? ' && !customOption' : '' }}"
                    class="px-3 py-2 text-[13px] text-neutral-500 dark:text-fg-dim">
                    @if ($searchable)
                        <span x-text="options.length === 0 ? @js($emptyText) : @js($searchEmptyText)"></span>
                    @else
                        {{ $emptyText }}
                    @endif
                </div>
                <template x-for="option in visibleOptions" :key="String(option.value)">
                    <div>
                        {{-- Non-selectable group header (options with header: true). --}}
                        <template x-if="option.header">
                            <div class="mt-1 border-t border-neutral-100 px-3 pt-2 pb-1 text-[10px] font-semibold tracking-wide text-neutral-400 uppercase dark:border-white/[0.06] dark:text-fg-faint"
                                x-text="option.label"></div>
                        </template>
                        <template x-if="!option.header">
                            <button type="button" class="listbox-option" role="option"
                                :class="{ 'listbox-option-disabled': option.disabled }"
                                :aria-selected="isSelected(option)" @click="choose(option)">
                                <span class="flex min-w-0 items-center gap-2 text-left">
                                    <span x-show="option.dot" class="size-1.5 shrink-0 rounded-full" :class="dotClass(option.dot)"></span>
                                    <span class="flex min-w-0 flex-col items-start">
                                        <span class="flex min-w-0 items-baseline gap-2">
                                            <span class="truncate" x-text="option.label"></span>
                                            <span x-show="option.state" x-text="option.state"
                                                class="shrink-0 text-xs text-neutral-500 dark:text-fg-dim"></span>
                                        </span>
                                        <span x-show="option.description" x-text="option.description"
                                            class="text-xs whitespace-normal text-neutral-500 dark:text-fg-dim"></span>
                                    </span>
                                </span>
                                <svg x-show="isSelected(option)" xmlns="http://www.w3.org/2000/svg"
                                    fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"
                                    class="ml-auto size-3.5 shrink-0">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" />
                                </svg>
                            </button>
                        </template>
                    </div>
                </template>
                @if ($searchable && $allowCustom)
                    <template x-if="customOption">
                        <button type="button" class="listbox-option" role="option" aria-selected="false"
                            @click="choose(customOption)">
                            <span class="truncate">Use <span class="font-mono" x-text="customOption.label"></span></span>
                        </button>
                    </template>
                @endif
                @if ($searchable)
                    </div>
                @endif
            </div>
        @if ($portal)
            </template>
        @endif
    </div>
    @if ($errorMessage)
        <label class="label">
            <span class="text-red-500 label-text-alt">{{ $errorMessage }}</span>
        </label>
    @endif
</div>