]> git.gir.st - VimFx.git/blob - extension/lib/hints.coffee
Refactor `utils.getAllElements` into hints.coffee
[VimFx.git] / extension / lib / hints.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013.
3 # Copyright Simon Lydell 2013, 2014.
4 #
5 # This file is part of VimFx.
6 #
7 # VimFx is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # VimFx is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
19 ###
20
21 utils = require('./utils')
22 huffman = require('n-ary-huffman')
23
24 { interfaces: Ci } = Components
25
26 Element = Ci.nsIDOMElement
27 HTMLDocument = Ci.nsIDOMHTMLDocument
28 XULDocument = Ci.nsIDOMXULDocument
29
30 injectHints = (rootWindow, window, filter) ->
31 {
32 clientWidth, clientHeight # Viewport size excluding scrollbars, usually.
33 scrollWidth, scrollHeight
34 } = window.document.documentElement
35 { innerWidth, innerHeight } = window # Viewport size including scrollbars.
36 # We don’t want markers to cover the scrollbars, so we should use
37 # `clientWidth` and `clientHeight`. However, when there are no scrollbars
38 # those might be too small. Then we use `innerWidth` and `innerHeight`.
39 width = if scrollWidth > innerWidth then clientWidth else innerWidth
40 height = if scrollHeight > innerHeight then clientHeight else innerHeight
41 viewport = {
42 left: 0
43 top: 0
44 right: width
45 bottom: height
46 width
47 height
48 }
49
50 groups = {semantic: [], unsemantic: [], combined: []}
51 createMarkers(window, viewport, groups, filter)
52 { semantic, unsemantic, combined } = groups
53 markers = semantic.concat(unsemantic)
54
55 return [[], null] if markers.length == 0
56
57 # Each marker gets a unique `z-index`, so that it can be determined if a
58 # marker overlaps another. Put more important markers (higher weight) at the
59 # end, so that they get higher `z-index`, in order not to be overlapped.
60 zIndex = 0
61 setZIndexes = (markers) ->
62 markers.sort((a, b) -> a.weight - b.weight)
63 for marker in markers when marker not instanceof huffman.BranchPoint
64 marker.markerElement.style.zIndex = zIndex++
65 # Add `z-index` space for all the children of the marker (usually 0).
66 zIndex += marker.numChildren
67
68 # The `markers` passed to this function have been sorted by `setZIndexes` in
69 # advance, so we can skip sorting in the `huffman.createTree` function.
70 hintChars = utils.getHintChars()
71 createHuffmanTree = (markers) ->
72 return huffman.createTree(markers, hintChars.length, {sorted: true})
73
74 # Semantic elements should always get better hints and higher `z-index`:es
75 # than unsemantic ones, even if they are smaller. The latter is achieved by
76 # putting the unsemantic elements in their own branch of the huffman tree.
77 if unsemantic.length > 0
78 if markers.length > hintChars.length
79 setZIndexes(unsemantic)
80 subTree = createHuffmanTree(unsemantic)
81 semantic.push(subTree)
82 else
83 semantic.push(unsemantic...)
84
85 setZIndexes(semantic)
86
87 tree = createHuffmanTree(semantic)
88 tree.assignCodeWords(hintChars, (marker, hint) -> marker.setHint(hint))
89
90 # Markers for links with the same href can be combined to use the same hint.
91 # They should all have the same `z-index` (because they all have the same
92 # combined weight), but in case any of them cover another they still get a
93 # unique `z-index` (space for this was added in `setZIndexes`).
94 for marker in combined
95 { parent } = marker
96 marker.markerElement.style.zIndex = parent.markerElement.style.zIndex++
97 marker.setHint(parent.hint)
98 markers.push(combined...)
99
100 container = rootWindow.document.createElement('box')
101 container.classList.add('VimFxMarkersContainer')
102 rootWindow.gBrowser.mCurrentBrowser.parentNode.appendChild(container)
103
104 for marker in markers
105 container.appendChild(marker.markerElement)
106 # Must be done after the hints have been inserted into the DOM (see
107 # marker.coffee).
108 marker.setPosition(viewport)
109
110 return [markers, container]
111
112 # `filter` is a function that is given every element in every frame of the page.
113 # It should return new `Marker`s for markable elements and a falsy value for all
114 # other elements. All returned `Marker`s are added to `groups`. `groups` is
115 # modified instead of using return values to avoid array concatenation for each
116 # frame. It might sound expensive to go through _every_ element, but that’s
117 # actually what other methods like using XPath or CSS selectors would need to do
118 # anyway behind the scenes.
119 createMarkers = (window, viewport, groups, filter, parents = []) ->
120 { document } = window
121
122 localGetElementShape = getElementShape.bind(null, window, viewport, parents)
123 for element in getElements(document, viewport) when element instanceof Element
124 continue unless marker = filter(element, localGetElementShape)
125 if marker.parent
126 groups.combined.push(marker)
127 else if marker.semantic
128 groups.semantic.push(marker)
129 else
130 groups.unsemantic.push(marker)
131
132 for frame in window.frames
133 rect = frame.frameElement.getBoundingClientRect() # Frames only have one.
134 continue unless isInsideViewport(rect, viewport)
135
136 # Calculate the visible part of the frame, according to the parent.
137 { clientWidth, clientHeight } = frame.document.documentElement
138 frameViewport =
139 left: Math.max(viewport.left - rect.left, 0)
140 top: Math.max(viewport.top - rect.top, 0)
141 right: clientWidth + Math.min(viewport.right - rect.right, 0)
142 bottom: clientHeight + Math.min(viewport.bottom - rect.bottom, 0)
143
144 # `.getComputedStyle()` may return `null` if the computed style isn’t
145 # availble yet. If so, consider the element not visible.
146 continue unless computedStyle = window.getComputedStyle(frame.frameElement)
147 offset =
148 left: rect.left +
149 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
150 parseFloat(computedStyle.getPropertyValue('padding-left'))
151 top: rect.top +
152 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
153 parseFloat(computedStyle.getPropertyValue('padding-top'))
154
155 createMarkers(frame, frameViewport, groups, filter,
156 parents.concat({ window, offset }))
157
158 return
159
160 # Returns a suitable set of elements in `document` that could possibly get
161 # markers.
162 getElements = (document, viewport) -> switch
163 # In HTML documents we can use a super-fast Firefox API to get all elements in
164 # the viewport.
165 when document instanceof HTMLDocument
166 windowUtils = document.defaultView
167 .QueryInterface(Ci.nsIInterfaceRequestor)
168 .getInterface(Ci.nsIDOMWindowUtils)
169 return windowUtils.nodesFromRect(
170 viewport.left, viewport.top, # Rect coordinates, relative to the viewport.
171 # Distances to expand in all directions: top, right, bottom, left.
172 0, viewport.right, viewport.bottom, 0,
173 true, # Unsure what this does. Toggling it seems to make no difference.
174 true # Ensure that the list of matching elements is fully up to date.
175 )
176 # In XUL documents we have to resort to get every single element in the entire
177 # document, because there are lots of complicated “anonymous” elements, which
178 # `windowUtils.nodesFromRect()` does not catch.
179 when document instanceof XULDocument
180 elements = []
181 getAllRegular = (element) ->
182 for child in element.getElementsByTagName('*')
183 elements.push(child)
184 getAllAnonymous(child)
185 return
186 getAllAnonymous = (element) ->
187 for child in document.getAnonymousNodes(element) or []
188 continue unless child instanceof Element
189 elements.push(child)
190 getAllRegular(child)
191 return
192 getAllRegular(document.documentElement)
193 return elements
194
195 # Returns the “shape” of `element`:
196 #
197 # - `rects`: Its `.getClientRects()` rectangles.
198 # - `visibleRects`: The parts of rectangles out of the above that are inside
199 # `viewport`.
200 # - `nonCoveredPoint`: The coordinates of the first point of `element` that
201 # isn’t covered by another element (except children of `element`). It also
202 # contains the offset needed to make those coordinates relative to the top
203 # frame, as well as the rectangle that the coordinates occur in.
204 # - `area`: The area of the part of `element` that is inside `viewport`.
205 #
206 # Returns `null` if `element` is outside `viewport` or entirely covered by other
207 # elements.
208 getElementShape = (window, viewport, parents, element) ->
209 # `element.getClientRects()` returns a list of rectangles, usually just one,
210 # which is identical to the one returned by `element.getBoundingClientRect()`.
211 # However, if `element` is inline and line-wrapped, then it returns one
212 # rectangle for each line, since each line may be of different length, for
213 # example. That allows us to properly add hints to line-wrapped links.
214 rects = element.getClientRects()
215 totalArea = 0
216 visibleRects = []
217 # The `isInsideViewport` check is not needed in HTML documents, but in XUL
218 # documents (see `getElements()`). However, there seems to be no performance
219 # gain in not running the check in HTML documents, so let’s keep it simple.
220 for rect in rects when isInsideViewport(rect, viewport)
221 visibleRect = adjustRectToViewport(rect, viewport)
222 continue if visibleRect.area == 0
223 totalArea += visibleRect.area
224 visibleRects.push(visibleRect)
225
226 if visibleRects.length == 0
227 if rects.length == 1 and totalArea == 0
228 [ rect ] = rects
229 if rect.width > 0 or rect.height > 0
230 # If we get here, it means that everything inside `element` is floated
231 # and/or absolutely positioned (and that `element` hasn’t been made to
232 # “contain” the floats). For example, a link in a menu could contain a
233 # span of text floated to the left and an icon floated to the right.
234 # Those are still clickable. Therefore we return the shape of the first
235 # visible child instead. At least in that example, that’s the best bet.
236 for child in element.children
237 shape = getElementShape(window, viewport, parents, child)
238 return shape if shape
239 return null
240
241 # Even if `element` has a visible rect, it might be covered by other elements.
242 for visibleRect in visibleRects
243 nonCoveredPoint = getFirstNonCoveredPoint(window, viewport, element,
244 visibleRect, parents)
245 if nonCoveredPoint
246 nonCoveredPoint.rect = visibleRect
247 break
248
249 return null unless nonCoveredPoint
250
251 return {
252 rects, visibleRects, nonCoveredPoint, area: totalArea
253 }
254
255
256 MINIMUM_EDGE_DISTANCE = 4
257 isInsideViewport = (rect, viewport) ->
258 return \
259 rect.left <= viewport.right - MINIMUM_EDGE_DISTANCE and
260 rect.top <= viewport.bottom + MINIMUM_EDGE_DISTANCE and
261 rect.right >= viewport.left + MINIMUM_EDGE_DISTANCE and
262 rect.bottom >= viewport.top - MINIMUM_EDGE_DISTANCE
263
264
265 adjustRectToViewport = (rect, viewport) ->
266 # The right and bottom values are subtracted by 1 because
267 # `document.elementFromPoint(right, bottom)` does not return the element
268 # otherwise.
269 left = Math.max(rect.left, viewport.left)
270 right = Math.min(rect.right - 1, viewport.right)
271 top = Math.max(rect.top, viewport.top)
272 bottom = Math.min(rect.bottom - 1, viewport.bottom)
273
274 # Make sure that `right >= left and bottom >= top`, since we subtracted by 1
275 # above.
276 right = Math.max(right, left)
277 bottom = Math.max(bottom, top)
278
279 width = right - left
280 height = bottom - top
281 area = Math.floor(width * height)
282
283 return {
284 left, right, top, bottom
285 height, width, area
286 }
287
288
289 getFirstNonCoveredPoint = (window, viewport, element, elementRect, parents) ->
290 # Before we start we need to hack around a little problem. If `element` has
291 # `border-radius`, the corners won’t really belong to `element`, so
292 # `document.elementFromPoint()` will return whatever is behind. This will
293 # result in missing or out-of-place markers. The solution is to temporarily
294 # add a CSS class that removes `border-radius`.
295 element.classList.add('VimFxNoBorderRadius')
296
297 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset)
298 # if it passes the tests. Otherwise it tries to the right of whatever is at
299 # `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
300 # and `dy` are used to offset the wanted point `(x, y)` while trying (see the
301 # invocations of `tryPoint` below).
302 tryPoint = (x, dx, y, dy, tryRight = 0) ->
303 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
304 offset = {left: 0, top: 0}
305 found = false
306
307 # Ensure that `element`, or a child of `element` (anything inside an `<a>`
308 # is clickable too), really is present at (x,y). Note that this is not 100%
309 # bullet proof: Combinations of CSS can cause this check to fail, even
310 # though `element` isn’t covered. We don’t try to temporarily reset such CSS
311 # (as with `border-radius`) because of performance. Instead we rely on that
312 # some of the attempts below will work.
313 if element.contains(elementAtPoint) or # Note that `a.contains(a) == true`!
314 (window.document instanceof XULDocument and
315 getClosestNonAnonymousParent(element) == elementAtPoint)
316 found = true
317 # If we’re currently in a frame, there might be something on top of the
318 # frame that covers `element`. Therefore we ensure that the frame really
319 # is present at the point for each parent in `parents`.
320 currentWindow = window
321 for parent in parents by -1
322 offset.left += parent.offset.left
323 offset.top += parent.offset.top
324 elementAtPoint = parent.window.document.elementFromPoint(
325 offset.left + x + dx, offset.top + y + dy
326 )
327 unless elementAtPoint == currentWindow.frameElement
328 found = false
329 break
330 currentWindow = parent.window
331
332 if found
333 return {x, y, offset}
334 else
335 return false if elementAtPoint == null or tryRight == 0
336 rect = elementAtPoint.getBoundingClientRect()
337 x = rect.right - offset.left + 1
338 return false if x > viewport.right
339 return tryPoint(x, 0, y, 0, tryRight - 1)
340
341
342 # Try the following 3 positions, or immediately to the right of a covering
343 # element at one of those positions, in order. If all of those are covered the
344 # whole element is considered to be covered. The reasoning is:
345 #
346 # - A marker should show up as near the left edge of its visible area as
347 # possible. Having it appear to the far right (for example) is confusing.
348 # - We can’t try too many times because of performance.
349 #
350 # +-------------------------------+
351 # |1 left-top |
352 # | |
353 # |2 left-middle |
354 # | |
355 # |3 left-bottom |
356 # +-------------------------------+
357 #
358 # It is safer to try points at least one pixel into the element from the
359 # edges, hence the `+1`s and `-1`s.
360 { left, top, bottom, height } = elementRect
361 nonCoveredPoint =
362 tryPoint(left, +1, top, +1, 1) or
363 tryPoint(left, +1, top + height / 2, 0, 1) or
364 tryPoint(left, +1, bottom, -1, 1)
365
366 element.classList.remove('VimFxNoBorderRadius')
367
368 return nonCoveredPoint
369
370 # In XUL documents there are “anonymous” elements, whose node names start with
371 # `xul:` or `html:`. These are not never returned by `document.elementFromPoint`
372 # but their closest non-anonymous parents are.
373 getClosestNonAnonymousParent = (element) ->
374 element = element.parentNode while element.prefix?
375 return element
376
377 exports.injectHints = injectHints
Imprint / Impressum