UI

Shortcut

A labelled keyboard shortcut recorder with live platform-aware key caps, conflict and reserved-chord warnings, standalone key displays, and a searchable cheatsheet.

import { ShortcutInput } from '@uthereal/ui/shortcut-input'

Shortcut input playground

Click to record a new chord, or press Backspace to clear.
Loading interactive preview…

Overview

ShortcutInput renders a labelled field that records keyboard shortcuts as platform-neutral chords such as "mod+shift+k". Pressing the control starts recording: held modifiers pop in as live key caps while the chord builds, and releasing a complete combination settles the caps in place. If a chord matches an entry in bindings or a reserved browser shortcut, an inline warning row asks the user to confirm or cancel before replacing it.

Your application owns the binding map and runs global key listeners with matchesShortcut. ShortcutInput reports every committed or cleared chord through onValueChange together with any replaced binding so the host can unbind it cleanly.

CapabilityBehavior
Platform chordsStores lowercase chords with mod; renders ⌃ ⌥ ⇧ ⌘ on macOS and Ctrl Alt Shift Win elsewhere (hydrates safely)
Live recordingCaptures physical key codes (⌥K records as alt+k); Escape cancels, Tab exits without trapping focus
Conflict checksChecks bindings and 12 reserved browser chords (warnReserved); asks before replacing and returns details.replaced
Reset & clearInline buttons restore resetValue (or defaultValue) and clear to null; Backspace or Delete clears when settled
Form & statesEmits a hidden <input type="hidden"> when name is set (disabled omits submission); readOnly blocks edits safely
Companion partsExports ShortcutKeys for inline key-cap display and ShortcutList for a searchable, live-highlighted cheatsheet

Use ShortcutInput in keybinding preferences, command palettes, and editor settings. Use Text for general text entry or Tags for free-form keyword lists.

Usage

'use client'
import { useState } from 'react'
import {
  ShortcutInput,
  type ShortcutBinding,
} from '@uthereal/ui/shortcut-input'

const existingBindings: ShortcutBinding[] = [
  { shortcut: 'mod+k', label: 'Command menu' },
  { shortcut: 'mod+shift+p', label: 'Quick actions' },
]

export function SearchShortcutField() {
  const [shortcut, setShortcut] = useState<string | null>('mod+shift+f')

  return (
    <ShortcutInput
      label="Find in files"
      name="find_shortcut"
      defaultValue="mod+shift+f"
      resetValue="mod+shift+f"
      bindings={existingBindings}
      value={shortcut}
      onValueChange={(next, { replaced }) => {
        setShortcut(next)
        if (replaced) {
          console.log('Unbind conflict:', replaced.label, replaced.shortcut)
        }
      }}
    />
  )
}

Omit value for an uncontrolled field initialized from defaultValue (null means no shortcut is set). When name is set, a hidden <input type="hidden"> submits the normalized chord (or an empty string when cleared) with the surrounding form unless the field is disabled.

Examples

Conflict checks, reserved chords, and reset targets

Pass existing application shortcuts in bindings so recording a taken chord opens an inline warning row with Use anyway and Cancel actions instead of overwriting silently. Keep warnReserved enabled to flag browser chords such as mod+w or mod+c, and set resetValue when the reset button should restore a factory binding that differs from the current value.

Try recording ⌘K or ⌘W to see conflict and reserved warnings.

Cross-platform labels, bare keys, and compact states

Set platform="other" to preview or lock Windows and Linux key names (Ctrl, Alt, Shift, Win) regardless of the viewer's operating system. Disable requireModifier when single keys or arrow keys are valid bindings, use size="sm" for 36px inspector rows with 22px caps, or set readOnly to present a locked binding in the tab order.

Windows and Linux key labels in a compact 36px row.
Accepts single keys without a modifier.
Managed by workspace defaults.

Shortcut model

Shortcuts are stored as lowercase +-separated strings with canonical modifier order (mod, ctrl, alt, shift, meta) followed by a physical key id. Using event.code for letters, digits, and punctuation prevents Option-key dead characters (⌥K records as "alt+k" rather than "˚").

TokenmacOS displayWindows / Linux displayMeaning
mod⌘CtrlPrimary platform modifier (Command or Ctrl)
ctrl⌃CtrlControl key (distinct from mod on macOS)
alt⌥AltOption on macOS, Alt elsewhere
shift⇧ShiftShift modifier
meta⌘WinCommand on macOS (normalized to mod), Win key

By default (requireModifier={true}), non-function keys require at least one strong modifier (mod, ctrl, alt, or meta); function keys F1–F12 are always accepted without a modifier. Twelve browser shortcuts (mod+w, mod+t, mod+n, mod+q, mod+l, mod+r, mod+shift+t, mod+c, mod+v, mod+x, mod+z, mod+a) are exported as RESERVED_SHORTCUTS.

API reference

These serializable arguments and defaults come directly from the component schema.

ArgumentType / defaultDescription
labelstringDefault: "Shortcut"Visible label and accessible name. Name the information asked for, in sentence case.
hideLabelbooleanDefault: falseHide the label visually when the context already names the field. It is still announced.
descriptionstring—Supporting text below the field, announced with it. Use it for format hints and constraints.
errorstring—Validation message from your application. Setting it marks the field invalid; the message is linked to the field and announced politely.
requiredbooleanDefault: falseMarks the field as required for assistive technology and shows an indicator. Your application validates the value.
readOnlybooleanDefault: falseThe value can be focused, selected, and copied, but not edited. It is still submitted with a form.
disabledbooleanDefault: falseUnavailable and removed from the tab order. A disabled field is not submitted with a form.
namestring—Native form field name, submitted with the value in a form.
defaultValuestring | nullDefault: nullInitial shortcut, e.g. "mod+shift+k", or null for none. Later argument edits do not reset an existing instance; use value and onValueChange to control it.
resetValuestring | null—What the reset button restores; omit it to restore the initial shortcut.
bindingsShortcutBinding[]Default: []Shortcuts already in use elsewhere in the application. Recording one asks before it is taken, and confirming reports the binding it replaced so the host can unbind it.
warnReservedbooleanDefault: trueWarn when the recorded combination is kept by the browser or the system, such as Command W or Command C. On by default.
requireModifierbooleanDefault: trueRequire Command, Ctrl or Alt, so a plain key is never recorded. Function keys F1-F12 are always allowed. On by default.
platformmac | other—Key names for macOS or other systems. Omit it to use the viewer platform, assumed macOS until hydration.
placeholderstringDefault: "Record shortcut"Text while no shortcut is set and the recorder is idle, e.g. "Record shortcut".
variantoutline | soft | ghostDefault: "outline"Field surface: outline for forms, soft on busy surfaces, ghost for inline editing without a border.
sizesm | mdDefault: "md"Field height and cap size: 36 pixels (22px caps) or 44 pixels (26px caps).
recipestudio | softDefault: "studio"Visual treatment. Both recipes use the same interaction behavior.
themeShortcutInputTheme—Color mode, accent, and semantic tokens, including key cap geometry, the recording light, and cheatsheet row height. See Motion and theming for all keys and defaults.
motionnone | subtle | expressiveDefault: "subtle"Key caps popping in as the chord builds, the recording light breathing, the message row springing to its content height, and the cheatsheet rows fading; the reset and clear actions scale in. Reduced motion fades; none makes every change immediate.
motionOptionsShortcutInputMotionOptions—How the message row and cheatsheet rows follow their height (the disclosure family; smooth spring by default). Durations are milliseconds.
dirltr | rtl—Reading direction. Omit it to inherit the page direction.

React integration

PropPurpose
value, onValueChangeControlled chord (string | null) and change callback (value, { replaced }) fired in both modes
refRef to the recorder <button> element.
presetApplication defaults (such as platform, size, warnReserved, and theme), overridden locally.
tokensCSS custom properties (--ui-*) applied after the typed theme on the field root.
className, styleApplied to the root field element, which carries the resolved --ui-* tokens.
Native attributesForwarded to the recorder <button> (id, aria-describedby, onClick, onKeyDown, onBlur).

Companion components and utilities

@uthereal/ui/shortcut-input also exports standalone display and cheatsheet components, platform hooks, and pure chord helpers.

ExportPurpose
ShortcutKeysStandalone key-cap display (shortcut, platform, pressed boolean or ReadonlySet<string>, size, tone, recipe, theme, motion, preset, tokens).
ShortcutListSearchable, grouped cheatsheet (groups, label, searchable, searchPlaceholder, highlightPressed, platform, size, recipe, theme, motion, motionOptions, preset, tokens).
usePlatformReturns 'mac' | 'other' with hydration-safe 'mac' server rendering; accepts an explicit override.
usePressedKeysTracks currently held physical key ids in capture phase; clears on window blur, visibility change, and Command lift.
Chord helpersnormalizeShortcut, shortcutFromEvent, matchesShortcut, shortcutTokens, formatShortcut, shortcutKeyId, MODIFIER_ORDER, RESERVED_SHORTCUTS.
'use client'
import { ShortcutKeys, ShortcutList } from '@uthereal/ui/shortcut-input'

const groups = [
  {
    label: 'Navigation',
    items: [
      { label: 'Command menu', shortcut: 'mod+k', keywords: 'palette search' },
      { label: 'Switch workspace', shortcut: 'mod+shift+w' },
    ],
  },
  {
    label: 'Editing',
    items: [
      { label: 'Format document', shortcut: 'alt+shift+f' },
      { label: 'Toggle comment', shortcut: 'mod+/' },
    ],
  },
]

export function ShortcutsCheatsheet() {
  return (
    <div>
      <p>
        Press <ShortcutKeys shortcut="mod+k" size="sm" /> to open search.
      </p>
      <ShortcutList groups={groups} />
    </div>
  )
}

In ShortcutList, holding a modifier key lights matching key caps across every row and dims rows that do not use that modifier. Holding every key of a row highlights the row. Search matches item labels, group headings, keywords, and key names or symbols such as "cmd k" or "⌘".

Keyboard & accessibility

Key / controlInteraction
Enter, SpaceStarts recording on the focused recorder button.
Key chord (recording)Shows held modifiers live; commits a valid chord or opens the conflict confirmation row.
Escape (recording)Cancels recording, preserves the previous shortcut, and announces "Recording canceled".
Tab (recording)Stops recording without capturing Tab so keyboard focus moves to the next control normally.
Backspace, DeleteClears the current shortcut (both while settled and while recording) and announces the clear.
Use anyway, CancelConfirms or rejects a conflicting chord and returns focus to the recorder button.
Reset, Clear buttonsSeparate tab stops that restore resetValue or clear to null, then return focus to the button.

The recorder is a native <button type="button"> with aria-pressed during recording, named by label and its spoken state ("Recording", spoken shortcut such as "Command Shift K", or placeholder) via aria-labelledby. Visual glyphs (⌘, ⇧, ⌥) sit inside aria-hidden="true" containers so assistive technology never reads raw symbol names. aria-describedby links description, error, and the inline message row only while mounted. State changes, nudges, and conflicts announce through a pre-mounted role="status" (aria-live="polite", aria-atomic="true") live region outside the button.

disabled removes the recorder from the tab order and disables the hidden form input. readOnly sets aria-disabled="true" so users can focus and inspect the bound shortcut while blocking recording, clearing, and resetting, and keeps the hidden form input active for submission.

In dir="rtl", the field chrome, label, recording light, placeholder, and ShortcutList rows mirror to reading order while rendered key-cap sequences isolate dir="ltr" so chords always read left to right (⌘ ⇧ K). Under forced-colors: active, recording and conflict borders, indicators, pressed caps, matched rows, and focus outlines map to Highlight, resting caps to CanvasText, links to LinkText, and disabled actions to GrayText.

Motion and theming

  • Key caps: live and committed caps pop in from 72% scale and 4px vertical travel through a 2px blur on Arc's snappy spring with a 35ms per-key stagger, gliding into position with layout="position". Newly settled caps stay lit in the pressed accent style for 700ms.
  • Recording indicator and actions: the recording dot breathes on a 1.4s opacity cycle while active; inline reset and clear buttons scale in on the snappy spring.
  • Message row and cheatsheet rows: the inline hint/conflict row and filtered ShortcutList groups and rows animate height on motionOptions.transition (Arc's critically damped smooth spring by default).
  • Reduced motion: prefers-reduced-motion: reduce disables scale, travel, blur, layout glide, pulsing dot animation, pressed cap drop, and height springs while keeping 120ms opacity crossfades. motion="none" makes every update immediate (0ms).

theme accepts the core, control, and accentTones token groups, plus borderStrong (resting cap and field edge), borderSubtle (cheatsheet row dividers), warning (conflict border, dot, and cap tint), and five component tokens: dotSize (6px at sm, 7px at md), rowHeight (32px at sm, 36px at md), capSize (22px at sm, 26px at md), capRadius (7px at sm, 8px at md), and capTextSize (11px at sm, 12px at md). An optional UtherealProvider supplies application-wide defaults.

Composition

ShortcutInput is a leaf component. Its normalized chord (string | null) is host state at /fields/instance-<id>/value, initialized from defaultValue. Stored chords survive configuration edits to labels, bindings, or appearance. See Building with agents.

{
  "type": "ShortcutInput",
  "props": {
    "label": "Open command menu",
    "defaultValue": "mod+k",
    "resetValue": "mod+k",
    "bindings": [{ "shortcut": "mod+shift+p", "label": "Quick actions" }]
  },
  "children": []
}

On this page