Skip to content

Commit

Permalink
Refactor handlerStack. Closes #657.
Browse files Browse the repository at this point in the history
Previously, handlerStack was designed only for removal of the handler
right at the top of the stack. However, some handlers sought to remove
themselves when they were not at the top of the stack, creating
confusion. The new handlerStack ensures that such removal can always be
done safely.
  • Loading branch information
int3 committed Oct 21, 2012
1 parent 2ed217b commit ea73be1
Show file tree
Hide file tree
Showing 11 changed files with 119 additions and 38 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
*.swp *.swp
*.crx *.crx
*.js *.js
node_modules/*
6 changes: 3 additions & 3 deletions content_scripts/link_hints.coffee
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ LinkHints =
{ id: "vimiumHintMarkerContainer", className: "vimiumReset" }) { id: "vimiumHintMarkerContainer", className: "vimiumReset" })


# handlerStack is declared by vimiumFrontend.js # handlerStack is declared by vimiumFrontend.js
handlerStack.push({ @handlerId = handlerStack.push({
keydown: @onKeyDownInMode.bind(this, hintMarkers), keydown: @onKeyDownInMode.bind(this, hintMarkers),
# trap all key events # trap all key events
keypress: -> false keypress: -> false
Expand Down Expand Up @@ -163,7 +163,7 @@ LinkHints =
keyup: (event) -> keyup: (event) ->
return if (event.keyCode != keyCodes.shiftKey) return if (event.keyCode != keyCodes.shiftKey)
LinkHints.setOpenLinkMode(!LinkHints.shouldOpenInNewTab, LinkHints.shouldOpenWithQueue, false) LinkHints.setOpenLinkMode(!LinkHints.shouldOpenInNewTab, LinkHints.shouldOpenWithQueue, false)
handlerStack.pop() @remove()
}) })


# TODO(philc): Ignore keys that have modifiers. # TODO(philc): Ignore keys that have modifiers.
Expand Down Expand Up @@ -231,7 +231,7 @@ LinkHints =
if (LinkHints.hintMarkerContainingDiv) if (LinkHints.hintMarkerContainingDiv)
DomUtils.removeElement LinkHints.hintMarkerContainingDiv DomUtils.removeElement LinkHints.hintMarkerContainingDiv
LinkHints.hintMarkerContainingDiv = null LinkHints.hintMarkerContainingDiv = null
handlerStack.pop() handlerStack.remove @handlerId
HUD.hide() HUD.hide()
@isActive = false @isActive = false


Expand Down
45 changes: 15 additions & 30 deletions content_scripts/vimium_frontend.coffee
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ findModeQuery = { rawQuery: "" }
findModeQueryHasResults = false findModeQueryHasResults = false
findModeAnchorNode = null findModeAnchorNode = null
isShowingHelpDialog = false isShowingHelpDialog = false
handlerStack = [] handlerStack = new HandlerStack
keyPort = null keyPort = null
# Users can disable Vimium on URL patterns via the settings page. # Users can disable Vimium on URL patterns via the settings page.
isEnabledForUrl = true isEnabledForUrl = true
Expand Down Expand Up @@ -355,7 +355,9 @@ extend window,
visibleInputs[selectedInputIndex].element.focus() visibleInputs[selectedInputIndex].element.focus()
else unless event.keyCode == KeyboardUtils.keyCodes.shiftKey else unless event.keyCode == KeyboardUtils.keyCodes.shiftKey
DomUtils.removeElement hintContainingDiv DomUtils.removeElement hintContainingDiv
handlerStack.pop() @remove()

false


# #
# Sends everything except i & ESC to the handler in background_page. i & ESC are special because they control # Sends everything except i & ESC to the handler in background_page. i & ESC are special because they control
Expand All @@ -365,7 +367,7 @@ extend window,
# Note that some keys will only register keydown events and not keystroke events, e.g. ESC. # Note that some keys will only register keydown events and not keystroke events, e.g. ESC.
# #
onKeypress = (event) -> onKeypress = (event) ->
return unless bubbleEvent('keypress', event) return unless handlerStack.bubbleEvent('keypress', event)


keyChar = "" keyChar = ""


Expand All @@ -381,32 +383,15 @@ onKeypress = (event) ->
if (keyChar) if (keyChar)
if (findMode) if (findMode)
handleKeyCharForFindMode(keyChar) handleKeyCharForFindMode(keyChar)
suppressEvent(event) DomUtils.suppressEvent(event)
else if (!isInsertMode() && !findMode) else if (!isInsertMode() && !findMode)
if (currentCompletionKeys.indexOf(keyChar) != -1) if (currentCompletionKeys.indexOf(keyChar) != -1)
suppressEvent(event) DomUtils.suppressEvent(event)


keyPort.postMessage({ keyChar:keyChar, frameId:frameId }) keyPort.postMessage({ keyChar:keyChar, frameId:frameId })


#
# Called whenever we receive a key event. Each individual handler has the option to stop the event's
# propagation by returning a falsy value.
#
bubbleEvent = (type, event) ->
for i in [(handlerStack.length - 1)..0]
# We need to check for existence of handler because the last function call may have caused the release of
# more than one handler.
if (handlerStack[i] && handlerStack[i][type] && !handlerStack[i][type](event))
suppressEvent(event)
return false
true

suppressEvent = (event) ->
event.preventDefault()
event.stopPropagation()

onKeydown = (event) -> onKeydown = (event) ->
return unless bubbleEvent('keydown', event) return unless handlerStack.bubbleEvent('keydown', event)


keyChar = "" keyChar = ""


Expand Down Expand Up @@ -442,20 +427,20 @@ onKeydown = (event) ->
if (isEditable(event.srcElement)) if (isEditable(event.srcElement))
event.srcElement.blur() event.srcElement.blur()
exitInsertMode() exitInsertMode()
suppressEvent(event) DomUtils.suppressEvent(event)


else if (findMode) else if (findMode)
if (KeyboardUtils.isEscape(event)) if (KeyboardUtils.isEscape(event))
handleEscapeForFindMode() handleEscapeForFindMode()
suppressEvent(event) DomUtils.suppressEvent(event)


else if (event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey) else if (event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey)
handleDeleteForFindMode() handleDeleteForFindMode()
suppressEvent(event) DomUtils.suppressEvent(event)


else if (event.keyCode == keyCodes.enter) else if (event.keyCode == keyCodes.enter)
handleEnterForFindMode() handleEnterForFindMode()
suppressEvent(event) DomUtils.suppressEvent(event)


else if (!modifiers) else if (!modifiers)
event.stopPropagation() event.stopPropagation()
Expand All @@ -466,7 +451,7 @@ onKeydown = (event) ->
else if (!isInsertMode() && !findMode) else if (!isInsertMode() && !findMode)
if (keyChar) if (keyChar)
if (currentCompletionKeys.indexOf(keyChar) != -1) if (currentCompletionKeys.indexOf(keyChar) != -1)
suppressEvent(event) DomUtils.suppressEvent(event)


keyPort.postMessage({ keyChar:keyChar, frameId:frameId }) keyPort.postMessage({ keyChar:keyChar, frameId:frameId })


Expand All @@ -485,7 +470,7 @@ onKeydown = (event) ->
isValidFirstKey(KeyboardUtils.getKeyChar(event)))) isValidFirstKey(KeyboardUtils.getKeyChar(event))))
event.stopPropagation() event.stopPropagation()


onKeyup = () -> return unless bubbleEvent('keyup', event) onKeyup = (event) -> return unless handlerStack.bubbleEvent('keyup', event)


checkIfEnabledForUrl = -> checkIfEnabledForUrl = ->
url = window.location.toString() url = window.location.toString()
Expand Down Expand Up @@ -750,7 +735,7 @@ findAndFocus = (backwards) ->
if (elementCanTakeInput) if (elementCanTakeInput)
handlerStack.push({ handlerStack.push({
keydown: (event) -> keydown: (event) ->
handlerStack.pop() @remove()
if (KeyboardUtils.isEscape(event)) if (KeyboardUtils.isEscape(event))
DomUtils.simulateSelect(document.activeElement) DomUtils.simulateSelect(document.activeElement)
enterInsertModeWithoutShowingIndicator(document.activeElement) enterInsertModeWithoutShowingIndicator(document.activeElement)
Expand Down
4 changes: 2 additions & 2 deletions content_scripts/vomnibar.coffee
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@ class VomnibarUI
show: -> show: ->
@box.style.display = "block" @box.style.display = "block"
@input.focus() @input.focus()
handlerStack.push({ keydown: @onKeydown.bind(this) }) @handlerId = handlerStack.push keydown: @onKeydown.bind @


hide: -> hide: ->
@box.style.display = "none" @box.style.display = "none"
@completionList.style.display = "none" @completionList.style.display = "none"
@input.blur() @input.blur()
handlerStack.pop() handlerStack.remove @handlerId


reset: -> reset: ->
@input.value = "" @input.value = ""
Expand Down
4 changes: 4 additions & 0 deletions lib/dom_utils.coffee
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -131,5 +131,9 @@ DomUtils =
document.documentElement.appendChild(flashEl) document.documentElement.appendChild(flashEl)
setTimeout((-> DomUtils.removeElement flashEl), 400) setTimeout((-> DomUtils.removeElement flashEl), 400)


suppressEvent: (event) ->
event.preventDefault()
event.stopPropagation()

root = exports ? window root = exports ? window
root.DomUtils = DomUtils root.DomUtils = DomUtils
37 changes: 37 additions & 0 deletions lib/handler_stack.coffee
Original file line number Original file line Diff line number Diff line change
@@ -0,0 +1,37 @@
root = exports ? window

class root.HandlerStack

constructor: ->
@stack = []
@counter = 0

genId: -> @counter = ++@counter & 0xffff

# Adds a handler to the stack. Returns a unique ID for that handler that can be used to remove it later.
push: (handler) ->
handler.id = @genId()
@stack.push handler
handler.id

# Called whenever we receive a key event. Each individual handler has the option to stop the event's
# propagation by returning a falsy value.
bubbleEvent: (type, event) ->
for i in [(@stack.length - 1)..0] by -1
handler = @stack[i]
# We need to check for existence of handler because the last function call may have caused the release
# of more than one handler.
if handler && handler[type]
@currentId = handler.id
passThrough = handler[type].call(@, event)
if not passThrough
DomUtils.suppressEvent(event)
return false
true

remove: (id = @currentId) ->
for i in [(@stack.length - 1)..0] by -1
handler = @stack[i]
if handler.id == id
@stack.splice(i, 1)
break
1 change: 1 addition & 0 deletions manifest.json
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"js": ["lib/utils.js", "js": ["lib/utils.js",
"lib/keyboard_utils.js", "lib/keyboard_utils.js",
"lib/dom_utils.js", "lib/dom_utils.js",
"lib/handler_stack.js",
"lib/clipboard.js", "lib/clipboard.js",
"content_scripts/link_hints.js", "content_scripts/link_hints.js",
"content_scripts/vomnibar.js", "content_scripts/vomnibar.js",
Expand Down
2 changes: 1 addition & 1 deletion test_harnesses/vomnibar.html
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<link rel="stylesheet" type="text/css" href="../vimium.css" /> <link rel="stylesheet" type="text/css" href="../vimium.css" />
<script> <script>
function setup() { function setup() {
window.handlerStack = []; window.handlerStack = new HandlerStack();
// This itemHtml was obtained just by copying and pasting what was generated when using it in practice. // This itemHtml was obtained just by copying and pasting what was generated when using it in practice.
var itemHtml = '<span class="source">history</span> http://<span class="fuzzyMatch">n</span><span class="fuzzyMatch">i</span><span class="fuzzyMatch">n</span><span class="fuzzyMatch">j</span><span class="fuzzyMatch">a</span>words.com/info/about <span class="title">Ninjawords - a really fast dictionary</span>'; var itemHtml = '<span class="source">history</span> http://<span class="fuzzyMatch">n</span><span class="fuzzyMatch">i</span><span class="fuzzyMatch">n</span><span class="fuzzyMatch">j</span><span class="fuzzyMatch">a</span>words.com/info/about <span class="title">Ninjawords - a really fast dictionary</span>';
var results = [{ html: itemHtml }, { html: itemHtml }]; var results = [{ html: itemHtml }, { html: itemHtml }];
Expand Down
4 changes: 2 additions & 2 deletions tests/dom_tests/dom_tests.coffee
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -177,11 +177,11 @@ context "Input focus",
focusInput 1 focusInput 1
assert.equal "first", document.activeElement.id assert.equal "first", document.activeElement.id
# deactivate the tabbing mode and its overlays # deactivate the tabbing mode and its overlays
handlerStack[handlerStack.length - 1].keydown mockKeyboardEvent("A") handlerStack.bubbleEvent 'keydown', mockKeyboardEvent("A")


focusInput 100 focusInput 100
assert.equal "third", document.activeElement.id assert.equal "third", document.activeElement.id
handlerStack[handlerStack.length - 1].keydown mockKeyboardEvent("A") handlerStack.bubbleEvent 'keydown', mockKeyboardEvent("A")


Tests.outputMethod = (args...) -> Tests.outputMethod = (args...) ->
newOutput = args.join "\n" newOutput = args.join "\n"
Expand Down
1 change: 1 addition & 0 deletions tests/dom_tests/dom_tests.html
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<script type="text/javascript" src="../../lib/utils.js"></script> <script type="text/javascript" src="../../lib/utils.js"></script>
<script type="text/javascript" src="../../lib/keyboard_utils.js"></script> <script type="text/javascript" src="../../lib/keyboard_utils.js"></script>
<script type="text/javascript" src="../../lib/dom_utils.js"></script> <script type="text/javascript" src="../../lib/dom_utils.js"></script>
<script type="text/javascript" src="../../lib/handler_stack.js"></script>
<script type="text/javascript" src="../../lib/clipboard.js"></script> <script type="text/javascript" src="../../lib/clipboard.js"></script>
<script type="text/javascript" src="../../content_scripts/link_hints.js"></script> <script type="text/javascript" src="../../content_scripts/link_hints.js"></script>
<script type="text/javascript" src="../../content_scripts/vomnibar.js"></script> <script type="text/javascript" src="../../content_scripts/vomnibar.js"></script>
Expand Down
52 changes: 52 additions & 0 deletions tests/unit_tests/handler_stack_test.coffee
Original file line number Original file line Diff line number Diff line change
@@ -0,0 +1,52 @@
require "./test_helper.js"
extend(global, require "../../lib/handler_stack.js")

context "handlerStack",
setup ->
stub global, "DomUtils", {}
stub DomUtils, "suppressEvent", ->
@handlerStack = new HandlerStack
@handler1Called = false
@handler2Called = false

should "bubble events", ->
@handlerStack.push { keydown: => @handler1Called = true }
@handlerStack.push { keydown: => @handler2Called = true }
@handlerStack.bubbleEvent 'keydown', {}
assert.isTrue @handler2Called
assert.isTrue @handler1Called

should "terminate bubbling on falsy return value", ->
@handlerStack.push { keydown: => @handler1Called = true }
@handlerStack.push { keydown: => @handler2Called = true; false }
@handlerStack.bubbleEvent 'keydown', {}
assert.isTrue @handler2Called
assert.isFalse @handler1Called

should "remove handlers correctly", ->
@handlerStack.push { keydown: => @handler1Called = true }
handlerId = @handlerStack.push { keydown: => @handler2Called = true }
@handlerStack.remove handlerId
@handlerStack.bubbleEvent 'keydown', {}
assert.isFalse @handler2Called
assert.isTrue @handler1Called

should "remove handlers correctly", ->
handlerId = @handlerStack.push { keydown: => @handler1Called = true }
@handlerStack.push { keydown: => @handler2Called = true }
@handlerStack.remove handlerId
@handlerStack.bubbleEvent 'keydown', {}
assert.isTrue @handler2Called
assert.isFalse @handler1Called

should "handle self-removing handlers correctly", ->
ctx = @
@handlerStack.push { keydown: => @handler1Called = true }
@handlerStack.push { keydown: ->
ctx.handler2Called = true
@remove()
}
@handlerStack.bubbleEvent 'keydown', {}
assert.isTrue @handler2Called
assert.isTrue @handler1Called
assert.equal @handlerStack.stack.length, 1

1 comment on commit ea73be1

@philc
Copy link
Owner

@philc philc commented on ea73be1 Oct 26, 2012

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice tests.

Please sign in to comment.