]> git.gir.st - VimFx.git/blob - extension/lib/mode-hints/hints.coffee
Give better hints to semantic elements than unsemantic ones
[VimFx.git] / extension / lib / mode-hints / hints.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013.
3 # Copyright Simon Lydell 2013, 2014.
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 utils = require('../utils')
22 { getPref } = require('../prefs')
23 { Marker } = require('./marker')
24 huffman = require('n-ary-huffman')
25
26 { interfaces: Ci } = Components
27
28 HTMLDocument = Ci.nsIDOMHTMLDocument
29 XULDocument = Ci.nsIDOMXULDocument
30
31 CONTAINER_ID = 'VimFxHintMarkerContainer'
32 Z_INDEX_START = 2147480001 # The highest `z-index` used in style.css plus one.
33 # In theory, `z-index` can be infinitely large. In practice, Firefox uses a
34 # 32-bit signed integer to store it, so the maximum value is 2147483647
35 # (http://www.puidokas.com/max-z-index/). Youtube (insanely) uses 1999999999 for
36 # its top bar. So by using 2147480001 as a base, we trump that value with lots
37 # of margin, still leaving a few thousand values for markers, which should be
38 # more than enough. Hopefully no sites are crazy enough to use even higher
39 # values.
40
41
42 removeHints = (document) ->
43 document.getElementById(CONTAINER_ID)?.remove()
44
45
46 injectHints = (window) ->
47 { document } = window
48
49 { clientWidth, clientHeight } = document.documentElement
50 viewport =
51 left: 0
52 top: 0
53 right: clientWidth
54 bottom: clientHeight
55 width: clientWidth
56 height: clientHeight
57 scrollX: window.scrollX
58 scrollY: window.scrollY
59 markers = createMarkers(window, viewport)
60
61 return 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 = Z_INDEX_START
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.setProperty('z-index', zIndex++, 'important')
71
72 # The `markers` passed to this function have been sorted by `setZIndexes` in
73 # advance, so we can skip sorting in the `huffman.createTree` function.
74 hintChars = utils.getHintChars()
75 createHuffmanTree = (markers) ->
76 return huffman.createTree(markers, hintChars.length, {sorted: true})
77
78 semantic = []
79 unsemantic = []
80 for marker in markers
81 marker.weight = marker.elementShape.area
82 if utils.isElementClickable(marker.element)
83 semantic.push(marker)
84 else
85 unsemantic.push(marker)
86
87 # Semantic elements should always get better hints than unsemantic ones, even
88 # if they are smaller. This is achieved by putting the unsemantic elements in
89 # their own branch of the huffman tree.
90 if unsemantic.length > 0
91 if markers.length > hintChars.length
92 setZIndexes(unsemantic)
93 subTree = createHuffmanTree(unsemantic)
94 semantic.push(subTree)
95 else
96 semantic.push(unsemantic...)
97
98 setZIndexes(semantic)
99
100 tree = createHuffmanTree(semantic)
101 tree.assignCodeWords(hintChars, (marker, hint) -> marker.setHint(hint))
102
103 removeHints(document)
104 container = utils.createElement(document, 'div', {id: CONTAINER_ID})
105 document.documentElement.appendChild(container)
106
107 for marker in markers
108 container.appendChild(marker.markerElement)
109 # Must be done after the hints have been inserted into the DOM (see
110 # marker.coffee).
111 marker.setPosition(viewport)
112
113 return markers
114
115 createMarkers = (window, viewport, parents = []) ->
116 { document } = window
117 markers = []
118
119 # For now we aren't able to handle hint markers in XUL Documents :(
120 return [] unless document instanceof HTMLDocument
121
122 candidates = utils.getMarkableElements(document, {type: 'all'})
123 for element in candidates
124 shape = getElementShape(window, element, viewport, parents)
125 # If `element` has no visible shape then it shouldn’t get any marker.
126 continue unless shape
127
128 markers.push(new Marker(element, shape))
129
130 for frame in window.frames
131 rect = frame.frameElement.getBoundingClientRect() # Frames only have one.
132 continue unless isInsideViewport(rect, viewport)
133
134 # Calculate the visible part of the frame, according to the parent.
135 { clientWidth, clientHeight } = frame.document.documentElement
136 frameViewport =
137 left: Math.max(viewport.left - rect.left, 0)
138 top: Math.max(viewport.top - rect.top, 0)
139 right: clientWidth + Math.min(viewport.right - rect.right, 0)
140 bottom: clientHeight + Math.min(viewport.bottom - rect.bottom, 0)
141
142 # `.getComputedStyle()` may return `null` if the computed style isn’t
143 # availble yet. If so, consider the element not visible.
144 continue unless computedStyle = window.getComputedStyle(frame.frameElement)
145 offset =
146 left: rect.left +
147 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
148 parseFloat(computedStyle.getPropertyValue('padding-left'))
149 top: rect.top +
150 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
151 parseFloat(computedStyle.getPropertyValue('padding-top'))
152
153 frameMarkers = createMarkers(frame, frameViewport,
154 parents.concat({ window, offset }))
155 markers.push(frameMarkers...)
156
157 return markers
158
159 # Returns the “shape” of `element`:
160 #
161 # - `rects`: Its `.getClientRects()` rectangles.
162 # - `visibleRects`: The parts of rectangles out of the above that are inside
163 # `viewport`.
164 # - `nonCoveredPoint`: The coordinates of the first point of `element` that
165 # isn’t covered by another element (except children of `element`). It also
166 # contains the offset needed to make those coordinates relative to the top
167 # frame, as well as the rectangle that the coordinates occur in.
168 # - `area`: The area of the part of `element` that is inside `viewport`.
169 #
170 # Returns `null` if `element` is outside `viewport` or entirely covered by other
171 # elements.
172 getElementShape = (window, element, viewport, parents) ->
173 # `element.getClientRects()` returns a list of rectangles, usually just one,
174 # which is identical to the one returned by `element.getBoundingClientRect()`.
175 # However, if `element` is inline and line-wrapped, then it returns one
176 # rectangle for each line, since each line may be of different length, for
177 # example. That allows us to properly add hints to line-wrapped links.
178 rects = element.getClientRects()
179 totalArea = 0
180 visibleRects = []
181 for rect in rects when isInsideViewport(rect, viewport)
182 visibleRect = adjustRectToViewport(rect, viewport)
183 continue if visibleRect.area == 0
184 totalArea += visibleRect.area
185 visibleRects.push(visibleRect)
186
187 if visibleRects.length == 0
188 if rects.length == 1 and totalArea == 0
189 [ rect ] = rects
190 if rect.width > 0 or rect.height > 0
191 # If we get here, it means that everything inside `element` is floated
192 # and/or absolutely positioned (and that `element` hasn’t been made to
193 # “contain” the floats). For example, a link in a menu could contain a
194 # span of text floated to the left and an icon floated to the right.
195 # Those are still clickable. Therefore we return the shape of the first
196 # visible child instead. At least in that example, that’s the best bet.
197 for child in element.children
198 shape = getElementShape(window, child, viewport, parents)
199 return shape if shape
200 return null
201
202
203 # Even if `element` has a visible rect, it might be covered by other elements.
204 for visibleRect in visibleRects
205 nonCoveredPoint = getFirstNonCoveredPoint(window, viewport, element,
206 visibleRect, parents)
207 if nonCoveredPoint
208 nonCoveredPoint.rect = visibleRect
209 break
210
211 return null unless nonCoveredPoint
212
213 return {
214 rects, visibleRects, nonCoveredPoint, area: totalArea
215 }
216
217
218 MINIMUM_EDGE_DISTANCE = 4
219 isInsideViewport = (rect, viewport) ->
220 return \
221 rect.left <= viewport.right - MINIMUM_EDGE_DISTANCE and
222 rect.top <= viewport.bottom + MINIMUM_EDGE_DISTANCE and
223 rect.right >= viewport.left + MINIMUM_EDGE_DISTANCE and
224 rect.bottom >= viewport.top - MINIMUM_EDGE_DISTANCE
225
226
227 adjustRectToViewport = (rect, viewport) ->
228 # The right and bottom values are subtracted by 1 because
229 # `document.elementFromPoint(right, bottom)` does not return the element
230 # otherwise.
231 left = Math.max(rect.left, viewport.left)
232 right = Math.min(rect.right - 1, viewport.right)
233 top = Math.max(rect.top, viewport.top)
234 bottom = Math.min(rect.bottom - 1, viewport.bottom)
235
236 # Make sure that `right >= left and bottom >= top`, since we subtracted by 1
237 # above.
238 right = Math.max(right, left)
239 bottom = Math.max(bottom, top)
240
241 width = right - left
242 height = bottom - top
243 area = Math.floor(width * height)
244
245 return {
246 left, right, top, bottom
247 height, width, area
248 }
249
250
251 getFirstNonCoveredPoint = (window, viewport, element, elementRect, parents) ->
252 # Before we start we need to hack around a little problem. If `element` has
253 # `border-radius`, the corners won’t really belong to `element`, so
254 # `document.elementFromPoint()` will return whatever is behind. This will
255 # result in missing or out-of-place markers. The solution is to temporarily
256 # add a CSS class that removes `border-radius`.
257 element.classList.add('VimFxNoBorderRadius')
258
259 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset)
260 # if it passes the tests. Otherwise it tries to the right of whatever is at
261 # `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
262 # and `dy` are used to offset the wanted point `(x, y)` while trying (see the
263 # invocations of `tryPoint` below).
264 tryPoint = (x, dx, y, dy, tryRight = 0) ->
265 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
266 offset = {left: 0, top: 0}
267 found = false
268
269 # Ensure that `element`, or a child of `element` (anything inside an `<a>`
270 # is clickable too), really is present at (x,y). Note that this is not 100%
271 # bullet proof: Combinations of CSS can cause this check to fail, even
272 # though `element` isn’t covered. We don’t try to temporarily reset such CSS
273 # (as with `border-radius`) because of performance. Instead we rely on that
274 # some of the attempts below will work.
275 if element.contains(elementAtPoint) # Note that `a.contains(a) == true`!
276 found = true
277 # If we’re currently in a frame, there might be something on top of the
278 # frame that covers `element`. Therefore we ensure that the frame really
279 # is present at the point for each parent in `parents`.
280 currentWindow = window
281 for parent in parents by -1
282 offset.left += parent.offset.left
283 offset.top += parent.offset.top
284 elementAtPoint = parent.window.document.elementFromPoint(
285 offset.left + x + dx, offset.top + y + dy
286 )
287 unless elementAtPoint == currentWindow.frameElement
288 found = false
289 break
290 currentWindow = parent.window
291
292 if found
293 return {x, y, offset}
294 else
295 return false if elementAtPoint == null or tryRight == 0
296 rect = elementAtPoint.getBoundingClientRect()
297 x = rect.right - offset.left + 1
298 return false if x > viewport.right
299 return tryPoint(x, 0, y, 0, tryRight - 1)
300
301
302 # Try the following 3 positions, or immediately to the right of a covering
303 # element at one of those positions, in order. If all of those are covered the
304 # whole element is considered to be covered. The reasoning is:
305 #
306 # - A marker should show up as near the left edge of its visible area as
307 # possible. Having it appear to the far right (for example) is confusing.
308 # - We can’t try too many times because of performance.
309 #
310 # +-------------------------------+
311 # |1 left-top |
312 # | |
313 # |2 left-middle |
314 # | |
315 # |3 left-bottom |
316 # +-------------------------------+
317 #
318 # It is safer to try points at least one pixel into the element from the
319 # edges, hence the `+1`s and `-1`s.
320 { left, top, bottom, height } = elementRect
321 nonCoveredPoint =
322 tryPoint(left, +1, top, +1, 1) or
323 tryPoint(left, +1, top + height / 2, 0, 1) or
324 tryPoint(left, +1, bottom, -1, 1)
325
326 element.classList.remove('VimFxNoBorderRadius')
327
328 return nonCoveredPoint
329
330
331 # Finds all stacks of markers that overlap each other (by using `getStackFor`)
332 # (#1), and rotates their `z-index`:es (#2), thus alternating which markers are
333 # visible.
334 rotateOverlappingMarkers = (originalMarkers, forward) ->
335 # Shallow working copy. This is necessary since `markers` will be mutated and
336 # eventually empty.
337 markers = originalMarkers[..]
338
339 # (#1)
340 stacks = (getStackFor(markers.pop(), markers) while markers.length > 0)
341
342 # (#2)
343 # Stacks of length 1 don't participate in any overlapping, and can therefore
344 # be skipped.
345 for stack in stacks when stack.length > 1
346 # This sort is not required, but makes the rotation more predictable.
347 stack.sort((a, b) -> a.markerElement.style.zIndex -
348 b.markerElement.style.zIndex)
349
350 # Array of z-indices.
351 indexStack = (marker.markerElement.style.zIndex for marker in stack)
352 # Shift the array of indices one item forward or back.
353 if forward
354 indexStack.unshift(indexStack.pop())
355 else
356 indexStack.push(indexStack.shift())
357
358 for marker, index in stack
359 marker.markerElement.style.setProperty('z-index', indexStack[index],
360 'important')
361
362 return
363
364 # Get an array containing `marker` and all markers that overlap `marker`, if
365 # any, which is called a "stack". All markers in the returned stack are spliced
366 # out from `markers`, thus mutating it.
367 getStackFor = (marker, markers) ->
368 stack = [marker]
369
370 { top, bottom, left, right } = marker.position
371
372 index = 0
373 while index < markers.length
374 nextMarker = markers[index]
375
376 next = nextMarker.position
377 overlapsVertically = (next.bottom >= top and next.top <= bottom)
378 overlapsHorizontally = (next.right >= left and next.left <= right)
379
380 if overlapsVertically and overlapsHorizontally
381 # Also get all markers overlapping this one.
382 markers.splice(index, 1)
383 stack = stack.concat(getStackFor(nextMarker, markers))
384 else
385 # Continue the search.
386 index++
387
388 return stack
389
390
391 exports.injectHints = injectHints
392 exports.removeHints = removeHints
393 exports.rotateOverlappingMarkers = rotateOverlappingMarkers
Imprint / Impressum