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