]> git.gir.st - VimFx.git/blob - extension/lib/hints.coffee
Fix hints mode not exiting when focusing text input
[VimFx.git] / extension / lib / hints.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013.
3 # Copyright Simon Lydell 2013, 2014, 2015.
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 # as well as for creating and inserting markers for markable elements.
23
24 huffman = require('n-ary-huffman')
25 {Marker} = require('./marker')
26 utils = require('./utils')
27
28 CONTAINER_ID = 'VimFxMarkersContainer'
29
30 Element = Ci.nsIDOMElement
31 XULDocument = Ci.nsIDOMXULDocument
32
33 # For some time we used to return the hints container from `injectHints`, and
34 # use that reference to remove the hints when needed. That’s fine in theory, but
35 # in case anything breaks we might loose that reference and end up with
36 # unremovable hints on the screen. Explicitly looking for an element with the
37 # container ID is more fail-safe.
38 removeHints = (window) ->
39 window.document.getElementById(CONTAINER_ID)?.remove()
40
41 # Create `Marker`s for every element (represented by a regular object of data
42 # about the element—a “wrapper,” a stand-in for the real element, which is only
43 # accessible in frame scripts) in `wrappers`, and insert them into `window`.
44 injectHints = (window, wrappers, viewport, options) ->
45 semantic = []
46 unsemantic = []
47 combined = []
48 markerMap = {}
49
50 for wrapper in wrappers
51 marker = new Marker(wrapper, window.document)
52 group = switch
53 when wrapper.parentIndex? then combined
54 when wrapper.semantic then semantic
55 else unsemantic
56 group.push(marker)
57 markerMap[wrapper.elementIndex] = marker
58
59 markers = semantic.concat(unsemantic)
60
61 return null if markers.length == 0
62
63 # Each marker gets a unique `z-index`, so that it can be determined if a
64 # marker overlaps another. Put more important markers (higher weight) at the
65 # end, so that they get higher `z-index`, in order not to be overlapped.
66 zIndex = 0
67 setZIndexes = (markers) ->
68 markers.sort((a, b) -> a.weight - b.weight)
69 for marker in markers when marker not instanceof huffman.BranchPoint
70 marker.markerElement.style.zIndex = zIndex++
71 # Add `z-index` space for all the children of the marker.
72 zIndex += marker.wrapper.numChildren if marker.wrapper.numChildren?
73 return
74
75 # The `markers` passed to this function have been sorted by `setZIndexes` in
76 # advance, so we can skip sorting in the `huffman.createTree` function.
77 hintChars = options.hint_chars
78 createHuffmanTree = (markers) ->
79 return huffman.createTree(markers, hintChars.length, {sorted: true})
80
81 # Semantic elements should always get better hints and higher `z-index`:es
82 # than unsemantic ones, even if they are smaller. The former is achieved by
83 # putting the unsemantic elements in their own branch of the huffman tree.
84 if unsemantic.length > 0
85 if markers.length > hintChars.length
86 setZIndexes(unsemantic)
87 subTree = createHuffmanTree(unsemantic)
88 semantic.push(subTree)
89 else
90 semantic.push(unsemantic...)
91
92 setZIndexes(semantic)
93
94 tree = createHuffmanTree(semantic)
95 tree.assignCodeWords(hintChars, (marker, hint) -> marker.setHint(hint))
96
97 # Markers for links with the same href can be combined to use the same hint.
98 # They should all have the same `z-index` (because they all have the same
99 # combined weight), but in case any of them cover another they still get a
100 # unique `z-index` (space for this was added in `setZIndexes`).
101 for marker in combined
102 parent = markerMap[marker.wrapper.parentIndex]
103 marker.markerElement.style.zIndex = parent.markerElement.style.zIndex++
104 marker.setHint(parent.hint)
105 markers.push(combined...)
106
107 removeHints(window) # Better safe than sorry.
108 container = window.document.createElement('box')
109 container.id = CONTAINER_ID
110 window.gBrowser.mCurrentBrowser.parentNode.appendChild(container)
111
112 zoom =
113 if window.ZoomManager.useFullZoom
114 window.ZoomManager.getZoomForBrowser(window.gBrowser.selectedBrowser)
115 else
116 # If “full zoom” is not used, it means that “Zoom text only” is enabled.
117 # If so, that “zoom” does not need to be taken into account.
118 1
119
120 for marker in markers
121 container.appendChild(marker.markerElement)
122 # Must be done after the hints have been inserted into the DOM (see
123 # marker.coffee).
124 marker.setPosition(viewport, zoom)
125
126 return markers
127
128
129 getMarkableElementsAndViewport = (window, filter) ->
130 {
131 clientWidth, clientHeight # Viewport size excluding scrollbars, usually.
132 scrollWidth, scrollHeight
133 } = window.document.documentElement
134 {innerWidth, innerHeight} = window # Viewport size including scrollbars.
135 # We don’t want markers to cover the scrollbars, so we should use
136 # `clientWidth` and `clientHeight`. However, when there are no scrollbars
137 # those might be too small. Then we use `innerWidth` and `innerHeight`.
138 width = if scrollWidth > innerWidth then clientWidth else innerWidth
139 height = if scrollHeight > innerHeight then clientHeight else innerHeight
140 viewport = {
141 left: 0
142 top: 0
143 right: width
144 bottom: height
145 width
146 height
147 }
148
149 wrappers = []
150 getMarkableElements(window, viewport, wrappers, filter)
151 return {wrappers, viewport}
152
153 # `filter` is a function that is given every element in every frame of the page.
154 # It should return wrapper objects for markable elements and a falsy value for
155 # all other elements. All returned wrappers are added to `wrappers`. `wrappers`
156 # is modified instead of using return values to avoid array concatenation for
157 # each frame. It might sound expensive to go through _every_ element, but that’s
158 # actually what other methods like using XPath or CSS selectors would need to do
159 # anyway behind the scenes.
160 getMarkableElements = (window, viewport, wrappers, filter, parents = []) ->
161 {document} = window
162
163 for element in getAllElements(document) when element instanceof Element
164 # `getRects` is fast and filters out most elements, so run it first of all.
165 rects = getRects(element, viewport)
166 continue unless rects.length > 0
167 continue unless wrapper = filter(
168 element, getElementShape.bind(null, window, viewport, rects, parents)
169 )
170 wrappers.push(wrapper)
171
172 for frame in window.frames
173 rect = frame.frameElement.getBoundingClientRect() # Frames only have one.
174 continue unless isInsideViewport(rect, viewport)
175
176 # Calculate the visible part of the frame, according to the parent.
177 {clientWidth, clientHeight} = frame.document.documentElement
178 frameViewport =
179 left: Math.max(viewport.left - rect.left, 0)
180 top: Math.max(viewport.top - rect.top, 0)
181 right: clientWidth + Math.min(viewport.right - rect.right, 0)
182 bottom: clientHeight + Math.min(viewport.bottom - rect.bottom, 0)
183
184 # `.getComputedStyle()` may return `null` if the computed style isn’t
185 # availble yet. If so, consider the element not visible.
186 continue unless computedStyle = window.getComputedStyle(frame.frameElement)
187 offset =
188 left: rect.left +
189 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
190 parseFloat(computedStyle.getPropertyValue('padding-left'))
191 top: rect.top +
192 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
193 parseFloat(computedStyle.getPropertyValue('padding-top'))
194
195 getMarkableElements(frame, frameViewport, wrappers, filter,
196 parents.concat({window, offset}))
197
198 return
199
200 getAllElements = (document) ->
201 unless document instanceof XULDocument
202 return document.getElementsByTagName('*')
203
204 elements = []
205 getAllRegular = (element) ->
206 for child in element.getElementsByTagName('*')
207 elements.push(child)
208 getAllAnonymous(child)
209 return
210 getAllAnonymous = (element) ->
211 for child in document.getAnonymousNodes(element) or []
212 continue unless child instanceof Element
213 elements.push(child)
214 getAllRegular(child)
215 return
216 getAllRegular(document.documentElement)
217 return elements
218
219 getRects = (element, viewport) ->
220 # `element.getClientRects()` returns a list of rectangles, usually just one,
221 # which is identical to the one returned by `element.getBoundingClientRect()`.
222 # However, if `element` is inline and line-wrapped, then it returns one
223 # rectangle for each line, since each line may be of different length, for
224 # example. That allows us to properly add hints to line-wrapped links.
225 return Array.filter(
226 element.getClientRects(), (rect) -> isInsideViewport(viewport, rect)
227 )
228
229 # Returns the “shape” of `element`:
230 #
231 # - `nonCoveredPoint`: The coordinates of the first point of `element` that
232 # isn’t covered by another element (except children of `element`). It also
233 # contains the offset needed to make those coordinates relative to the top
234 # frame, as well as the rectangle that the coordinates occur in.
235 # - `area`: The area of the part of `element` that is inside `viewport`.
236 #
237 # Returns `null` if `element` is outside `viewport` or entirely covered by other
238 # elements.
239 getElementShape = (window, viewport, rects, parents, element) ->
240 totalArea = 0
241 visibleRects = []
242 for rect in rects
243 visibleRect = adjustRectToViewport(rect, viewport)
244 continue if visibleRect.area == 0
245 totalArea += visibleRect.area
246 visibleRects.push(visibleRect)
247
248 if visibleRects.length == 0
249 if rects.length == 1 and totalArea == 0
250 [rect] = rects
251 if rect.width > 0 or rect.height > 0
252 # If we get here, it means that everything inside `element` is floated
253 # and/or absolutely positioned (and that `element` hasn’t been made to
254 # “contain” the floats). For example, a link in a menu could contain a
255 # span of text floated to the left and an icon floated to the right.
256 # Those are still clickable. Therefore we return the shape of the first
257 # visible child instead. At least in that example, that’s the best bet.
258 for child in element.children
259 shape = getElementShape(window, viewport, getRects(child, viewport),
260 parents, child)
261 return shape if shape
262 return null
263
264 # Even if `element` has a visible rect, it might be covered by other elements.
265 for visibleRect in visibleRects
266 nonCoveredPoint = getFirstNonCoveredPoint(window, viewport, element,
267 visibleRect, parents)
268 if nonCoveredPoint
269 nonCoveredPoint.rect = visibleRect
270 break
271
272 return null unless nonCoveredPoint
273
274 return {
275 nonCoveredPoint, area: totalArea
276 }
277
278
279 MINIMUM_EDGE_DISTANCE = 4
280 isInsideViewport = (rect, viewport) ->
281 return \
282 rect.left <= viewport.right - MINIMUM_EDGE_DISTANCE and
283 rect.top <= viewport.bottom + MINIMUM_EDGE_DISTANCE and
284 rect.right >= viewport.left + MINIMUM_EDGE_DISTANCE and
285 rect.bottom >= viewport.top - MINIMUM_EDGE_DISTANCE
286
287
288 adjustRectToViewport = (rect, viewport) ->
289 # The right and bottom values are subtracted by 1 because
290 # `document.elementFromPoint(right, bottom)` does not return the element
291 # otherwise.
292 left = Math.max(rect.left, viewport.left)
293 right = Math.min(rect.right - 1, viewport.right)
294 top = Math.max(rect.top, viewport.top)
295 bottom = Math.min(rect.bottom - 1, viewport.bottom)
296
297 # Make sure that `right >= left and bottom >= top`, since we subtracted by 1
298 # above.
299 right = Math.max(right, left)
300 bottom = Math.max(bottom, top)
301
302 width = right - left
303 height = bottom - top
304 area = Math.floor(width * height)
305
306 return {
307 left, right, top, bottom
308 height, width, area
309 }
310
311
312 getFirstNonCoveredPoint = (window, viewport, element, elementRect, parents) ->
313 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset)
314 # if it passes the tests. Otherwise it tries to the right of whatever is at
315 # `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
316 # and `dy` are used to offset the wanted point `(x, y)` while trying (see the
317 # invocations of `tryPoint` below).
318 tryPoint = (x, dx, y, dy, tryRight = 0) ->
319 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
320 offset = {left: 0, top: 0}
321 found = false
322
323 # Ensure that `element`, or a child of `element` (anything inside an `<a>`
324 # is clickable too), really is present at (x,y). Note that this is not 100%
325 # bullet proof: Combinations of CSS can cause this check to fail, even
326 # though `element` isn’t covered. We don’t try to temporarily reset such CSS
327 # because of performance. Instead we rely on that some of the attempts below
328 # will work.
329 if element.contains(elementAtPoint) or # Note that `a.contains(a) == true`!
330 (window.document instanceof XULDocument and
331 getClosestNonAnonymousParent(element) == elementAtPoint)
332 found = true
333 # If we’re currently in a frame, there might be something on top of the
334 # frame that covers `element`. Therefore we ensure that the frame really
335 # is present at the point for each parent in `parents`.
336 currentWindow = window
337 for parent in parents by -1
338 offset.left += parent.offset.left
339 offset.top += parent.offset.top
340 elementAtPoint = parent.window.document.elementFromPoint(
341 offset.left + x + dx, offset.top + y + dy
342 )
343 unless elementAtPoint == currentWindow.frameElement
344 found = false
345 break
346 currentWindow = parent.window
347
348 if found
349 return {x, y, offset}
350 else
351 return false if elementAtPoint == null or tryRight == 0
352 rect = elementAtPoint.getBoundingClientRect()
353 x = rect.right - offset.left + 1
354 return false if x > viewport.right
355 return tryPoint(x, 0, y, 0, tryRight - 1)
356
357
358 # Try the left-middle point, or immediately to the right of a covering element
359 # at that point. If both of those are covered the whole element is considered
360 # to be covered. The reasoning is:
361 #
362 # - A marker should show up as near the left edge of its visible area as
363 # possible. Having it appear to the far right (for example) is confusing.
364 # - We can’t try too many times because of performance.
365 # - We used to try left-top first, but if `element` has `border-radius`, the
366 # corners won’t really belong to `element`, so `document.elementFromPoint()`
367 # will return whatever is behind. This will result in missing or
368 # out-of-place markers. The solution is to temporarily add a CSS class that
369 # removes `border-radius`, but that turned out to be rather slow, making it
370 # not worth it. Usually you don’t see the difference between left-top and
371 # left-middle, because links are usually not that high.
372 # - We used to try left-bottom as well, but that is so rare that it’s not
373 # worth it.
374 #
375 # It is safer to try points at least one pixel into the element from the
376 # edges, hence the `+1`.
377 {left, top, bottom, height} = elementRect
378 nonCoveredPoint = tryPoint(left, +1, Math.floor(top + height / 2), 0, 1)
379
380 return nonCoveredPoint
381
382 # In XUL documents there are “anonymous” elements, whose node names start with
383 # `xul:` or `html:`. These are never returned by `document.elementFromPoint` but
384 # their closest non-anonymous parents are.
385 getClosestNonAnonymousParent = (element) ->
386 element = element.parentNode while element.prefix?
387 return element
388
389 module.exports = {
390 removeHints
391 injectHints
392 getMarkableElementsAndViewport
393 }
Imprint / Impressum