kd-keyboard
Version:
keyboard module for kd
76 lines (58 loc) • 1.77 kB
text/coffeescript
require 'mousetrap'
require 'mousetrap/plugins/mousetrap-global-bind.js'
module.exports = class KDKeyboardListener
constructor: ->
= {}
= no
makeUpdater = (fn) -> ->
{ isListening } = this
if isListening
retVal = fn.apply this, arguments
if isListening
return retVal
addComboMap: makeUpdater (comboMap, priority) ->
m = [priority ? comboMap.priority ? 0] ?= []
m.push comboMap
return this
removeComboMap: makeUpdater (comboMap) ->
for own priority, ms of
[priority] = ms.filter (m) -> m isnt comboMap
return this
listen: ->
return this if
KDKeyboardListener.currentListener?.reset()
seen = {}
(combo, options = { global: yes }, listener) ->
return if seen[combo]
seen[combo] = yes
method = if options.global then 'bindGlobal' else 'bind'
Mousetrap[method] combo, listener
KDKeyboardListener.currentListener = this
= yes
return this
reset: ->
return this unless
Mousetrap.reset()
= no
KDKeyboardListener.currentListener = null
return this
getCombos: ->
Object.keys
# prioritize by key:
.sort (a, b) -> b - a # descending priority
# map back to value:
.map (k) => [k]
# flatten:
.reduce (a, b) ->
a.concat b
, []
combos: (fn) ->
.forEach (m) -> m.eachCombo fn
return this
isActive: ->
and this is KDKeyboardListener.currentListener
= ->
return if ?
= new this
.listen()
return