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