CommandK
Global βK / Ctrl+K site launcher β navigation + action registry, current-route aware via SvelteKit.
Live demo
01Press βK (or Ctrl+K) anywhere
The launcher listens on svelte:window. Try it now β focus the
input, type to filter, ββ to navigate, Enter to activate, Esc to close.
βK / Ctrl+K opens it. Last activation: Press βK (Mac) or Ctrl+K to open the launcher.
Built-in sections
The demo sections include both navigation targets (with href) and action items (with action callbacks). Real apps would source sections from the route manifest + a caller-supplied actions array.
- π§ Navigation
HomeComponents directoryDrawer demoSplitView demoNavbar demo
- β‘ Actions
Console.log from launcherShow alert
How consumers mount it
Mount once near the app root (e.g. in +layout.svelte) so the hotkey
listener is global. The component is otherwise inert.
<script lang="ts">
import CommandK from '$lib/components/CommandK.svelte';
</script>
<CommandK
sections={[
{ id: 'nav', label: 'Navigation', items: [...] },
{ id: 'actions', label: 'Actions', items: [...] }
]}
/>
<slot />Implementation
02<script lang="ts">
import CommandK from '$lib/components/CommandK.svelte';
</script>
β
<CommandK
sections={[
{
id: 'navigation',
label: 'Navigation',
items: [
{ id: 'home', label: 'Home', href: '/', keywords: 'index landing root' },
{ id: 'components', label: 'Components directory', href: '/components', keywords: 'catalog browse' }
]
},
{
id: 'actions',
label: 'Actions',
items: [
{
id: 'theme-toggle',
label: 'Toggle theme',
action: () => console.log('toggle')
}
]
}
]}
/>CommandK mounts a global βK/Ctrl+K hotkey listener via svelte:window. When triggered it shows a modal with role=dialog and aria-modal=true. Sections come from the caller (or a default fallback). Items with href navigate via SvelteKit goto() (dynamically imported so unit tests run without the SvelteKit runtime); items with action() invoke the function. Keyboard nav: ββ to move, Enter to activate, Esc to close. Tab cycles inside the focus trap; body scroll is locked while open.
Logic explainer
03What Does It Do? (Plain English)
A modal launcher that opens on βK (Mac) / Ctrl+K (everywhere else). Bound to the current SvelteKit app: it shows navigation routes + caller-supplied action items, grouped into sections, with substring filtering across each item's label and keywords, full keyboard navigation, and a focus trap while open.
Differentiated from CommandPalette.svelte (a generic fuzzy item picker over arbitrary items), this is navigation-and-actions over the app's own catalog. It knows about the current route via SvelteKit's afterNavigate, highlights the matching item so users see where they are, and navigates via goto() when an item with an href is activated β or invokes an action() callback if the item has no destination.
Mount it once near the app root and the launcher is global; users don't need to know which page they're on to navigate anywhere.
How It Works (Pseudo-Code)
state:
open = false // dialog open/closed
query = '' // current input value
activeIndex = 0 // index into flatItems for keyboard cursor
currentPath = '/' // tracked via afterNavigate for badge
inputEl = bound DOM ref
listEl = bound DOM ref
derive effectiveSections:
if sections.length > 0:
return sections
else:
return built-in fallback (Home + Components)
derive filteredSections:
q = query.trim().toLowerCase()
if q == '': return effectiveSections
return effectiveSections
.map(section => {
items: section.items.filter(item => {
haystack = (item.label + ' ' + (item.keywords ?? '')).toLowerCase()
return haystack.includes(q)
})
})
.filter(section => section.items.length > 0)
derive flatItems:
filteredSections.flatMap(section => section.items)
derive totalResults:
sum of filteredSections[i].items.length
events:
on global keydown:
if !open:
if (mod && key == 'k') and hotkey.endsWith('+k'):
openDialog()
else:
if key == 'Escape': closeDialog()
if key == 'ArrowDown': activeIndex = min(activeIndex + 1, len-1)
if key == 'ArrowUp': activeIndex = max(activeIndex - 1, 0)
if key == 'Enter': activate(activeIndex)
on Tab on dialog (focus trap):
if shiftKey && active == first focusable: focus last
if !shiftKey && active == last focusable: focus first
on click item: activate(flatIndexOf(item))
on mouseenter item: activeIndex = flatIndexOf(item)Why Hotkey Detection Lives On svelte:window
The hotkey listener is attached to window, not the dialog itself. This is deliberate: the launcher should open from anywhere in the app, including pages where the dialog isn't even mounted yet. The component is always mounted (per the consumer-must-mount-once contract), so svelte:window is always listening, regardless of which route the user is on.
The hotkey detection logic is intentionally simple β match on event.metaKey || event.ctrlKey plus event.key.toLowerCase() === 'k' and hotkey.endsWith('+k'). This covers βK and Ctrl+K without needing to know the platform; macOS users get β, everyone else gets Ctrl, both feel native.
Focus Trap: Why It's Manual
The dialog traps focus manually rather than relying on <dialog>'s native behaviour or inert on the rest of the page. Two reasons:
- Browser inconsistency. Native
<dialog>focus-trap behaviour varies between Chromium, Firefox, and Safari, and theinertattribute has spotty support in older versions. A manual Tab/Shift+Tab trap is the only cross-browser reliable approach. - Test compatibility.
<dialog>element semantics interact with the SvelteKit runtime in ways that break unit tests (the test environment isn't a real browser). A plain<div role="dialog">with manual focus management tests cleanly without the SvelteKit runtime.
The trap walks the focusables inside the dialog (anchors, buttons, non-disabled inputs, non-negative tabindex) on each Tab, wrapping from last back to first. Esc closes; the focus-snapshot taken at open time is restored on close.
The SvelteKit Dynamic-Import Trick
$app/state and $app/navigation are SvelteKit runtime-only modules β they don't exist in unit test environments, so a top-level import would break bun run test. The component uses runtime dynamic imports instead:
onMount:
if (!browser) return cleanup
await Promise.all([
import('$app/state'), // for page.url.pathname
import('$app/navigation') // for afterNavigate + goto
])The try { ... } catch { /* $app/* unavailable β keep defaults */ } guard means the component works in pure Svelte (no SvelteKit), in SvelteKit, and in unit tests β three environments, one source.
Current-Route Awareness
afterNavigate(({ to }) => { currentPath = to.url.pathname }) listens for SvelteKit navigation events and updates currentPath. The item list checks each item's href against this and adds data-current="true" to the matching one, which the stylesheet paints with a "β" badge. The highlight follows the user as they navigate β useful when the launcher is open during navigation (rare but possible).
Reduced-Motion Is Boring On Purpose
The dialog opens with a 220ms cubic-bezier slide-in and the backdrop fades in over 180ms. Under prefers-reduced-motion: reduce, both animations are removed entirely. There's no opacity fade either β the dialog just appears. That's the right choice: a fade on a modal that responds to a hotkey would add latency between the user's intent (press βK) and the visual confirmation (dialog appears), and that latency is motion sickness territory for some users.
Distinct From
- CommandPalette.svelte: a generic fuzzy item picker over an arbitrary array. CommandK is purpose-built for SvelteKit app navigation, with current-route awareness and the
mod+khotkey contract. Use CommandPalette for "pick anything"; use CommandK for "navigate this app". - Drawer: Drawer is a slide-in modal panel from an edge. CommandK is a centred dialog at the top of the viewport with focus-trap semantics. They serve different visual affordances.
- Navbar drawer fuzzy search (Pair B improvement #2 from the site-nav pitch): the Navbar drawer is mouse-first browse; CommandK is keyboard-first jump. They coexist.
State Flow Diagram
ββββββββββββββββββ
β mounted β
β open = false β
βββββββββ¬βββββββββ
β
βK / Ctrl+K β
βΌ
ββββββββββββββββββ
β openDialog() β
β snapshot focusβ
β lock body β
β open = true β
β focus input β
βββββββββ¬βββββββββ
β
βββββββββββββββββββΌββββββββββββββββββ
βΌ βΌ βΌ
type query ββ navigate Enter / click
β β β
βΌ βΌ βΌ
filteredSections activeIndex activate(idx)
flatItems updates goto(item.href)
or
item.action()
β
βΌ
closeDialog()
restore focus
unlock bodyProps Reference
| Prop | Type | Default | Description |
|---|---|---|---|
hotkey |
string |
'mod+k' |
Hotkey to open. mod = Cmd on Mac, Ctrl elsewhere. |
placeholder |
string |
'Type to navigateβ¦' |
Input placeholder text. |
emptyMessage |
string |
'No matches' |
Shown when the filter yields no results. |
sections |
CommandSection[] |
built-in fallback | Sections to render. Each has {id, label, icon?, items} where items are {id, label, href?, action?, keywords?}. |
ariaLabel |
string |
'Command launcher' |
Accessible name for the dialog. |
onNavigate |
(href: string) => void |
uses SvelteKit goto() |
Override the default navigation handler. |
children |
Snippet |
undefined |
Optional content rendered inside the dialog (e.g. footer hints). |
Edge Cases
- No
sectionsprop: the built-in fallback (Home + Components directory) is shown. Useful for a minimal mount before the consumer wires up real sections. hrefitems +goto(): items withhrefnavigate viagoto()(dynamic-imported so unit tests work). Items withaction()call the function. Items with neither are filtered out (the type system prevents this but the runtime is tolerant).- Current-route badge during navigation:
afterNavigateupdatescurrentPathwhile the dialog is open, so the badge moves in real time if the user navigates from inside the dialog (rare but supported). - Empty query: all sections and items are shown. The user can scroll or arrow-key through the list.
- Long item lists:
flatItems.lengthis the upper bound for arrow-key navigation. The list itself scrolls within the dialog. - Body scroll lock:
document.body.style.overflow = 'hidden'on open, restored to the previous value on close. Saves the prior value (not blanking to'') so any pre-existing inline style is preserved. - Focus restoration on close: the element that had focus when
openDialog()ran is restored on close. If that element is no longer in the DOM (rare, e.g. route change removed it), the focus is left where it is rather than throwing.
Dependencies
Zero at build time. The $app/state and $app/navigation modules are runtime-imported from SvelteKit (which the consumer is presumed to have). The component fails gracefully in non-SvelteKit environments (the dynamic-imports are caught and swallowed).
File Structure
src/lib/components/
CommandK.svelte # the component
CommandK.test.ts # render, hotkey, filter, navigation, source checks
CommandKTestHarness.test.svelte # internal harness for the test
CommandK.md # this fileThe catalog entry and the /commandk demo route live next to the other components in src/lib/componentCatalog.ts and src/routes/commandk/+page.svelte.
API
04| Prop | Type | Default | Description |
|---|---|---|---|
hotkey | string | 'mod+k' | Hotkey to open. mod = Cmd on Mac, Ctrl elsewhere. |
placeholder | string | 'Type to navigateβ¦' | Input placeholder text. |
emptyMessage | string | 'No matches' | Shown when the filter yields no results. |
sections | CommandSection[] | built-in fallback | Sections to render. Each has {id, label, icon?, items} where items are {id, label, href?, action?, keywords?}. |
ariaLabel | string | 'Command launcher' | Accessible name for the dialog. |
onNavigate | (href: string) => void | uses SvelteKit goto() | Override the default navigation handler. |