-
Notifications
You must be signed in to change notification settings - Fork 59
/
zenscroll5.js
323 lines (301 loc) · 11.2 KB
/
zenscroll5.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/**
* Zenscroll 5.0.1
* https://github.com/zengabor/zenscroll/
*
* Copyright 2015–2022 Gabor Lenard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Detect if the browser already supports native smooth scrolling (e.g., Firefox 36+ and Chrome 49+) and it is enabled:
const isNativeSmoothScrollEnabledOn = function(elem) {
return elem && window.getComputedStyle(elem)["scroll-behavior"] === "smooth"
}
export const makeScroller = function(container, defaultDuration, edgeOffset) {
// Use defaults if not provided
defaultDuration = defaultDuration || 999 // ms
if (!edgeOffset && edgeOffset !== 0) {
// When scrolling, this amount of distance is kept from the edges of the container:
edgeOffset = 9 // px
}
// Handling the life-cycle of the scroller
let scrollTimeoutId
const setScrollTimeoutId = (newValue) => scrollTimeoutId = newValue
/**
* Stop the current smooth scroll operation immediately
*/
const stopScroll = () => {
clearTimeout(scrollTimeoutId)
setScrollTimeoutId(0)
}
const topOf = (elem) => Math.min(
Math.max(0, container.getTopOf(elem)-edgeOffset),
container.getHeight()-window.innerHeight-edgeOffset
)
/**
* Scrolls to a specific vertical position in the document.
*
* @param {int} targetY The vertical position within the document.
* @param {int} duration Optionally the duration of the scroll operation in miliseconds.
* If not provided the default duration is used.
* @return {Promise} A promise which resolves when the scroll has finished.
*/
const scrollToY = function(targetY, duration) {
stopScroll()
return new Promise((resolve) => {
if (duration === 0 || (duration && duration < 0) || isNativeSmoothScrollEnabledOn(container.body)) {
container.toY(targetY)
resolve()
} else {
const startY = container.getY()
const distance = Math.max(0, targetY) - startY
const startTime = new Date().getTime()
duration = duration || Math.min(Math.abs(distance), defaultDuration);
(function loopScroll() {
setScrollTimeoutId(setTimeout(() => {
// Calculate percentage:
const p = Math.min(1, (new Date().getTime() - startTime) / duration)
// Calculate the absolute vertical position:
const y = Math.max(0, Math.floor(startY + distance*(p < 0.5 ? 2*p*p : p*(4 - p*2)-1)))
container.toY(y)
if (p < 1 && (container.getHeight() + y) < container.body.scrollHeight) {
loopScroll()
} else {
setTimeout(stopScroll, 99) // with cooldown time
resolve()
}
}, 9))
})()
}
})
}
/**
* Scrolls to the top of a specific element.
*
* @param {HTMLElement} elem The element to scroll to.
* @param {int} duration Optionally the duration of the scroll operation in miliseconds.
* @return {Promise} A promise which resolves when the scroll has finished.
*/
const scrollToElem = function(elem, duration) {
return scrollToY(topOf(elem), duration)
}
/**
* Scrolls an element into view if necessary.
*
* @param {HTMLElement} elem The element.
* @param {int} duration Optionally the duration of the scroll operation in miliseconds.
* @return {Promise} A promise which resolves when the scroll has finished.
*/
const scrollIntoView = function(elem, duration) {
const elemHeight = elem.getBoundingClientRect().height
const elemBottom = container.getTopOf(elem) + elemHeight
const containerHeight = container.getHeight()
const y = container.getY()
const containerBottom = y + containerHeight
if (topOf(elem) < y || (elemHeight + edgeOffset) > containerHeight) {
// Element is clipped at top or is higher than screen.
return scrollToElem(elem, duration)
} else if ((elemBottom + edgeOffset) > containerBottom) {
// Element is clipped at the bottom.
return scrollToY(elemBottom - containerHeight + edgeOffset, duration)
} else {
return new Promise((resolve) => resolve())
}
}
/**
* Scrolls to the center of an element.
*
* @param {HTMLElement} elem The element.
* @param {int} duration Optionally the duration of the scroll operation in miliseconds.
* @param {int} offset Optionally the offset of the top of the element from the
* center of the screen in pixel lines. A value of 0 is ignored.
* @return {Promise} A promise which resolves when the scroll has finished.
*/
const scrollToCenterOf = function(elem, duration, offset) {
return scrollToY(
Math.max(0, container.getTopOf(elem) - container.getHeight()/2 +
(offset || elem.getBoundingClientRect().height/2)),
duration
)
}
/**
* Changes default settings for this scroller.
*
* @param {int} newDefaultDuration Optionally a new value for default duration,
* used for each scroll method by default. Ignored if null or undefined.
* @param {init} newEdgeOffset Optionally a new value for the edge offset in pixel lines,
* used by each scroll method by default. Ignored if null or undefined.
* @return {object} An object with the current values.
*/
const setup = function(newDefaultDuration, newEdgeOffset) {
if (newDefaultDuration === 0 || newDefaultDuration) {
defaultDuration = newDefaultDuration
}
if (newEdgeOffset === 0 || newEdgeOffset) {
edgeOffset = newEdgeOffset
}
return {
defaultDuration: defaultDuration,
edgeOffset: edgeOffset,
}
}
return {
setup: setup,
to: scrollToElem,
toY: scrollToY,
intoView: scrollIntoView,
center: scrollToCenterOf,
stop: stopScroll,
moving: () => !!scrollTimeoutId,
getY: container.getY,
getTopOf: container.getTopOf,
}
}
const getDocY = () => window.scrollY || document.documentElement.scrollTop
// Create a scroller for the document:
const Zenscroll = makeScroller({
body: document.scrollingElement || document.body,
toY: (y) => window.scrollTo(0, y),
getY: getDocY,
getHeight: () => document.documentElement.clientHeight || window.innerHeight,
getTopOf: (elem) => elem.getBoundingClientRect().top + getDocY() - document.documentElement.offsetTop,
})
/**
* Creates a scroller from the provided container element (e.g., a DIV)
*
* @param {HTMLElement} scrollContainer The vertical position within the document.
* @param {int} defaultDuration Optionally a value for default duration, used for each scroll method by default.
* Ignored if 0 or null or undefined.
* @param {int} edgeOffset Optionally a value for the edge offset, used by each scroll method by default.
* Ignored if null or undefined.
* @return {object} A scroller object, similar to `zenscroll` but controlling the provided element.
*/
export const createScroller = function(scrollContainer, defaultDuration, edgeOffset) {
return makeScroller(
{
body: scrollContainer,
toY: (y) => scrollContainer.scrollTop = y,
getY: () => scrollContainer.scrollTop,
getHeight: () => Math.min(scrollContainer.clientHeight,
document.documentElement.clientHeight || window.innerHeight),
getTopOf: (elem) => elem.offsetTop,
},
defaultDuration, edgeOffset
)
}
// Automatic link-smoothing on achors
// Exclude when native is enabled or Zenscroll auto- is disabled
if (!window.noZensmooth && !isNativeSmoothScrollEnabledOn(document.scrollingElement)) {
const isScrollRestorationSupported = "scrollRestoration" in history
// On first load & refresh make sure the browser restores the position first
if (isScrollRestorationSupported) {
history.scrollRestoration = "auto"
}
let lastPathname
window.addEventListener("load", () => {
if (isScrollRestorationSupported) {
// Set it to manual
setTimeout(() => history.scrollRestoration = "manual", 9)
window.addEventListener("popstate", (event) => {
if (event.state && "zenscrollY" in event.state) {
Zenscroll.toY(event.state.zenscrollY, location.pathname === lastPathname ? null : 0)
}
})
}
// Add edge offset on first load if necessary
if (location.hash) {
setTimeout(() => {
// Adjustment is only needed if there is an edge offset:
const edgeOffset = Zenscroll.setup().edgeOffset
if (edgeOffset) {
const anchor = location.href.split("#")[1]
let targetElem = document.getElementById(anchor)
if (!targetElem) {
const elements = document.getElementsByName(anchor)
for (const e of elements) {
if (e.tagName === "A") {
targetElem = e
break
}
}
}
if (targetElem) {
const targetY = Math.max(0, Zenscroll.getTopOf(targetElem) - edgeOffset)
const diff = Zenscroll.getY() - targetY
// Only do the adjustment if the browser is very close to the element:
if (0 <= diff && diff < 9 ) {
window.scrollTo(0, targetY)
}
}
}
}, 9)
}
})
// Handling clicks on anchors
const REnoZensmooth = new RegExp(/(^|\\s)noZensmooth(\\s|$)/i)
window.addEventListener("click", (event) => {
if (window.noZensmooth || event.button !== 0 || event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) {
// Let the browser handle the click if window.noZensmooth is trueish
// or it wasn't with the primary button, or some modifier key was pressed.
return
}
let anchor = event.target
while (anchor && anchor.tagName !== "A") {
anchor = anchor.parentNode
}
if (!anchor) {
return
}
// Save the current scrolling position so it can be used for scroll restoration:
if (isScrollRestorationSupported) {
const historyState = history.state || {}
historyState.zenscrollY = Zenscroll.getY()
try {
history.replaceState(historyState, "")
} catch (e) {
// Avoid the Chrome Security exception on file protocol, e.g., file://index.html
}
}
// Find the referenced ID:
const href = anchor.getAttribute("href") || ""
if (href.indexOf("#") === 0 && !REnoZensmooth.test(anchor.className)) {
let targetY = 0
const targetElem = document.getElementById(href.substring(1))
if (href !== "#") {
if (!targetElem) {
// Let the browser handle the click if the target ID is not found.
return
}
targetY = Zenscroll.getTopOf(targetElem)
}
event.preventDefault()
let onDone = () => location.assign(href) // By default trigger the browser's `hashchange` event...
// ...unless there is an edge offset specified in which case it would jump abruptly so:
const edgeOffset = Zenscroll.setup().edgeOffset
if (edgeOffset) {
targetY = Math.max(0, targetY - edgeOffset)
lastPathname = location.pathname
onDone = () => {
const historyState = history.state || {}
historyState.zenscrollY = Zenscroll.getY()
try {
history.pushState(historyState, "", href)
} catch (e) {
// Avoid the Chrome Security exception on file protocol, e.g., file://index.html
}
}
}
Zenscroll.toY(targetY, null).then(onDone)
}
}, { capture: true })
}
export default Zenscroll