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