JointJS+ Keyboard

ui.Keyboard

The ui.Keyboard is an essential plugin for creating keyboard shortcuts in your JointJS+ application. It allows you to bind custom handlers (functions) to arbitrary keyboard events (e.g a single keystroke, key combination).

Configuration

The keyboard constructor accepts the following options:

filter(event, keyboard) Prevent keyboard events from triggering. The callback will be invoked whenever the keyboard DOM event is fired. If the function returns false, the keyboard event will not be not fired. The default filter is isConsumerElement().
const keyboard = new ui.Keyboard({
    filter: (evt, keyboard) => {
        const { target } = evt;
        if (target.tagName === 'INPUT' && target.type === 'range') {
            // Prevent range inputs from consuming events.
            return true;
        }
        // Otherwise return the default behavior
        return !keyboard.isConsumerElement(evt);
    }
});

API

on(event, callback, [context]) Bind a callback function to an object. The callback will be invoked whenever the keyboard event is fired. It is the same logic as Backbone.Events.on. More information about event can be found in the Event description section.
off(event, callback, [context]) Remove a previously-bound callback function from an object. It is the same logic as Backbone.Events.off. More information about event can be found in the Event description section.
enable() Start tracking keyboard events (enabled by default).
disable() Stop tracking keyboard events.
isActive(name, event) Check if key name is currently pressed. event is the DOM Event KeyboardEvent. It is available for modifiers only - alt, ctrl, shift, command
isKeyPrintable(event) Check if the key pressed is a printable character. event is the DOM Event KeyboardEvent.
isConsumerElement(event) Checks if the element onto which the event was dispatched should consume this event and thus prevent the ui.Keyboard event from firing. event is the DOM Event KeyboardEvent. The method returns true for inputs, selects, text-areas and elements defined as content-editable.

Event description

The shortcut can be defined as a string, either a single keystroke e.g. enter, esc, up, down, left or a combination like ctr+c, ctrl+alt+t etc. If you need to be more specific - in terms of keydown, keyup, keypress events - you can also define the shortcut as keydown:a, keyup:enter or even keyup:ctrl+x.

Multiple shortcuts bound to a single handler can be defined as a list of shortcuts, separated by a space.

keyboard.on('ctrl+v shift+insert', pasteHandler);

Please note that all Backbone event methods also support an event map syntax.

keyboard.on({
    'enter': addNewHandler,
    'ctrl+enter' : createNewHandler,
    'up down left right': moveHandler
});

Demo