npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@clinth/ui-commands

v1.2.1

Published

A general-purpose library for managing UI commands, keyboard shortcuts, MIDI input, and tooltips.

Readme

@clinth/ui-commands

A general-purpose library for managing UI commands, keyboard shortcuts, MIDI input, and tooltips.

Installation

npm install @clinth/ui-commands

Quick Start

import {
  CommandRegistry,
  createCommandRegistry,
  KeyboardManager,
  loadKeyBindings,
  InputManager,
  createInputManager,
  UiInputManager,
  TooltipManager,
  createTooltipManager,
  type KeyBindingConfig,
} from '@clinth/ui-commands';

// 1. Create a command registry
interface AppState {
  isPlaying: boolean;
}

const registry = createCommandRegistry<AppState>({
  onInvoke: (id, args) => console.log(`Command invoked: ${id}`, args),
  onCommandNotFound: (id) => console.warn(`Unknown command: ${id}`),
});

// 2. Register commands
registry.register({
  id: 'play-stop',
  label: 'Play/Stop',
  description: 'Toggle playback',
  execute: (args) => console.log('Toggling playback', args?.context),
});

registry.register({
  id: 'zoom-in',
  label: 'Zoom In',
  description: 'Increase zoom level',
  enabledWhen: (state) => !state.isPlaying,
  execute: () => console.log('Zooming in'),
});

// 3. Create keyboard manager and load bindings
type AppMode = 'detail' | 'coarse';
const keyboard = new KeyboardManager<AppMode>();

const bindings: KeyBindingConfig<AppMode>[] = [
  { key: ' ', mode: 'all', command: 'play-stop', description: 'Play/Stop' },
  {
    key: '=',
    mode: 'detail',
    command: 'zoom-in',
    description: 'Zoom in',
    nonExclusive: true,
    commandContext: 'panel/detail',
  },
  {
    key: '=',
    mode: 'detail',
    command: 'zoom-in',
    description: 'Zoom in (list)',
    nonExclusive: true,
    commandContext: 'panel/list*',
  },
];

loadKeyBindings(keyboard, bindings);

// 4. Create input manager and initialize
const input = createInputManager(registry, keyboard);
input.setModeGetter(() => 'detail' as AppMode);
input.init();

// 5. Optionally, initialize UI input manager for button clicks
const uiInput = new UiInputManager({ parentContainer: document.body }, input);
uiInput.init();

// 6. Add tooltips for keyboard shortcuts
const tooltip = createTooltipManager(document.body, {
  getBindings: () => bindings,
  getMode: () => 'detail' as AppMode,
});
tooltip.init();

Core Concepts

CommandRegistry

Manages registration and invocation of commands.

const registry = createCommandRegistry({
  onInvoke: (id, args) => { /* called on successful command */ },
  onInvokeError: (id, error, stage) => { /* called when command throws */ },
  onCommandNotFound: (id) => { /* called when command not found */ },
});

registry.register({
  id: 'my-command',
  label: 'My Command',
  description: 'Does something',
  execute: (args) => { /* ... */ },
});

// Listen for command invocations
const unsubscribe = registry.addOnInvokeHandler((id, args) => {
  console.log(`Command ${id} was invoked`);
});

registry.invoke('my-command', { foo: 'bar' });
unsubscribe(); // Stop listening

Labels

label is a string, or a function of the state (like enabledWhen). Resolve it with getLabel. A host can also override it at runtime with setLabel, with no re-registration.

registry.register({
  id: 'play',
  label: (state) => (state.playing ? 'Stop' : 'Play'),
  description: 'Toggle playback',
  execute: () => { /* ... */ },
});

registry.getLabel('play', { playing: true }); // 'Stop'

registry.addOnLabelChangeHandler((id, label) => { /* re-render */ });
registry.setLabel('play', 'Pause');   // override; listeners notified
registry.getLabel('play', state);     // 'Pause'
registry.setLabel('play', undefined); // clear override

Command invocations from input managers include a context payload with the input source and focused element.

registry.register({
  id: 'my-command',
  label: 'My Command',
  description: 'Does something',
  execute: (args) => {
    console.log(args?.context?.source);
    console.log(args?.context?.commandContext);
    console.log(args?.context?.element);
  },
});

captureKeyBinding

captureKeyBinding({ signal?, manager?, target? }) returns Promise<{ key, modifiers: ModifierKey[] } | undefined> for "press the shortcut" dialogs. It suspends the manager's key handling while waiting, ignores a lone modifier, resolves on the first complete combination, and resolves undefined on Escape or abort. Use manager.bind({ ...captured, commandId }) and formatKeyboardBinding(undefined, captured.key, captured.modifiers).

KeyboardManager

Handles keyboard event binding and matching.

Bindings are exclusive by default. Registering a binding with the same key, modifiers, and mode throws unless nonExclusive: true is set.

A binding's modifiers are a minimum: the pressed modifiers must include them, and extra modifiers are allowed. For example, a Shift+Tab binding also fires on Ctrl+Shift+Tab unless a more specific binding exists for that combination. When several bindings match, the one with the most modifiers wins. Set exact: true to require the pressed modifiers to match exactly.

When multiple bindings match a gesture, any binding whose commandContext matches the input context wins. Use prefix* to match by prefix.

Key events from text fields (input, textarea and contenteditable elements, including those inside shadow roots) are ignored, so typing does not trigger shortcuts. Set inTextInput: true on bindings that should still fire while typing, such as Ctrl+F.

Holding a key fires auto-repeat keydown events. They reach the command with context.repeat === true. Set allowRepeat: false on a binding (a toggle or cycle, say) to ignore repeats; the default is true. The repeat is still swallowed with preventDefault().

const keyboard = new KeyboardManager<AppMode>();

keyboard.bind({
  key: 'a',
  modifiers: new Set(['ctrl']),
  mode: 'detail',
  nonExclusive: true,
  commandContext: 'panel/*',
  inTextInput: false, // default: don't fire while typing in a text field
  exact: false,       // default: extra modifiers are allowed
  allowRepeat: true,  // default: fire again while the key is held
  commandId: 'my-command',
});

// Get all current bindings
const bindings = keyboard.getBindings();

// Enable/disable keyboard handling
keyboard.setActive(false);

InputManager

Coordinates between command registry and keyboard, plus handles button bindings.

const input = createInputManager(registry, keyboard);

// Bind keys directly
input.bindKey('Enter', [], 'my-command', 'detail');

// Bind a button element to a command
const button = document.getElementById('my-button');
input.bindButton(button, 'my-command');

// Set the current app mode
input.setModeGetter(() => currentMode);

// Access the registry
const reg = input.getRegistry();

UiInputManager

Automatically binds buttons with data-command attributes.

<button data-command="play-stop">Play</button>
<button data-command="zoom-in" data-command-context="panel/list" data-args='{"level": 2}'>Zoom</button>
const uiInput = new UiInputManager({ parentContainer: document.body }, input);
uiInput.init();

Context selection favors bindings that match commandContext. Wildcards are supported using a trailing * to match prefixes.

TooltipManager

Shows keyboard shortcut tooltips on hover.

const tooltip = createTooltipManager(document.body, {
  getBindings: () => keyboard.getBindings().map(b => ({
    key: b.key,
    mode: b.mode,
    command: b.commandId,
    description: '...',
  })),
  getMode: () => currentMode,
  showDelayMs: 500,
  dismissDelayMs: 3000,
});
tooltip.init();

MIDI Support

import { MidiManager, midiManager, loadMidiBindings, type MidiBindingConfig } from '@clinth/ui-commands';

const midi = new MidiManager();

if (midi.isSupported()) {
  await midi.init();

  loadMidiBindings([
    { channel: 1, control: 1, command: 'play-stop', description: 'Play/Stop' },
  ]);
}

API Reference

CommandRegistry

  • register(command) - Register a command (throws if duplicate)
  • unregister(id) - Unregister a command, returns boolean
  • invoke(id, args?) - Invoke a command, returns boolean
  • addOnInvokeHandler(handler) - Add listener for invocations, returns unsubscribe
  • get(id) - Get command by ID
  • getAll() - Get all registered commands
  • getEnabled(state) - Get commands enabled for given state
  • has(id) - Check if command exists

KeyboardManager

  • new KeyboardManager({ defaultExact? }) - defaultExact sets exact for bindings that don't specify it
  • bind(binding) - Add a key binding (modifiers may be a Set or array); throws on an exclusive clash
  • findConflict(binding) - Existing binding that bind would reject this one for, or undefined
  • unbind(key, modifiers) / unbind({ commandId?, key?, modifiers?, mode?, commandContext? }) / unbind(predicate) - Remove matching bindings (keys case-insensitive), returns count
  • unbindCommand(commandId) - Remove all of a command's bindings, returns count
  • isActive() - Whether keyboard handling is active
  • setActive(active) - Enable/disable keyboard handling
  • setModeGetter(getter) - Set function that returns current mode
  • onKeyEvent(handler) - Add handler for key events, returns unsubscribe
  • attach(element) - Attach keyboard events to element
  • detach() - Remove keyboard events
  • getBindings() - Get all bindings

InputManager

  • init() - Initialize and attach keyboard to document.body
  • destroy() - Cleanup
  • bindKey(key, modifiers, commandId, mode?) - Bind a key
  • bindButton(element, commandId) - Bind a button click
  • unbindButton(element) - Remove button binding
  • setActive(active) - Enable/disable input handling
  • setModeGetter(getter) - Set function that returns current mode
  • getRegistry() - Access the command registry

UiInputManager

  • init() - Initialize and start listening for button clicks
  • destroy() - Stop listening for button clicks

TooltipManager

  • init() - Initialize tooltips
  • destroy() - Cleanup

MidiManager

  • init() - Initialize MIDI access
  • destroy() - Cleanup
  • isSupported() - Check if Web MIDI is supported

loadKeyBindings(keyboard, bindings)

Load an array of KeyBindingConfig into a KeyboardManager.

loadMidiBindings(bindings)

Load MIDI bindings (future implementation).

Types

Command

{
  id: CommandId;
  label: string | ((state: TState) => string);
  icon?: string;
  description: string;
  enabledWhen?: (state: TState) => boolean;
  execute: (args?: Record<string, unknown>) => void;
}

KeyBindingConfig

{
  key: string;
  modifiers?: Array<'ctrl' | 'shift' | 'alt' | 'meta'>;
  mode?: TAppModes | 'all';
  nonExclusive?: boolean;
  commandContext?: string;
  inTextInput?: boolean;
  exact?: boolean;
  allowRepeat?: boolean;
  command: string;
  description: string;
}

MidiBindingConfig

{
  channel: number;
  control?: number;
  note?: number;
  command: string;
  description: string;
}

TooltipOptions

{
  getBindings: () => Array<KeyBindingConfig<TAppModes>>;
  getMode: () => TAppModes;
  showDelayMs?: number;
  dismissDelayMs?: number;
  platform?: 'mac' | 'win';
}

UiInputOptions

{
  parentContainer: HTMLElement;
  bindButtonClicks?: boolean;
  onUnboundButton?: (button: HTMLButtonElement) => void;
  onUnboundCommandId?: (id: CommandId, button: HTMLButtonElement) => void;
}

Utilities

formatKeyboardBinding(platform, key, modifiers?)

Formats a keyboard binding for display. Returns strings like "Cmd + A" or "Ctrl + Shift + B".

detectPlatform()

Returns 'mac' or 'win' based on navigator.platform.

Type Aliases

  • Platform - 'mac' | 'win'
  • ModifierKey - 'ctrl' | 'shift' | 'alt' | 'meta'
  • Modifiers - { ctrl: boolean; shift: boolean; alt: boolean; meta: boolean; }
  • KeyBinding<TAppModes> - { key: string; modifiers: Set<ModifierKey>; mode?: TAppModes | 'all'; nonExclusive?: boolean; commandContext?: string; inTextInput?: boolean; exact?: boolean; allowRepeat?: boolean; commandId: CommandId; }
  • KeyEventHandler - (commandId: CommandId, modifiers: Modifiers, context: InputContext) => void
  • InputContext - { source: 'keyboard' | 'pointer' | 'midi'; element: HTMLElement | null; commandContext?: string; repeat?: boolean }