النماذج
combobox
قائمة اختيار قابلة للبحث: يفتح الزر قائمة خيارات قابلة للتصفية مع دعم كامل للوحة المفاتيح. تُرسَل مع النموذج عبر حقل مخفي.
@php
// In a real app these come from the controller.
$frameworks = [
'laravel' => 'لارافيل',
'symfony' => 'سيمفوني',
'rails' => 'روبي أون ريلز',
'django' => 'جانغو',
'phoenix' => 'فينيكس',
'nextjs' => 'نكست جي إس',
'sveltekit' => 'سفيلت كيت',
'nuxt' => 'نكست',
];
@endphp
<div class="w-full max-w-xs space-y-2">
<x-ui.label for="framework">إطار العمل</x-ui.label>
<x-ui.combobox id="framework" name="framework" :options="$frameworks"
placeholder="اختر إطار العمل..." search-placeholder="ابحث عن إطار عمل..."
empty="لم يُعثر على إطار عمل." />
</div>
التثبيت
php artisan ui:add combobox
1. ثبّت الاعتماديات
- composer:
gehrisandro/tailwind-merge-laravel
2.
انسخ الكود إلى
resources/views/components/ui/
resources/views/components/ui/combobox.blade.php
@props([
'name' => null,
'options' => [],
'value' => null,
'placeholder' => 'Select an option...',
'searchPlaceholder' => 'Search...',
'empty' => 'No results.',
'disabled' => false,
])
@php
// A searchable select. The value lives in a hidden input, so it submits
// with a normal form and fires a bubbling change event when it changes.
// `id` lands on the trigger button (so a label's for= points at it),
// `class` and `style` on the wrapper, everything else (wire:model,
// x-model, x-on:change, form, data-*) on the hidden input.
$id = 'ui-combobox-' . bin2hex(random_bytes(4));
$selected = $value !== null && array_key_exists((string) $value, $options) ? (string) $value : null;
$classes = \TailwindMerge\Laravel\Facades\TailwindMerge::merge(
'group/combobox relative w-full text-start',
$attributes->get('class'),
);
@endphp
<div class="{{ $classes }}" data-ui-combobox data-state="closed"
@if ($attributes->has('style')) style="{{ $attributes->get('style') }}" @endif>
<input type="hidden" data-ui-combobox-input
@if ($name) name="{{ $name }}" @endif value="{{ $selected }}"
@disabled($disabled)
{{ $attributes->except(['class', 'style', 'id']) }} />
<button type="button" data-ui-combobox-trigger role="combobox"
@if ($attributes->has('id')) id="{{ $attributes->get('id') }}" @endif
aria-haspopup="listbox" aria-expanded="false"
aria-controls="{{ $id }}-listbox" @disabled($disabled)
class="flex h-9 w-full items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30 dark:hover:bg-input/50 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]">
<span data-ui-combobox-label
class="truncate data-[placeholder]:text-muted-foreground"
@if ($selected === null) data-placeholder @endif>{{ $selected === null ? $placeholder : $options[$selected] }}</span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"
viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="size-4 shrink-0 opacity-50" aria-hidden="true">
<path d="m7 15 5 5 5-5" />
<path d="m7 9 5-5 5 5" />
</svg>
</button>
<div data-ui-combobox-content
class="absolute start-0 z-50 mt-1 hidden w-full min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md">
<div class="flex items-center gap-2 border-b px-3">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"
viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="size-4 shrink-0 opacity-50" aria-hidden="true">
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</svg>
<input type="text" data-ui-combobox-search role="combobox"
aria-expanded="true" aria-autocomplete="list"
aria-controls="{{ $id }}-listbox" autocomplete="off"
spellcheck="false" placeholder="{{ $searchPlaceholder }}"
aria-label="{{ $searchPlaceholder }}"
class="flex h-9 w-full bg-transparent py-2 text-sm outline-none placeholder:text-muted-foreground" />
</div>
<ul id="{{ $id }}-listbox" role="listbox"
class="max-h-60 overflow-y-auto p-1">
@foreach ($options as $optionValue => $optionLabel)
<li id="{{ $id }}-{{ $loop->index }}" role="option"
data-ui-combobox-option data-value="{{ $optionValue }}"
aria-selected="{{ (string) $optionValue === $selected ? 'true' : 'false' }}"
class="group/option relative flex cursor-default select-none items-center rounded-sm py-1.5 pe-8 ps-2 text-sm outline-none data-[active=true]:bg-accent data-[active=true]:text-accent-foreground">
<span class="truncate">{{ $optionLabel }}</span>
<svg xmlns="http://www.w3.org/2000/svg" width="16"
height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round"
class="absolute end-2 size-4 opacity-0 group-aria-selected/option:opacity-100"
aria-hidden="true">
<path d="M20 6 9 17l-5-5" />
</svg>
</li>
@endforeach
</ul>
<p data-ui-combobox-empty hidden
class="py-6 text-center text-sm text-muted-foreground">
{{ $empty }}</p>
</div>
</div>
@once
<script>
(function() {
// The Blade once-directive keeps this to one copy per page; the
// flag also covers markup echoed twice by a parent component.
if (window.__laralcnCombobox) return;
window.__laralcnCombobox = true;
// Case- and accent-insensitive, and Arabic harakat are ignored too.
function fold(text) {
return text.normalize('NFD').replace(/[̀-ًͯ-ْ]/g, '').toLowerCase();
}
function part(root, name) {
return root.querySelector('[data-ui-combobox-' + name + ']');
}
function visible(root) {
return Array.from(root.querySelectorAll('[data-ui-combobox-option]'))
.filter(function(option) { return !option.hidden; });
}
function setActive(root, option) {
root.querySelectorAll('[data-ui-combobox-option][data-active]').forEach(function(o) {
o.removeAttribute('data-active');
});
var search = part(root, 'search');
if (!option) return search.removeAttribute('aria-activedescendant');
option.setAttribute('data-active', 'true');
search.setAttribute('aria-activedescendant', option.id);
option.scrollIntoView({ block: 'nearest' });
}
function filter(root) {
var query = fold(part(root, 'search').value.trim());
root.querySelectorAll('[data-ui-combobox-option]').forEach(function(option) {
option.hidden = query !== '' && fold(option.textContent).indexOf(query) === -1;
});
var shown = visible(root);
part(root, 'empty').hidden = shown.length > 0;
setActive(root, shown[0]);
}
function open(root, seed) {
closeAll(root);
root.dataset.state = 'open';
part(root, 'trigger').setAttribute('aria-expanded', 'true');
part(root, 'content').classList.remove('hidden');
var search = part(root, 'search');
search.value = seed || '';
filter(root);
if (!seed) setActive(root, root.querySelector('[data-ui-combobox-option][aria-selected="true"]') || visible(root)[0]);
search.focus();
}
function close(root, refocus) {
if (root.dataset.state !== 'open') return;
root.dataset.state = 'closed';
part(root, 'trigger').setAttribute('aria-expanded', 'false');
part(root, 'content').classList.add('hidden');
if (refocus) part(root, 'trigger').focus();
}
function closeAll(except) {
document.querySelectorAll('[data-ui-combobox][data-state="open"]').forEach(function(root) {
if (root !== except) close(root, false);
});
}
function select(root, option) {
var input = part(root, 'input');
var label = part(root, 'label');
var changed = input.value !== option.dataset.value;
root.querySelectorAll('[data-ui-combobox-option]').forEach(function(o) {
o.setAttribute('aria-selected', o === option ? 'true' : 'false');
});
label.textContent = option.textContent.trim();
label.removeAttribute('data-placeholder');
input.value = option.dataset.value;
close(root, true);
// input for x-model and wire:model, change for everything else.
if (changed) {
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
}
document.addEventListener('click', function(event) {
var trigger = event.target.closest('[data-ui-combobox-trigger]');
if (trigger) {
var root = trigger.closest('[data-ui-combobox]');
root.dataset.state === 'open' ? close(root, false) : open(root);
return;
}
var option = event.target.closest('[data-ui-combobox-option]');
if (option) return select(option.closest('[data-ui-combobox]'), option);
var inside = event.target.closest('[data-ui-combobox]');
closeAll(inside);
});
document.addEventListener('mousemove', function(event) {
var option = event.target.closest('[data-ui-combobox-option]');
if (option && !option.hasAttribute('data-active')) setActive(option.closest('[data-ui-combobox]'), option);
});
// Capture phase, then stop: the search box's own input and change
// events must not reach a wrapper listening for the value.
['input', 'change'].forEach(function(type) {
document.addEventListener(type, function(event) {
if (!event.target.matches('[data-ui-combobox-search]')) return;
event.stopPropagation();
if (type === 'input') filter(event.target.closest('[data-ui-combobox]'));
}, true);
});
document.addEventListener('keydown', function(event) {
var trigger = event.target.closest('[data-ui-combobox-trigger]');
if (trigger) {
var key = event.key;
// Arrows open it; so does typing, which seeds the search.
if (key === 'ArrowDown' || key === 'ArrowUp') {
event.preventDefault();
open(trigger.closest('[data-ui-combobox]'));
} else if (key.length === 1 && key !== ' ' && !event.ctrlKey && !event.metaKey && !event.altKey) {
event.preventDefault();
open(trigger.closest('[data-ui-combobox]'), key);
}
return;
}
if (!event.target.matches('[data-ui-combobox-search]')) return;
var root = event.target.closest('[data-ui-combobox]');
var options = visible(root);
var current = options.indexOf(root.querySelector('[data-ui-combobox-option][data-active]'));
switch (event.key) {
case 'ArrowDown':
event.preventDefault();
setActive(root, options[(current + 1) % options.length]);
break;
case 'ArrowUp':
event.preventDefault();
setActive(root, options[(current - 1 + options.length) % options.length]);
break;
case 'Home':
case 'End':
event.preventDefault();
setActive(root, options[event.key === 'Home' ? 0 : options.length - 1]);
break;
case 'Enter':
// Never submit the surrounding form from the search box.
event.preventDefault();
if (current > -1) select(root, options[current]);
break;
case 'Escape':
event.preventDefault();
close(root, true);
break;
case 'Tab':
close(root, false);
break;
}
});
})();
</script>
@endonce
الاستخدام
<x-ui.combobox name="framework" :options="$frameworks"
placeholder="Select framework..." />
{{-- Preselected value, translated copy, disabled --}}
<x-ui.combobox name="country" :options="$countries" value="ae"
search-placeholder="Search country..." empty="No country found." />
<x-ui.combobox name="plan" :options="$plans" disabled />
{{-- Livewire / Alpine: the attribute lands on the hidden input --}}
<x-ui.combobox wire:model.live="framework" :options="$frameworks" />
{{-- React to the value: change bubbles from the hidden input --}}
<x-ui.combobox name="framework" :options="$frameworks"
onchange="console.log('Picked', event.target.value)" />
مرّر name و:options بالشكل ['value' => 'Label'] وقيمة اختيارية value؛ وتحدد placeholder وsearch-placeholder وempty النصوص. يحمل حقل مخفي القيمة ويطلق حدثَي input وchange المتصاعدين، ويستقبل wire:model وx-model وأي سمات أخرى غير معروفة، بينما يوضع id على زر الفتح ليشير إليه الوسم. يأتي مع سكربت مضمّن خاص به، بلا اعتماديات JS.
الخصائص
كل خاصية مع قيمتها الافتراضية. مرّر أيًّا منها كسمة، واستخدم : لربط قيمة PHP.
@props([
'name' => null,
'options' => [],
'value' => null,
'placeholder' => 'Select an option...',
'searchPlaceholder' => 'Search...',
'empty' => 'No results.',
'disabled' => false,
])