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