]> git.gir.st - VimFx.git/blob - extension/packages/mode-hints/hints.coffee
Merge branch 'develop' into proper-modes
[VimFx.git] / extension / packages / mode-hints / hints.coffee
1 utils = require 'utils'
2 { getPref } = require 'prefs'
3 { Marker } = require 'mode-hints/marker'
4 { addHuffmanCodeWordsTo } = require 'mode-hints/huffman'
5
6 { interfaces: Ci } = Components
7
8 HTMLDocument = Ci.nsIDOMHTMLDocument
9 XULDocument = Ci.nsIDOMXULDocument
10 XPathResult = Ci.nsIDOMXPathResult
11
12 CONTAINER_ID = 'VimFxHintMarkerContainer'
13
14 # All the following elements qualify for their own marker in hints mode
15 MARKABLE_ELEMENTS = [
16 "a"
17 "iframe"
18 "area[@href]"
19 "textarea"
20 "button"
21 "select"
22 "input[not(@type='hidden' or @disabled or @readonly)]"
23 "embed"
24 "object"
25 ]
26
27 # All elements that have one or more of the following properties
28 # qualify for their own marker in hints mode
29 MARKABLE_ELEMENT_PROPERTIES = [
30 "@tabindex"
31 "@onclick"
32 "@onmousedown"
33 "@onmouseup"
34 "@oncommand"
35 "@role='link'"
36 "@role='button'"
37 "contains(@class, 'button')"
38 "contains(@class, 'js-new-tweets-bar')"
39 "@contenteditable='' or translate(@contenteditable, 'TRUE', 'true')='true'"
40 ]
41
42
43 # Remove previously injected hints from the DOM
44 removeHints = (document) ->
45 if container = document.getElementById(CONTAINER_ID)
46 document.documentElement.removeChild(container)
47
48 for frame in document.defaultView.frames
49 removeHints(frame.document)
50
51
52 # Like `insertHints`, but also sets hints for the markers
53 injectHints = (document) ->
54 markers = createMarkers(document)
55 hintChars = utils.getHintChars()
56
57 addHuffmanCodeWordsTo(markers, {alphabet: hintChars}, (marker, hint) -> marker.setHint(hint))
58
59 removeHints(document)
60 insertHints(markers)
61
62 # Must be done after the hints have been inserted into the DOM (see marker.coffee)
63 for marker in markers
64 marker.completePosition()
65
66 return markers
67
68 insertHints = (markers) ->
69 docFrags = []
70
71 getFrag = (document) ->
72 for [doc, frag] in docFrags
73 if document == doc
74 return frag
75
76 for marker in markers
77 doc = marker.element.ownerDocument
78 if not getFrag(doc)
79 docFrags.push([doc, doc.createDocumentFragment()])
80
81 frag = getFrag(doc)
82 frag.appendChild(marker.markerElement)
83
84 for [doc, frag] in docFrags
85 container = createHintsContainer(doc)
86 container.appendChild(frag)
87 doc.documentElement.appendChild(container)
88
89
90 # Creates and injects markers into the DOM
91 createMarkers = (document) ->
92 # For now we aren't able to handle hint markers in XUL Documents :(
93 if document instanceof HTMLDocument# or document instanceof XULDocument
94 if document.documentElement
95 # Select all markable elements in the document, create markers
96 # for each of them, and position them on the page.
97 # Note that the markers are not given hints.
98 set = getMarkableElements(document)
99 markers = []
100 for i in [0...set.snapshotLength] by 1
101 element = set.snapshotItem(i)
102 if rect = getElementRect(element)
103 marker = new Marker(element)
104 marker.setPosition(rect.top, rect.left)
105 marker.weight = rect.area * marker.calcBloomRating()
106
107 markers.push(marker)
108
109 for frame in document.defaultView.frames
110 markers = markers.concat(createMarkers(frame.document))
111
112 return markers or []
113
114
115 createHintsContainer = (document) ->
116 container = document.createElement('div')
117 container.id = CONTAINER_ID
118 container.className = 'VimFxReset'
119 return container
120
121
122 # Returns elements that qualify for hint markers in hints mode.
123 # Generates and memoizes an XPath query internally
124 getMarkableElements = do ->
125 # Some preparations done on startup
126 elements = [
127 MARKABLE_ELEMENTS...
128 "*[#{ MARKABLE_ELEMENT_PROPERTIES.join(' or ') }]"
129 ]
130
131 reduce = (m, rule) -> m.concat(["//#{ rule }", "//xhtml:#{ rule }"])
132 xpath = elements.reduce(reduce, []).join(' | ')
133
134 namespaceResolver = (namespace) ->
135 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
136
137 # The actual function that will return the desired elements
138 return (document, resultType = XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) ->
139 return document.evaluate(xpath, document.documentElement, namespaceResolver, resultType, null)
140
141
142 # Uses `element.getBoundingClientRect()`. If that does not return a visible rectange, then looks at
143 # the children of the markable node.
144 #
145 # The logic has been copied over from Vimiun originally.
146 getElementRect = (element) ->
147 document = element.ownerDocument
148 window = document.defaultView
149 docElem = document.documentElement
150 body = document.body
151
152 # Prune elements that aren't visible on the page
153 computedStyle = window.getComputedStyle(element, null)
154 if computedStyle
155 if computedStyle.getPropertyValue('visibility') != 'visible' or \
156 computedStyle.getPropertyValue('display') == 'none' or \
157 computedStyle.getPropertyValue('opacity') == '0'
158 return
159
160 clientTop = docElem.clientTop or body?.clientTop or 0
161 clientLeft = docElem.clientLeft or body?.clientLeft or 0
162 scrollTop = window.pageYOffset or docElem.scrollTop
163 scrollLeft = window.pageXOffset or docElem.scrollLeft
164
165 clientRect = element.getBoundingClientRect()
166
167 if isRectOk(clientRect, window)
168 return {
169 top: clientRect.top + scrollTop - clientTop
170 left: clientRect.left + scrollLeft - clientLeft
171 width: clientRect.width
172 height: clientRect.height
173 area: clientRect.width * clientRect.height
174 }
175
176 # If the rect has 0 dimensions, then check what's inside.
177 # Floated or absolutely positioned elements are of particular interest.
178 if clientRect.width is 0 or clientRect.height is 0
179 for childElement in element.children
180 if computedStyle = window.getComputedStyle(childElement, null)
181 if computedStyle.getPropertyValue('float') != 'none' or \
182 computedStyle.getPropertyValue('position') == 'absolute'
183
184 return getElementRect(childElement)
185
186 return
187
188
189 # Checks if the given TextRectangle object qualifies
190 # for its own Marker with respect to the `window` object
191 isRectOk = (rect, window) ->
192 minimum = 2
193 rect.width > minimum and rect.height > minimum and \
194 rect.top > -minimum and rect.left > -minimum and \
195 rect.top < window.innerHeight - minimum and \
196 rect.left < window.innerWidth - minimum
197
198
199
200 # Finds all stacks of markers that overlap each other (by using `getStackFor`) (#1), and rotates
201 # their `z-index`:es (#2), thus alternating which markers are visible.
202 rotateOverlappingMarkers = (originalMarkers, forward) ->
203 # Shallow working copy. This is necessary since `markers` will be mutated and eventually empty.
204 markers = originalMarkers[..]
205
206 # (#1)
207 stacks = (getStackFor(markers.pop(), markers) while markers.length > 0)
208
209 # (#2)
210 # Stacks of length 1 don't participate in any overlapping, and can therefore be skipped.
211 for stack in stacks when stack.length > 1
212 # This sort is not required, but makes the rotation more predictable.
213 stack.sort((a, b) -> a.markerElement.style.zIndex - b.markerElement.style.zIndex)
214
215 # Array of z indices
216 indexStack = (m.markerElement.style.zIndex for m in stack)
217 # Shift the array of indices one item forward or back
218 if forward
219 indexStack.unshift(indexStack.pop())
220 else
221 indexStack.push(indexStack.shift())
222
223 for marker, index in stack
224 marker.markerElement.style.setProperty('z-index', indexStack[index], 'important')
225
226 return
227
228 # Get an array containing `marker` and all markers that overlap `marker`, if any, which is called
229 # a "stack". All markers in the returned stack are spliced out from `markers`, thus mutating it.
230 getStackFor = (marker, markers) ->
231 stack = [marker]
232
233 { top, bottom, left, right } = marker.position
234
235 index = 0
236 while index < markers.length
237 nextMarker = markers[index]
238
239 { top: nextTop, bottom: nextBottom, left: nextLeft, right: nextRight } = nextMarker.position
240 overlapsVertically = (nextBottom >= top and nextTop <= bottom)
241 overlapsHorizontally = (nextRight >= left and nextLeft <= right)
242
243 if overlapsVertically and overlapsHorizontally
244 # Also get all markers overlapping this one
245 markers.splice(index, 1)
246 stack = stack.concat(getStackFor(nextMarker, markers))
247 else
248 # Continue the search
249 index++
250
251 return stack
252
253
254 exports.injectHints = injectHints
255 exports.removeHints = removeHints
256 exports.rotateOverlappingMarkers = rotateOverlappingMarkers
Imprint / Impressum