scroll-snap-kit 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,779 @@
1
+ /**
2
+ * scroll-snap-kit v2.0.0 (UMD — use via <script> or CDN)
3
+ * MIT License — https://github.com/farazfarid/scroll-snap-kit
4
+ */
5
+ (function (root, factory) {
6
+ if (typeof module === 'object' && module.exports) { module.exports = factory(); }
7
+ else if (typeof define === 'function' && define.amd) { define([], factory); }
8
+ else { root.ScrollSnapKit = factory(); }
9
+ }(typeof self !== 'undefined' ? self : this, function () {
10
+ 'use strict';
11
+
12
+ /**
13
+ * scroll-snap-kit — Core Utilities
14
+ */
15
+
16
+ /**
17
+ * Smoothly scrolls to a target element or position.
18
+ * @param {Element|number} target - A DOM element or Y pixel value
19
+ * @param {{ behavior?: ScrollBehavior, block?: ScrollLogicalPosition, offset?: number }} options
20
+ */
21
+ function scrollTo(target, options = {}) {
22
+ const { behavior = 'smooth', block = 'start', offset = 0 } = options;
23
+
24
+ if (typeof target === 'number') {
25
+ window.scrollTo({ top: target + offset, behavior });
26
+ return;
27
+ }
28
+
29
+ if (!(target instanceof Element)) {
30
+ console.warn('[scroll-snap-kit] scrollTo: target must be an Element or a number');
31
+ return;
32
+ }
33
+
34
+ if (offset !== 0) {
35
+ const y = target.getBoundingClientRect().top + window.scrollY + offset;
36
+ window.scrollTo({ top: y, behavior });
37
+ } else {
38
+ target.scrollIntoView({ behavior, block });
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Smoothly scrolls to the top of the page.
44
+ * @param {{ behavior?: ScrollBehavior }} options
45
+ */
46
+ function scrollToTop(options = {}) {
47
+ const { behavior = 'smooth' } = options;
48
+ window.scrollTo({ top: 0, behavior });
49
+ }
50
+
51
+ /**
52
+ * Smoothly scrolls to the bottom of the page.
53
+ * @param {{ behavior?: ScrollBehavior }} options
54
+ */
55
+ function scrollToBottom(options = {}) {
56
+ const { behavior = 'smooth' } = options;
57
+ window.scrollTo({ top: document.body.scrollHeight, behavior });
58
+ }
59
+
60
+ /**
61
+ * Returns the current scroll position and scroll percentage.
62
+ * @param {Element} [container=window] - Optional scrollable container
63
+ * @returns {{ x: number, y: number, percentX: number, percentY: number }}
64
+ */
65
+ function getScrollPosition(container) {
66
+ if (container && container instanceof Element) {
67
+ const { scrollLeft, scrollTop, scrollWidth, scrollHeight, clientWidth, clientHeight } = container;
68
+ return {
69
+ x: scrollLeft,
70
+ y: scrollTop,
71
+ percentX: scrollWidth > clientWidth ? Math.round((scrollLeft / (scrollWidth - clientWidth)) * 100) : 0,
72
+ percentY: scrollHeight > clientHeight ? Math.round((scrollTop / (scrollHeight - clientHeight)) * 100) : 0,
73
+ };
74
+ }
75
+
76
+ const x = window.scrollX;
77
+ const y = window.scrollY;
78
+ const maxX = document.body.scrollWidth - window.innerWidth;
79
+ const maxY = document.body.scrollHeight - window.innerHeight;
80
+
81
+ return {
82
+ x,
83
+ y,
84
+ percentX: maxX > 0 ? Math.round((x / maxX) * 100) : 0,
85
+ percentY: maxY > 0 ? Math.round((y / maxY) * 100) : 0,
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Attaches a throttled scroll event listener.
91
+ * @param {(position: ReturnType<typeof getScrollPosition>) => void} callback
92
+ * @param {{ throttle?: number, container?: Element }} options
93
+ * @returns {() => void} Cleanup function to remove the listener
94
+ */
95
+ function onScroll(callback, options = {}) {
96
+ const { throttle: throttleMs = 100, container } = options;
97
+ const target = container || window;
98
+
99
+ let ticking = false;
100
+ let lastTime = 0;
101
+
102
+ const handler = () => {
103
+ const now = Date.now();
104
+ if (now - lastTime < throttleMs) {
105
+ if (!ticking) {
106
+ ticking = true;
107
+ requestAnimationFrame(() => {
108
+ callback(getScrollPosition(container));
109
+ ticking = false;
110
+ lastTime = Date.now();
111
+ });
112
+ }
113
+ return;
114
+ }
115
+ lastTime = now;
116
+ callback(getScrollPosition(container));
117
+ };
118
+
119
+ target.addEventListener('scroll', handler, { passive: true });
120
+ return () => target.removeEventListener('scroll', handler);
121
+ }
122
+
123
+ /**
124
+ * Checks whether an element is currently visible in the viewport.
125
+ * @param {Element} element
126
+ * @param {{ threshold?: number }} options - threshold: 0–1, portion of element that must be visible
127
+ * @returns {boolean}
128
+ */
129
+ function isInViewport(element, options = {}) {
130
+ if (!(element instanceof Element)) {
131
+ console.warn('[scroll-snap-kit] isInViewport: argument must be an Element');
132
+ return false;
133
+ }
134
+
135
+ const { threshold = 0 } = options;
136
+ const rect = element.getBoundingClientRect();
137
+ const windowHeight = window.innerHeight || document.documentElement.clientHeight;
138
+ const windowWidth = window.innerWidth || document.documentElement.clientWidth;
139
+
140
+ const verticalVisible = rect.top + rect.height * threshold < windowHeight && rect.bottom - rect.height * threshold > 0;
141
+ const horizontalVisible = rect.left + rect.width * threshold < windowWidth && rect.right - rect.width * threshold > 0;
142
+
143
+ return verticalVisible && horizontalVisible;
144
+ }
145
+
146
+ /**
147
+ * Locks the page scroll (e.g. when a modal is open).
148
+ */
149
+ function lockScroll() {
150
+ const scrollY = window.scrollY;
151
+ document.body.style.position = 'fixed';
152
+ document.body.style.top = `-${scrollY}px`;
153
+ document.body.style.width = '100%';
154
+ }
155
+
156
+ /**
157
+ * Unlocks the page scroll and restores position.
158
+ */
159
+ function unlockScroll() {
160
+ const scrollY = document.body.style.top;
161
+ document.body.style.position = '';
162
+ document.body.style.top = '';
163
+ document.body.style.width = '';
164
+ window.scrollTo(0, parseInt(scrollY || '0') * -1);
165
+ }
166
+
167
+ // ─────────────────────────────────────────────
168
+ // NEW FEATURES
169
+ // ─────────────────────────────────────────────
170
+
171
+ /**
172
+ * scrollSpy — watches scroll position and highlights nav links
173
+ * matching the currently active section.
174
+ *
175
+ * @param {string} sectionsSelector CSS selector for the sections to spy on
176
+ * @param {string} linksSelector CSS selector for the nav links
177
+ * @param {{ offset?: number, activeClass?: string }} options
178
+ * @returns {() => void} cleanup / stop function
179
+ *
180
+ * @example
181
+ * const stop = scrollSpy('section[id]', 'nav a', { offset: 80, activeClass: 'active' })
182
+ */
183
+ function scrollSpy(sectionsSelector, linksSelector, options = {}) {
184
+ const { offset = 0, activeClass = 'scroll-spy-active' } = options;
185
+
186
+ const sections = Array.from(document.querySelectorAll(sectionsSelector));
187
+ const links = Array.from(document.querySelectorAll(linksSelector));
188
+
189
+ if (!sections.length || !links.length) {
190
+ console.warn('[scroll-snap-kit] scrollSpy: no sections or links found');
191
+ return () => { };
192
+ }
193
+
194
+ function update() {
195
+ const scrollY = window.scrollY + offset;
196
+ let current = sections[0];
197
+
198
+ for (const section of sections) {
199
+ if (section.offsetTop <= scrollY) current = section;
200
+ }
201
+
202
+ links.forEach(link => {
203
+ link.classList.remove(activeClass);
204
+ const href = link.getAttribute('href');
205
+ if (href && current && href === `#${current.id}`) {
206
+ link.classList.add(activeClass);
207
+ }
208
+ });
209
+ }
210
+
211
+ update();
212
+ window.addEventListener('scroll', update, { passive: true });
213
+ return () => window.removeEventListener('scroll', update);
214
+ }
215
+
216
+ /**
217
+ * onScrollEnd — fires a callback once the user stops scrolling.
218
+ *
219
+ * @param {() => void} callback
220
+ * @param {{ delay?: number, container?: Element }} options
221
+ * @returns {() => void} cleanup function
222
+ *
223
+ * @example
224
+ * const stop = onScrollEnd(() => console.log('Scrolling stopped!'), { delay: 150 })
225
+ */
226
+ function onScrollEnd(callback, options = {}) {
227
+ const { delay = 150, container } = options;
228
+ const target = container || window;
229
+ let timer = null;
230
+
231
+ const handler = () => {
232
+ clearTimeout(timer);
233
+ timer = setTimeout(() => {
234
+ callback(getScrollPosition(container));
235
+ }, delay);
236
+ };
237
+
238
+ target.addEventListener('scroll', handler, { passive: true });
239
+ return () => {
240
+ clearTimeout(timer);
241
+ target.removeEventListener('scroll', handler);
242
+ };
243
+ }
244
+
245
+ /**
246
+ * scrollIntoViewIfNeeded — scrolls to an element only if it is
247
+ * partially or fully outside the visible viewport.
248
+ *
249
+ * @param {Element} element
250
+ * @param {{ behavior?: ScrollBehavior, offset?: number, threshold?: number }} options
251
+ * threshold: 0–1, how much of the element must be visible before we skip scrolling (default 1 = fully visible)
252
+ *
253
+ * @example
254
+ * scrollIntoViewIfNeeded(document.querySelector('.card'))
255
+ */
256
+ function scrollIntoViewIfNeeded(element, options = {}) {
257
+ if (!(element instanceof Element)) {
258
+ console.warn('[scroll-snap-kit] scrollIntoViewIfNeeded: argument must be an Element');
259
+ return;
260
+ }
261
+
262
+ const { behavior = 'smooth', offset = 0, threshold = 1 } = options;
263
+ const rect = element.getBoundingClientRect();
264
+ const wh = window.innerHeight || document.documentElement.clientHeight;
265
+ const ww = window.innerWidth || document.documentElement.clientWidth;
266
+
267
+ const visibleH = Math.min(rect.bottom, wh) - Math.max(rect.top, 0);
268
+ const visibleW = Math.min(rect.right, ww) - Math.max(rect.left, 0);
269
+ const visibleRatio =
270
+ (Math.max(0, visibleH) * Math.max(0, visibleW)) / (rect.height * rect.width);
271
+
272
+ if (visibleRatio >= threshold) return; // already sufficiently visible — skip
273
+
274
+ const y = rect.top + window.scrollY - offset;
275
+ window.scrollTo({ top: y, behavior });
276
+ }
277
+
278
+ /**
279
+ * Built-in easing functions for use with easeScroll().
280
+ */
281
+ const Easings = {
282
+ linear: (t) => t,
283
+ easeInQuad: (t) => t * t,
284
+ easeOutQuad: (t) => t * (2 - t),
285
+ easeInOutQuad: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
286
+ easeInCubic: (t) => t * t * t,
287
+ easeOutCubic: (t) => (--t) * t * t + 1,
288
+ easeInOutCubic: (t) => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1,
289
+ easeInQuart: (t) => t * t * t * t,
290
+ easeOutQuart: (t) => 1 - (--t) * t * t * t,
291
+ easeOutElastic: (t) => {
292
+ const c4 = (2 * Math.PI) / 3;
293
+ return t === 0 ? 0 : t === 1 ? 1
294
+ : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * c4) + 1;
295
+ },
296
+ easeOutBounce: (t) => {
297
+ const n1 = 7.5625, d1 = 2.75;
298
+ if (t < 1 / d1) return n1 * t * t;
299
+ if (t < 2 / d1) return n1 * (t -= 1.5 / d1) * t + 0.75;
300
+ if (t < 2.5 / d1) return n1 * (t -= 2.25 / d1) * t + 0.9375;
301
+ return n1 * (t -= 2.625 / d1) * t + 0.984375;
302
+ },
303
+ };
304
+
305
+ /**
306
+ * easeScroll — scroll to a position with a custom easing curve,
307
+ * bypassing the browser's native smooth scroll.
308
+ *
309
+ * @param {Element|number} target DOM element or pixel Y value
310
+ * @param {{ duration?: number, easing?: (t: number) => number, offset?: number }} options
311
+ * @returns {Promise<void>} resolves when animation completes
312
+ *
313
+ * @example
314
+ * await easeScroll('#contact', { duration: 800, easing: Easings.easeOutElastic })
315
+ */
316
+ function easeScroll(target, options = {}) {
317
+ const { duration = 600, easing = Easings.easeInOutCubic, offset = 0 } = options;
318
+
319
+ let targetY;
320
+ if (typeof target === 'number') {
321
+ targetY = target + offset;
322
+ } else {
323
+ const el = typeof target === 'string' ? document.querySelector(target) : target;
324
+ if (!el) { console.warn('[scroll-snap-kit] easeScroll: target not found'); return Promise.resolve(); }
325
+ targetY = el.getBoundingClientRect().top + window.scrollY + offset;
326
+ }
327
+
328
+ const startY = window.scrollY;
329
+ const distance = targetY - startY;
330
+ const startTime = performance.now();
331
+
332
+ return new Promise((resolve) => {
333
+ function step(now) {
334
+ const elapsed = now - startTime;
335
+ const progress = Math.min(elapsed / duration, 1);
336
+ const easedProgress = easing(progress);
337
+
338
+ window.scrollTo(0, startY + distance * easedProgress);
339
+
340
+ if (progress < 1) {
341
+ requestAnimationFrame(step);
342
+ } else {
343
+ resolve();
344
+ }
345
+ }
346
+ requestAnimationFrame(step);
347
+ });
348
+ }
349
+
350
+ // ─────────────────────────────────────────────
351
+ // v1.2 FEATURES
352
+ // ─────────────────────────────────────────────
353
+
354
+ /**
355
+ * scrollSequence — run multiple easeScroll animations one after another.
356
+ * Returns { promise, cancel } — cancel() aborts mid-sequence.
357
+ *
358
+ * @example
359
+ * const { promise, cancel } = scrollSequence([
360
+ * { target: '#intro', duration: 600 },
361
+ * { target: '#features', duration: 800, pause: 400 },
362
+ * { target: '#pricing', duration: 600, easing: Easings.easeOutElastic },
363
+ * ])
364
+ */
365
+ function scrollSequence(steps) {
366
+ let cancelled = false;
367
+ const promise = (async () => {
368
+ for (const step of steps) {
369
+ if (cancelled) break;
370
+ const { target, duration = 600, easing = Easings.easeInOutCubic, offset = 0, pause = 0 } = step;
371
+ await easeScroll(target, { duration, easing, offset });
372
+ if (pause > 0 && !cancelled) await new Promise(res => setTimeout(res, pause));
373
+ }
374
+ })();
375
+ return { promise, cancel: () => { cancelled = true; } };
376
+ }
377
+
378
+ /**
379
+ * parallax — attach a parallax scroll effect to one or more elements.
380
+ * speed < 1 = slower (background), speed > 1 = faster (foreground), speed < 0 = reverse.
381
+ * Returns a destroy / cleanup function.
382
+ *
383
+ * @example
384
+ * const destroy = parallax('.hero-bg', { speed: 0.4 })
385
+ * const destroy = parallax('.clouds', { speed: -0.2, axis: 'x' })
386
+ */
387
+ function parallax(targets, options = {}) {
388
+ const { speed = 0.5, axis = 'y', container } = options;
389
+ let els;
390
+ if (typeof targets === 'string') els = Array.from(document.querySelectorAll(targets));
391
+ else if (targets instanceof Element) els = [targets];
392
+ else els = Array.from(targets);
393
+ if (!els.length) { console.warn('[scroll-snap-kit] parallax: no elements found'); return () => { }; }
394
+
395
+ const origins = els.map(el => ({
396
+ el,
397
+ originY: el.getBoundingClientRect().top + window.scrollY,
398
+ originX: el.getBoundingClientRect().left + window.scrollX,
399
+ }));
400
+
401
+ let rafId = null;
402
+ function update() {
403
+ const scrollY = container ? container.scrollTop : window.scrollY;
404
+ const scrollX = container ? container.scrollLeft : window.scrollX;
405
+ origins.forEach(({ el, originY, originX }) => {
406
+ const dy = (scrollY - (originY - window.innerHeight / 2)) * (speed - 1);
407
+ const dx = (scrollX - (originX - window.innerWidth / 2)) * (speed - 1);
408
+ if (axis === 'y') el.style.transform = `translateY(${dy}px)`;
409
+ else if (axis === 'x') el.style.transform = `translateX(${dx}px)`;
410
+ else el.style.transform = `translate(${dx}px, ${dy}px)`;
411
+ });
412
+ rafId = null;
413
+ }
414
+ const handler = () => { if (!rafId) rafId = requestAnimationFrame(update); };
415
+ const t = container || window;
416
+ t.addEventListener('scroll', handler, { passive: true });
417
+ update();
418
+ return () => {
419
+ t.removeEventListener('scroll', handler);
420
+ if (rafId) cancelAnimationFrame(rafId);
421
+ origins.forEach(({ el }) => { el.style.transform = ''; });
422
+ };
423
+ }
424
+
425
+ /**
426
+ * scrollProgress — track how far the user has scrolled through a specific element (0→1).
427
+ * 0 = element top just entered the viewport, 1 = element bottom just left the viewport.
428
+ * Returns a cleanup function.
429
+ *
430
+ * @example
431
+ * const stop = scrollProgress('#article', progress => {
432
+ * bar.style.width = `${progress * 100}%`
433
+ * })
434
+ */
435
+ function scrollProgress(element, callback, options = {}) {
436
+ const el = typeof element === 'string' ? document.querySelector(element) : element;
437
+ if (!el) { console.warn('[scroll-snap-kit] scrollProgress: element not found'); return () => { }; }
438
+ const { offset = 0 } = options;
439
+ function calculate() {
440
+ const rect = el.getBoundingClientRect();
441
+ const wh = window.innerHeight;
442
+ const total = rect.height + wh;
443
+ const passed = wh - rect.top + offset;
444
+ callback(Math.min(1, Math.max(0, passed / total)));
445
+ }
446
+ calculate();
447
+ window.addEventListener('scroll', calculate, { passive: true });
448
+ window.addEventListener('resize', calculate);
449
+ return () => {
450
+ window.removeEventListener('scroll', calculate);
451
+ window.removeEventListener('resize', calculate);
452
+ };
453
+ }
454
+
455
+ /**
456
+ * snapToSection — after scrolling stops, auto-snap to the nearest section.
457
+ * Returns a destroy function.
458
+ *
459
+ * @example
460
+ * const destroy = snapToSection('section[id]', { delay: 150, offset: -70 })
461
+ */
462
+ function snapToSection(sections, options = {}) {
463
+ const { delay = 150, offset = 0, duration = 500, easing = Easings.easeInOutCubic } = options;
464
+ const els = typeof sections === 'string'
465
+ ? Array.from(document.querySelectorAll(sections))
466
+ : Array.from(sections);
467
+ if (!els.length) { console.warn('[scroll-snap-kit] snapToSection: no sections found'); return () => { }; }
468
+
469
+ let timer = null, snapping = false;
470
+ const handler = () => {
471
+ clearTimeout(timer);
472
+ timer = setTimeout(async () => {
473
+ if (snapping) return;
474
+ snapping = true;
475
+ const scrollMid = window.scrollY + window.innerHeight / 2;
476
+ let closest = els[0], minDist = Infinity;
477
+ els.forEach(el => {
478
+ const mid = el.offsetTop + el.offsetHeight / 2;
479
+ const d = Math.abs(mid - scrollMid);
480
+ if (d < minDist) { minDist = d; closest = el; }
481
+ });
482
+ await easeScroll(closest, { duration, easing, offset });
483
+ snapping = false;
484
+ }, delay);
485
+ };
486
+ window.addEventListener('scroll', handler, { passive: true });
487
+ return () => { clearTimeout(timer); window.removeEventListener('scroll', handler); };
488
+ }
489
+
490
+ // ─────────────────────────────────────────────
491
+ // v2.0 FEATURES
492
+ // ─────────────────────────────────────────────
493
+
494
+ /**
495
+ * scrollReveal — animate elements in as they scroll into view.
496
+ * Supports fade, slide (up/down/left/right), scale, and combinations.
497
+ * Uses IntersectionObserver for performance.
498
+ * Returns a destroy function.
499
+ *
500
+ * @param {string|Element|Element[]} targets
501
+ * @param {{ effect?: 'fade'|'slide-up'|'slide-down'|'slide-left'|'slide-right'|'scale'|'fade-scale',
502
+ * duration?: number, delay?: number, easing?: string,
503
+ * threshold?: number, once?: boolean, distance?: string }} options
504
+ * @returns {() => void}
505
+ *
506
+ * @example
507
+ * const destroy = scrollReveal('.card', { effect: 'slide-up', duration: 600, delay: 100 })
508
+ */
509
+ function scrollReveal(targets, options = {}) {
510
+ const {
511
+ effect = 'fade',
512
+ duration = 500,
513
+ delay = 0,
514
+ easing = 'cubic-bezier(0.4, 0, 0.2, 1)',
515
+ threshold = 0.15,
516
+ once = true,
517
+ distance = '24px',
518
+ } = options;
519
+
520
+ const els = typeof targets === 'string'
521
+ ? Array.from(document.querySelectorAll(targets))
522
+ : targets instanceof Element ? [targets] : Array.from(targets);
523
+
524
+ if (!els.length) { console.warn('[scroll-snap-kit] scrollReveal: no elements found'); return () => { }; }
525
+
526
+ const hiddenStyles = {
527
+ 'fade': { opacity: '0' },
528
+ 'slide-up': { opacity: '0', transform: `translateY(${distance})` },
529
+ 'slide-down': { opacity: '0', transform: `translateY(-${distance})` },
530
+ 'slide-left': { opacity: '0', transform: `translateX(${distance})` },
531
+ 'slide-right': { opacity: '0', transform: `translateX(-${distance})` },
532
+ 'scale': { opacity: '0', transform: 'scale(0.9)' },
533
+ 'fade-scale': { opacity: '0', transform: `scale(0.95) translateY(${distance})` },
534
+ };
535
+
536
+ const hidden = hiddenStyles[effect] || hiddenStyles['fade'];
537
+
538
+ // Save original styles and apply hidden state
539
+ els.forEach((el, i) => {
540
+ el._ssk_origin = { transition: el.style.transition, ...Object.fromEntries(Object.keys(hidden).map(k => [k, el.style[k]])) };
541
+ Object.assign(el.style, hidden);
542
+ el.style.transition = `opacity ${duration}ms ${easing} ${delay + i * 0}ms, transform ${duration}ms ${easing} ${delay}ms`;
543
+ });
544
+
545
+ const obs = new IntersectionObserver((entries) => {
546
+ entries.forEach(entry => {
547
+ if (entry.isIntersecting) {
548
+ const el = entry.target;
549
+ const i = els.indexOf(el);
550
+ setTimeout(() => {
551
+ el.style.opacity = '';
552
+ el.style.transform = '';
553
+ }, i * (delay || 0));
554
+ if (once) obs.unobserve(el);
555
+ } else if (!once) {
556
+ Object.assign(entry.target.style, hidden);
557
+ }
558
+ });
559
+ }, { threshold });
560
+
561
+ els.forEach(el => obs.observe(el));
562
+
563
+ return () => {
564
+ obs.disconnect();
565
+ els.forEach(el => {
566
+ if (el._ssk_origin) {
567
+ el.style.transition = el._ssk_origin.transition;
568
+ el.style.opacity = el._ssk_origin.opacity || '';
569
+ el.style.transform = el._ssk_origin.transform || '';
570
+ delete el._ssk_origin;
571
+ }
572
+ });
573
+ };
574
+ }
575
+
576
+ /**
577
+ * scrollTimeline — drive CSS custom properties (variables) from scroll position,
578
+ * letting you animate anything via CSS using `var(--scroll-progress)` etc.
579
+ * Also supports directly animating numeric CSS properties on elements.
580
+ *
581
+ * @param {Array<{
582
+ * property: string, // CSS custom property name e.g. '--hero-opacity'
583
+ * from: number, // value at scrollStart
584
+ * to: number, // value at scrollEnd
585
+ * unit?: string, // CSS unit e.g. 'px', '%', 'deg', 'rem' (default: '')
586
+ * scrollStart?: number, // page scroll Y to begin (default: 0)
587
+ * scrollEnd?: number, // page scroll Y to end (default: document height)
588
+ * target?: Element|string, // element to set the property on (default: document.documentElement)
589
+ * }>} tracks
590
+ * @returns {() => void} cleanup function
591
+ *
592
+ * @example
593
+ * const stop = scrollTimeline([
594
+ * { property: '--hero-opacity', from: 1, to: 0, scrollStart: 0, scrollEnd: 400 },
595
+ * { property: '--nav-blur', from: 0, to: 16, unit: 'px', scrollStart: 0, scrollEnd: 200 },
596
+ * ])
597
+ */
598
+ function scrollTimeline(tracks, options = {}) {
599
+ if (!Array.isArray(tracks) || !tracks.length) {
600
+ console.warn('[scroll-snap-kit] scrollTimeline: tracks must be a non-empty array');
601
+ return () => { };
602
+ }
603
+
604
+ const resolved = tracks.map(t => ({
605
+ ...t,
606
+ unit: t.unit ?? '',
607
+ scrollStart: t.scrollStart ?? 0,
608
+ scrollEnd: t.scrollEnd ?? (document.body.scrollHeight - window.innerHeight),
609
+ target: typeof t.target === 'string'
610
+ ? document.querySelector(t.target)
611
+ : (t.target ?? document.documentElement),
612
+ }));
613
+
614
+ let rafId = null;
615
+
616
+ function update() {
617
+ const scrollY = window.scrollY;
618
+ resolved.forEach(({ property, from, to, unit, scrollStart, scrollEnd, target }) => {
619
+ const range = scrollEnd - scrollStart;
620
+ const progress = range <= 0 ? 1 : Math.min(1, Math.max(0, (scrollY - scrollStart) / range));
621
+ const value = from + (to - from) * progress;
622
+ target.style.setProperty(property, `${value}${unit}`);
623
+ });
624
+ rafId = null;
625
+ }
626
+
627
+ const handler = () => { if (!rafId) rafId = requestAnimationFrame(update); };
628
+ window.addEventListener('scroll', handler, { passive: true });
629
+ update();
630
+
631
+ return () => {
632
+ window.removeEventListener('scroll', handler);
633
+ if (rafId) cancelAnimationFrame(rafId);
634
+ resolved.forEach(({ property, target }) => target.style.removeProperty(property));
635
+ };
636
+ }
637
+
638
+ /**
639
+ * infiniteScroll — fire a callback when the user scrolls near the bottom of the
640
+ * page (or a scrollable container), typically used to load more content.
641
+ *
642
+ * Automatically re-arms itself after the callback resolves (if it returns a Promise)
643
+ * or after a configurable cooldown, so rapid triggers are prevented.
644
+ *
645
+ * @param {() => void | Promise<void>} callback
646
+ * @param {{ threshold?: number, cooldown?: number, container?: Element }} options
647
+ * @returns {() => void} cleanup / stop function
648
+ *
649
+ * @example
650
+ * const stop = infiniteScroll(async () => {
651
+ * const items = await fetchMoreItems()
652
+ * appendItems(items)
653
+ * }, { threshold: 300 })
654
+ */
655
+ function infiniteScroll(callback, options = {}) {
656
+ const { threshold = 200, cooldown = 500, container } = options;
657
+ let loading = false;
658
+
659
+ const getRemaining = () => {
660
+ if (container) {
661
+ return container.scrollHeight - container.scrollTop - container.clientHeight;
662
+ }
663
+ return document.body.scrollHeight - window.scrollY - window.innerHeight;
664
+ };
665
+
666
+ const handler = async () => {
667
+ if (loading) return;
668
+ if (getRemaining() <= threshold) {
669
+ loading = true;
670
+ try {
671
+ await Promise.resolve(callback());
672
+ } finally {
673
+ setTimeout(() => { loading = false; }, cooldown);
674
+ }
675
+ }
676
+ };
677
+
678
+ const target = container || window;
679
+ target.addEventListener('scroll', handler, { passive: true });
680
+ handler(); // check immediately in case already near bottom
681
+
682
+ return () => target.removeEventListener('scroll', handler);
683
+ }
684
+
685
+ /**
686
+ * scrollTrap — contain scroll within a specific element (like a modal or drawer),
687
+ * preventing the background page from scrolling while the element is open.
688
+ * Handles mouse wheel, touch, and keyboard arrow/space/pageup/pagedown events.
689
+ *
690
+ * Returns a release function.
691
+ *
692
+ * @param {Element | string} element
693
+ * @param {{ allowKeys?: boolean }} options
694
+ * @returns {() => void} release function
695
+ *
696
+ * @example
697
+ * const release = scrollTrap(document.querySelector('.modal'))
698
+ * // …later, when modal closes:
699
+ * release()
700
+ */
701
+ function scrollTrap(element, options = {}) {
702
+ const el = typeof element === 'string' ? document.querySelector(element) : element;
703
+ if (!(el instanceof Element)) {
704
+ console.warn('[scroll-snap-kit] scrollTrap: element not found');
705
+ return () => { };
706
+ }
707
+
708
+ const { allowKeys = true } = options;
709
+
710
+ const canScrollUp = () => el.scrollTop > 0;
711
+ const canScrollDown = () => el.scrollTop < el.scrollHeight - el.clientHeight;
712
+
713
+ // Wheel handler — block wheel events that would escape the element
714
+ const onWheel = (e) => {
715
+ const goingDown = e.deltaY > 0;
716
+ if (goingDown && !canScrollDown()) { e.preventDefault(); return; }
717
+ if (!goingDown && !canScrollUp()) { e.preventDefault(); return; }
718
+ };
719
+
720
+ // Touch handler
721
+ let touchStartY = 0;
722
+ const onTouchStart = (e) => { touchStartY = e.touches[0].clientY; };
723
+ const onTouchMove = (e) => {
724
+ const dy = touchStartY - e.touches[0].clientY;
725
+ if (dy > 0 && !canScrollDown()) { e.preventDefault(); return; }
726
+ if (dy < 0 && !canScrollUp()) { e.preventDefault(); return; }
727
+ };
728
+
729
+ // Key handler
730
+ const SCROLL_KEYS = { ArrowUp: -40, ArrowDown: 40, PageUp: -300, PageDown: 300, ' ': 300 };
731
+ const onKeyDown = (e) => {
732
+ const delta = SCROLL_KEYS[e.key];
733
+ if (!delta) return;
734
+ if (!el.contains(document.activeElement) && document.activeElement !== el) return;
735
+ e.preventDefault();
736
+ el.scrollTop += delta;
737
+ };
738
+
739
+ el.addEventListener('wheel', onWheel, { passive: false });
740
+ el.addEventListener('touchstart', onTouchStart, { passive: true });
741
+ el.addEventListener('touchmove', onTouchMove, { passive: false });
742
+ if (allowKeys) document.addEventListener('keydown', onKeyDown);
743
+
744
+ // Also lock the body
745
+ lockScroll();
746
+
747
+ return () => {
748
+ el.removeEventListener('wheel', onWheel);
749
+ el.removeEventListener('touchstart', onTouchStart);
750
+ el.removeEventListener('touchmove', onTouchMove);
751
+ if (allowKeys) document.removeEventListener('keydown', onKeyDown);
752
+ unlockScroll();
753
+ };
754
+ }
755
+
756
+ return {
757
+ scrollTo,
758
+ scrollToTop,
759
+ scrollToBottom,
760
+ getScrollPosition,
761
+ onScroll,
762
+ isInViewport,
763
+ lockScroll,
764
+ unlockScroll,
765
+ scrollSpy,
766
+ onScrollEnd,
767
+ scrollIntoViewIfNeeded,
768
+ Easings,
769
+ easeScroll,
770
+ scrollSequence,
771
+ parallax,
772
+ scrollProgress,
773
+ snapToSection,
774
+ scrollReveal,
775
+ scrollTimeline,
776
+ infiniteScroll,
777
+ scrollTrap,
778
+ };
779
+ }));