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