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


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

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

Class Attribute Details

.shortcutsObject (readonly)

Returns the value of attribute shortcuts


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

def shortcuts
  @shortcuts
end

Class Method Details

.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


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

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

Instance Method Details

#handleShortcut(shortcut) ⇒ Object

Handles the shortcut.


58
59
60
61
62
63
64
65
66
67
# File 'opal/fron/utils/keyboard.rb', line 58

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

#onKeydown(event) ⇒ Object

Handles keydown event, and shortcut matching.


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

def onKeydown(event)
  return if DOM::Document.activeElement
  combo = [event.key]
  combo << 'ctrl'  if event.ctrl?
  combo << 'shift' if event.shift?
  combo << 'alt'   if event.alt?
  combo.uniq!

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