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