]> git.gir.st - VimFx.git/blob - extension/lib/viewport.coffee
Improve Find mode search start position
[VimFx.git] / extension / lib / viewport.coffee
1 ###
2 # Copyright Simon Lydell 2016.
3 #
4 # This file is part of VimFx.
5 #
6 # VimFx is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # VimFx is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
18 ###
19
20 # This file provides utility functions for working with the viewport.
21
22 utils = require('./utils')
23
24 MINIMUM_EDGE_DISTANCE = 4
25
26 adjustRectToViewport = (rect, viewport) ->
27 # The right and bottom values are subtracted by 1 because
28 # `document.elementFromPoint(right, bottom)` does not return the element
29 # otherwise.
30 left = Math.max(rect.left, viewport.left)
31 right = Math.min(rect.right - 1, viewport.right)
32 top = Math.max(rect.top, viewport.top)
33 bottom = Math.min(rect.bottom - 1, viewport.bottom)
34
35 # Make sure that `right >= left and bottom >= top`, since we subtracted by 1
36 # above.
37 right = Math.max(right, left)
38 bottom = Math.max(bottom, top)
39
40 width = right - left
41 height = bottom - top
42 area = Math.floor(width * height)
43
44 return {
45 left, right, top, bottom
46 height, width, area
47 }
48
49 getAllRangesInsideViewport = (window, viewport, offset = {left: 0, top: 0}) ->
50 selection = window.getSelection()
51 {rangeCount} = selection
52 ranges = []
53
54 if rangeCount > 0
55 {header, headerBottom, footer, footerTop} =
56 getFixedHeaderAndFooter(window, viewport)
57
58 # Many sites use `text-indent: -9999px;` or similar to hide text intended
59 # for screen readers only. That text can still be selected and found by
60 # searching, though. Therefore, we have to allow selection ranges that are
61 # within the viewport vertically but not horizontally, even though they
62 # actually are outside the viewport. Otherwise you won’t be able to press
63 # `n` to get past those elements (instead, `n` would start over from the top
64 # of the viewport).
65 for index in [0...rangeCount]
66 range = selection.getRangeAt(index)
67 continue if range.collapsed
68 rect = range.getBoundingClientRect()
69 if (rect.top >= headerBottom - MINIMUM_EDGE_DISTANCE and
70 rect.bottom <= footerTop + MINIMUM_EDGE_DISTANCE) or
71 header.contains(range.commonAncestorContainer) or
72 footer.contains(range.commonAncestorContainer)
73 adjustedRect = {
74 left: offset.left + rect.left
75 top: offset.top + rect.top
76 right: offset.left + rect.right
77 bottom: offset.top + rect.bottom
78 width: rect.width
79 height: rect.height
80 }
81 ranges.push({range, rect: adjustedRect})
82
83 for frame in window.frames
84 {viewport: frameViewport, offset: frameOffset} =
85 getFrameViewport(frame.frameElement, viewport) ? {}
86 continue unless frameViewport
87 newOffset = {
88 left: offset.left + frameOffset.left
89 top: offset.top + frameOffset.top
90 }
91 frameRanges = getAllRangesInsideViewport(frame, frameViewport, newOffset)
92 ranges.push(frameRanges...)
93
94 return ranges
95
96 getFirstNonWhitespace = (element) ->
97 window = element.ownerGlobal
98 viewport = getWindowViewport(window)
99 for node in element.childNodes then switch node.nodeType
100 when 3 # TextNode.
101 firstVisibleOffset = getFirstVisibleOffset(node, viewport)
102 if firstVisibleOffset?
103 offset = node.data.slice(firstVisibleOffset).search(/\S/)
104 return [node, firstVisibleOffset + offset] if offset >= 0
105 when 1 # Element.
106 result = getFirstNonWhitespace(node)
107 return result if result
108 return null
109
110 getFirstVisibleOffset = (textNode, viewport) ->
111 {length} = textNode.data
112 return null if length == 0
113 {headerBottom} = getFixedHeaderAndFooter(textNode.ownerGlobal, viewport)
114 [nonMatch, match] = utils.bisect(0, length - 1, (offset) ->
115 range = textNode.ownerDocument.createRange()
116 # Using a zero-width range sometimes gives a bad rect, so make it span one
117 # character instead.
118 range.setStart(textNode, offset)
119 range.setEnd(textNode, offset + 1)
120 rect = range.getBoundingClientRect()
121 # Ideally, we should also make sure that the text node is visible
122 # horizintally, but there seems to be no performant way of doing so.
123 # Luckily, horizontal scrolling is much less common than vertical.
124 return rect.top >= headerBottom - MINIMUM_EDGE_DISTANCE
125 )
126 return match
127
128 getFirstVisibleRange = (window, viewport) ->
129 ranges = getAllRangesInsideViewport(window, viewport)
130 first = null
131 for item in ranges
132 if not first or item.rect.top < first.rect.top
133 first = item
134 return if first then first.range else null
135
136 getFirstVisibleText = (window, viewport) ->
137 for element in window.document.getElementsByTagName('*')
138 rect = element.getBoundingClientRect()
139 continue unless isInsideViewport(rect, viewport)
140
141 if element.contentWindow and
142 not utils.checkElementOrAncestor(element, utils.isPositionFixed)
143 {viewport: frameViewport} = getFrameViewport(element, viewport) ? {}
144 continue unless frameViewport
145 result = getFirstVisibleText(element.contentWindow, frameViewport)
146 return result if result
147 continue
148
149 continue unless Array.some(element.childNodes, utils.isNonEmptyTextNode)
150
151 continue if utils.checkElementOrAncestor(element, utils.isPositionFixed)
152
153 result = getFirstNonWhitespace(element)
154 return result if result
155
156 return null
157
158 # Adapted from Firefox’s source code for `<space>` scrolling (which is where the
159 # arbitrary constants below come from).
160 #
161 # coffeelint: disable=max_line_length
162 # <https://hg.mozilla.org/mozilla-central/file/4d75bd6fd234/layout/generic/nsGfxScrollFrame.cpp#l3829>
163 # coffeelint: enable=max_line_length
164 getFixedHeaderAndFooter = (window) ->
165 viewport = getWindowViewport(window)
166 header = null
167 headerBottom = viewport.top
168 footer = null
169 footerTop = viewport.bottom
170 maxHeight = viewport.height / 3
171 minWidth = Math.min(viewport.width / 2, 800)
172
173 # Restricting the candidates for headers and footers to the most likely set of
174 # elements results in a noticeable performance boost.
175 candidates = window.document.querySelectorAll(
176 'div, ul, nav, header, footer, section'
177 )
178
179 for candidate in candidates
180 rect = candidate.getBoundingClientRect()
181 continue unless rect.height <= maxHeight and rect.width >= minWidth
182 # Checking for `position: fixed;` is the absolutely most expensive
183 # operation, so that is done last.
184 switch
185 when rect.top <= headerBottom and rect.bottom > headerBottom and
186 utils.isPositionFixed(candidate)
187 header = candidate
188 headerBottom = rect.bottom
189 when rect.bottom >= footerTop and rect.top < footerTop and
190 utils.isPositionFixed(candidate)
191 footer = candidate
192 footerTop = rect.top
193
194 return {header, headerBottom, footer, footerTop}
195
196 getFrameViewport = (frame, parentViewport) ->
197 rect = frame.getBoundingClientRect()
198 return null unless isInsideViewport(rect, parentViewport)
199
200 # `.getComputedStyle()` may return `null` if the computed style isn’t availble
201 # yet. If so, consider the element not visible.
202 return null unless computedStyle = frame.ownerGlobal.getComputedStyle(frame)
203 offset = {
204 left: rect.left +
205 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
206 parseFloat(computedStyle.getPropertyValue('padding-left'))
207 top: rect.top +
208 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
209 parseFloat(computedStyle.getPropertyValue('padding-top'))
210 right: rect.right -
211 parseFloat(computedStyle.getPropertyValue('border-right-width')) -
212 parseFloat(computedStyle.getPropertyValue('padding-right'))
213 bottom: rect.bottom -
214 parseFloat(computedStyle.getPropertyValue('border-bottom-width')) -
215 parseFloat(computedStyle.getPropertyValue('padding-bottom'))
216 }
217
218 # Calculate the visible part of the frame, according to the parent.
219 viewport = getWindowViewport(frame.contentWindow)
220 left = viewport.left + Math.max(parentViewport.left - offset.left, 0)
221 top = viewport.top + Math.max(parentViewport.top - offset.top, 0)
222 right = viewport.right + Math.min(parentViewport.right - offset.right, 0)
223 bottom = viewport.bottom + Math.min(parentViewport.bottom - offset.bottom, 0)
224
225 return {
226 viewport: {
227 left, top, right, bottom
228 width: right - left
229 height: bottom - top
230 }
231 offset
232 }
233
234 # Returns the minimum of `element.clientHeight` and the height of the viewport,
235 # taking fixed headers and footers into account.
236 getViewportCappedClientHeight = (element) ->
237 window = element.ownerGlobal
238 viewport = getWindowViewport(window)
239 {headerBottom, footerTop} = getFixedHeaderAndFooter(window)
240 return Math.min(element.clientHeight, footerTop - headerBottom)
241
242 getWindowViewport = (window) ->
243 {
244 clientWidth, clientHeight # Viewport size excluding scrollbars, usually.
245 scrollWidth, scrollHeight
246 } = utils.getRootElement(window.document)
247 {innerWidth, innerHeight} = window # Viewport size including scrollbars.
248 # When there are no scrollbars `clientWidth` and `clientHeight` might be too
249 # small. Then we use `innerWidth` and `innerHeight` instead.
250 width = if scrollWidth > innerWidth then clientWidth else innerWidth
251 height = if scrollHeight > innerHeight then clientHeight else innerHeight
252 return {
253 left: 0
254 top: 0
255 right: width
256 bottom: height
257 width
258 height
259 }
260
261 isInsideViewport = (rect, viewport) ->
262 return \
263 rect.left <= viewport.right - MINIMUM_EDGE_DISTANCE and
264 rect.top <= viewport.bottom + MINIMUM_EDGE_DISTANCE and
265 rect.right >= viewport.left + MINIMUM_EDGE_DISTANCE and
266 rect.bottom >= viewport.top - MINIMUM_EDGE_DISTANCE
267
268 scroll = (element, args) ->
269 {method, type, directions, amounts, properties, adjustment, smooth} = args
270 options = {
271 behavior: if smooth then 'smooth' else 'instant'
272 }
273 for direction, index in directions
274 amount = amounts[index]
275 options[direction] = -Math.sign(amount) * adjustment + switch type
276 when 'lines'
277 amount
278 when 'pages'
279 amount *
280 if properties[index] == 'clientHeight'
281 getViewportCappedClientHeight(element)
282 else
283 element[properties[index]]
284 when 'other'
285 Math.min(amount, element[properties[index]])
286 element[method](options)
287
288 module.exports = {
289 MINIMUM_EDGE_DISTANCE
290 adjustRectToViewport
291 getAllRangesInsideViewport
292 getFirstNonWhitespace
293 getFirstVisibleOffset
294 getFirstVisibleRange
295 getFirstVisibleText
296 getFixedHeaderAndFooter
297 getFrameViewport
298 getViewportCappedClientHeight
299 getWindowViewport
300 isInsideViewport
301 scroll
302 }
Imprint / Impressum