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