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