]> git.gir.st - VimFx.git/blob - extension/lib/markable-elements.coffee
fix lint error for overlong line
[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 try
165 bounds = quads.getBounds()
166 catch
167 bounds = quads.bounds # waterfox 56
168 if bounds.width < MIN_TEXTNODE_SIZE or bounds.height < MIN_TEXTNODE_SIZE
169 continue
170
171 if utils.overlaps(bounds, nonCoveredPointRect)
172 lefts.push(bounds.left)
173
174 if hasSingleRect
175 # The element is likely a block and has several lines of text; ignore
176 # the `textOffset` (see the description of `textOffset` at the
177 # beginning of the function).
178 if bounds.top > smallestBottom
179 result.isBlock = true
180 return true
181
182 if bounds.bottom < smallestBottom
183 smallestBottom = bounds.bottom
184
185 return false
186 )
187
188 if lefts.length > 0
189 result.textOffset =
190 Math.round(Math.min(lefts...) - nonCoveredPointRect.left)
191
192 return result
193
194 getFirstNonCoveredPoint = (elementData, elementRect, tryRight) ->
195 # Try the left-middle point, or immediately to the right of a covering element
196 # at that point (when `tryRight == 1`). If both of those are covered the whole
197 # element is considered to be covered. The reasoning is:
198 #
199 # - A marker should show up as near the left edge of its visible area as
200 # possible. Having it appear to the far right (for example) is confusing.
201 # - We can’t try too many times because of performance.
202 # - We used to try left-top first, but if the element has `border-radius`, the
203 # corners won’t belong to the element, so `document.elementFromPoint()` will
204 # return whatever is behind. One _could_ temporarily add a CSS class that
205 # removes `border-radius`, but that turned out to be too slow. Trying
206 # left-middle instead avoids the problem, and looks quite nice, actually.
207 # - We used to try left-bottom as well, but that is so rare that it’s not
208 # worth it.
209 #
210 # It is safer to try points at least one pixel into the element from the
211 # edges, hence the `+1`.
212 {left, top, bottom, height} = elementRect
213 return tryPoint(
214 elementData, elementRect,
215 left, +1, Math.round(top + height / 2), 0, tryRight
216 )
217
218 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset) if
219 # the element passes the tests. Otherwise it tries to the right of whatever is
220 # at `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
221 # and `dy` are used to offset the wanted point `(x, y)` while trying.
222 tryPoint = (elementData, elementRect, x, dx, y, dy, tryRight = 0) ->
223 {window, viewport, parents, element} = elementData
224 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
225 offset = {left: 0, top: 0}
226 found = false
227 firstLevel = true
228
229 # Ensure that `element`, or a child of `element` (anything inside an `<a>` is
230 # clickable too), really is present at (x,y). Note that this is not 100%
231 # bullet proof: Combinations of CSS can cause this check to fail, even though
232 # `element` isn’t covered. We don’t try to temporarily reset such CSS because
233 # of performance. (See further down for the special value `-1` of `tryRight`.)
234 if contains(element, elementAtPoint) or tryRight == -1
235 found = true
236 # If we’re currently in a frame, there might be something on top of the
237 # frame that covers `element`. Therefore we ensure that the frame really is
238 # present at the point for each parent in `parents`.
239 currentWindow = window
240 for parent in parents by -1
241 # If leaving the devtools container take the devtools zoom into account.
242 if utils.isDevtoolsWindow(currentWindow)
243 docShell = currentWindow
244 .getInterface(Ci.nsIWebNavigation)
245 .QueryInterface(Ci.nsIDocShell)
246 if docShell
247 devtoolsZoom = docShell.contentViewer.fullZoom
248 offset.left *= devtoolsZoom
249 offset.top *= devtoolsZoom
250 x *= devtoolsZoom
251 y *= devtoolsZoom
252 dx *= devtoolsZoom
253 dy *= devtoolsZoom
254
255 offset.left += parent.offset.left
256 offset.top += parent.offset.top
257 elementAtPoint = parent.window.document.elementFromPoint(
258 offset.left + x + dx, offset.top + y + dy
259 )
260 firstLevel = false
261 unless contains(currentWindow.frameElement, elementAtPoint)
262 found = false
263 break
264 currentWindow = parent.window
265
266 return {x, y, offset} if found
267
268 return false if elementAtPoint == null or tryRight <= 0
269 rect = elementAtPoint.getBoundingClientRect()
270
271 # `.getBoundingClientRect()` does not include pseudo-elements that are
272 # absolutely positioned so that they go outside of the element (which is
273 # common for `/###\`-looking tabs), but calling `.elementAtPoint()` on the
274 # pseudo-element _does_ return the element. This means that the covering
275 # element’s _rect_ won’t cover the element we’re looking for. If so, it’s
276 # better to try again, forcing the element to be considered located at this
277 # point. That’s what `-1` for the `tryRight` argument means. This is also used
278 # in the 'complementary' pass, to include elements considered covered in
279 # earlier passes (which might have been false positives).
280 if firstLevel and rect.right <= x + offset.left
281 return tryPoint(elementData, elementRect, x, dx, y, dy, -1)
282
283 # If `elementAtPoint` is a parent to `element`, it most likely means that
284 # `element` is hidden some way. It can also mean that a pseudo-element of
285 # `elementAtPoint` covers `element` partly. Therefore, try once at the most
286 # likely point: The center of the part of the rect to the right of `x`.
287 if elementRect.right > x and contains(elementAtPoint, element)
288 return tryPoint(
289 elementData, elementRect,
290 (x + elementRect.right) / 2, 0, y, 0, 0
291 )
292
293 newX = rect.right - offset.left + 1
294 return false if newX > viewport.right or newX > elementRect.right
295 return tryPoint(elementData, elementRect, newX, 0, y, 0, tryRight - 1)
296
297 # In XUL documents there are “anonymous” elements. These are never returned by
298 # `document.elementFromPoint` but their closest non-anonymous parents are.
299 # The same is true for Web Components (where their hosts are returned), with
300 # the further caveat that they might be nested.
301 # Note: getBindingParent() has been removed from fx72.
302 normalize = (element) ->
303 element = e while (e = element.ownerDocument.getBindingParent?(element))?
304 element = e while (e = element.containingShadowRoot?.host)? # >=fx72
305 element = element.parentNode while element.prefix?
306 return element
307
308 # Returns whether `element` corresponds to `elementAtPoint`. This is only
309 # complicated for browser elements in the web page content area.
310 # `.elementAtPoint()` always returns `<tabbrowser#content>` then. The element
311 # might be in another tab and thus invisible, but `<tabbrowser#content>` is the
312 # same and visible in _all_ tabs, so we have to check that the element really
313 # belongs to the current tab.
314 contains = (element, elementAtPoint) ->
315 return false unless elementAtPoint
316 container = normalize(element)
317 if elementAtPoint.localName == 'tabbrowser' and elementAtPoint.id == 'content'
318 {gBrowser} = element.ownerGlobal.top
319 tabpanel = gBrowser.getNotificationBox(gBrowser.selectedBrowser)
320 return tabpanel.contains(element)
321 else
322 # Note that `a.contains(a)` is supposed to be true, but strangely aren’t for
323 # `<menulist>`s in the Add-ons Manager, so do a direct comparison as well.
324 return container == elementAtPoint or container.contains(elementAtPoint)
325
326 module.exports = {
327 find
328 }
Imprint / Impressum