@apsc/keyboard-shortcut-action
TypeScript icon, indicating that this package has built-in type declarations

0.0.4 • Public • Published

Action to call a function by keyboard shortcut for Svelte directive use

Docs & Demo

Install

NPM

npm i -D @apsc/keyboard-shortcut-action

PNPM

pnpm add -D @apsc/keyboard-shortcut-action

API

let active = 0;
const items = [...Array(20).keys()].map((i) => ({
  id: i + 1,
  message: `Text #${(i + 1).toString().padStart(2, '0')}`
}));

<div
  tabindex="0"
  use:useKeyboardShortcut={{
    event: 'keydown',
    preventDefault: true,
    fns: {
      'Ctrl+ArrowUp': () => (active = 0),
      'ArrowUp': () => (active = Math.max(0, active - 1)),
      'Ctrl+ArrowDown': () => (active = items.length - 1),
      'ArrowDown': () => (active = Math.min(items.length - 1, active + 1))
    }
  }}
>
  {#each items as item, index}
    <div class:active={active === index}>{item.id} {item.message}</div>
  {/each}
</div>

useKeyboardShortcut options

export interface UseKeyboardShortcutOptions {
  event: 'keypress' | 'keydown' | 'keyup';
  capture?: boolean; // default false
  passive?: boolean; // default false
  preventDefault?: boolean; // default false
  stopPropagation?: boolean; // default false
  stopImmediatePropagation?: boolean; // default false
  fns: Record<string, (event: KeyboardEvent) => void>;
}

Lifecycle

The action attaches a handler to the corresponding event options.event with parameters

  • capture
  • passive

The handler converts event to shortcut using package keyboard-event-to-string.

If function options.fns[shortcut] exists then handler executes

  • event.preventDefault() if options.preventDefault == true
  • event.stopPropagation() if options.stopPropagation == true
  • event.stopImmediatePropagation() if options.stopImmediatePropagation == true

After it calls options.fns[shortcut](event).

Note! The action modifies global options

setOptions({ joinWith: '+' });

Therefore, the shortcut obtained in the action are Ctrl+A instead Ctrl + A.

Package Sidebar

Install

npm i @apsc/keyboard-shortcut-action

Weekly Downloads

0

Version

0.0.4

License

MIT

Unpacked Size

8.29 kB

Total Files

5

Last publish

Collaborators

  • andrey-pavlenko