Navigation
command
Command palette on a native dialog: opens with Cmd/Ctrl+K, filters grouped items as you type, navigates to links or dispatches a command-select event.
Press ⌘K or click the button.
@php
// In a real app these come from the controller.
$commands = [
'Suggestions' => [
['label' => 'Calendar', 'value' => 'calendar'],
['label' => 'Search emoji', 'value' => 'emoji'],
['label' => 'Calculator', 'value' => 'calculator'],
],
'Settings' => [
['label' => 'Profile', 'value' => 'profile', 'shortcut' => '⌘P'],
['label' => 'Billing', 'value' => 'billing', 'shortcut' => '⌘B'],
['label' => 'Settings', 'value' => 'settings', 'shortcut' => '⌘S'],
],
'Pages' => [
['label' => 'Components', 'href' => '/components'],
],
];
@endphp
<div class="flex w-full flex-col items-center gap-3">
<x-ui.command :groups="$commands" />
<p class="text-sm text-muted-foreground" data-command-demo-output>
Press ⌘K or click the button.</p>
</div>
<script>
window.addEventListener('command-select', function(event) {
document.querySelector('[data-command-demo-output]').textContent =
'Selected: ' + event.detail.label + ' (' + event.detail.value + ')';
});
</script>
Installation
php artisan ui:add command
1. Install dependencies
- composer:
gehrisandro/tailwind-merge-laravel
2.
Copy the source into
resources/views/components/ui/
resources/views/components/ui/command.blade.php
@props([
'groups' => [],
'shortcut' => 'k',
'placeholder' => 'Search...',
'searchPlaceholder' => 'Type a command or search...',
'empty' => 'No results found.',
'label' => 'Command palette',
])
@php
// A command palette on a native dialog element: top layer, focus trap and
// Esc come from the platform. groups is ['Heading' => [item, ...]] where
// an item is ['label' => ..., 'href' => ...] (navigates) or
// ['label' => ..., 'value' => ...] (dispatches a bubbling command-select
// event on the dialog, which reaches window), plus an optional 'shortcut'.
$id = 'ui-command-' . bin2hex(random_bytes(4));
$shortcut = strtolower((string) $shortcut);
// Not bg-black/50: Chrome does not paint oklab() with alpha in the dialog
// top layer, so the scrim would render as nothing. Legacy rgb() works.
$overlay = 'absolute inset-0 bg-[rgb(0_0_0/0.5)] opacity-0 transition-opacity duration-200 group-data-[state=open]/command:opacity-100';
$panel = \TailwindMerge\Laravel\Facades\TailwindMerge::merge(
'absolute left-1/2 top-[15%] w-full max-w-[calc(100%-2rem)] -translate-x-1/2 scale-95 overflow-hidden rounded-lg border bg-popover text-popover-foreground opacity-0 shadow-lg transition-all duration-200 group-data-[state=open]/command:scale-100 group-data-[state=open]/command:opacity-100 sm:max-w-lg',
$attributes->get('class'),
);
$item = 'flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none data-[active=true]:bg-accent data-[active=true]:text-accent-foreground';
@endphp
<div data-ui-command-trigger aria-controls="{{ $id }}" aria-haspopup="dialog"
{{ $attributes->except('class') }}>
@isset($trigger)
{{ $trigger }}
@else
<button type="button"
class="inline-flex h-9 w-full items-center gap-2 rounded-md border border-input bg-transparent px-3 text-sm text-muted-foreground shadow-xs outline-none transition-[color,box-shadow] hover:bg-accent hover:text-accent-foreground dark:bg-input/30 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] sm:w-64">
<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>
<span class="truncate">{{ $placeholder }}</span>
@if ($shortcut !== '')
<kbd data-ui-command-kbd
class="pointer-events-none ms-auto inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground"
dir="ltr">⌘{{ strtoupper($shortcut) }}</kbd>
@endif
</button>
@endisset
</div>
<dialog id="{{ $id }}" data-ui-command data-state="closed"
data-shortcut="{{ $shortcut }}" aria-label="{{ $label }}"
class="group/command m-0 h-full max-h-none w-full max-w-none bg-transparent p-0 text-foreground backdrop:bg-transparent">
<div class="{{ $overlay }}" data-ui-command-close></div>
<div class="{{ $panel }}">
<div class="flex h-12 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-command-search role="combobox" autofocus
aria-expanded="true" aria-autocomplete="list"
aria-controls="{{ $id }}-listbox" autocomplete="off"
spellcheck="false" placeholder="{{ $searchPlaceholder }}"
aria-label="{{ $searchPlaceholder }}"
class="flex h-full w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground" />
</div>
<div id="{{ $id }}-listbox" role="listbox" aria-label="{{ $label }}"
class="max-h-80 overflow-y-auto p-1">
@foreach ($groups as $heading => $items)
<div role="group" data-ui-command-group
aria-labelledby="{{ $id }}-g{{ $loop->index }}"
class="py-1">
<div id="{{ $id }}-g{{ $loop->index }}"
class="px-2 py-1.5 text-xs font-medium text-muted-foreground">
{{ $heading }}</div>
@foreach ($items as $entry)
@php($tag = empty($entry['href']) ? 'div' : 'a')
<{{ $tag }} id="{{ $id }}-{{ $loop->parent->index }}-{{ $loop->index }}"
role="option" data-ui-command-item
@if ($tag === 'a') href="{{ $entry['href'] }}" tabindex="-1"
@else data-value="{{ $entry['value'] ?? $entry['label'] }}" @endif
class="{{ $item }}">
<span data-ui-command-label
class="truncate">{{ $entry['label'] }}</span>
@if (!empty($entry['shortcut']))
<span
class="ms-auto text-xs tracking-widest text-muted-foreground"
dir="ltr">{{ $entry['shortcut'] }}</span>
@endif
</{{ $tag }}>
@endforeach
</div>
@endforeach
</div>
<p data-ui-command-empty hidden
class="py-6 text-center text-sm text-muted-foreground">
{{ $empty }}</p>
</div>
</dialog>
@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.__laralcnCommand) return;
window.__laralcnCommand = true;
var mac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
// Case- and accent-insensitive, and Arabic harakat are ignored too.
function fold(text) {
return text.normalize('NFD').replace(/[̀-ًͯ-ْ]/g, '').toLowerCase();
}
function items(dialog) {
return Array.from(dialog.querySelectorAll('[data-ui-command-item]'))
.filter(function(item) { return !item.hidden; });
}
function setActive(dialog, item) {
dialog.querySelectorAll('[data-ui-command-item][data-active]').forEach(function(i) {
i.removeAttribute('data-active');
});
var search = dialog.querySelector('[data-ui-command-search]');
if (!item) return search.removeAttribute('aria-activedescendant');
item.setAttribute('data-active', 'true');
search.setAttribute('aria-activedescendant', item.id);
item.scrollIntoView({ block: 'nearest' });
}
function filter(dialog) {
var query = fold(dialog.querySelector('[data-ui-command-search]').value.trim());
dialog.querySelectorAll('[data-ui-command-item]').forEach(function(item) {
var text = item.querySelector('[data-ui-command-label]').textContent + ' ' + (item.dataset.value || '');
item.hidden = query !== '' && fold(text).indexOf(query) === -1;
});
dialog.querySelectorAll('[data-ui-command-group]').forEach(function(group) {
group.hidden = !group.querySelector('[data-ui-command-item]:not([hidden])');
});
var shown = items(dialog);
dialog.querySelector('[data-ui-command-empty]').hidden = shown.length > 0;
setActive(dialog, shown[0]);
}
function open(dialog) {
if (dialog.open) return;
// The top layer does not rescue a display:none ancestor, so move
// the dialog to the body, keeping its direction and language.
if (dialog.parentElement !== document.body) {
if (!dialog.dir) dialog.dir = getComputedStyle(dialog.parentElement).direction;
var lang = dialog.parentElement.closest('[lang]');
if (!dialog.lang && lang) dialog.lang = lang.lang;
document.body.appendChild(dialog);
}
var search = dialog.querySelector('[data-ui-command-search]');
search.value = '';
filter(dialog);
dialog.showModal();
search.focus();
document.documentElement.style.overflow = 'hidden';
// Flush the closed frame, then flip the state in the same tick.
dialog.getBoundingClientRect();
dialog.dataset.state = 'open';
}
function close(dialog) {
if (dialog.dataset.state === 'closed') return;
dialog.dataset.state = 'closed';
document.documentElement.style.overflow = '';
// Let the exit transition play out before leaving the top layer.
setTimeout(function() { dialog.close(); }, 200);
}
function run(dialog, item, viaClick) {
if (item.tagName === 'A') {
// A real click on a link already navigates on its own.
if (!viaClick) item.click();
} else {
dialog.dispatchEvent(new CustomEvent('command-select', {
bubbles: true,
detail: {
value: item.dataset.value,
label: item.querySelector('[data-ui-command-label]').textContent.trim(),
},
}));
}
close(dialog);
}
// Show Ctrl instead of the Mac command key everywhere else.
function relabel() {
if (mac) return;
document.querySelectorAll('[data-ui-command-kbd]').forEach(function(kbd) {
kbd.textContent = kbd.textContent.replace('⌘', 'Ctrl ');
});
}
document.readyState === 'loading' ? document.addEventListener('DOMContentLoaded', relabel) : relabel();
document.addEventListener('click', function(event) {
var trigger = event.target.closest('[data-ui-command-trigger]');
if (trigger) {
var target = document.getElementById(trigger.getAttribute('aria-controls'));
if (target) open(target);
return;
}
var item = event.target.closest('[data-ui-command-item]');
if (item) return run(item.closest('[data-ui-command]'), item, true);
var closer = event.target.closest('[data-ui-command-close]');
if (closer) close(closer.closest('[data-ui-command]'));
});
document.addEventListener('mousemove', function(event) {
var item = event.target.closest('[data-ui-command-item]');
if (item && !item.hasAttribute('data-active')) setActive(item.closest('[data-ui-command]'), item);
});
// Capture phase, then stop: the search box's typing is internal and
// must not reach form or wire:model listeners around the palette.
['input', 'change'].forEach(function(type) {
document.addEventListener(type, function(event) {
if (!event.target.matches('[data-ui-command-search]')) return;
event.stopPropagation();
if (type === 'input') filter(event.target.closest('[data-ui-command]'));
}, true);
});
document.addEventListener('keydown', function(event) {
// Cmd/Ctrl + shortcut toggles the first palette bound to it.
if ((event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && event.key.length === 1) {
var bound = document.querySelector('[data-ui-command][data-shortcut="' + event.key.toLowerCase() + '"]');
if (bound) {
event.preventDefault();
bound.dataset.state === 'open' ? close(bound) : open(bound);
return;
}
}
if (!event.target.matches('[data-ui-command-search]')) return;
var dialog = event.target.closest('[data-ui-command]');
var list = items(dialog);
var current = list.indexOf(dialog.querySelector('[data-ui-command-item][data-active]'));
switch (event.key) {
case 'ArrowDown':
event.preventDefault();
setActive(dialog, list[(current + 1) % list.length]);
break;
case 'ArrowUp':
event.preventDefault();
setActive(dialog, list[(current - 1 + list.length) % list.length]);
break;
case 'Home':
case 'End':
event.preventDefault();
setActive(dialog, list[event.key === 'Home' ? 0 : list.length - 1]);
break;
case 'Enter':
event.preventDefault();
if (current > -1) run(dialog, list[current], false);
break;
}
});
// Esc: animate out instead of the instant native dismissal. cancel
// and close do not bubble, so both listen in the capture phase.
document.addEventListener('cancel', function(event) {
if (!event.target.matches('[data-ui-command]')) return;
event.preventDefault();
close(event.target);
}, true);
// Chrome force-closes on a repeated Esc; release the lock anyway.
document.addEventListener('close', function(event) {
if (!event.target.matches('[data-ui-command]')) return;
event.target.dataset.state = 'closed';
document.documentElement.style.overflow = '';
}, true);
})();
</script>
@endonce
Usage
@php
$commands = [
'Pages' => [
['label' => 'Profile', 'href' => '/profile', 'shortcut' => '⌘P'],
['label' => 'Billing', 'href' => '/billing'],
],
'Actions' => [
['label' => 'New invoice', 'value' => 'new-invoice'],
['label' => 'Log out', 'value' => 'logout'],
],
];
@endphp
<x-ui.command :groups="$commands" />
{{-- Your own trigger, a different shortcut (empty disables it) --}}
<x-ui.command :groups="$commands" shortcut="j">
<x-slot:trigger>
<x-ui.button variant="outline">Open palette</x-ui.button>
</x-slot:trigger>
</x-ui.command>
<script>
// Items with a value dispatch command-select; it bubbles to window.
window.addEventListener('command-select', (event) => {
const { value, label } = event.detail;
if (value === 'new-invoice') location.href = '/invoices/create';
});
</script>
{{-- Livewire: listen with Alpine and call the component,
e.g. x-on:command-select.window="$wire.run($event.detail.value)"
on any element, or in a script block:
window.addEventListener('command-select', e => $wire.run(e.detail.value)) --}}
Pass :groups as ['Heading' => [['label' => ..., 'href' => ...], ['label' => ..., 'value' => ...]]]; items with href navigate, items with value dispatch a bubbling command-select event (detail { value, label }) that reaches window. shortcut (default k, empty to disable) binds Cmd/Ctrl+key, an optional trigger slot replaces the default search button, and placeholder, search-placeholder, empty and label set the copy.
Props
Every prop with its default. Pass any of them as attributes, using : to bind a PHP value.
@props([
'groups' => [],
'shortcut' => 'k',
'placeholder' => 'Search...',
'searchPlaceholder' => 'Type a command or search...',
'empty' => 'No results found.',
'label' => 'Command palette',
])