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