Add CommandRegistry::findCommands

This commit is contained in:
Nathan Sobo 2014-09-09 12:42:55 -06:00
parent 155fb675ec
commit 3e0e19d51b
2 changed files with 30 additions and 0 deletions

View File

@ -111,3 +111,16 @@ describe "CommandRegistry", ->
grandchild.dispatchEvent(new CustomEvent('command-1', bubbles: true))
grandchild.dispatchEvent(new CustomEvent('command-2', bubbles: true))
expect(calls).toEqual []
describe "::findCommands({target})", ->
it "returns commands that can be invoked on the target or its ancestors", ->
registry.add '.parent', 'namespace:command-1', ->
registry.add '.child', 'namespace:command-2', ->
registry.add '.grandchild', 'namespace:command-3', ->
registry.add '.grandchild.no-match', 'namespace:command-4', ->
expect(registry.findCommands(target: grandchild)).toEqual [
{name: 'namespace:command-3', displayName: 'Namespace: Command 3'}
{name: 'namespace:command-2', displayName: 'Namespace: Command 2'}
{name: 'namespace:command-1', displayName: 'Namespace: Command 1'}
]

View File

@ -1,5 +1,6 @@
{Disposable, CompositeDisposable} = require 'event-kit'
{specificity} = require 'clear-cut'
_ = require 'underscore-plus'
SequenceCount = 0
SpecificityCache = {}
@ -67,6 +68,22 @@ class CommandRegistry
break if currentTarget is @rootNode
currentTarget = currentTarget.parentNode
findCommands: ({target}) ->
commands = []
currentTarget = target
loop
for commandName, listeners of @listenersByCommandName
for listener in listeners
if currentTarget.webkitMatchesSelector(listener.selector)
commands.push
name: commandName
displayName: _.humanizeEventName(commandName)
break if currentTarget is @rootNode
currentTarget = currentTarget.parentNode
commands
class CommandListener
constructor: (@selector, @callback) ->
@specificity = (SpecificityCache[@selector] ?= specificity(@selector))