This commit is contained in:
Corey Johnson
2012-05-30 10:20:20 -07:00
parent cbf5c5d16c
commit 46e94b33d4
2 changed files with 21 additions and 29 deletions

View File

@@ -1,8 +1,8 @@
$ = require 'jquery'
_ = require 'underscore'
Specificity = require 'specificity'
fs = require 'fs'
Specificity = require 'specificity'
PEG = require 'pegjs'
module.exports =
@@ -10,33 +10,31 @@ class BindingSet
selector: null
keystrokeMap: null
commandForEvent: null
keystrokePatternParser: null
parser: null
constructor: (@selector, mapOrFunction) ->
@parser = PEG.buildParser(fs.read(require.resolve 'keystroke-pattern.pegjs'))
@specificity = Specificity(@selector)
@commandForEvent = @buildEventHandler(mapOrFunction)
@keystrokeMap = if not _.isFunction(mapOrFunction) then mapOrFunction else {}
@keystrokeMap = {}
buildEventHandler: (mapOrFunction) ->
if _.isFunction(mapOrFunction)
mapOrFunction
@commandForEvent = mapOrFunction
else
mapOrFunction = @normalizeKeystrokePatterns(mapOrFunction)
(event) =>
for pattern, command of mapOrFunction
return command if event.keystroke == pattern
@keystrokeMap = @normalizeKeystrokeMap(mapOrFunction)
@commandForEvent = (event) =>
for keystroke, command of @keystrokeMap
return command if event.keystroke == keystroke
null
normalizeKeystrokePatterns: (map) ->
normalizedMap = {}
for pattern, event of map
normalizedMap[@normalizeKeystrokePattern(pattern)] = event
normalizedMap
normalizeKeystrokeMap: (keystrokeMap) ->
normalizeKeystrokeMap = {}
for keystroke, command of keystrokeMap
normalizeKeystrokeMap[@normalizeKeystroke(keystroke)] = command
normalizeKeystrokePattern: (pattern) ->
keys = @parser.parse(pattern)
normalizeKeystrokeMap
normalizeKeystroke: (keystroke) ->
keys = @parser.parse(keystroke)
modifiers = keys[0...-1]
modifiers.sort()
[modifiers..., _.last(keys)].join('-')

View File

@@ -1,9 +1,10 @@
$ = require 'jquery'
_ = require 'underscore'
fs = require 'fs'
BindingSet = require 'binding-set'
Specificity = require 'specificity'
$ = require 'jquery'
module.exports =
class Keymap
bindingSets: null
@@ -27,17 +28,13 @@ class Keymap
@bindingSets.unshift(new BindingSet(selector, bindings))
bindingsForElement: (element) ->
currentNode = $(element)
keystrokeMap = {}
currentNode = $(element)
while currentNode.length
bindingSets = @bindingSets.filter (set) -> currentNode.is(set.selector)
bindingSets.sort (a, b) -> b.specificity - a.specificity
for bindingSet in bindingSets
for keystroke, command of bindingSet.keystrokeMap
keystrokeMap[keystroke] ?= command
_.defaults(keystrokeMap, set.keystrokeMap) for set in bindingSets
currentNode = currentNode.parent()
keystrokeMap
@@ -58,9 +55,6 @@ class Keymap
currentNode = currentNode.parent()
true
reset: ->
@bindingSets = []
triggerCommandEvent: (keyEvent, commandName) ->
commandEvent = $.Event(commandName)
commandEvent.keyEvent = keyEvent