Command Palette
Searchable list of commands in a modal dialog, filtered as you type, with arrow key navigation and an optional Ctrl+K or Cmd+K shortcut.
<x-markas.command
hotkey
:items="[
['group' => 'Suggestions', 'label' => 'Calendar', 'value' => 'calendar'],
['group' => 'Suggestions', 'label' => 'Search emoji', 'value' => 'emoji'],
['group' => 'Suggestions', 'label' => 'Calculator', 'value' => 'calculator'],
['group' => 'Settings', 'label' => 'Profile', 'value' => 'profile', 'shortcut' => 'Ctrl+P'],
['group' => 'Settings', 'label' => 'Billing', 'value' => 'billing', 'shortcut' => 'Ctrl+B'],
['group' => 'Settings', 'label' => 'Settings', 'value' => 'settings', 'shortcut' => 'Ctrl+S'],
]"
>
<x-slot:trigger>
<x-markas.button variant="secondary">Open command palette</x-markas.button>
</x-slot:trigger>
</x-markas.command>import { Button } from "@/components/markas/Button";
import { Command } from "@/components/markas/Command";
const items = [
{ group: "Suggestions", label: "Calendar", value: "calendar" },
{ group: "Suggestions", label: "Search emoji", value: "emoji" },
{ group: "Suggestions", label: "Calculator", value: "calculator" },
{ group: "Settings", label: "Profile", value: "profile", shortcut: "Ctrl+P" },
{ group: "Settings", label: "Billing", value: "billing", shortcut: "Ctrl+B" },
{
group: "Settings",
label: "Settings",
value: "settings",
shortcut: "Ctrl+S",
},
];
export default function CommandExample() {
return (
<Command
hotkey
items={items}
trigger={<Button variant="secondary">Open command palette</Button>}
/>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import Command from "@/components/markas/Command.vue";
const items = [
{ group: "Suggestions", label: "Calendar", value: "calendar" },
{ group: "Suggestions", label: "Search emoji", value: "emoji" },
{ group: "Suggestions", label: "Calculator", value: "calculator" },
{ group: "Settings", label: "Profile", value: "profile", shortcut: "Ctrl+P" },
{ group: "Settings", label: "Billing", value: "billing", shortcut: "Ctrl+B" },
{
group: "Settings",
label: "Settings",
value: "settings",
shortcut: "Ctrl+S",
},
];
</script>
<template>
<Command hotkey :items="items">
<template #trigger>
<Button variant="secondary">Open command palette</Button>
</template>
</Command>
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import Command from "$lib/components/markas/Command.svelte";
const items = [
{ group: "Suggestions", label: "Calendar", value: "calendar" },
{ group: "Suggestions", label: "Search emoji", value: "emoji" },
{ group: "Suggestions", label: "Calculator", value: "calculator" },
{
group: "Settings",
label: "Profile",
value: "profile",
shortcut: "Ctrl+P",
},
{
group: "Settings",
label: "Billing",
value: "billing",
shortcut: "Ctrl+B",
},
{
group: "Settings",
label: "Settings",
value: "settings",
shortcut: "Ctrl+S",
},
];
</script>
<Command hotkey {items}>
{#snippet trigger()}
<Button variant="secondary">Open command palette</Button>
{/snippet}
</Command>---
import Button from "@/components/markas/Button.astro";
import Command from "@/components/markas/Command.astro";
const items = [
{ group: "Suggestions", label: "Calendar", value: "calendar" },
{ group: "Suggestions", label: "Search emoji", value: "emoji" },
{ group: "Suggestions", label: "Calculator", value: "calculator" },
{ group: "Settings", label: "Profile", value: "profile", shortcut: "Ctrl+P" },
{ group: "Settings", label: "Billing", value: "billing", shortcut: "Ctrl+B" },
{
group: "Settings",
label: "Settings",
value: "settings",
shortcut: "Ctrl+S",
},
];
---
<Command hotkey items={items}>
<Button slot="trigger" variant="secondary">Open command palette</Button>
</Command>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Command } from "./markas/command.component";
@Component({
selector: "markas-example",
imports: [Button, Command],
template: `
<markas-command hotkey [items]="items">
<button markas-button trigger variant="secondary">
Open command palette
</button>
</markas-command>
`,
})
export default class CommandExample {
protected readonly items = [
{ group: "Suggestions", label: "Calendar", value: "calendar" },
{ group: "Suggestions", label: "Search emoji", value: "emoji" },
{ group: "Suggestions", label: "Calculator", value: "calculator" },
{
group: "Settings",
label: "Profile",
value: "profile",
shortcut: "Ctrl+P",
},
{
group: "Settings",
label: "Billing",
value: "billing",
shortcut: "Ctrl+B",
},
{
group: "Settings",
label: "Settings",
value: "settings",
shortcut: "Ctrl+S",
},
];
}Examples
Search field trigger
<x-markas.command
hotkey
:items="[
['group' => 'Pages', 'label' => 'Dashboard', 'value' => 'dashboard'],
['group' => 'Pages', 'label' => 'Invoices', 'value' => 'invoices'],
['group' => 'Pages', 'label' => 'Customers', 'value' => 'customers'],
['group' => 'Actions', 'label' => 'Create invoice', 'value' => 'create-invoice'],
['group' => 'Actions', 'label' => 'Add customer', 'value' => 'add-customer'],
]"
>
<x-slot:trigger>
<button type="button" class="flex h-10 w-full items-center gap-2 rounded-lg border border-line bg-surface px-3 text-left text-sm text-muted transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none">
<svg class="size-4 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></svg>
Search
<kbd class="ms-auto rounded-md border border-line bg-subtle px-1.5 py-0.5 font-sans text-xs text-muted">Ctrl K</kbd>
</button>
</x-slot:trigger>
</x-markas.command>import { Command } from "@/components/markas/Command";
const items = [
{ group: "Pages", label: "Dashboard", value: "dashboard" },
{ group: "Pages", label: "Invoices", value: "invoices" },
{ group: "Pages", label: "Customers", value: "customers" },
{ group: "Actions", label: "Create invoice", value: "create-invoice" },
{ group: "Actions", label: "Add customer", value: "add-customer" },
];
export default function Example() {
return (
<Command
hotkey
items={items}
trigger={
<button
type="button"
className="flex h-10 w-full items-center gap-2 rounded-lg border border-line bg-surface px-3 text-left text-sm text-muted transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none"
>
<svg
className="size-4 shrink-0"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
Search
<kbd className="ms-auto rounded-md border border-line bg-subtle px-1.5 py-0.5 font-sans text-xs text-muted">
Ctrl K
</kbd>
</button>
}
/>
);
}<script setup lang="ts">
import Command from "@/components/markas/Command.vue";
const items = [
{ group: "Pages", label: "Dashboard", value: "dashboard" },
{ group: "Pages", label: "Invoices", value: "invoices" },
{ group: "Pages", label: "Customers", value: "customers" },
{ group: "Actions", label: "Create invoice", value: "create-invoice" },
{ group: "Actions", label: "Add customer", value: "add-customer" },
];
</script>
<template>
<Command hotkey :items="items">
<template #trigger>
<button
type="button"
class="flex h-10 w-full items-center gap-2 rounded-lg border border-line bg-surface px-3 text-left text-sm text-muted transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none"
>
<svg
class="size-4 shrink-0"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
Search
<kbd
class="ms-auto rounded-md border border-line bg-subtle px-1.5 py-0.5 font-sans text-xs text-muted"
>
Ctrl K
</kbd>
</button>
</template>
</Command>
</template><script lang="ts">
import Command from "$lib/components/markas/Command.svelte";
const items = [
{ group: "Pages", label: "Dashboard", value: "dashboard" },
{ group: "Pages", label: "Invoices", value: "invoices" },
{ group: "Pages", label: "Customers", value: "customers" },
{ group: "Actions", label: "Create invoice", value: "create-invoice" },
{ group: "Actions", label: "Add customer", value: "add-customer" },
];
const field =
"flex h-10 w-full items-center gap-2 rounded-lg border border-line bg-surface px-3 text-left text-sm text-muted transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const key =
"ms-auto rounded-md border border-line bg-subtle px-1.5 py-0.5 font-sans text-xs text-muted";
</script>
<Command hotkey {items}>
{#snippet trigger()}
<button type="button" class={field}>
<svg
class="size-4 shrink-0"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
Search
<kbd class={key}>Ctrl K</kbd>
</button>
{/snippet}
</Command>---
import Command from "@/components/markas/Command.astro";
const items = [
{ group: "Pages", label: "Dashboard", value: "dashboard" },
{ group: "Pages", label: "Invoices", value: "invoices" },
{ group: "Pages", label: "Customers", value: "customers" },
{ group: "Actions", label: "Create invoice", value: "create-invoice" },
{ group: "Actions", label: "Add customer", value: "add-customer" },
];
const field =
"flex h-10 w-full items-center gap-2 rounded-lg border border-line bg-surface px-3 text-left text-sm text-muted transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const key =
"ms-auto rounded-md border border-line bg-subtle px-1.5 py-0.5 font-sans text-xs text-muted";
---
<Command hotkey items={items}>
<button slot="trigger" type="button" class={field}>
<svg
class="size-4 shrink-0"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="7"></circle>
<path d="m20 20-3.5-3.5"></path>
</svg>
Search
<kbd class={key}>Ctrl K</kbd>
</button>
</Command>import { Component } from "@angular/core";
import { Command } from "./markas/command.component";
@Component({
selector: "markas-example",
imports: [Command],
template: `
<markas-command hotkey [items]="items">
<button trigger type="button" [class]="field">
<svg
class="size-4 shrink-0"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
Search
<kbd [class]="key">Ctrl K</kbd>
</button>
</markas-command>
`,
})
export default class CommandSearchFieldExample {
protected readonly items = [
{ group: "Pages", label: "Dashboard", value: "dashboard" },
{ group: "Pages", label: "Invoices", value: "invoices" },
{ group: "Pages", label: "Customers", value: "customers" },
{ group: "Actions", label: "Create invoice", value: "create-invoice" },
{ group: "Actions", label: "Add customer", value: "add-customer" },
];
protected readonly field =
"flex h-10 w-full items-center gap-2 rounded-lg border border-line bg-surface px-3 text-left text-sm text-muted transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
protected readonly key =
"ms-auto rounded-md border border-line bg-subtle px-1.5 py-0.5 font-sans text-xs text-muted";
}With links
<x-markas.command
:items="[
['group' => 'Documentation', 'label' => 'Getting started', 'href' => '#getting-started'],
['group' => 'Documentation', 'label' => 'Installation', 'href' => '#installation'],
['group' => 'Documentation', 'label' => 'Theming', 'href' => '#theming'],
['group' => 'Components', 'label' => 'Button', 'href' => '#button'],
['group' => 'Components', 'label' => 'Modal', 'href' => '#modal'],
]"
>
<x-slot:trigger>
<x-markas.button variant="ghost">Search documentation</x-markas.button>
</x-slot:trigger>
</x-markas.command>import { Button } from "@/components/markas/Button";
import { Command } from "@/components/markas/Command";
const items = [
{
group: "Documentation",
label: "Getting started",
href: "#getting-started",
},
{ group: "Documentation", label: "Installation", href: "#installation" },
{ group: "Documentation", label: "Theming", href: "#theming" },
{ group: "Components", label: "Button", href: "#button" },
{ group: "Components", label: "Modal", href: "#modal" },
];
export default function Example() {
return (
<Command
items={items}
trigger={<Button variant="ghost">Search documentation</Button>}
/>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import Command from "@/components/markas/Command.vue";
const items = [
{
group: "Documentation",
label: "Getting started",
href: "#getting-started",
},
{ group: "Documentation", label: "Installation", href: "#installation" },
{ group: "Documentation", label: "Theming", href: "#theming" },
{ group: "Components", label: "Button", href: "#button" },
{ group: "Components", label: "Modal", href: "#modal" },
];
</script>
<template>
<Command :items="items">
<template #trigger>
<Button variant="ghost">Search documentation</Button>
</template>
</Command>
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import Command from "$lib/components/markas/Command.svelte";
const items = [
{
group: "Documentation",
label: "Getting started",
href: "#getting-started",
},
{ group: "Documentation", label: "Installation", href: "#installation" },
{ group: "Documentation", label: "Theming", href: "#theming" },
{ group: "Components", label: "Button", href: "#button" },
{ group: "Components", label: "Modal", href: "#modal" },
];
</script>
<Command {items}>
{#snippet trigger()}
<Button variant="ghost">Search documentation</Button>
{/snippet}
</Command>---
import Button from "@/components/markas/Button.astro";
import Command from "@/components/markas/Command.astro";
const items = [
{
group: "Documentation",
label: "Getting started",
href: "#getting-started",
},
{ group: "Documentation", label: "Installation", href: "#installation" },
{ group: "Documentation", label: "Theming", href: "#theming" },
{ group: "Components", label: "Button", href: "#button" },
{ group: "Components", label: "Modal", href: "#modal" },
];
---
<Command items={items}>
<Button slot="trigger" variant="ghost">Search documentation</Button>
</Command>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Command } from "./markas/command.component";
@Component({
selector: "markas-example",
imports: [Button, Command],
template: `
<markas-command [items]="items">
<button markas-button trigger variant="ghost">
Search documentation
</button>
</markas-command>
`,
})
export default class CommandLinksExample {
protected readonly items = [
{
group: "Documentation",
label: "Getting started",
href: "#getting-started",
},
{ group: "Documentation", label: "Installation", href: "#installation" },
{ group: "Documentation", label: "Theming", href: "#theming" },
{ group: "Components", label: "Button", href: "#button" },
{ group: "Components", label: "Modal", href: "#modal" },
];
}Icon trigger
MarkasUI
MarkasUI
MarkasUI
MarkasUI
MarkasUI
<div class="flex items-center justify-between rounded-lg border border-line bg-surface px-4 py-2">
<span class="flex items-center gap-2 text-sm font-semibold text-ink"><svg class="size-6 shrink-0" viewBox="0 0 1464 1430" aria-hidden="true"><polygon points="354,578 1256,138 1171,430 268,868" class="fill-ink/15" /><polygon points="553,443 1455,3 1370,295 467,733" class="fill-ink/55" /><polygon points="421,762 1325,318 1240,611 336,1050" class="fill-success/35" /><polygon points="265,1073 1169,629 1084,922 180,1362" class="fill-ink/25" /><polygon points="93,965 997,521 912,814 8,1253" class="fill-ink/75" /><polygon points="347,1135 1251,691 1166,984 262,1424" class="fill-success" /></svg>MarkasUI</span>
<x-markas.command
placeholder-label="Run a command..."
:items="[
['group' => 'Workspace', 'label' => 'Create project', 'value' => 'create-project', 'shortcut' => 'Ctrl+N'],
['group' => 'Workspace', 'label' => 'Invite member', 'value' => 'invite', 'shortcut' => 'Ctrl+I'],
['group' => 'Account', 'label' => 'Switch theme', 'value' => 'theme'],
['group' => 'Account', 'label' => 'Sign out', 'value' => 'sign-out'],
]"
>
<x-slot:trigger>
<x-markas.button variant="ghost" size="sm" aria-label="Open commands">
<svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01" /></svg>
</x-markas.button>
</x-slot:trigger>
</x-markas.command>
</div>import { Button } from "@/components/markas/Button";
import { Command } from "@/components/markas/Command";
const mark = [
{ points: "354,578 1256,138 1171,430 268,868", className: "fill-ink/15" },
{ points: "553,443 1455,3 1370,295 467,733", className: "fill-ink/55" },
{
points: "421,762 1325,318 1240,611 336,1050",
className: "fill-success/35",
},
{ points: "265,1073 1169,629 1084,922 180,1362", className: "fill-ink/25" },
{ points: "93,965 997,521 912,814 8,1253", className: "fill-ink/75" },
{
points: "347,1135 1251,691 1166,984 262,1424",
className: "fill-success",
},
];
const items = [
{
group: "Workspace",
label: "Create project",
value: "create-project",
shortcut: "Ctrl+N",
},
{
group: "Workspace",
label: "Invite member",
value: "invite",
shortcut: "Ctrl+I",
},
{ group: "Account", label: "Switch theme", value: "theme" },
{ group: "Account", label: "Sign out", value: "sign-out" },
];
export default function Example() {
return (
<div className="flex items-center justify-between rounded-lg border border-line bg-surface px-4 py-2">
<span className="flex items-center gap-2 text-sm font-semibold text-ink">
<svg
className="size-6 shrink-0"
viewBox="0 0 1464 1430"
aria-hidden="true"
>
{mark.map((shape) => (
<polygon
key={shape.points}
points={shape.points}
className={shape.className}
/>
))}
</svg>
MarkasUI
</span>
<Command
placeholderLabel="Run a command..."
items={items}
trigger={
<Button variant="ghost" size="sm" aria-label="Open commands">
<svg
className="size-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01" />
</svg>
</Button>
}
/>
</div>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import Command from "@/components/markas/Command.vue";
const mark = [
{ points: "354,578 1256,138 1171,430 268,868", className: "fill-ink/15" },
{ points: "553,443 1455,3 1370,295 467,733", className: "fill-ink/55" },
{
points: "421,762 1325,318 1240,611 336,1050",
className: "fill-success/35",
},
{ points: "265,1073 1169,629 1084,922 180,1362", className: "fill-ink/25" },
{ points: "93,965 997,521 912,814 8,1253", className: "fill-ink/75" },
{
points: "347,1135 1251,691 1166,984 262,1424",
className: "fill-success",
},
];
const items = [
{
group: "Workspace",
label: "Create project",
value: "create-project",
shortcut: "Ctrl+N",
},
{
group: "Workspace",
label: "Invite member",
value: "invite",
shortcut: "Ctrl+I",
},
{ group: "Account", label: "Switch theme", value: "theme" },
{ group: "Account", label: "Sign out", value: "sign-out" },
];
</script>
<template>
<div
class="flex items-center justify-between rounded-lg border border-line bg-surface px-4 py-2"
>
<span class="flex items-center gap-2 text-sm font-semibold text-ink"
><svg class="size-6 shrink-0" viewBox="0 0 1464 1430" aria-hidden="true">
<polygon
v-for="shape in mark"
:key="shape.points"
:points="shape.points"
:class="shape.className"
/></svg
>MarkasUI</span
>
<Command placeholder-label="Run a command..." :items="items">
<template #trigger>
<Button variant="ghost" size="sm" aria-label="Open commands">
<svg
class="size-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01" />
</svg>
</Button>
</template>
</Command>
</div>
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import Command from "$lib/components/markas/Command.svelte";
const mark = [
{ points: "354,578 1256,138 1171,430 268,868", className: "fill-ink/15" },
{ points: "553,443 1455,3 1370,295 467,733", className: "fill-ink/55" },
{
points: "421,762 1325,318 1240,611 336,1050",
className: "fill-success/35",
},
{
points: "265,1073 1169,629 1084,922 180,1362",
className: "fill-ink/25",
},
{ points: "93,965 997,521 912,814 8,1253", className: "fill-ink/75" },
{
points: "347,1135 1251,691 1166,984 262,1424",
className: "fill-success",
},
];
const items = [
{
group: "Workspace",
label: "Create project",
value: "create-project",
shortcut: "Ctrl+N",
},
{
group: "Workspace",
label: "Invite member",
value: "invite",
shortcut: "Ctrl+I",
},
{ group: "Account", label: "Switch theme", value: "theme" },
{ group: "Account", label: "Sign out", value: "sign-out" },
];
const bar =
"flex items-center justify-between rounded-lg border border-line bg-surface px-4 py-2";
const brand = "flex items-center gap-2 text-sm font-semibold text-ink";
</script>
<div class={bar}>
<span class={brand}
><svg class="size-6 shrink-0" viewBox="0 0 1464 1430" aria-hidden="true">
{#each mark as shape (shape.points)}
<polygon points={shape.points} class={shape.className} />
{/each}
</svg>MarkasUI</span
>
<Command placeholderLabel="Run a command..." {items}>
{#snippet trigger()}
<Button variant="ghost" size="sm" aria-label="Open commands">
<svg
class="size-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01" />
</svg>
</Button>
{/snippet}
</Command>
</div>---
import Button from "@/components/markas/Button.astro";
import Command from "@/components/markas/Command.astro";
const mark = [
{ points: "354,578 1256,138 1171,430 268,868", className: "fill-ink/15" },
{ points: "553,443 1455,3 1370,295 467,733", className: "fill-ink/55" },
{
points: "421,762 1325,318 1240,611 336,1050",
className: "fill-success/35",
},
{ points: "265,1073 1169,629 1084,922 180,1362", className: "fill-ink/25" },
{ points: "93,965 997,521 912,814 8,1253", className: "fill-ink/75" },
{
points: "347,1135 1251,691 1166,984 262,1424",
className: "fill-success",
},
];
const items = [
{
group: "Workspace",
label: "Create project",
value: "create-project",
shortcut: "Ctrl+N",
},
{
group: "Workspace",
label: "Invite member",
value: "invite",
shortcut: "Ctrl+I",
},
{ group: "Account", label: "Switch theme", value: "theme" },
{ group: "Account", label: "Sign out", value: "sign-out" },
];
const bar =
"flex items-center justify-between rounded-lg border border-line bg-surface px-4 py-2";
const brand = "flex items-center gap-2 text-sm font-semibold text-ink";
---
<div class={bar}>
<span class={brand}
><svg class="size-6 shrink-0" viewBox="0 0 1464 1430" aria-hidden="true">
{mark.map((shape) => <polygon points={shape.points} class={shape.className} />)}
</svg>MarkasUI</span
>
<Command placeholderLabel="Run a command..." items={items}>
<Button slot="trigger" variant="ghost" size="sm" aria-label="Open commands">
<svg
class="size-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01"></path>
</svg>
</Button>
</Command>
</div>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Command } from "./markas/command.component";
@Component({
selector: "markas-example",
imports: [Button, Command],
template: `
<div [class]="bar">
<span [class]="brand"
><svg
class="size-6 shrink-0"
viewBox="0 0 1464 1430"
aria-hidden="true"
>
@for (shape of mark; track shape.points) {
<polygon
[attr.points]="shape.points"
[attr.class]="shape.className"
/>
}</svg
>MarkasUI</span
>
<markas-command placeholderLabel="Run a command..." [items]="items">
<button
markas-button
trigger
variant="ghost"
size="sm"
aria-label="Open commands"
>
<svg
class="size-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01" />
</svg>
</button>
</markas-command>
</div>
`,
})
export default class CommandIconTriggerExample {
protected readonly bar =
"flex items-center justify-between rounded-lg border border-line bg-surface px-4 py-2";
protected readonly brand =
"flex items-center gap-2 text-sm font-semibold text-ink";
protected readonly mark = [
{ points: "354,578 1256,138 1171,430 268,868", className: "fill-ink/15" },
{ points: "553,443 1455,3 1370,295 467,733", className: "fill-ink/55" },
{
points: "421,762 1325,318 1240,611 336,1050",
className: "fill-success/35",
},
{
points: "265,1073 1169,629 1084,922 180,1362",
className: "fill-ink/25",
},
{ points: "93,965 997,521 912,814 8,1253", className: "fill-ink/75" },
{
points: "347,1135 1251,691 1166,984 262,1424",
className: "fill-success",
},
];
protected readonly items = [
{
group: "Workspace",
label: "Create project",
value: "create-project",
shortcut: "Ctrl+N",
},
{
group: "Workspace",
label: "Invite member",
value: "invite",
shortcut: "Ctrl+I",
},
{ group: "Account", label: "Switch theme", value: "theme" },
{ group: "Account", label: "Sign out", value: "sign-out" },
];
}Installation
npx markasui@latest add commandpnpm dlx markasui@latest add commandyarn dlx markasui@latest add commandbunx --bun markasui@latest add command- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Install the dependency:
npm install alpinejs - Copy the component source below to
resources/views/components/markas/command.blade.php.
resources/views/components/markas/command.blade.php
@props([
'items' => [],
'hotkey' => false,
'placeholderLabel' => 'Type a command or search...',
'emptyLabel' => 'No results found.',
'searchLabel' => 'Search commands',
'dialogLabel' => 'Command palette',
])
@php
$dialog = 'mx-auto mt-24 mb-auto w-[calc(100%-2rem)] max-w-lg overflow-hidden rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40';
$search = 'flex items-center gap-2 border-b border-line px-4';
$searchIcon = 'size-4 shrink-0 text-muted';
$input = 'h-12 w-full bg-transparent text-sm text-ink outline-none placeholder:text-muted';
$list = 'max-h-72 overflow-y-auto p-1';
$groupClass = 'py-1';
$heading = 'px-3 pt-1 pb-1.5 text-xs font-medium text-muted';
$option = 'flex w-full cursor-pointer items-center justify-between gap-4 rounded-md px-3 py-2 text-left text-sm text-ink transition-colors duration-150 ease-out aria-selected:bg-subtle motion-reduce:transition-none';
$shortcutClass = 'font-sans text-xs text-muted';
$empty = 'px-4 py-6 text-center text-sm text-muted';
// Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#".
$safeHref = function (string $href): string {
$value = ltrim(str_replace(["\t", "\n", "\r"], '', $href), "\x00..\x20");
$hasScheme = preg_match('/^[a-z][a-z0-9+.\-]*:/i', $value) === 1;
return $hasScheme && preg_match('/^(https?|mailto|tel):/i', $value) !== 1 ? '#' : $href;
};
// Kelompokkan item per grup sesuai urutan kemunculan pertama, indeks asli dipakai untuk id opsi.
$groups = [];
foreach (array_values($items) as $index => $entry) {
$groups[(string) ($entry['group'] ?? '')][$index] = $entry;
}
// Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
$idKey = 'markas-command|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $attributes->get('name')).'|';
for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
$__env->markAsRenderedOnce($idKey.$idIndex);
$id = $attributes->get('id') ?? 'markas-command-'.hash('xxh32', $idKey.$idIndex);
@endphp
<div
class="contents"
x-data="{
open: false,
query: '',
active: 0,
matches(label) {
return label.toLowerCase().includes(this.query.trim().toLowerCase());
},
visible() {
return Array.from(this.$root.querySelectorAll('[role=listbox] [role=option]')).filter((el) => this.matches(el.dataset.label));
},
get activeId() {
const list = this.visible();
return list[Math.min(this.active, list.length - 1)]?.id ?? null;
},
show() {
this.$refs.dialog.showModal();
this.open = true;
},
{{-- Ctrl+K atau Cmd+K membuka dan menutup palet. --}}
onHotkey(event) {
if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 'k') return;
event.preventDefault();
if (this.$refs.dialog.open) return this.$refs.dialog.close();
this.show();
},
select(value) {
this.$dispatch('markas-select', value);
this.$refs.dialog.close();
},
onClose() {
this.open = false;
this.query = '';
this.active = 0;
},
reveal() {
this.$nextTick(() => document.getElementById(this.activeId)?.scrollIntoView({ block: 'nearest' }));
},
onKeydown(event) {
const count = this.visible().length;
const step = { ArrowDown: 1, ArrowUp: -1 }[event.key];
if (step !== undefined) {
event.preventDefault();
if (count > 0) this.active = (this.active + step + count) % count;
return this.reveal();
}
if (event.key !== 'Enter' || !this.activeId) return;
event.preventDefault();
document.getElementById(this.activeId)?.click();
},
}"
@if ($hotkey) @keydown.window="onHotkey($event)" @endif
>
@isset($trigger)
<div class="contents" @click="show()">{{ $trigger }}</div>
@endisset
<dialog
wire:ignore.self
x-ref="dialog"
aria-label="{{ $dialogLabel }}"
:data-state="open ? 'open' : 'closed'"
@close="onClose()"
@click.self="$refs.dialog.close()"
{{ $attributes->merge(['id' => $id, 'data-state' => 'closed'])->class([$dialog]) }}
>
<div class="{{ $search }}">
<svg class="{{ $searchIcon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></svg>
<input
type="text"
role="combobox"
aria-label="{{ $searchLabel }}"
aria-expanded="true"
aria-controls="{{ $id }}-list"
aria-autocomplete="list"
autocomplete="off"
spellcheck="false"
placeholder="{{ $placeholderLabel }}"
x-model="query"
:aria-expanded="visible().length > 0 ? 'true' : 'false'"
:aria-activedescendant="activeId"
@input="active = 0"
@keydown="onKeydown($event)"
class="{{ $input }}"
/>
</div>
<div
id="{{ $id }}-list"
role="listbox"
aria-label="{{ $dialogLabel }}"
:hidden="visible().length === 0"
class="{{ $list }}"
>
@foreach ($groups as $name => $entries)
@php
$groupId = $id.'-group-'.$loop->index;
$labels = array_map(fn ($entry) => (string) $entry['label'], array_values($entries));
@endphp
<div role="group" aria-labelledby="{{ $groupId }}-heading" x-show="@js($labels).some((label) => matches(label))" class="{{ $groupClass }}">
<div id="{{ $groupId }}-heading" class="{{ $heading }}">{{ $name }}</div>
@foreach ($entries as $index => $entry)
@php
$optionId = $id.'-option-'.$index;
$label = (string) $entry['label'];
$value = (string) ($entry['value'] ?? $label);
$tag = isset($entry['href']) ? 'a' : 'div';
@endphp
<{{ $tag }}
@if ($tag === 'a') href="{{ $safeHref((string) $entry['href']) }}" @endif
id="{{ $optionId }}"
role="option"
aria-selected="false"
tabindex="-1"
data-label="{{ $label }}"
x-show="matches($el.dataset.label)"
:aria-selected="activeId === @js($optionId) ? 'true' : 'false'"
@mousemove="active = visible().indexOf($el)"
@click="select(@js($value))"
class="{{ $option }}"
><span>{{ $label }}</span>@isset($entry['shortcut'])<kbd class="{{ $shortcutClass }}">{{ $entry['shortcut'] }}</kbd>@endisset</{{ $tag }}>
@endforeach
</div>
@endforeach
</div>
<p x-show="visible().length === 0" style="display: none" class="{{ $empty }}">{{ $emptyLabel }}</p>
</dialog>
</div>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/Command.tsx.
src/components/markas/Command.tsx
"use client";
import {
useEffect,
useId,
useRef,
useState,
type ComponentProps,
type KeyboardEvent,
type MouseEvent,
type ReactNode,
} from "react";
const dialogClass =
"mx-auto mt-24 mb-auto w-[calc(100%-2rem)] max-w-lg overflow-hidden rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const search = "flex items-center gap-2 border-b border-line px-4";
const searchIcon = "size-4 shrink-0 text-muted";
const input =
"h-12 w-full bg-transparent text-sm text-ink outline-none placeholder:text-muted";
const list = "max-h-72 overflow-y-auto p-1";
const groupClass = "py-1";
const heading = "px-3 pt-1 pb-1.5 text-xs font-medium text-muted";
const option =
"flex w-full cursor-pointer items-center justify-between gap-4 rounded-md px-3 py-2 text-left text-sm text-ink transition-colors duration-150 ease-out aria-selected:bg-subtle motion-reduce:transition-none";
const shortcutClass = "font-sans text-xs text-muted";
const empty = "px-4 py-6 text-center text-sm text-muted";
const cx = (...c: (string | false | null | undefined)[]) =>
c.filter(Boolean).join(" ");
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;
/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
const cleaned = href.replace(/[\t\n\r]/g, "");
const start = [...cleaned].findIndex((char) => char > " ");
const value = cleaned.slice(Math.max(start, 0));
return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
export type CommandItem = {
group: string;
label: string;
value?: string;
href?: string;
shortcut?: string;
};
type Entry = { item: CommandItem; index: number };
/** Nama grup sesuai urutan kemunculan pertama. */
const groupNames = (items: CommandItem[]) => [
...new Set(items.map((entry) => entry.group)),
];
const matches = (item: CommandItem, query: string) =>
item.label.toLowerCase().includes(query.trim().toLowerCase());
export type CommandProps = Omit<
ComponentProps<"dialog">,
"onSelect" | "ref" | "open"
> & {
items: CommandItem[];
trigger?: ReactNode;
/** Ctrl+K atau Cmd+K membuka dan menutup palet. */
hotkey?: boolean;
placeholderLabel?: string;
emptyLabel?: string;
/** Label aksesibel kolom pencarian. */
searchLabel?: string;
/** Label aksesibel dialog dan daftar hasil. */
dialogLabel?: string;
onSelect?: (value: string) => void;
};
export function Command({
items,
trigger,
hotkey = false,
placeholderLabel = "Type a command or search...",
emptyLabel = "No results found.",
searchLabel = "Search commands",
dialogLabel = "Command palette",
onSelect,
id,
className,
onClose,
onClick,
...props
}: CommandProps) {
const generatedId = useId();
const dialogId = id ?? generatedId;
const listId = `${dialogId}-list`;
const optionId = (index: number) => `${dialogId}-option-${index}`;
const dialogRef = useRef<HTMLDialogElement>(null);
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const groups = groupNames(items).map((name, groupIndex) => ({
name,
id: `${dialogId}-group-${groupIndex}`,
entries: items
.map((item, index): Entry => ({ item, index }))
.filter((entry) => entry.item.group === name)
.filter((entry) => matches(entry.item, query)),
}));
const visible = groups.flatMap((group) => group.entries);
const activeEntry = visible[Math.min(active, visible.length - 1)];
const activeId = activeEntry ? optionId(activeEntry.index) : undefined;
const show = () => {
dialogRef.current?.showModal();
setOpen(true);
};
useEffect(() => {
if (!hotkey) return;
const handleHotkey = (event: globalThis.KeyboardEvent) => {
if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "k")
return;
event.preventDefault();
const dialog = dialogRef.current;
if (dialog?.open) return dialog.close();
dialog?.showModal();
setOpen(true);
};
window.addEventListener("keydown", handleHotkey);
return () => window.removeEventListener("keydown", handleHotkey);
}, [hotkey]);
useEffect(() => {
if (activeId)
document.getElementById(activeId)?.scrollIntoView?.({ block: "nearest" });
}, [activeId]);
const select = (value: string) => {
onSelect?.(value);
dialogRef.current?.close();
};
const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
const count = visible.length;
const steps: Record<string, number | undefined> = {
ArrowDown: 1,
ArrowUp: -1,
};
const step = steps[event.key];
if (step !== undefined) {
event.preventDefault();
if (count > 0) setActive((current) => (current + step + count) % count);
return;
}
if (event.key !== "Enter" || !activeId) return;
event.preventDefault();
document.getElementById(activeId)?.click();
};
const handleClick = (event: MouseEvent<HTMLDialogElement>) => {
if (event.target === event.currentTarget) dialogRef.current?.close();
onClick?.(event);
};
const renderOption = ({ item, index }: Entry, position: number) => {
const shared = {
id: optionId(index),
role: "option",
"aria-selected": optionId(index) === activeId,
tabIndex: -1,
className: option,
onMouseMove: () => setActive(position),
onClick: () => select(item.value ?? item.label),
};
const content = (
<>
<span>{item.label}</span>
{item.shortcut && <kbd className={shortcutClass}>{item.shortcut}</kbd>}
</>
);
if (item.href)
return (
<a key={index} href={safeHref(item.href)} {...shared}>
{content}
</a>
);
return (
<div key={index} {...shared}>
{content}
</div>
);
};
return (
<div className="contents">
{trigger && (
<div className="contents" onClick={show}>
{trigger}
</div>
)}
<dialog
ref={dialogRef}
id={dialogId}
aria-label={dialogLabel}
data-state={open ? "open" : "closed"}
className={cx(dialogClass, className)}
onClose={(event) => {
setOpen(false);
setQuery("");
setActive(0);
onClose?.(event);
}}
onClick={handleClick}
{...props}
>
<div className={search}>
<svg
className={searchIcon}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
<input
type="text"
role="combobox"
aria-label={searchLabel}
aria-expanded={visible.length > 0}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={activeId}
autoComplete="off"
spellCheck={false}
placeholder={placeholderLabel}
value={query}
className={input}
onChange={(event) => {
setQuery(event.target.value);
setActive(0);
}}
onKeyDown={handleKeyDown}
/>
</div>
<div
id={listId}
role="listbox"
aria-label={dialogLabel}
hidden={visible.length === 0}
className={list}
>
{groups.map(
(group) =>
group.entries.length > 0 && (
<div
key={group.id}
role="group"
aria-labelledby={`${group.id}-heading`}
className={groupClass}
>
<div id={`${group.id}-heading`} className={heading}>
{group.name}
</div>
{group.entries.map((entry) =>
renderOption(entry, visible.indexOf(entry)),
)}
</div>
),
)}
</div>
{visible.length === 0 && <p className={empty}>{emptyLabel}</p>}
</dialog>
</div>
);
}- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/Command.vue.
src/components/markas/Command.vue
<script setup lang="ts">
import {
computed,
nextTick,
onBeforeUnmount,
onMounted,
ref,
useId,
useTemplateRef,
watch,
} from "vue";
defineOptions({ inheritAttrs: false });
export type CommandItem = {
group: string;
label: string;
value?: string;
href?: string;
shortcut?: string;
};
type Entry = { item: CommandItem; index: number };
const props = withDefaults(
defineProps<{
items: CommandItem[];
hotkey?: boolean;
placeholderLabel?: string;
emptyLabel?: string;
searchLabel?: string;
dialogLabel?: string;
id?: string;
}>(),
{
hotkey: false,
placeholderLabel: "Type a command or search...",
emptyLabel: "No results found.",
searchLabel: "Search commands",
dialogLabel: "Command palette",
id: undefined,
},
);
const emit = defineEmits<{ select: [value: string] }>();
const dialogClass =
"mx-auto mt-24 mb-auto w-[calc(100%-2rem)] max-w-lg overflow-hidden rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const search = "flex items-center gap-2 border-b border-line px-4";
const searchIcon = "size-4 shrink-0 text-muted";
const input =
"h-12 w-full bg-transparent text-sm text-ink outline-none placeholder:text-muted";
const list = "max-h-72 overflow-y-auto p-1";
const groupClass = "py-1";
const heading = "px-3 pt-1 pb-1.5 text-xs font-medium text-muted";
const option =
"flex w-full cursor-pointer items-center justify-between gap-4 rounded-md px-3 py-2 text-left text-sm text-ink transition-colors duration-150 ease-out aria-selected:bg-subtle motion-reduce:transition-none";
const shortcutClass = "font-sans text-xs text-muted";
const empty = "px-4 py-6 text-center text-sm text-muted";
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;
/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
const cleaned = href.replace(/[\t\n\r]/g, "");
const start = [...cleaned].findIndex((char) => char > " ");
const value = cleaned.slice(Math.max(start, 0));
return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
/** Nama grup sesuai urutan kemunculan pertama. */
const groupNames = (items: CommandItem[]) => [
...new Set(items.map((entry) => entry.group)),
];
const matches = (item: CommandItem, query: string) =>
item.label.toLowerCase().includes(query.trim().toLowerCase());
const generatedId = useId();
const dialogId = computed(() => props.id ?? generatedId);
const listId = computed(() => `${dialogId.value}-list`);
const optionId = (index: number) => `${dialogId.value}-option-${index}`;
const dialog = useTemplateRef<HTMLDialogElement>("dialog");
const open = ref(false);
const query = ref("");
const active = ref(0);
const groups = computed(() =>
groupNames(props.items).map((name, groupIndex) => ({
name,
id: `${dialogId.value}-group-${groupIndex}`,
entries: props.items
.map((item, index): Entry => ({ item, index }))
.filter((entry) => entry.item.group === name)
.filter((entry) => matches(entry.item, query.value)),
})),
);
const visible = computed(() => groups.value.flatMap((group) => group.entries));
const activeId = computed(() => {
const entry = visible.value[Math.min(active.value, visible.value.length - 1)];
return entry ? optionId(entry.index) : undefined;
});
function show() {
dialog.value?.showModal();
open.value = true;
}
function onHotkey(event: KeyboardEvent) {
if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "k")
return;
event.preventDefault();
if (dialog.value?.open) return dialog.value.close();
show();
}
onMounted(() => {
if (props.hotkey) window.addEventListener("keydown", onHotkey);
});
onBeforeUnmount(() => window.removeEventListener("keydown", onHotkey));
watch(activeId, async (id) => {
if (!id) return;
await nextTick();
document.getElementById(id)?.scrollIntoView?.({ block: "nearest" });
});
function select(value: string) {
emit("select", value);
dialog.value?.close();
}
function onClose() {
open.value = false;
query.value = "";
active.value = 0;
}
function onInput(event: Event) {
query.value = (event.target as HTMLInputElement).value;
active.value = 0;
}
function onKeydown(event: KeyboardEvent) {
const count = visible.value.length;
const steps: Record<string, number | undefined> = {
ArrowDown: 1,
ArrowUp: -1,
};
const step = steps[event.key];
if (step !== undefined) {
event.preventDefault();
if (count > 0) active.value = (active.value + step + count) % count;
return;
}
if (event.key !== "Enter" || !activeId.value) return;
event.preventDefault();
document.getElementById(activeId.value)?.click();
}
</script>
<template>
<div class="contents">
<div v-if="$slots.trigger" class="contents" @click="show">
<slot name="trigger" />
</div>
<dialog
:id="dialogId"
ref="dialog"
:aria-label="props.dialogLabel"
:data-state="open ? 'open' : 'closed'"
:class="dialogClass"
v-bind="$attrs"
@close="onClose"
@click.self="dialog?.close()"
>
<div :class="search">
<svg
:class="searchIcon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
<input
type="text"
role="combobox"
:aria-label="props.searchLabel"
:aria-expanded="visible.length > 0 ? 'true' : 'false'"
:aria-controls="listId"
aria-autocomplete="list"
:aria-activedescendant="activeId"
autocomplete="off"
spellcheck="false"
:placeholder="props.placeholderLabel"
:value="query"
:class="input"
@input="onInput"
@keydown="onKeydown"
/>
</div>
<div
:id="listId"
role="listbox"
:aria-label="props.dialogLabel"
:hidden="visible.length === 0"
:class="list"
>
<template v-for="group in groups" :key="group.id">
<div
v-if="group.entries.length > 0"
role="group"
:aria-labelledby="`${group.id}-heading`"
:class="groupClass"
>
<div :id="`${group.id}-heading`" :class="heading">
{{ group.name }}
</div>
<component
:is="entry.item.href ? 'a' : 'div'"
v-for="entry in group.entries"
:id="optionId(entry.index)"
:key="entry.index"
:href="entry.item.href ? safeHref(entry.item.href) : undefined"
role="option"
:aria-selected="
optionId(entry.index) === activeId ? 'true' : 'false'
"
tabindex="-1"
:class="option"
@mousemove="active = visible.indexOf(entry)"
@click="select(entry.item.value ?? entry.item.label)"
>
<span>{{ entry.item.label }}</span>
<kbd v-if="entry.item.shortcut" :class="shortcutClass">{{
entry.item.shortcut
}}</kbd>
</component>
</div>
</template>
</div>
<p v-if="visible.length === 0" :class="empty">{{ props.emptyLabel }}</p>
</dialog>
</div>
</template>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/lib/components/markas/Command.svelte.
src/lib/components/markas/Command.svelte
<script lang="ts" module>
export type CommandItem = {
group: string;
label: string;
value?: string;
href?: string;
shortcut?: string;
};
</script>
<script lang="ts">
import { tick, type Snippet } from "svelte";
import type { HTMLDialogAttributes } from "svelte/elements";
const dialogClass =
"mx-auto mt-24 mb-auto w-[calc(100%-2rem)] max-w-lg overflow-hidden rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const search = "flex items-center gap-2 border-b border-line px-4";
const searchIcon = "size-4 shrink-0 text-muted";
const input =
"h-12 w-full bg-transparent text-sm text-ink outline-none placeholder:text-muted";
const list = "max-h-72 overflow-y-auto p-1";
const groupClass = "py-1";
const heading = "px-3 pt-1 pb-1.5 text-xs font-medium text-muted";
const option =
"flex w-full cursor-pointer items-center justify-between gap-4 rounded-md px-3 py-2 text-left text-sm text-ink transition-colors duration-150 ease-out aria-selected:bg-subtle motion-reduce:transition-none";
const shortcutClass = "font-sans text-xs text-muted";
const empty = "px-4 py-6 text-center text-sm text-muted";
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;
/** Href with a scheme other than http, https, mailto, and tel (such as javascript:) becomes "#". */
const safeHref = (href: string) => {
const cleaned = href.replace(/[\t\n\r]/g, "");
const start = [...cleaned].findIndex((char) => char > " ");
const value = cleaned.slice(Math.max(start, 0));
return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
type Entry = { item: CommandItem; index: number };
/** Group names in order of first appearance. */
const groupNames = (items: CommandItem[]) => [
...new Set(items.map((entry) => entry.group)),
];
const matches = (item: CommandItem, query: string) =>
item.label.toLowerCase().includes(query.trim().toLowerCase());
type Props = Omit<HTMLDialogAttributes, "open" | "onselect"> & {
items: CommandItem[];
/** Ctrl+K or Cmd+K opens and closes the palette. */
hotkey?: boolean;
placeholderLabel?: string;
emptyLabel?: string;
/** Accessible label of the search field. */
searchLabel?: string;
/** Accessible label of the dialog and the result list. */
dialogLabel?: string;
/** Called with the value (or label) of the chosen command. */
onselect?: (value: string) => void;
trigger?: Snippet;
};
let {
items,
hotkey = false,
placeholderLabel = "Type a command or search...",
emptyLabel = "No results found.",
searchLabel = "Search commands",
dialogLabel = "Command palette",
onselect,
trigger,
id,
class: className,
onclose,
onclick,
...rest
}: Props = $props();
const generatedId = $props.id();
const dialogId = $derived(id ?? generatedId);
const listId = $derived(`${dialogId}-list`);
const optionId = (index: number) => `${dialogId}-option-${index}`;
let dialog = $state<HTMLDialogElement>();
let open = $state(false);
let query = $state("");
let active = $state(0);
const groups = $derived(
groupNames(items).map((name, groupIndex) => ({
name,
id: `${dialogId}-group-${groupIndex}`,
entries: items
.map((item, index): Entry => ({ item, index }))
.filter((entry) => entry.item.group === name)
.filter((entry) => matches(entry.item, query)),
})),
);
const visible = $derived(groups.flatMap((group) => group.entries));
const activeId = $derived.by(() => {
const entry = visible[Math.min(active, visible.length - 1)];
return entry ? optionId(entry.index) : undefined;
});
function show() {
dialog?.showModal();
open = true;
}
function handleHotkey(event: KeyboardEvent) {
if (!hotkey) return;
if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "k")
return;
event.preventDefault();
if (dialog?.open) return dialog.close();
show();
}
$effect(() => {
const target = activeId;
if (!target) return;
tick().then(() =>
document.getElementById(target)?.scrollIntoView?.({ block: "nearest" }),
);
});
function select(value: string) {
onselect?.(value);
dialog?.close();
}
function handleClose(event: Event & { currentTarget: HTMLDialogElement }) {
open = false;
query = "";
active = 0;
onclose?.(event);
}
function handleClick(
event: MouseEvent & { currentTarget: HTMLDialogElement },
) {
if (event.target === event.currentTarget) dialog?.close();
onclick?.(event);
}
function handleInput(event: Event & { currentTarget: HTMLInputElement }) {
query = event.currentTarget.value;
active = 0;
}
function handleKeydown(event: KeyboardEvent) {
const count = visible.length;
const steps: Record<string, number | undefined> = {
ArrowDown: 1,
ArrowUp: -1,
};
const step = steps[event.key];
if (step !== undefined) {
event.preventDefault();
if (count > 0) active = (active + step + count) % count;
return;
}
if (event.key !== "Enter" || !activeId) return;
event.preventDefault();
document.getElementById(activeId)?.click();
}
</script>
<svelte:window onkeydown={handleHotkey} />
<div class="contents">
{#if trigger}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="contents" onclick={show}>{@render trigger()}</div>
{/if}
<dialog
bind:this={dialog}
id={dialogId}
aria-label={dialogLabel}
data-state={open ? "open" : "closed"}
class={[dialogClass, className]}
onclose={handleClose}
onclick={handleClick}
{...rest}
>
<div class={search}>
<svg
class={searchIcon}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
<input
type="text"
role="combobox"
aria-label={searchLabel}
aria-expanded={visible.length > 0}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={activeId}
autocomplete="off"
spellcheck={false}
placeholder={placeholderLabel}
value={query}
class={input}
oninput={handleInput}
onkeydown={handleKeydown}
/>
</div>
<div
id={listId}
role="listbox"
aria-label={dialogLabel}
hidden={visible.length === 0}
class={list}
>
{#each groups as group (group.id)}
{#if group.entries.length > 0}
<div
role="group"
aria-labelledby={`${group.id}-heading`}
class={groupClass}
>
<div id={`${group.id}-heading`} class={heading}>{group.name}</div>
{#each group.entries as entry (entry.index)}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<svelte:element
this={entry.item.href ? "a" : "div"}
href={entry.item.href ? safeHref(entry.item.href) : undefined}
id={optionId(entry.index)}
role="option"
aria-selected={optionId(entry.index) === activeId}
tabindex="-1"
class={option}
onmousemove={() => (active = visible.indexOf(entry))}
onclick={() => select(entry.item.value ?? entry.item.label)}
><span>{entry.item.label}</span>{#if entry.item.shortcut}<kbd
class={shortcutClass}>{entry.item.shortcut}</kbd
>{/if}</svelte:element
>
{/each}
</div>
{/if}
{/each}
</div>
{#if visible.length === 0}
<p class={empty}>{emptyLabel}</p>
{/if}
</dialog>
</div>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/Command.astro.
src/components/markas/Command.astro
---
import type { HTMLAttributes } from "astro/types";
const dialogClass =
"mx-auto mt-24 mb-auto w-[calc(100%-2rem)] max-w-lg overflow-hidden rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const search = "flex items-center gap-2 border-b border-line px-4";
const searchIcon = "size-4 shrink-0 text-muted";
const input =
"h-12 w-full bg-transparent text-sm text-ink outline-none placeholder:text-muted";
const list = "max-h-72 overflow-y-auto p-1";
const groupClass = "py-1";
const heading = "px-3 pt-1 pb-1.5 text-xs font-medium text-muted";
const option =
"flex w-full cursor-pointer items-center justify-between gap-4 rounded-md px-3 py-2 text-left text-sm text-ink transition-colors duration-150 ease-out aria-selected:bg-subtle motion-reduce:transition-none";
const shortcutClass = "font-sans text-xs text-muted";
const empty = "px-4 py-6 text-center text-sm text-muted";
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;
/** Href with a scheme other than http, https, mailto, and tel (such as javascript:) becomes "#". */
const safeHref = (href: string) => {
const cleaned = href.replace(/[\t\n\r]/g, "");
const start = [...cleaned].findIndex((char) => char > " ");
const value = cleaned.slice(Math.max(start, 0));
return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
export type CommandItem = {
group: string;
label: string;
value?: string;
href?: string;
shortcut?: string;
};
type Props = Omit<HTMLAttributes<"dialog">, "open"> & {
items: CommandItem[];
/** Ctrl+K or Cmd+K opens and closes the palette. */
hotkey?: boolean;
placeholderLabel?: string;
emptyLabel?: string;
/** Accessible label of the search field. */
searchLabel?: string;
/** Accessible label of the dialog and the result list. */
dialogLabel?: string;
};
const {
items,
hotkey = false,
placeholderLabel = "Type a command or search...",
emptyLabel = "No results found.",
searchLabel = "Search commands",
dialogLabel = "Command palette",
id,
class: className,
...rest
} = Astro.props;
const dialogId = id ?? `markas-command-${crypto.randomUUID().slice(0, 8)}`;
const listId = `${dialogId}-list`;
const optionId = (index: number) => `${dialogId}-option-${index}`;
// Groups in order of first appearance; the original index keeps option ids stable.
const groups = [...new Set(items.map((item) => item.group))].map(
(name, groupIndex) => ({
name,
id: `${dialogId}-group-${groupIndex}`,
entries: items
.map((item, index) => ({ item, index }))
.filter((entry) => entry.item.group === name),
}),
);
const firstId = groups[0] ? optionId(groups[0].entries[0]!.index) : undefined;
---
<markas-command class="contents" data-hotkey={hotkey ? "" : undefined}>
{
Astro.slots.has("trigger") && (
<div class="contents" data-markas-command-trigger>
<slot name="trigger" />
</div>
)
}
<dialog
id={dialogId}
aria-label={dialogLabel}
data-state="closed"
class:list={[dialogClass, className]}
{...rest}
>
<div class={search}>
<svg
class={searchIcon}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="7"></circle>
<path d="m20 20-3.5-3.5"></path>
</svg>
<input
type="text"
role="combobox"
aria-label={searchLabel}
aria-expanded={items.length > 0 ? "true" : "false"}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={firstId}
autocomplete="off"
spellcheck="false"
placeholder={placeholderLabel}
class={input}
/>
</div>
<div
id={listId}
role="listbox"
aria-label={dialogLabel}
hidden={items.length === 0}
class={list}
>
{
groups.map((group) => (
<div
role="group"
aria-labelledby={`${group.id}-heading`}
class={groupClass}
>
<div id={`${group.id}-heading`} class={heading}>
{group.name}
</div>
{group.entries.map(({ item, index }) => {
const Tag = item.href ? "a" : "div";
return (
<Tag
href={item.href ? safeHref(item.href) : undefined}
id={optionId(index)}
role="option"
aria-selected={optionId(index) === firstId ? "true" : "false"}
tabindex="-1"
data-label={item.label}
data-value={item.value ?? item.label}
class={option}
>
<span>{item.label}</span>
{item.shortcut && (
<kbd class={shortcutClass}>{item.shortcut}</kbd>
)}
</Tag>
);
})}
</div>
))
}
</div>
<p class={empty} hidden={items.length > 0}>{emptyLabel}</p>
</dialog>
</markas-command>
<script>
// One custom element per palette: it keeps its own query and highlight, and registers the
// Ctrl+K listener only while it is on the page (also after view transitions).
class MarkasCommand extends HTMLElement {
private active = 0;
private dialog!: HTMLDialogElement;
private input!: HTMLInputElement;
private readonly onHotkey = (event: KeyboardEvent) => {
if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "k")
return;
event.preventDefault();
if (this.dialog.open) return this.dialog.close();
this.show();
};
connectedCallback() {
if (this.dialog) return this.listen();
this.dialog = this.querySelector("dialog")!;
this.input = this.dialog.querySelector("input")!;
this.addEventListener("click", (event) => this.handleClick(event));
this.addEventListener("mousemove", (event) => {
const target = (event.target as Element).closest("[role=option]");
const index = this.visible().indexOf(target as HTMLElement);
if (index >= 0 && index !== this.active) this.update(index);
});
this.input.addEventListener("input", () => this.update(0));
this.input.addEventListener("keydown", (event) => this.handleKey(event));
this.dialog.addEventListener("close", () => {
this.dialog.dataset.state = "closed";
this.input.value = "";
this.update(0);
});
this.listen();
}
disconnectedCallback() {
window.removeEventListener("keydown", this.onHotkey);
}
private listen() {
if (this.hasAttribute("data-hotkey"))
window.addEventListener("keydown", this.onHotkey);
}
private show() {
this.dialog.showModal();
this.dialog.dataset.state = "open";
}
private options() {
return [...this.dialog.querySelectorAll<HTMLElement>("[role=option]")];
}
private visible() {
return this.options().filter((el) => el.style.display !== "none");
}
private activeOption() {
const visible = this.visible();
return visible[Math.min(this.active, visible.length - 1)];
}
/** Filters by the query, then moves the highlight to the given position. */
private update(active: number) {
const query = this.input.value.trim().toLowerCase();
for (const el of this.options())
el.style.display = (el.dataset.label ?? "")
.toLowerCase()
.includes(query)
? ""
: "none";
for (const group of this.dialog.querySelectorAll<HTMLElement>(
"[role=group]",
))
group.style.display = group.querySelector(
"[role=option]:not([style*=none])",
)
? ""
: "none";
const count = this.visible().length;
this.dialog.querySelector<HTMLElement>("[role=listbox]")!.hidden =
count === 0;
this.dialog.querySelector("p")!.hidden = count > 0;
this.input.setAttribute("aria-expanded", String(count > 0));
this.active = active;
const current = this.activeOption();
for (const el of this.options())
el.setAttribute("aria-selected", String(el === current));
if (current) {
this.input.setAttribute("aria-activedescendant", current.id);
current.scrollIntoView?.({ block: "nearest" });
} else this.input.removeAttribute("aria-activedescendant");
}
private handleKey(event: KeyboardEvent) {
const count = this.visible().length;
const step = ({ ArrowDown: 1, ArrowUp: -1 } as Record<string, number>)[
event.key
];
if (step !== undefined) {
event.preventDefault();
if (count > 0) this.update((this.active + step + count) % count);
return;
}
if (event.key !== "Enter" || !count) return;
event.preventDefault();
this.activeOption()?.click();
}
private handleClick(event: MouseEvent) {
const target = event.target as Element;
if (target.closest("[data-markas-command-trigger]")) return this.show();
// A click on the dialog itself (not its content) is a click on the backdrop.
if (target === this.dialog) return this.dialog.close();
const option = target.closest<HTMLElement>("[role=option]");
if (!option) return;
this.dialog.dispatchEvent(
new CustomEvent("markas-select", {
bubbles: true,
detail: option.dataset.value,
}),
);
this.dialog.close();
}
}
if (!customElements.get("markas-command"))
customElements.define("markas-command", MarkasCommand);
</script>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/app/markas/command.component.ts.
src/app/markas/command.component.ts
import {
afterRenderEffect,
booleanAttribute,
ChangeDetectionStrategy,
Component,
computed,
type ElementRef,
input,
output,
signal,
viewChild,
} from "@angular/core";
const dialogClass =
"mx-auto mt-24 mb-auto w-[calc(100%-2rem)] max-w-lg overflow-hidden rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const search = "flex items-center gap-2 border-b border-line px-4";
const searchIcon = "size-4 shrink-0 text-muted";
const inputClass =
"h-12 w-full bg-transparent text-sm text-ink outline-none placeholder:text-muted";
const list = "max-h-72 overflow-y-auto p-1";
const groupClass = "py-1";
const heading = "px-3 pt-1 pb-1.5 text-xs font-medium text-muted";
const option =
"flex w-full cursor-pointer items-center justify-between gap-4 rounded-md px-3 py-2 text-left text-sm text-ink transition-colors duration-150 ease-out aria-selected:bg-subtle motion-reduce:transition-none";
const shortcutClass = "font-sans text-xs text-muted";
const empty = "px-4 py-6 text-center text-sm text-muted";
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;
/** Href with a scheme other than http, https, mailto, and tel (such as javascript:) becomes "#". */
const safeHref = (href: string) => {
const cleaned = href.replace(/[\t\n\r]/g, "");
const start = [...cleaned].findIndex((char) => char > " ");
const value = cleaned.slice(Math.max(start, 0));
return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
export type CommandItem = {
group: string;
label: string;
value?: string;
href?: string;
shortcut?: string;
};
type Entry = { item: CommandItem; index: number };
const matches = (item: CommandItem, query: string) =>
item.label.toLowerCase().includes(query.trim().toLowerCase());
let nextId = 0;
/**
* Slot: an element with the `trigger` attribute opens the palette.
* Host stays out of layout; id and class move to the dialog.
*/
@Component({
selector: "markas-command",
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: "contents",
"[attr.id]": "null",
"(window:keydown)": "handleHotkey($event)",
},
template: `
<div class="contents" (click)="show()">
<ng-content select="[trigger]" />
</div>
<dialog
#dialog
[id]="dialogId()"
[attr.aria-label]="dialogLabel()"
[attr.data-state]="open() ? 'open' : 'closed'"
[class]="dialogClasses()"
(close)="handleClose()"
(click)="handleClick($event)"
>
<div [class]="search">
<svg
[class]="searchIcon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
<input
type="text"
role="combobox"
[attr.aria-label]="searchLabel()"
[attr.aria-expanded]="visible().length > 0"
[attr.aria-controls]="dialogId() + '-list'"
aria-autocomplete="list"
[attr.aria-activedescendant]="activeId() ?? null"
autocomplete="off"
spellcheck="false"
[placeholder]="placeholderLabel()"
[value]="query()"
[class]="inputClass"
(input)="handleInput($event)"
(keydown)="handleKeydown($event)"
/>
</div>
<div
[id]="dialogId() + '-list'"
role="listbox"
[attr.aria-label]="dialogLabel()"
[hidden]="visible().length === 0"
[class]="list"
>
@for (group of groups(); track group.id) {
@if (group.entries.length > 0) {
<div
role="group"
[attr.aria-labelledby]="group.id + '-heading'"
[class]="groupClass"
>
<div [id]="group.id + '-heading'" [class]="heading">
{{ group.name }}
</div>
@for (entry of group.entries; track entry.index) {
@if (entry.item.href) {
<a
[href]="safeHref(entry.item.href)"
[id]="optionId(entry.index)"
role="option"
[attr.aria-selected]="optionId(entry.index) === activeId()"
tabindex="-1"
[class]="option"
(mousemove)="active.set(visible().indexOf(entry))"
(click)="select(entry.item)"
>
<span>{{ entry.item.label }}</span>
@if (entry.item.shortcut) {
<kbd [class]="shortcutClass">{{
entry.item.shortcut
}}</kbd>
}
</a>
} @else {
<div
[id]="optionId(entry.index)"
role="option"
[attr.aria-selected]="optionId(entry.index) === activeId()"
tabindex="-1"
[class]="option"
(mousemove)="active.set(visible().indexOf(entry))"
(click)="select(entry.item)"
>
<span>{{ entry.item.label }}</span>
@if (entry.item.shortcut) {
<kbd [class]="shortcutClass">{{
entry.item.shortcut
}}</kbd>
}
</div>
}
}
</div>
}
}
</div>
@if (visible().length === 0) {
<p [class]="empty">{{ emptyLabel() }}</p>
}
</dialog>
`,
})
export class Command {
readonly items = input.required<CommandItem[]>();
/** Ctrl+K or Cmd+K opens and closes the palette. */
readonly hotkey = input(false, { transform: booleanAttribute });
readonly placeholderLabel = input("Type a command or search...");
readonly emptyLabel = input("No results found.");
/** Accessible label of the search field. */
readonly searchLabel = input("Search commands");
/** Accessible label of the dialog and the result list. */
readonly dialogLabel = input("Command palette");
readonly id = input<string>();
readonly userClass = input("", { alias: "class" });
/** Emits the value (or label) of the chosen command. */
readonly selected = output<string>();
protected readonly search = search;
protected readonly searchIcon = searchIcon;
protected readonly inputClass = inputClass;
protected readonly list = list;
protected readonly groupClass = groupClass;
protected readonly heading = heading;
protected readonly option = option;
protected readonly shortcutClass = shortcutClass;
protected readonly empty = empty;
protected readonly safeHref = safeHref;
protected readonly open = signal(false);
protected readonly query = signal("");
protected readonly active = signal(0);
private readonly generatedId = `markas-command-${nextId++}`;
protected readonly dialogId = computed(() => this.id() ?? this.generatedId);
protected readonly dialogClasses = computed(() =>
[dialogClass, this.userClass()].filter(Boolean).join(" "),
);
/** Groups in order of first appearance, each with its matching entries. */
protected readonly groups = computed(() => {
const items = this.items();
return [...new Set(items.map((item) => item.group))].map(
(name, groupIndex) => ({
name,
id: `${this.dialogId()}-group-${groupIndex}`,
entries: items
.map((item, index): Entry => ({ item, index }))
.filter((entry) => entry.item.group === name)
.filter((entry) => matches(entry.item, this.query())),
}),
);
});
protected readonly visible = computed(() =>
this.groups().flatMap((group) => group.entries),
);
protected readonly activeId = computed(() => {
const visible = this.visible();
const entry = visible[Math.min(this.active(), visible.length - 1)];
return entry ? this.optionId(entry.index) : undefined;
});
private readonly dialog =
viewChild.required<ElementRef<HTMLDialogElement>>("dialog");
constructor() {
afterRenderEffect(() => {
const id = this.activeId();
if (id)
document.getElementById(id)?.scrollIntoView?.({ block: "nearest" });
});
}
/** Opens the palette. Also callable from a template reference: command.show(). */
show() {
this.dialog().nativeElement.showModal();
this.open.set(true);
}
protected optionId(index: number) {
return `${this.dialogId()}-option-${index}`;
}
protected handleHotkey(event: KeyboardEvent) {
if (!this.hotkey()) return;
if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "k")
return;
event.preventDefault();
const dialog = this.dialog().nativeElement;
if (dialog.open) return dialog.close();
this.show();
}
protected select(item: CommandItem) {
this.selected.emit(item.value ?? item.label);
this.dialog().nativeElement.close();
}
protected handleClose() {
this.open.set(false);
this.query.set("");
this.active.set(0);
}
protected handleClick(event: MouseEvent) {
// A click on the dialog itself (not its content) is a click on the backdrop.
if (event.target === event.currentTarget)
this.dialog().nativeElement.close();
}
protected handleInput(event: Event) {
this.query.set((event.target as HTMLInputElement).value);
this.active.set(0);
}
protected handleKeydown(event: KeyboardEvent) {
const count = this.visible().length;
const steps: Record<string, number | undefined> = {
ArrowDown: 1,
ArrowUp: -1,
};
const step = steps[event.key];
if (step !== undefined) {
event.preventDefault();
if (count > 0)
this.active.update((current) => (current + step + count) % count);
return;
}
const activeId = this.activeId();
if (event.key !== "Enter" || !activeId) return;
event.preventDefault();
document.getElementById(activeId)?.click();
}
}Usage
<x-markas.command
hotkey
:items="[
['group' => 'Navigation', 'label' => 'Dashboard', 'href' => '/dashboard'],
['group' => 'Navigation', 'label' => 'Projects', 'href' => '/projects'],
['group' => 'Actions', 'label' => 'Create project', 'value' => 'create', 'shortcut' => 'Ctrl+N'],
['group' => 'Actions', 'label' => 'Invite member', 'value' => 'invite'],
]"
x-on:markas-select="console.log($event.detail)"
>
<x-slot:trigger>
<x-markas.button variant="secondary">Search</x-markas.button>
</x-slot:trigger>
</x-markas.command>Needs Alpine.js. Choosing a command dispatches a markas-select event with the value in $event.detail. In Livewire: x-on:markas-select="$wire.
Livewire
<x-markas.command hotkey :items="$commands" wire:markas-select="go($event.detail)" />wire:markas-select calls a Livewire action with the picked value. The Ctrl+K listener is removed when the component leaves the page, so wire:navigate never stacks listeners.
import { Button } from "@/components/markas/Button";
import { Command } from "@/components/markas/Command";
<Command
hotkey
trigger={<Button variant="secondary">Search</Button>}
items={[
{ group: "Navigation", label: "Dashboard", href: "/dashboard" },
{ group: "Navigation", label: "Projects", href: "/projects" },
{
group: "Actions",
label: "Create project",
value: "create",
shortcut: "Ctrl+N",
},
{ group: "Actions", label: "Invite member", value: "invite" },
]}
onSelect={(value) => console.log(value)}
/>;<template>
<Command
hotkey
:items="[
{ group: 'Navigation', label: 'Dashboard', href: '/dashboard' },
{ group: 'Navigation', label: 'Projects', href: '/projects' },
{
group: 'Actions',
label: 'Create project',
value: 'create',
shortcut: 'Ctrl+N',
},
{ group: 'Actions', label: 'Invite member', value: 'invite' },
]"
@select="(value) => console.log(value)"
>
<template #trigger>
<Button variant="secondary">Search</Button>
</template>
</Command>
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import Command from "$lib/components/markas/Command.svelte";
const items = [
{ group: "Navigation", label: "Dashboard", href: "/dashboard" },
{ group: "Navigation", label: "Projects", href: "/projects" },
{
group: "Actions",
label: "Create project",
value: "create",
shortcut: "Ctrl+N",
},
{ group: "Actions", label: "Invite member", value: "invite" },
];
</script>
<Command hotkey {items} onselect={(value) => console.log(value)}>
{#snippet trigger()}
<Button variant="secondary">Search</Button>
{/snippet}
</Command>---
import Button from "@/components/markas/Button.astro";
import Command from "@/components/markas/Command.astro";
const items = [
{ group: "Navigation", label: "Dashboard", href: "/dashboard" },
{ group: "Navigation", label: "Projects", href: "/projects" },
{ group: "Actions", label: "Create project", value: "create", shortcut: "Ctrl+N" },
{ group: "Actions", label: "Invite member", value: "invite" },
];
---
<Command hotkey items={items}>
<Button slot="trigger" variant="secondary">Search</Button>
</Command>
<script>
document.addEventListener("markas-select", (event) => {
console.log((event as CustomEvent<string>).detail);
});
</script>A small bundled script filters the list and handles the keyboard. Choosing a command dispatches a bubbling markas-select event with the value in detail.
import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Command } from "./markas/command.component";
@Component({
selector: "app-launcher",
imports: [Button, Command],
template: `
<markas-command hotkey [items]="items" (selected)="run($event)">
<button markas-button trigger variant="secondary">Search</button>
</markas-command>
`,
})
export class Launcher {
readonly items = [
{ group: "Navigation", label: "Dashboard", href: "/dashboard" },
{ group: "Navigation", label: "Projects", href: "/projects" },
{
group: "Actions",
label: "Create project",
value: "create",
shortcut: "Ctrl+N",
},
{ group: "Actions", label: "Invite member", value: "invite" },
];
run(value: string) {}
}- The search is a case-insensitive match on the label. The search resets when the dialog closes.
- Items with
hrefnavigate like normal links and also call the select callback. - Attributes and
classgo to thedialogelement. placeholderLabel,emptyLabel,searchLabel, anddialogLabeldefault to English. Translate them for other languages.
Props
| Name | Type | Default | Description |
|---|---|---|---|
items | { group, label, value?, href?, shortcut? }[] | [] | Commands. Items are grouped by group in order of first appearance. Items with href render as links. |
trigger | slot / ReactNode / snippet | - | Element that opens the palette on click, usually a button. Angular: an element with the trigger attribute. |
hotkey | boolean | false | Ctrl+K or Cmd+K anywhere on the page opens and closes the palette. |
placeholderLabel | string | Type a command or search... | Placeholder of the search field. |
emptyLabel | string | No results found. | Message shown when no command matches the search. |
searchLabel | string | Search commands | Accessible name of the search field. |
dialogLabel | string | Command palette | Accessible name of the dialog and the result list. |
onSelect / @select / markas-select | (value: string) => void | - | Called when a command is chosen, with its value (or label when value is empty). Svelte: onselect. Blade and Astro dispatch a bubbling markas-select event with the value in detail. |
id | string | auto | Dialog id. The list and options use it as a prefix. |
selected | output<string> | - | Angular only. Emits the value (or label) of the chosen command. |
Accessibility
- Native modal dialog: focus moves to the search field on open, stays inside the dialog, and returns to the trigger on close.
- The search field is a combobox with aria-controls pointing to the role=listbox result list and aria-activedescendant on the highlighted option.
- Arrow Down and Arrow Up move the highlight (wrapping at the ends), Enter runs the highlighted command, Escape closes the dialog.
- Options are grouped with role=group labelled by the group heading; the empty message replaces the list when nothing matches.
Related components
More overlay components with the same classes in every framework.
- Alert DialogModal confirmation built on the native dialog element. It needs an explicit cancel or action choice and never closes on a backdrop click.
- Context MenuMenu opened by right-clicking an area or pressing Shift+F10, shown at the pointer through the Popover API with WAI-ARIA Menu keyboard support.
- DrawerFull-height side panel built on the native dialog element, sliding in from the right or left.
- Dropdown MenuAction menu built on the Popover API, with keyboard navigation following the WAI-ARIA Menu Button pattern.
- Hover CardPreview card built on the Popover API, shown when a link is hovered or focused, for profiles, repositories, and other previews.
- ModalModal dialog built on the native dialog element, with focus trapping and a close button.