]> git.gir.st - VimFx.git/blob - extension/lib/hints.coffee
Reduce unnecessary vertical code alignment
[VimFx.git] / extension / lib / hints.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013.
3 # Copyright Simon Lydell 2013, 2014, 2015, 2016.
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 # This file contains functions for getting markable elements, and related data,
22 # as well as for creating and inserting markers for markable elements.
23
24 huffman = require('n-ary-huffman')
25 {Marker} = require('./marker')
26 utils = require('./utils')
27
28 try
29 # TODO: Only use this path when Firefox 44 is released.
30 {devtools} = Cu.import('resource://devtools/shared/Loader.jsm', {})
31 catch
32 {devtools} = Cu.import('resource://gre/modules/devtools/Loader.jsm', {})
33
34 CONTAINER_ID = 'VimFxMarkersContainer'
35
36 Element = Ci.nsIDOMElement
37 XULDocument = Ci.nsIDOMXULDocument
38
39 shutdownHandlerAdded = false
40
41 # For some time we used to return the hints container from `injectHints`, and
42 # use that reference to remove the hints when needed. That’s fine in theory, but
43 # in case anything breaks we might loose that reference and end up with
44 # unremovable hints on the screen. Explicitly looking for an element with the
45 # container ID is more fail-safe.
46 removeHints = (window) ->
47 window.document.getElementById(CONTAINER_ID)?.remove()
48
49 # Create `Marker`s for every element (represented by a regular object of data
50 # about the element—a “wrapper,” a stand-in for the real element, which is only
51 # accessible in frame scripts) in `wrappers`, and insert them into `window`.
52 injectHints = (window, wrappers, viewport, options) ->
53 semantic = []
54 unsemantic = []
55 combined = []
56 markerMap = {}
57
58 for wrapper in wrappers
59 marker = new Marker(wrapper, window.document)
60 group = switch
61 when wrapper.parentIndex? then combined
62 when wrapper.semantic then semantic
63 else unsemantic
64 group.push(marker)
65 markerMap[wrapper.elementIndex] = marker
66
67 markers = semantic.concat(unsemantic)
68
69 # Each marker gets a unique `z-index`, so that it can be determined if a
70 # marker overlaps another. Put more important markers (higher weight) at the
71 # end, so that they get higher `z-index`, in order not to be overlapped.
72 zIndex = 0
73 setZIndexes = (markers) ->
74 markers.sort((a, b) -> a.weight - b.weight)
75 for marker in markers when marker not instanceof huffman.BranchPoint
76 marker.markerElement.style.zIndex = zIndex
77 zIndex += 1
78 # Add `z-index` space for all the children of the marker.
79 zIndex += marker.wrapper.numChildren if marker.wrapper.numChildren?
80 return
81
82 # The `markers` passed to this function have been sorted by `setZIndexes` in
83 # advance, so we can skip sorting in the `huffman.createTree` function.
84 hintChars = options.hint_chars
85 createHuffmanTree = (markers) ->
86 return huffman.createTree(markers, hintChars.length, {sorted: true})
87
88 # Semantic elements should always get better hints and higher `z-index`:es
89 # than unsemantic ones, even if they are smaller. The former is achieved by
90 # putting the unsemantic elements in their own branch of the huffman tree.
91 if unsemantic.length > 0
92 if markers.length > hintChars.length
93 setZIndexes(unsemantic)
94 subTree = createHuffmanTree(unsemantic)
95 semantic.push(subTree)
96 else
97 semantic.push(unsemantic...)
98
99 setZIndexes(semantic)
100
101 tree = createHuffmanTree(semantic)
102 tree.assignCodeWords(hintChars, (marker, hint) -> marker.setHint(hint))
103
104 # Markers for links with the same href can be combined to use the same hint.
105 # They should all have the same `z-index` (because they all have the same
106 # combined weight), but in case any of them cover another they still get a
107 # unique `z-index` (space for this was added in `setZIndexes`).
108 for marker in combined
109 parent = markerMap[marker.wrapper.parentIndex]
110 marker.markerElement.style.zIndex = parent.markerElement.style.zIndex
111 parent.markerElement.style.zIndex += 1
112 marker.setHint(parent.hint)
113 markers.push(combined...)
114
115 removeHints(window) # Better safe than sorry.
116 container = window.document.createElement('box')
117 container.id = CONTAINER_ID
118
119 zoom = 1
120
121 if options.ui
122 container.classList.add('ui')
123 window.document.getElementById('browser-panel').appendChild(container)
124 else
125 {ZoomManager, gBrowser: {selectedBrowser: browser}} = window
126 browser.parentNode.appendChild(container)
127 # If “full zoom” is not used, it means that “Zoom text only” is enabled.
128 # If so, that “zoom” does not need to be taken into account.
129 # `.getCurrentMode()` is added by the “Default FullZoom Level” extension.
130 if ZoomManager.getCurrentMode?(browser) ? ZoomManager.useFullZoom
131 zoom = ZoomManager.getZoomForBrowser(browser)
132
133 for marker in markers
134 container.appendChild(marker.markerElement)
135 # Must be done after the hints have been inserted into the DOM (see
136 # marker.coffee).
137 marker.setPosition(viewport, zoom)
138
139 unless shutdownHandlerAdded
140 module.onShutdown(removeHints.bind(null, window))
141 shutdownHandlerAdded = true
142
143 return {markers, markerMap}
144
145 getMarkableElementsAndViewport = (window, filter) ->
146 {
147 clientWidth, clientHeight # Viewport size excluding scrollbars, usually.
148 scrollWidth, scrollHeight
149 } = window.document.documentElement
150 {innerWidth, innerHeight} = window # Viewport size including scrollbars.
151 # We don’t want markers to cover the scrollbars, so we should use
152 # `clientWidth` and `clientHeight`. However, when there are no scrollbars
153 # those might be too small. Then we use `innerWidth` and `innerHeight`.
154 width = if scrollWidth > innerWidth then clientWidth else innerWidth
155 height = if scrollHeight > innerHeight then clientHeight else innerHeight
156 viewport = {
157 left: 0
158 top: 0
159 right: width
160 bottom: height
161 width
162 height
163 }
164
165 wrappers = []
166 getMarkableElements(window, viewport, wrappers, filter)
167 return {wrappers, viewport}
168
169 # `filter` is a function that is given every element in every frame of the page.
170 # It should return wrapper objects for markable elements and a falsy value for
171 # all other elements. All returned wrappers are added to `wrappers`. `wrappers`
172 # is modified instead of using return values to avoid array concatenation for
173 # each frame. It might sound expensive to go through _every_ element, but that’s
174 # actually what other methods like using XPath or CSS selectors would need to do
175 # anyway behind the scenes.
176 getMarkableElements = (window, viewport, wrappers, filter, parents = []) ->
177 {document} = window
178
179 for element in getAllElements(document) when element instanceof Element
180 # `getRects` is fast and filters out most elements, so run it first of all.
181 rects = getRects(element, viewport)
182 continue unless rects.length > 0
183 continue unless wrapper = filter(
184 element, (elementArg) ->
185 return getElementShape(window, viewport, parents, elementArg,
186 if elementArg == element then rects else null)
187 )
188 wrappers.push(wrapper)
189
190 for frame in window.frames when frame.frameElement
191 rect = frame.frameElement.getBoundingClientRect() # Frames only have one.
192 continue unless isInsideViewport(rect, viewport)
193
194 # Calculate the visible part of the frame, according to the parent.
195 # coffeelint: disable=colon_assignment_spacing
196 {clientWidth, clientHeight} = frame.document.documentElement
197 frameViewport = {
198 left: Math.max(viewport.left - rect.left, 0)
199 top: Math.max(viewport.top - rect.top, 0)
200 right: clientWidth + Math.min(viewport.right - rect.right, 0)
201 bottom: clientHeight + Math.min(viewport.bottom - rect.bottom, 0)
202 }
203 # coffeelint: enable=colon_assignment_spacing
204
205 # `.getComputedStyle()` may return `null` if the computed style isn’t
206 # availble yet. If so, consider the element not visible.
207 continue unless computedStyle = window.getComputedStyle(frame.frameElement)
208 offset = {
209 left: rect.left +
210 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
211 parseFloat(computedStyle.getPropertyValue('padding-left'))
212 top: rect.top +
213 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
214 parseFloat(computedStyle.getPropertyValue('padding-top'))
215 }
216
217 getMarkableElements(frame, frameViewport, wrappers, filter,
218 parents.concat({window, offset}))
219
220 return
221
222 getAllElements = (document) ->
223 unless document instanceof XULDocument
224 return document.getElementsByTagName('*')
225
226 # Use a `Set` since this algorithm may find the same element more than once.
227 # Ideally we should find a way to find all elements without duplicates.
228 elements = new Set()
229 getAllRegular = (element) ->
230 # The first time `zF` is run `.getElementsByTagName('*')` may oddly include
231 # `undefined` in its result! Filter those out.
232 for child in element.getElementsByTagName('*') when child
233 elements.add(child)
234 getAllAnonymous(child)
235 return
236 getAllAnonymous = (element) ->
237 for child in document.getAnonymousNodes(element) or []
238 continue unless child instanceof Element
239 elements.add(child)
240 getAllRegular(child)
241 return
242 getAllRegular(document.documentElement)
243 return Array.from(elements)
244
245 getRects = (element, viewport) ->
246 # `element.getClientRects()` returns a list of rectangles, usually just one,
247 # which is identical to the one returned by `element.getBoundingClientRect()`.
248 # However, if `element` is inline and line-wrapped, then it returns one
249 # rectangle for each line, since each line may be of different length, for
250 # example. That allows us to properly add hints to line-wrapped links.
251 return Array.filter(
252 element.getClientRects(), (rect) -> isInsideViewport(viewport, rect)
253 )
254
255 # Returns the “shape” of `element`:
256 #
257 # - `nonCoveredPoint`: The coordinates of the first point of `element` that
258 # isn’t covered by another element (except children of `element`). It also
259 # contains the offset needed to make those coordinates relative to the top
260 # frame, as well as the rectangle that the coordinates occur in.
261 # - `area`: The area of the part of `element` that is inside `viewport`.
262 #
263 # Returns `null` if `element` is outside `viewport` or entirely covered by other
264 # elements.
265 getElementShape = (window, viewport, parents, element, rects = null) ->
266 rects ?= getRects(element, viewport)
267 totalArea = 0
268 visibleRects = []
269 for rect in rects
270 visibleRect = adjustRectToViewport(rect, viewport)
271 continue if visibleRect.area == 0
272 totalArea += visibleRect.area
273 visibleRects.push(visibleRect)
274
275 if visibleRects.length == 0
276 if rects.length == 1 and totalArea == 0
277 [rect] = rects
278 if rect.width > 0 or rect.height > 0
279 # If we get here, it means that everything inside `element` is floated
280 # and/or absolutely positioned (and that `element` hasn’t been made to
281 # “contain” the floats). For example, a link in a menu could contain a
282 # span of text floated to the left and an icon floated to the right.
283 # Those are still clickable. Therefore we return the shape of the first
284 # visible child instead. At least in that example, that’s the best bet.
285 for child in element.children
286 shape = getElementShape(window, viewport, parents, child)
287 return shape if shape
288 return null
289
290 # Even if `element` has a visible rect, it might be covered by other elements.
291 for visibleRect in visibleRects
292 nonCoveredPoint = getFirstNonCoveredPoint(window, viewport, element,
293 visibleRect, parents)
294 break if nonCoveredPoint
295
296 return null unless nonCoveredPoint
297
298 return {
299 nonCoveredPoint, area: totalArea
300 }
301
302 MINIMUM_EDGE_DISTANCE = 4
303 isInsideViewport = (rect, viewport) ->
304 return \
305 rect.left <= viewport.right - MINIMUM_EDGE_DISTANCE and
306 rect.top <= viewport.bottom + MINIMUM_EDGE_DISTANCE and
307 rect.right >= viewport.left + MINIMUM_EDGE_DISTANCE and
308 rect.bottom >= viewport.top - MINIMUM_EDGE_DISTANCE
309
310 adjustRectToViewport = (rect, viewport) ->
311 # The right and bottom values are subtracted by 1 because
312 # `document.elementFromPoint(right, bottom)` does not return the element
313 # otherwise.
314 left = Math.max(rect.left, viewport.left)
315 right = Math.min(rect.right - 1, viewport.right)
316 top = Math.max(rect.top, viewport.top)
317 bottom = Math.min(rect.bottom - 1, viewport.bottom)
318
319 # Make sure that `right >= left and bottom >= top`, since we subtracted by 1
320 # above.
321 right = Math.max(right, left)
322 bottom = Math.max(bottom, top)
323
324 width = right - left
325 height = bottom - top
326 area = Math.floor(width * height)
327
328 return {
329 left, right, top, bottom
330 height, width, area
331 }
332
333 getFirstNonCoveredPoint = (window, viewport, element, elementRect, parents) ->
334 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset)
335 # if it passes the tests. Otherwise it tries to the right of whatever is at
336 # `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
337 # and `dy` are used to offset the wanted point `(x, y)` while trying (see the
338 # invocations of `tryPoint` below).
339 tryPoint = (x, dx, y, dy, tryRight = 0) ->
340 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
341 offset = {left: 0, top: 0}
342 found = false
343 firstLevel = true
344
345 # Ensure that `element`, or a child of `element` (anything inside an `<a>`
346 # is clickable too), really is present at (x,y). Note that this is not 100%
347 # bullet proof: Combinations of CSS can cause this check to fail, even
348 # though `element` isn’t covered. We don’t try to temporarily reset such CSS
349 # because of performance. Instead we rely on that some of the attempts below
350 # will work. (See further down for the special value `-1` of `tryRight`.)
351 if contains(element, elementAtPoint) or tryRight == -1
352 found = true
353 # If we’re currently in a frame, there might be something on top of the
354 # frame that covers `element`. Therefore we ensure that the frame really
355 # is present at the point for each parent in `parents`.
356 currentWindow = window
357 for parent in parents by -1
358 # If leaving the devtools container take the devtools zoom into account.
359 if currentWindow.DevTools and not parent.window.DevTools
360 toolbox = window.gDevTools.getToolbox(
361 devtools.TargetFactory.forTab(window.top.gBrowser.selectedTab)
362 )
363 if toolbox
364 devtoolsZoom = toolbox.zoomValue
365 offset.left *= devtoolsZoom
366 offset.top *= devtoolsZoom
367 x *= devtoolsZoom
368 y *= devtoolsZoom
369 dx *= devtoolsZoom
370 dy *= devtoolsZoom
371
372 offset.left += parent.offset.left
373 offset.top += parent.offset.top
374 elementAtPoint = parent.window.document.elementFromPoint(
375 offset.left + x + dx, offset.top + y + dy
376 )
377 firstLevel = false
378 unless contains(currentWindow.frameElement, elementAtPoint)
379 found = false
380 break
381 currentWindow = parent.window
382
383 return {x, y, offset} if found
384
385 return false if elementAtPoint == null or tryRight <= 0
386 rect = elementAtPoint.getBoundingClientRect()
387
388 # `.getBoundingClientRect()` does not include pseudo-elements that are
389 # absolutely positioned so that they go outside of the element (which is
390 # common for `/###\`-looking tabs), but calling `.elementAtPoint()` on the
391 # pseudo-element _does_ return the element. This means that the covering
392 # element’s _rect_ won’t cover the element we’re looking for. If so, it’s
393 # better to try again, forcing the element to be considered located at this
394 # point. That’s what `-1` for the `tryRight` argument means.
395 if firstLevel and rect.right <= x + offset.left
396 return tryPoint(x, dx, y, dy, -1)
397
398 x = rect.right - offset.left + 1
399 return false if x > viewport.right
400 return tryPoint(x, 0, y, 0, tryRight - 1)
401
402
403 # Try the left-middle point, or immediately to the right of a covering element
404 # at that point. If both of those are covered the whole element is considered
405 # to be covered. The reasoning is:
406 #
407 # - A marker should show up as near the left edge of its visible area as
408 # possible. Having it appear to the far right (for example) is confusing.
409 # - We can’t try too many times because of performance.
410 # - We used to try left-top first, but if `element` has `border-radius`, the
411 # corners won’t really belong to `element`, so `document.elementFromPoint()`
412 # will return whatever is behind. This will result in missing or
413 # out-of-place markers. The solution is to temporarily add a CSS class that
414 # removes `border-radius`, but that turned out to be rather slow, making it
415 # not worth it. Usually you don’t see the difference between left-top and
416 # left-middle, because links are usually not that high.
417 # - We used to try left-bottom as well, but that is so rare that it’s not
418 # worth it.
419 #
420 # It is safer to try points at least one pixel into the element from the
421 # edges, hence the `+1`.
422 {left, top, bottom, height} = elementRect
423 nonCoveredPoint = tryPoint(left, +1, Math.floor(top + height / 2), 0, 1)
424
425 return nonCoveredPoint
426
427 # In XUL documents there are “anonymous” elements. These are never returned by
428 # `document.elementFromPoint` but their closest non-anonymous parents are.
429 normalize = (element) ->
430 normalized = element.ownerDocument.getBindingParent(element) or element
431 normalized = normalized.parentNode while normalized.prefix?
432 return normalized
433
434 # Returns whether `element` corresponds to `elementAtPoint`. This is only
435 # complicated for browser elements in the web page content area.
436 # `.elementAtPoint()` always returns `<tabbrowser#content>` then. The element
437 # might be in another tab and thus invisible, but `<tabbrowser#content>` is the
438 # same and visible in _all_ tabs, so we have to check that the element really
439 # belongs to the current tab.
440 contains = (element, elementAtPoint) ->
441 return false unless elementAtPoint
442 container = normalize(element)
443 if elementAtPoint.nodeName == 'tabbrowser' and elementAtPoint.id == 'content'
444 {gBrowser} = element.ownerGlobal.top
445 tabpanel = gBrowser.getNotificationBox(gBrowser.selectedBrowser)
446 return tabpanel.contains(element)
447 else
448 # Note that `a.contains(a)` is supposed to be true, but strangely aren’t for
449 # `<menulist>`s in the Add-ons Manager, so do a direct comparison as well.
450 return container == elementAtPoint or container.contains(elementAtPoint)
451
452 module.exports = {
453 removeHints
454 injectHints
455 getMarkableElementsAndViewport
456 }
Imprint / Impressum