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