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