Class: Fron::Keyboard

Inherits:
Object show all
Defined in:
opal/fron/utils/keyboard.rb

Overview

Keyboard class that handles matcing keyp presses to shortcuts.

Constant Summary collapse

DELIMETERS =

Delimeters to separate shortcut parts

/-|\+|:|_/

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeKeyboard

Create a new instance



33
34
35
# File 'opal/fron/utils/keyboard.rb', line 33

def initialize
  DOM::Document.body.on 'keydown' do |event| keydown event end
end

Class Attribute Details

.shortcutsArray (readonly)

Returns The data for the shortcuts.

Returns:

  • (Array)

    The data for the shortcuts



6
7
8
# File 'opal/fron/utils/keyboard.rb', line 6

def shortcuts
  @shortcuts
end

Class Method Details

.calculate_shortcut(event) ⇒ Object



53
54
55
56
57
58
59
60
# File 'opal/fron/utils/keyboard.rb', line 53

def self.calculate_shortcut(event)
  combo = [event.key]
  combo << 'ctrl'  if event.ctrl?
  combo << 'shift' if event.shift?
  combo << 'alt'   if event.alt?
  combo << 'meta'  if event.meta?
  combo.uniq
end

.sc(shortcut, action = nil, &block) ⇒ Object

Defines a shortcut. If a block given it will run that block on a match and not the action. Otherwise it will run the action named method on the instance.

The shortcut order is not relevant, and it can have many delimiters.

Exmaple shortcuts:

  • ctrl+click

  • ctrl:up

  • ctrl-down

  • ctrl-shift_up

Parameters:

  • shortcut (String)

    The shortcut

  • action (Symbol) (defaults to: nil)

    The action to run

  • block (Proc)

    The block to run



26
27
28
29
# File 'opal/fron/utils/keyboard.rb', line 26

def sc(shortcut, action = nil, &block)
  @shortcuts ||= []
  @shortcuts << { parts: shortcut.split(DELIMETERS), action: action, block: block }
end

Instance Method Details

#handle_shortcut(shortcut) ⇒ Object

Handles the shortcut.

Parameters:

  • shortcut (Hash)

    The shortcut



65
66
67
68
69
70
# File 'opal/fron/utils/keyboard.rb', line 65

def handle_shortcut(shortcut)
  action = shortcut[:action]
  return instance_exec(&shortcut[:block]) if shortcut[:block]
  return send(action) if respond_to? action
  warn self.class.name + " - shortcut #{shortcut[:parts].join('+')}:#{action} is not implemented!"
end

#keydown(event) ⇒ Object

Handles keydown event, and shortcut matching.

Parameters:



40
41
42
43
44
45
46
47
48
49
50
51
# File 'opal/fron/utils/keyboard.rb', line 40

def keydown(event)
  return if DOM::Document.active_element

  combo = Keyboard.calculate_shortcut event

  self.class.shortcuts.each do |shortcut|
    next unless shortcut[:parts].sort == combo.sort
    handle_shortcut shortcut
    event.stop
    break
  end
end