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