]> git.gir.st - VimFx.git/blob - extension/lib/markable-elements.coffee
fix hints on about:preferences (nightly72)
[VimFx.git] / extension / lib / markable-elements.coffee
1 # This file contains functions for getting markable elements and related data.
2
3 utils = require('./utils')
4 viewportUtils = require('./viewport')
5
6 {devtools} = Cu.import('resource://devtools/shared/Loader.jsm', {})
7
8 _Element = Ci.nsIDOMElement
9 if _Element
10 isElementInstance = (el) -> el instanceof _Element
11 else
12 Cu.importGlobalProperties(['Element'])
13 isElementInstance = (el) -> Element.isInstance(el)
14
15 MIN_TEXTNODE_SIZE = 4
16
17 find = (window, filter, selector = '*') ->
18 viewport = viewportUtils.getWindowViewport(window)
19 wrappers = []
20 getMarkableElements(window, viewport, wrappers, filter, selector)
21 return wrappers
22
23 # `filter` is a function that is given every element in every frame of the page.
24 # It should return wrapper objects for markable elements and a falsy value for
25 # all other elements. All returned wrappers are added to `wrappers`. `wrappers`
26 # is modified instead of using return values to avoid array concatenation for
27 # each frame. It might sound expensive to go through _every_ element, but that’s
28 # actually what other methods like using XPath or CSS selectors would need to do
29 # anyway behind the scenes. However, it is possible to pass in a CSS selector,
30 # which allows getting markable elements in several passes with different sets
31 # of candidates.
32 getMarkableElements = (
33 window, viewport, wrappers, filter, selector, parents = []
34 ) ->
35 {document} = window
36
37 for element in getAllElements(document, selector)
38 continue unless isElementInstance(element)
39 # `getRects` is fast and filters out most elements, so run it first of all.
40 rects = getRects(element, viewport)
41 continue unless rects.insideViewport.length > 0
42 continue unless wrapper = filter(
43 element, (elementArg, tryRight = 1) ->
44 return getElementShape(
45 {window, viewport, parents, element: elementArg}, tryRight,
46 if elementArg == element then rects else null
47 )
48 )
49 wrappers.push(wrapper)
50
51 for frame in window.frames when frame.frameElement
52 continue unless result = viewportUtils.getFrameViewport(
53 frame.frameElement, viewport
54 )
55 {viewport: frameViewport, offset} = result
56 getMarkableElements(
57 frame, frameViewport, wrappers, filter, selector,
58 parents.concat({window, offset})
59 )
60
61 return
62
63 findAllDOMs = (dom) ->
64 return [dom].concat(
65 Array.from(dom.querySelectorAll('*'))
66 .filter((e) -> e.shadowRoot?)
67 .map((e) -> findAllDOMs(e.shadowRoot))...
68 )
69
70 getAllElements = (document, selector) ->
71 unless utils.isXULDocument(document)
72 return [].concat(
73 findAllDOMs(document).map((d) ->
74 Array.from(d.querySelectorAll(selector))
75 )...
76 )
77
78 # Use a `Set` since this algorithm may find the same element more than once.
79 # Ideally we should find a way to find all elements without duplicates.
80 elements = new Set()
81 getAllRegular = (element) ->
82 # The first time `eb` is run `.getElementsByTagName('*')` may oddly include
83 # `undefined` in its result! Filter those out. (Also, `selector` is ignored
84 # here since it doesn’t make sense in XUL documents because of all the
85 # trickery around anonymous elements.)
86 for child in element.getElementsByTagName('*') when child
87 elements.add(child)
88 getAllAnonymous(child)
89 return
90 getAllAnonymous = (element) ->
91 for child in document.getAnonymousNodes(element) or []
92 continue unless isElementInstance(child)
93 elements.add(child)
94 getAllRegular(child)
95 getAllAnonymous(child)
96 return
97 getAllRegular(document.documentElement)
98 return Array.from(elements)
99
100 getRects = (element, viewport) ->
101 # `element.getClientRects()` returns a list of rectangles, usually just one,
102 # which is identical to the one returned by `element.getBoundingClientRect()`.
103 # However, if `element` is inline and line-wrapped, then it returns one
104 # rectangle for each line, since each line may be of different length, for
105 # example. That allows us to properly add hints to line-wrapped links.
106 rects = element.getClientRects?() or []
107 return {
108 all: rects,
109 insideViewport: Array.prototype.filter.call(
110 rects,
111 (rect) -> viewportUtils.isInsideViewport(rect, viewport)
112 )
113 }
114
115 # Returns the “shape” of an element:
116 #
117 # - `nonCoveredPoint`: The coordinates of the first point of the element that
118 # isn’t covered by another element (except children of the element). It also
119 # contains the offset needed to make those coordinates relative to the top
120 # frame, as well as the rectangle that the coordinates occur in. It is `null`
121 # if the element is outside `viewport` or entirely covered by other elements.
122 # - `area`: The area of the part of the element that is inside the viewport.
123 # - `width`: The width of the visible rect at `nonCoveredPoint`.
124 # - `textOffset`: The distance between the left edge of the element and the left
125 # edge of its text vertically near `nonCoveredPoint`. Might be `null`. The
126 # calculation might stop early if `isBlock`.
127 # - `isBlock`: `true` if the element is a block and has several lines of text
128 # (which is the case for “cards” with an image to the left and a title as well
129 # as some text to the right (where the entire “card” is a link)). This is used
130 # to place the the marker at the edge of the block.
131 getElementShape = (elementData, tryRight, rects = null) ->
132 {viewport, element} = elementData
133 result =
134 {nonCoveredPoint: null, area: 0, width: 0, textOffset: null, isBlock: false}
135
136 rects ?= getRects(element, viewport)
137 totalArea = 0
138 visibleRects = []
139 for rect, index in rects.insideViewport
140 visibleRect = viewportUtils.adjustRectToViewport(rect, viewport)
141 continue if visibleRect.area == 0
142 visibleRect.index = index
143 totalArea += visibleRect.area
144 visibleRects.push(visibleRect)
145
146 if visibleRects.length == 0
147 if rects.all.length == 1 and totalArea == 0
148 [rect] = rects.all
149 if rect.width > 0 or rect.height > 0
150 # If we get here, it means that everything inside `element` is floated
151 # and/or absolutely positioned (and that `element` hasn’t been made to
152 # “contain” the floats). For example, a link in a menu could contain a
153 # span of text floated to the left and an icon floated to the right.
154 # Those are still clickable. Therefore we return the shape of the first
155 # visible child instead. At least in that example, that’s the best bet.
156 for child in element.children
157 childData = Object.assign({}, elementData, {element: child})
158 shape = getElementShape(childData, tryRight)
159 return shape if shape
160 return result
161
162 result.area = totalArea
163
164 # Even if `element` has a visible rect, it might be covered by other elements.
165 nonCoveredPoint = null
166 nonCoveredPointRect = null
167 for visibleRect in visibleRects
168 nonCoveredPoint = getFirstNonCoveredPoint(
169 elementData, visibleRect, tryRight
170 )
171 if nonCoveredPoint
172 nonCoveredPointRect = visibleRect
173 break
174
175 return result unless nonCoveredPoint
176 result.nonCoveredPoint = nonCoveredPoint
177
178 result.width = nonCoveredPointRect.width
179
180 lefts = []
181 smallestBottom = Infinity
182 hasSingleRect = (rects.all.length == 1)
183
184 utils.walkTextNodes(element, (node) ->
185 unless node.data.trim() == ''
186 for quads in node.getBoxQuads()
187 try
188 bounds = quads.getBounds()
189 catch
190 bounds = quads.bounds # waterfox 56
191 if bounds.width < MIN_TEXTNODE_SIZE or bounds.height < MIN_TEXTNODE_SIZE
192 continue
193
194 if utils.overlaps(bounds, nonCoveredPointRect)
195 lefts.push(bounds.left)
196
197 if hasSingleRect
198 # The element is likely a block and has several lines of text; ignore
199 # the `textOffset` (see the description of `textOffset` at the
200 # beginning of the function).
201 if bounds.top > smallestBottom
202 result.isBlock = true
203 return true
204
205 if bounds.bottom < smallestBottom
206 smallestBottom = bounds.bottom
207
208 return false
209 )
210
211 if lefts.length > 0
212 result.textOffset =
213 Math.round(Math.min(lefts...) - nonCoveredPointRect.left)
214
215 return result
216
217 getFirstNonCoveredPoint = (elementData, elementRect, tryRight) ->
218 # Try the left-middle point, or immediately to the right of a covering element
219 # at that point (when `tryRight == 1`). If both of those are covered the whole
220 # element is considered to be covered. The reasoning is:
221 #
222 # - A marker should show up as near the left edge of its visible area as
223 # possible. Having it appear to the far right (for example) is confusing.
224 # - We can’t try too many times because of performance.
225 # - We used to try left-top first, but if the element has `border-radius`, the
226 # corners won’t belong to the element, so `document.elementFromPoint()` will
227 # return whatever is behind. One _could_ temporarily add a CSS class that
228 # removes `border-radius`, but that turned out to be too slow. Trying
229 # left-middle instead avoids the problem, and looks quite nice, actually.
230 # - We used to try left-bottom as well, but that is so rare that it’s not
231 # worth it.
232 #
233 # It is safer to try points at least one pixel into the element from the
234 # edges, hence the `+1`.
235 {left, top, bottom, height} = elementRect
236 return tryPoint(
237 elementData, elementRect,
238 left, +1, Math.round(top + height / 2), 0, tryRight
239 )
240
241 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset) if
242 # the element passes the tests. Otherwise it tries to the right of whatever is
243 # at `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
244 # and `dy` are used to offset the wanted point `(x, y)` while trying.
245 tryPoint = (elementData, elementRect, x, dx, y, dy, tryRight = 0) ->
246 {window, viewport, parents, element} = elementData
247 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
248 offset = {left: 0, top: 0}
249 found = false
250 firstLevel = true
251
252 # Ensure that `element`, or a child of `element` (anything inside an `<a>` is
253 # clickable too), really is present at (x,y). Note that this is not 100%
254 # bullet proof: Combinations of CSS can cause this check to fail, even though
255 # `element` isn’t covered. We don’t try to temporarily reset such CSS because
256 # of performance. (See further down for the special value `-1` of `tryRight`.)
257 if contains(element, elementAtPoint) or tryRight == -1
258 found = true
259 # If we’re currently in a frame, there might be something on top of the
260 # frame that covers `element`. Therefore we ensure that the frame really is
261 # present at the point for each parent in `parents`.
262 currentWindow = window
263 for parent in parents by -1
264 # If leaving the devtools container take the devtools zoom into account.
265 if utils.isDevtoolsWindow(currentWindow)
266 docShell = currentWindow
267 .getInterface(Ci.nsIWebNavigation)
268 .QueryInterface(Ci.nsIDocShell)
269 if docShell
270 devtoolsZoom = docShell.contentViewer.fullZoom
271 offset.left *= devtoolsZoom
272 offset.top *= devtoolsZoom
273 x *= devtoolsZoom
274 y *= devtoolsZoom
275 dx *= devtoolsZoom
276 dy *= devtoolsZoom
277
278 offset.left += parent.offset.left
279 offset.top += parent.offset.top
280 elementAtPoint = parent.window.document.elementFromPoint(
281 offset.left + x + dx, offset.top + y + dy
282 )
283 firstLevel = false
284 unless contains(currentWindow.frameElement, elementAtPoint)
285 found = false
286 break
287 currentWindow = parent.window
288
289 return {x, y, offset} if found
290
291 return false if elementAtPoint == null or tryRight <= 0
292 rect = elementAtPoint.getBoundingClientRect()
293
294 # `.getBoundingClientRect()` does not include pseudo-elements that are
295 # absolutely positioned so that they go outside of the element (which is
296 # common for `/###\`-looking tabs), but calling `.elementAtPoint()` on the
297 # pseudo-element _does_ return the element. This means that the covering
298 # element’s _rect_ won’t cover the element we’re looking for. If so, it’s
299 # better to try again, forcing the element to be considered located at this
300 # point. That’s what `-1` for the `tryRight` argument means. This is also used
301 # in the 'complementary' pass, to include elements considered covered in
302 # earlier passes (which might have been false positives).
303 if firstLevel and rect.right <= x + offset.left
304 return tryPoint(elementData, elementRect, x, dx, y, dy, -1)
305
306 # If `elementAtPoint` is a parent to `element`, it most likely means that
307 # `element` is hidden some way. It can also mean that a pseudo-element of
308 # `elementAtPoint` covers `element` partly. Therefore, try once at the most
309 # likely point: The center of the part of the rect to the right of `x`.
310 if elementRect.right > x and contains(elementAtPoint, element)
311 return tryPoint(
312 elementData, elementRect,
313 (x + elementRect.right) / 2, 0, y, 0, 0
314 )
315
316 newX = rect.right - offset.left + 1
317 return false if newX > viewport.right or newX > elementRect.right
318 return tryPoint(elementData, elementRect, newX, 0, y, 0, tryRight - 1)
319
320 # In XUL documents there are “anonymous” elements. These are never returned by
321 # `document.elementFromPoint` but their closest non-anonymous parents are.
322 # The same is true for Web Components (where their hosts are returned), with
323 # the further caveat that they might be nested.
324 normalize = (element) ->
325 element = elem while (elem = element.ownerDocument.getBindingParent(element))?
326 element = element.parentNode while element.prefix?
327 return element
328
329 # Returns whether `element` corresponds to `elementAtPoint`. This is only
330 # complicated for browser elements in the web page content area.
331 # `.elementAtPoint()` always returns `<tabbrowser#content>` then. The element
332 # might be in another tab and thus invisible, but `<tabbrowser#content>` is the
333 # same and visible in _all_ tabs, so we have to check that the element really
334 # belongs to the current tab.
335 contains = (element, elementAtPoint) ->
336 return false unless elementAtPoint
337 container = normalize(element)
338 if elementAtPoint.localName == 'tabbrowser' and elementAtPoint.id == 'content'
339 {gBrowser} = element.ownerGlobal.top
340 tabpanel = gBrowser.getNotificationBox(gBrowser.selectedBrowser)
341 return tabpanel.contains(element)
342 else
343 # Note that `a.contains(a)` is supposed to be true, but strangely aren’t for
344 # `<menulist>`s in the Add-ons Manager, so do a direct comparison as well.
345 return container == elementAtPoint or container.contains(elementAtPoint)
346
347 module.exports = {
348 find
349 }
Imprint / Impressum