2.0.0 • Published 3 years ago

cf.keybindings v2.0.0

Weekly downloads
3
License
ISC
Repository
-
Last release
3 years ago

Keybindings utility

Manage keyboard binding, mapping key strokes to events

Installation

$ npm install --save cf.keybindings

Usage

Mapping keystrokes to functions is a two step process.

The first step maps keyboard commands to event names for a given scope. A keyboard command can only be mapped to a single event name in a scope, but can be reused across multiple scopes.

The second step maps events to functions. Any number of functions can be assigned to an event. This uses Backbone events behind the scenes. Event names incorporate the scope. E.g. if a binding is added as follows:

keybindings.add('scope1', {
  'ctrl+1', 'eventname'
}

When ctrl+1 is pressed (and scope1 is active), the event 'scope1:eventname' is triggered. Functions can be triggered on events using keybindings.on() or by using Backbone's listenTo method on the keybindings object.

Scopes are used to segregate groups of events which might share the same keystrokes. The current example is the zone picker. A trigger for the zone picker exists in the global scope (assigned to 'z'). When the zone picker opens, it changes to a new scope in which a number of new keyboard commands are assigned. These temporarily replace the global scope key events. When the zone picker closes, the previous scope is restored.

NOTE: Mapping a keybinding prevents the browser default action taking place, even if no function is assigned to the resulting event.

var keybindings = require('cf.keybindings');

// Add a scope which will trigger 'scope1:eventname1' when ctrl+1 is pressed,
// and 'scope2:eventname2' on ctrl+2

keybindings.add('scope1', {
  'ctrl+1', 'eventname1',
  'ctrl+2', 'eventname2'
}

// Log something when the first event triggers (ctrl+1)
keybindings.on('scope1:eventname1', function() {
  console.log('Event one');
}

// Log something when the second event triggers (ctrl+2)
keybindings.on('scope1:eventname2', function() {
  console.log('Event two');
}

keybindings.setScope('scope1');

Keymaster filters can be defined when adding a scope, e.g.

keybindings.add('scope1', {
  'ctrl+1', 'eventname1',
  'ctrl+2', 'eventname2'
}, function filter() {...}

The filters are activated automatically when the scope becomes active and are also set when scopes are popped or deleted. If a scope without a filter becomes active, keymaster's default filter is used.

API

Testing

Tests are written with mocha in BDD style and can be found in the tests/ directory.

$ npm test