]> git.gir.st - VimFx.git/blob - extension/lib/markable-elements.coffee
Update nl locale (#731)
[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) ->
58 return getElementShape(
59 window, viewport, parents, elementArg,
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 `element`:
114 #
115 # - `nonCoveredPoint`: The coordinates of the first point of `element` that
116 # isn’t covered by another element (except children of `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.
119 # - `area`: The area of the part of `element` that is inside `viewport`.
120 #
121 # Returns `null` if `element` is outside `viewport` or entirely covered by other
122 # elements.
123 getElementShape = (window, viewport, parents, element, rects = null) ->
124 rects ?= getRects(element, viewport)
125 totalArea = 0
126 visibleRects = []
127 for rect in rects
128 visibleRect = viewportUtils.adjustRectToViewport(rect, viewport)
129 continue if visibleRect.area == 0
130 totalArea += visibleRect.area
131 visibleRects.push(visibleRect)
132
133 if visibleRects.length == 0
134 if rects.length == 1 and totalArea == 0
135 [rect] = rects
136 if rect.width > 0 or rect.height > 0
137 # If we get here, it means that everything inside `element` is floated
138 # and/or absolutely positioned (and that `element` hasn’t been made to
139 # “contain” the floats). For example, a link in a menu could contain a
140 # span of text floated to the left and an icon floated to the right.
141 # Those are still clickable. Therefore we return the shape of the first
142 # visible child instead. At least in that example, that’s the best bet.
143 for child in element.children
144 shape = getElementShape(window, viewport, parents, child)
145 return shape if shape
146 return null
147
148 # Even if `element` has a visible rect, it might be covered by other elements.
149 for visibleRect in visibleRects
150 nonCoveredPoint = getFirstNonCoveredPoint(
151 window, viewport, element, visibleRect, parents
152 )
153 break if nonCoveredPoint
154
155 return null unless nonCoveredPoint
156
157 return {
158 nonCoveredPoint, area: totalArea
159 }
160
161 getFirstNonCoveredPoint = (window, viewport, element, elementRect, parents) ->
162 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset)
163 # if it passes the tests. Otherwise it tries to the right of whatever is at
164 # `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
165 # and `dy` are used to offset the wanted point `(x, y)` while trying (see the
166 # invocations of `tryPoint` below).
167 tryPoint = (x, dx, y, dy, tryRight = 0) ->
168 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
169 offset = {left: 0, top: 0}
170 found = false
171 firstLevel = true
172
173 # Ensure that `element`, or a child of `element` (anything inside an `<a>`
174 # is clickable too), really is present at (x,y). Note that this is not 100%
175 # bullet proof: Combinations of CSS can cause this check to fail, even
176 # though `element` isn’t covered. We don’t try to temporarily reset such CSS
177 # because of performance. Instead we rely on that some of the attempts below
178 # will work. (See further down for the special value `-1` of `tryRight`.)
179 if contains(element, elementAtPoint) or tryRight == -1
180 found = true
181 # If we’re currently in a frame, there might be something on top of the
182 # frame that covers `element`. Therefore we ensure that the frame really
183 # is present at the point for each parent in `parents`.
184 currentWindow = window
185 for parent in parents by -1
186 # If leaving the devtools container take the devtools zoom into account.
187 if utils.isDevtoolsWindow(currentWindow)
188 toolbox = window.top.gDevTools.getToolbox(
189 devtools.TargetFactory.forTab(window.top.gBrowser.selectedTab)
190 )
191 if toolbox
192 devtoolsZoom = toolbox.zoomValue
193 offset.left *= devtoolsZoom
194 offset.top *= devtoolsZoom
195 x *= devtoolsZoom
196 y *= devtoolsZoom
197 dx *= devtoolsZoom
198 dy *= devtoolsZoom
199
200 offset.left += parent.offset.left
201 offset.top += parent.offset.top
202 elementAtPoint = parent.window.document.elementFromPoint(
203 offset.left + x + dx, offset.top + y + dy
204 )
205 firstLevel = false
206 unless contains(currentWindow.frameElement, elementAtPoint)
207 found = false
208 break
209 currentWindow = parent.window
210
211 return {x, y, offset} if found
212
213 return false if elementAtPoint == null or tryRight <= 0
214 rect = elementAtPoint.getBoundingClientRect()
215
216 # `.getBoundingClientRect()` does not include pseudo-elements that are
217 # absolutely positioned so that they go outside of the element (which is
218 # common for `/###\`-looking tabs), but calling `.elementAtPoint()` on the
219 # pseudo-element _does_ return the element. This means that the covering
220 # element’s _rect_ won’t cover the element we’re looking for. If so, it’s
221 # better to try again, forcing the element to be considered located at this
222 # point. That’s what `-1` for the `tryRight` argument means.
223 if firstLevel and rect.right <= x + offset.left
224 return tryPoint(x, dx, y, dy, -1)
225
226 x = rect.right - offset.left + 1
227 return false if x > viewport.right
228 return tryPoint(x, 0, y, 0, tryRight - 1)
229
230
231 # Try the left-middle point, or immediately to the right of a covering element
232 # at that point. If both of those are covered the whole element is considered
233 # to be covered. The reasoning is:
234 #
235 # - A marker should show up as near the left edge of its visible area as
236 # possible. Having it appear to the far right (for example) is confusing.
237 # - We can’t try too many times because of performance.
238 # - We used to try left-top first, but if `element` has `border-radius`, the
239 # corners won’t really belong to `element`, so `document.elementFromPoint()`
240 # will return whatever is behind. This will result in missing or
241 # out-of-place markers. The solution is to temporarily add a CSS class that
242 # removes `border-radius`, but that turned out to be rather slow, making it
243 # not worth it. Usually you don’t see the difference between left-top and
244 # left-middle, because links are usually not that high.
245 # - We used to try left-bottom as well, but that is so rare that it’s not
246 # worth it.
247 #
248 # It is safer to try points at least one pixel into the element from the
249 # edges, hence the `+1`.
250 {left, top, bottom, height} = elementRect
251 nonCoveredPoint = tryPoint(left, +1, Math.floor(top + height / 2), 0, 1)
252
253 return nonCoveredPoint
254
255 # In XUL documents there are “anonymous” elements. These are never returned by
256 # `document.elementFromPoint` but their closest non-anonymous parents are.
257 normalize = (element) ->
258 normalized = element.ownerDocument.getBindingParent(element) or element
259 normalized = normalized.parentNode while normalized.prefix?
260 return normalized
261
262 # Returns whether `element` corresponds to `elementAtPoint`. This is only
263 # complicated for browser elements in the web page content area.
264 # `.elementAtPoint()` always returns `<tabbrowser#content>` then. The element
265 # might be in another tab and thus invisible, but `<tabbrowser#content>` is the
266 # same and visible in _all_ tabs, so we have to check that the element really
267 # belongs to the current tab.
268 contains = (element, elementAtPoint) ->
269 return false unless elementAtPoint
270 container = normalize(element)
271 if elementAtPoint.localName == 'tabbrowser' and elementAtPoint.id == 'content'
272 {gBrowser} = element.ownerGlobal.top
273 tabpanel = gBrowser.getNotificationBox(gBrowser.selectedBrowser)
274 return tabpanel.contains(element)
275 else
276 # Note that `a.contains(a)` is supposed to be true, but strangely aren’t for
277 # `<menulist>`s in the Add-ons Manager, so do a direct comparison as well.
278 return container == elementAtPoint or container.contains(elementAtPoint)
279
280 module.exports = {
281 find
282 }
Imprint / Impressum