2 # Copyright Simon Lydell 2016.
4 # This file is part of VimFx.
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.
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.
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/>.
20 # This file provides utility functions for working with the viewport.
22 utils = require('./utils')
24 MINIMUM_EDGE_DISTANCE = 4
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
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)
35 # Make sure that `right >= left and bottom >= top`, since we subtracted by 1
37 right = Math.max(right, left)
38 bottom = Math.max(bottom, top)
42 area = Math.floor(width * height)
45 left, right, top, bottom
49 getAllRangesInsideViewport = (window, viewport, offset = {left: 0, top: 0}) ->
50 selection = window.getSelection()
51 {rangeCount} = selection
55 {header, headerBottom, footer, footerTop} =
56 getFixedHeaderAndFooter(window, viewport)
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
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)
74 left: offset.left + rect.left
75 top: offset.top + rect.top
76 right: offset.left + rect.right
77 bottom: offset.top + rect.bottom
81 ranges.push({range, rect: adjustedRect})
83 for frame in window.frames
84 {viewport: frameViewport, offset: frameOffset} =
85 getFrameViewport(frame.frameElement, viewport) ? {}
86 continue unless frameViewport
88 left: offset.left + frameOffset.left
89 top: offset.top + frameOffset.top
91 frameRanges = getAllRangesInsideViewport(frame, frameViewport, newOffset)
92 ranges.push(frameRanges...)
96 getFirstNonWhitespace = (element) ->
97 window = element.ownerGlobal
98 viewport = getWindowViewport(window)
99 for node in element.childNodes then switch node.nodeType
101 firstVisibleOffset = getFirstVisibleOffset(node, viewport)
102 if firstVisibleOffset?
103 offset = node.data.slice(firstVisibleOffset).search(/\S/)
104 return [node, firstVisibleOffset + offset] if offset >= 0
106 result = getFirstNonWhitespace(node)
107 return result if result
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
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
128 getFirstVisibleRange = (window, viewport) ->
129 ranges = getAllRangesInsideViewport(window, viewport)
132 if not first or item.rect.top < first.rect.top
134 return if first then first.range else null
136 getFirstVisibleText = (window, viewport) ->
137 for element in window.document.getElementsByTagName('*')
138 rect = element.getBoundingClientRect()
139 continue unless isInsideViewport(rect, viewport)
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
149 continue unless Array.some(element.childNodes, utils.isNonEmptyTextNode)
151 continue if utils.checkElementOrAncestor(element, utils.isPositionFixed)
153 result = getFirstNonWhitespace(element)
154 return result if result
158 # Adapted from Firefox’s source code for `<space>` scrolling (which is where the
159 # arbitrary constants below come from).
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)
167 headerBottom = viewport.top
169 footerTop = viewport.bottom
170 maxHeight = viewport.height / 3
171 minWidth = Math.min(viewport.width / 2, 800)
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'
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.
185 when rect.top <= headerBottom and rect.bottom > headerBottom and
186 utils.isPositionFixed(candidate)
188 headerBottom = rect.bottom
189 when rect.bottom >= footerTop and rect.top < footerTop and
190 utils.isPositionFixed(candidate)
194 return {header, headerBottom, footer, footerTop}
196 getFrameViewport = (frame, parentViewport) ->
197 rect = frame.getBoundingClientRect()
198 return null unless isInsideViewport(rect, parentViewport)
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)
205 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
206 parseFloat(computedStyle.getPropertyValue('padding-left'))
208 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
209 parseFloat(computedStyle.getPropertyValue('padding-top'))
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'))
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)
227 left, top, right, bottom
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)
242 getWindowViewport = (window) ->
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
261 isInsideViewport = (rect, viewport) ->
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
268 scroll = (element, args) ->
269 {method, type, directions, amounts, properties, adjustment, smooth} = args
271 behavior: if smooth then 'smooth' else 'instant'
273 for direction, index in directions
274 amount = amounts[index]
275 options[direction] = -Math.sign(amount) * adjustment + switch type
280 if properties[index] == 'clientHeight'
281 getViewportCappedClientHeight(element)
283 element[properties[index]]
285 Math.min(amount, element[properties[index]])
286 element[method](options)
289 MINIMUM_EDGE_DISTANCE
291 getAllRangesInsideViewport
292 getFirstNonWhitespace
293 getFirstVisibleOffset
296 getFixedHeaderAndFooter
298 getViewportCappedClientHeight