1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
class Mode
# Static members.
@modes: []
@current: -> Mode.modes[0]
# Constants; readable shortcuts for event-handler return values.
continueBubbling: true
suppressEvent: false
stopBubblingAndTrue: handlerStack.stopBubblingAndTrue
stopBubblingAndFalse: handlerStack.stopBubblingAndFalse
# Default values.
name: "" # The name of this mode.
badge: "" # A badge to display on the popup when this mode is active.
keydown: "suppress" # A function, or "suppress", "bubble" or "pass"; see checkForBuiltInHandler().
keypress: "suppress" # A function, or "suppress", "bubble" or "pass"; see checkForBuiltInHandler().
keyup: "suppress" # A function, or "suppress", "bubble" or "pass"; see checkForBuiltInHandler().
constructor: (options) ->
extend @, options
@handlers = []
@handlers.push handlerStack.push
keydown: @checkForBuiltInHandler "keydown", @keydown
keypress: @checkForBuiltInHandler "keypress", @keypress
keyup: @checkForBuiltInHandler "keyup", @keyup
updateBadgeForMode: (badge) => @updateBadgeForMode badge
Mode.modes.unshift @
# Allow the strings "suppress" and "pass" to be used as proxies for the built-in handlers.
checkForBuiltInHandler: (type, handler) ->
switch handler
when "suppress" then @generateHandler type, @suppressEvent
when "bubble" then @generateHandler type, @continueBubbling
when "pass" then @generateHandler type, @stopBubblingAndTrue
else handler
# Generate a default handler which always always yields the same result; except Esc, which pops the current
# mode.
generateHandler: (type, result) ->
(event) =>
return result unless type == "keydown" and KeyboardUtils.isEscape event
@exit()
@suppressEvent
exit: ->
handlerStack.remove handlerId for handlerId in @handlers
Mode.modes = Mode.modes.filter (mode) => mode != @
Mode.updateBadge()
# Default updateBadgeForMode handler. This is overridden by sub-classes. The default is to install the
# current mode's badge, unless the bade is already set.
updateBadgeForMode: (badge) ->
handlerStack.alwaysContinueBubbling => badge.badge ||= @badge
# Static method. Used externally and internally to initiate bubbling of an updateBadgeForMode event.
# Do not update the badge:
# - if this document does not have the focus, or
# - if the document's body is a frameset
@updateBadge: ->
if document.hasFocus()
unless document.body?.tagName.toLowerCase() == "frameset"
badge = {badge: ""}
handlerStack.bubbleEvent "updateBadgeForMode", badge
Mode.sendBadge badge.badge
# Static utility to update the browser-popup badge.
@sendBadge: (badge) ->
chrome.runtime.sendMessage({ handler: "setBadge", badge: badge })
# Install a mode, call a function, and exit the mode again.
@runIn: (mode, func) ->
mode = new mode()
func()
mode.exit()
root = exports ? window
root.Mode = Mode
|