Module: Chamomile::KeyBinding

Defined in:
lib/chamomile/components/key_binding.rb

Overview

Utilities for matching KeyEvent against normalized key maps.

Class Method Summary collapse

Class Method Details

.key_matches?(msg, key_map, action) ⇒ Boolean

Check if a KeyEvent matches any binding for a named action. Expects a normalized key map (from .normalize) for best performance.

Returns:

  • (Boolean)


19
20
21
22
23
24
25
26
27
28
29
# File 'lib/chamomile/components/key_binding.rb', line 19

def self.key_matches?(msg, key_map, action)
  return false unless msg.is_a?(Chamomile::KeyMsg)

  bindings = key_map[action]
  return false unless bindings

  sorted_mod = msg.mod.sort
  bindings.any? do |key, mods|
    msg.key == key && sorted_mod == (mods || [])
  end
end

.normalize(key_map) ⇒ Object

Normalize a key map so mod arrays are sorted and frozen. Call once at definition time to avoid per-keystroke allocations.

normalize({ action => [[key, mods], ...] })
# => { action => [[key, sorted_frozen_mods], ...] }


11
12
13
14
15
# File 'lib/chamomile/components/key_binding.rb', line 11

def self.normalize(key_map)
  key_map.transform_values do |bindings|
    bindings.map { |key, mods| [key, (mods || []).sort.freeze] }.freeze
  end.freeze
end