]> git.gir.st - VimFx.git/blob - extension/lib/markable-elements.coffee
Include possibly covered elements for complementary hints
[VimFx.git] / extension / lib / markable-elements.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013.
3 # Copyright Simon Lydell 2013, 2014, 2015, 2016.
4 #
5 # This file is part of VimFx.
6 #
7 # VimFx is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # VimFx is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
19 ###
20
21 # This file contains functions for getting markable elements and related data.
22
23 utils = require('./utils')
24 viewportUtils = require('./viewport')
25
26 {devtools} = Cu.import('resource://devtools/shared/Loader.jsm', {})
27
28 Element = Ci.nsIDOMElement
29 XULDocument = Ci.nsIDOMXULDocument
30
31 find = (window, filter, selector = '*') ->
32 viewport = viewportUtils.getWindowViewport(window)
33 wrappers = []
34 getMarkableElements(window, viewport, wrappers, filter, selector)
35 return wrappers
36
37 # `filter` is a function that is given every element in every frame of the page.
38 # It should return wrapper objects for markable elements and a falsy value for
39 # all other elements. All returned wrappers are added to `wrappers`. `wrappers`
40 # is modified instead of using return values to avoid array concatenation for
41 # each frame. It might sound expensive to go through _every_ element, but that’s
42 # actually what other methods like using XPath or CSS selectors would need to do
43 # anyway behind the scenes. However, it is possible to pass in a CSS selector,
44 # which allows getting markable elements in several passes with different sets
45 # of candidates.
46 getMarkableElements = (
47 window, viewport, wrappers, filter, selector, parents = []
48 ) ->
49 {document} = window
50
51 for element in getAllElements(document, selector)
52 continue unless element instanceof Element
53 # `getRects` is fast and filters out most elements, so run it first of all.
54 rects = getRects(element, viewport)
55 continue unless rects.length > 0
56 continue unless wrapper = filter(
57 element, (elementArg, tryRight = 1) ->
58 return getElementShape(
59 {window, viewport, parents, element: elementArg}, tryRight,
60 if elementArg == element then rects else null
61 )
62 )
63 wrappers.push(wrapper)
64
65 for frame in window.frames when frame.frameElement
66 continue unless result = viewportUtils.getFrameViewport(
67 frame.frameElement, viewport
68 )
69 {viewport: frameViewport, offset} = result
70 getMarkableElements(
71 frame, frameViewport, wrappers, filter, selector,
72 parents.concat({window, offset})
73 )
74
75 return
76
77 getAllElements = (document, selector) ->
78 unless document instanceof XULDocument
79 return document.querySelectorAll(selector)
80
81 # Use a `Set` since this algorithm may find the same element more than once.
82 # Ideally we should find a way to find all elements without duplicates.
83 elements = new Set()
84 getAllRegular = (element) ->
85 # The first time `zF` is run `.getElementsByTagName('*')` may oddly include
86 # `undefined` in its result! Filter those out. (Also, `selector` is ignored
87 # here since it doesn’t make sense in XUL documents because of all the
88 # trickery around anonymous elements.)
89 for child in element.getElementsByTagName('*') when child
90 elements.add(child)
91 getAllAnonymous(child)
92 return
93 getAllAnonymous = (element) ->
94 for child in document.getAnonymousNodes(element) or []
95 continue unless child instanceof Element
96 elements.add(child)
97 getAllRegular(child)
98 return
99 getAllRegular(document.documentElement)
100 return Array.from(elements)
101
102 getRects = (element, viewport) ->
103 # `element.getClientRects()` returns a list of rectangles, usually just one,
104 # which is identical to the one returned by `element.getBoundingClientRect()`.
105 # However, if `element` is inline and line-wrapped, then it returns one
106 # rectangle for each line, since each line may be of different length, for
107 # example. That allows us to properly add hints to line-wrapped links.
108 return Array.filter(
109 element.getClientRects(),
110 (rect) -> viewportUtils.isInsideViewport(rect, viewport)
111 )
112
113 # Returns the “shape” of an element:
114 #
115 # - `nonCoveredPoint`: The coordinates of the first point of the element that
116 # isn’t covered by another element (except children of the element). It also
117 # contains the offset needed to make those coordinates relative to the top
118 # frame, as well as the rectangle that the coordinates occur in. It is `null`
119 # if the element is outside `viewport` or entirely covered by other elements.
120 # - `area`: The area of the part of the element that is inside the viewport.
121 getElementShape = (elementData, tryRight, rects = null) ->
122 {viewport, element} = elementData
123 result = {nonCoveredPoint: null, area: 0}
124
125 rects ?= getRects(element, viewport)
126 totalArea = 0
127 visibleRects = []
128 for rect in rects
129 visibleRect = viewportUtils.adjustRectToViewport(rect, viewport)
130 continue if visibleRect.area == 0
131 totalArea += visibleRect.area
132 visibleRects.push(visibleRect)
133
134 if visibleRects.length == 0
135 if rects.length == 1 and totalArea == 0
136 [rect] = rects
137 if rect.width > 0 or rect.height > 0
138 # If we get here, it means that everything inside `element` is floated
139 # and/or absolutely positioned (and that `element` hasn’t been made to
140 # “contain” the floats). For example, a link in a menu could contain a
141 # span of text floated to the left and an icon floated to the right.
142 # Those are still clickable. Therefore we return the shape of the first
143 # visible child instead. At least in that example, that’s the best bet.
144 for child in element.children
145 childData = Object.assign({}, elementData, {element: child})
146 shape = getElementShape(childData, tryRight)
147 return shape if shape
148 return result
149
150 result.area = totalArea
151
152 # Even if `element` has a visible rect, it might be covered by other elements.
153 for visibleRect in visibleRects
154 nonCoveredPoint = getFirstNonCoveredPoint(
155 elementData, visibleRect, tryRight
156 )
157 break if nonCoveredPoint
158
159 result.nonCoveredPoint = nonCoveredPoint
160 return result
161
162 getFirstNonCoveredPoint = (elementData, elementRect, tryRight) ->
163 # Try the left-middle point, or immediately to the right of a covering element
164 # at that point (when `tryRight == 1`). If both of those are covered the whole
165 # element is considered to be covered. The reasoning is:
166 #
167 # - A marker should show up as near the left edge of its visible area as
168 # possible. Having it appear to the far right (for example) is confusing.
169 # - We can’t try too many times because of performance.
170 # - We used to try left-top first, but if the element has `border-radius`, the
171 # corners won’t belong to the element, so `document.elementFromPoint()` will
172 # return whatever is behind. One _could_ temporarily add a CSS class that
173 # removes `border-radius`, but that turned out to be too slow. Trying
174 # left-middle instead avoids the problem, and looks quite nice, actually.
175 # - We used to try left-bottom as well, but that is so rare that it’s not
176 # worth it.
177 #
178 # It is safer to try points at least one pixel into the element from the
179 # edges, hence the `+1`.
180 {left, top, bottom, height} = elementRect
181 return tryPoint(
182 elementData, left, +1, Math.floor(top + height / 2), 0, tryRight
183 )
184
185 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset) if
186 # the element passes the tests. Otherwise it tries to the right of whatever is
187 # at `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
188 # and `dy` are used to offset the wanted point `(x, y)` while trying.
189 tryPoint = (elementData, x, dx, y, dy, tryRight = 0) ->
190 {window, viewport, parents, element} = elementData
191 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
192 offset = {left: 0, top: 0}
193 found = false
194 firstLevel = true
195
196 # Ensure that `element`, or a child of `element` (anything inside an `<a>` is
197 # clickable too), really is present at (x,y). Note that this is not 100%
198 # bullet proof: Combinations of CSS can cause this check to fail, even though
199 # `element` isn’t covered. We don’t try to temporarily reset such CSS because
200 # of performance. (See further down for the special value `-1` of `tryRight`.)
201 if contains(element, elementAtPoint) or tryRight == -1
202 found = true
203 # If we’re currently in a frame, there might be something on top of the
204 # frame that covers `element`. Therefore we ensure that the frame really is
205 # present at the point for each parent in `parents`.
206 currentWindow = window
207 for parent in parents by -1
208 # If leaving the devtools container take the devtools zoom into account.
209 if utils.isDevtoolsWindow(currentWindow)
210 toolbox = window.top.gDevTools.getToolbox(
211 devtools.TargetFactory.forTab(window.top.gBrowser.selectedTab)
212 )
213 if toolbox
214 devtoolsZoom = toolbox.zoomValue
215 offset.left *= devtoolsZoom
216 offset.top *= devtoolsZoom
217 x *= devtoolsZoom
218 y *= devtoolsZoom
219 dx *= devtoolsZoom
220 dy *= devtoolsZoom
221
222 offset.left += parent.offset.left
223 offset.top += parent.offset.top
224 elementAtPoint = parent.window.document.elementFromPoint(
225 offset.left + x + dx, offset.top + y + dy
226 )
227 firstLevel = false
228 unless contains(currentWindow.frameElement, elementAtPoint)
229 found = false
230 break
231 currentWindow = parent.window
232
233 return {x, y, offset} if found
234
235 return false if elementAtPoint == null or tryRight <= 0
236 rect = elementAtPoint.getBoundingClientRect()
237
238 # `.getBoundingClientRect()` does not include pseudo-elements that are
239 # absolutely positioned so that they go outside of the element (which is
240 # common for `/###\`-looking tabs), but calling `.elementAtPoint()` on the
241 # pseudo-element _does_ return the element. This means that the covering
242 # element’s _rect_ won’t cover the element we’re looking for. If so, it’s
243 # better to try again, forcing the element to be considered located at this
244 # point. That’s what `-1` for the `tryRight` argument means. This is also used
245 # in the 'complementary' pass, to include elements considered covered in
246 # earlier passes (which might have been false positives).
247 if firstLevel and rect.right <= x + offset.left
248 return tryPoint(elementData, x, dx, y, dy, -1)
249
250 x = rect.right - offset.left + 1
251 return false if x > viewport.right
252 return tryPoint(elementData, x, 0, y, 0, tryRight - 1)
253
254 # In XUL documents there are “anonymous” elements. These are never returned by
255 # `document.elementFromPoint` but their closest non-anonymous parents are.
256 normalize = (element) ->
257 normalized = element.ownerDocument.getBindingParent(element) or element
258 normalized = normalized.parentNode while normalized.prefix?
259 return normalized
260
261 # Returns whether `element` corresponds to `elementAtPoint`. This is only
262 # complicated for browser elements in the web page content area.
263 # `.elementAtPoint()` always returns `<tabbrowser#content>` then. The element
264 # might be in another tab and thus invisible, but `<tabbrowser#content>` is the
265 # same and visible in _all_ tabs, so we have to check that the element really
266 # belongs to the current tab.
267 contains = (element, elementAtPoint) ->
268 return false unless elementAtPoint
269 container = normalize(element)
270 if elementAtPoint.localName == 'tabbrowser' and elementAtPoint.id == 'content'
271 {gBrowser} = element.ownerGlobal.top
272 tabpanel = gBrowser.getNotificationBox(gBrowser.selectedBrowser)
273 return tabpanel.contains(element)
274 else
275 # Note that `a.contains(a)` is supposed to be true, but strangely aren’t for
276 # `<menulist>`s in the Add-ons Manager, so do a direct comparison as well.
277 return container == elementAtPoint or container.contains(elementAtPoint)
278
279 module.exports = {
280 find
281 }
Imprint / Impressum