Keyboard Shortcuts
Headless shortcut management with registration, conflict detection, user overrides, and platform-aware display formatting.
import { createShortcutManager } from "phoundry-ui";Basic Registration & Display
Loading interactive example…
View source
<script lang="ts"> import { Kbd } from "phoundry-ui";</script>
<div class="space-y-3"> <p class="text-xs text-txt-secondary"> Create a manager, register shortcuts, and display formatted key combos. </p> <div class="flex items-center gap-3"> <span class="text-xs text-txt-secondary">Save:</span> <Kbd keys="Mod+S" /> <span class="text-xs text-txt-secondary">New:</span> <Kbd keys="Mod+N" /> </div> <p class="text-[11px] text-txt-tertiary"> The manager listens to keyboard events via <code>handleKeyDown()</code>. Wire it up in your layout's <code>onkeydown</code>. </p></div>Platform-Specific Shortcuts
Loading interactive example…
View source
<script lang="ts"> import { Kbd } from "phoundry-ui";</script>
<div class="space-y-2"> <p class="text-xs text-txt-secondary"> Use per-platform objects for shortcuts that differ across operating systems. </p> <div class="flex items-center gap-3"> <span class="text-xs text-txt-tertiary">Mac:</span> <Kbd keys="Mod+Backspace" /> <span class="text-xs text-txt-tertiary">Win/Linux:</span> <Kbd keys="Ctrl+Shift+K" /> </div></div>User Overrides & Conflict Detection
Users can rebind shortcuts. The manager validates conflicts and persists overrides via callbacks.
// User wants to rebind Save to Ctrl+Shift+Sawait shortcuts.setOverride("app.save", ["Ctrl+Shift+S"]);
// Check for conflicts before settingconst conflict = shortcuts.checkConflict("Ctrl+N", "app.new");if (conflict) { console.warn(`Conflicts with "${conflict.existingActionLabel}"`);}
// Reset a single action or all overridesawait shortcuts.resetToDefault("app.save");await shortcuts.resetAll();Standalone Utilities
Low-level utilities for parsing, formatting, and matching shortcuts outside the manager.
import { parseShortcut, formatShortcut, matchesEvent } from "phoundry-ui";
const parsed = parseShortcut("CmdOrCtrl+Shift+P", "mac");// → { key: 'p', ctrl: false, meta: true, alt: false, shift: true }
const display = formatShortcut("CmdOrCtrl+S", "mac");// → "⌘S"
document.addEventListener("keydown", (e) => { if (matchesEvent(parsed, e)) { console.log("Matched!"); }});Factory vs getter
createShortcutManager installs the singleton; subsequent modules
can call getShortcutManager() without threading instances through
every import.
import { createShortcutManager, getShortcutManager } from "phoundry-ui";
// Typically once at startup:export const shortcuts = createShortcutManager({ loadOverrides, saveOverrides,});
// Elsewhere (after startup):const same = getShortcutManager();Construction
From phoundry-ui@0.4.21
createShortcutManager: (options?: ShortcutManagerOptions | undefined): ShortcutManagercreateShortcutManager(options?): Construct (or replace) the process singleton - must run before getShortcutManager().
getShortcutManager(): Throws if no manager was created yet - useful for modules that only consume shortcuts.
ShortcutManager (state)
From phoundry-ui@0.4.21
| Name | Type | Default | Description |
|---|---|---|---|
platform | ShortcutPlatform | — | Resolved platform key (mac, windows, linux) used when parsing definitions. |
isReady | boolean | — | Becomes true after init() resolves (safe to read shortcuts with overrides applied). |
ShortcutManagerOptions
From phoundry-ui@0.4.21
| Name | Type | Default | Description |
|---|---|---|---|
loadOverrides | (() => Promise<ShortcutOverrides> | ShortcutOverrides) | undefined | — | Callback to load persisted shortcut overrides at init. |
saveOverrides | ((overrides: ShortcutOverrides) => Promise<void> | void) | undefined | — | Callback to persist overrides after every change. |
shouldIgnore | ((event: KeyboardEvent) => boolean) | undefined | — | Filter to skip events. Defaults to ignoring inputs, textareas, and open modals. |
ShortcutRegistration
From phoundry-ui@0.4.21
| Name | Type | Default | Description |
|---|---|---|---|
idrequired | string | — | Unique identifier for the shortcut action. |
labelrequired | string | — | Human-readable label shown in settings UI. |
defaults | ShortcutDefinition[] | undefined | — | Default shortcut(s). Strings like "CmdOrCtrl+S" or per-platform objects. |
handlerrequired | (event: KeyboardEvent) => void | boolean | Promise<void> | — | Called when the shortcut fires. Return false to allow propagation. |
when | (() => boolean) | undefined | — | Guard - shortcut only fires when this returns true. |
section | string | undefined | — | Group in settings UI. |
subsection | string | undefined | — | Subgroup in settings UI. |
priority | number | undefined | — | Higher priority shortcuts are checked first. |
allowDefault | boolean | undefined | — | If true, does not call preventDefault(). |
ShortcutManager Methods
From phoundry-ui@0.4.21
| Name | Type | Default | Description |
|---|---|---|---|
register | (registration: ShortcutRegistration) => void | — | Register a keyboard shortcut with id, label, defaults, and handler. |
registerAll | (registrations: ShortcutRegistration[]) => void | — | Register multiple shortcuts at once. |
unregister | (id: string) => void | — | Remove a shortcut registration by id. |
unregisterByPrefix | (prefix: string) => void | — | Remove all registrations whose id starts with the given prefix. |
has | (id: string) => boolean | — | Check if a shortcut id is registered. |
get | (id: string) => ShortcutRegistration | undefined | — | Get a registration by id. |
getShortcutsForAction | (id: string) => string[] | — | Get the active shortcut strings for an action (respects overrides). |
getDisplayShortcut | (id: string) => string | null | — | Get the formatted display string for the primary shortcut. |
getDisplayShortcuts | (id: string) => string[] | — | Get formatted display strings for all shortcuts of an action. |
setOverride | (actionId: string, shortcuts: (string | null)[]) => Promise<void> | — | Set user-customized shortcut(s) for an action. Validates conflicts. |
resetToDefault | (actionId: string) => Promise<void> | — | Remove the user override for an action, restoring defaults. |
resetAll | () => Promise<void> | — | Clear all user overrides. |
hasOverride | (actionId: string) => boolean | — | Check if an action has a user override. |
checkConflict | (shortcut: string, excludeActionId?: string) => ShortcutConflict | null | — | Check if a shortcut string conflicts with existing registrations. |
handleKeyDown | (event: KeyboardEvent) => boolean | — | Process a keyboard event. Returns true if a shortcut matched. |
getSections | () => ShortcutSection[] | — | Get all registrations grouped by section/subsection for settings UI. |
init | () => Promise<void> | — | Load persisted overrides. Call once after creation. |
destroy | () => void | — | Clear all registrations and caches. |
Usage tips
- Use
CmdOrCtrlas a modifier prefix - it resolves toCmdon Mac andCtrlelsewhere. - Call
init()after creation to load persisted overrides before registering shortcuts. - The default
shouldIgnoreskips events in inputs, textareas, contenteditable, and when a modal is open. - Use
whenguards for context-dependent shortcuts (e.g., only active when a panel is focused). - Up to 3 shortcut bindings per action are supported.
getSections()returns grouped registrations - useful for building a keyboard shortcuts settings panel.