use-scroll-animate 1.2.0 → 1.5.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.
package/dist/index.esm.js CHANGED
@@ -1,697 +1,1249 @@
1
- /**
2
- * use-scroll-animate - Animation Presets
3
- * Defines keyframes for all built-in animation presets
4
- */
5
- const PRESETS = {
6
- 'fade-in': {
7
- from: { opacity: 0 },
8
- to: { opacity: 1 },
9
- },
10
- 'fade-in-up': {
11
- from: { opacity: 0, transform: 'translateY(40px)' },
12
- to: { opacity: 1, transform: 'translateY(0)' },
13
- },
14
- 'fade-in-down': {
15
- from: { opacity: 0, transform: 'translateY(-40px)' },
16
- to: { opacity: 1, transform: 'translateY(0)' },
17
- },
18
- 'fade-in-left': {
19
- from: { opacity: 0, transform: 'translateX(-40px)' },
20
- to: { opacity: 1, transform: 'translateX(0)' },
21
- },
22
- 'fade-in-right': {
23
- from: { opacity: 0, transform: 'translateX(40px)' },
24
- to: { opacity: 1, transform: 'translateX(0)' },
25
- },
26
- 'zoom-in': {
27
- from: { opacity: 0, transform: 'scale(0.8)' },
28
- to: { opacity: 1, transform: 'scale(1)' },
29
- },
30
- 'zoom-out': {
31
- from: { opacity: 0, transform: 'scale(1.2)' },
32
- to: { opacity: 1, transform: 'scale(1)' },
33
- },
34
- 'flip-x': {
35
- from: { opacity: 0, transform: 'rotateX(-90deg)' },
36
- to: { opacity: 1, transform: 'rotateX(0)' },
37
- },
38
- 'flip-y': {
39
- from: { opacity: 0, transform: 'rotateY(-90deg)' },
40
- to: { opacity: 1, transform: 'rotateY(0)' },
41
- },
42
- 'slide-up': {
43
- from: { transform: 'translateY(100%)' },
44
- to: { transform: 'translateY(0)' },
45
- },
46
- 'slide-down': {
47
- from: { transform: 'translateY(-100%)' },
48
- to: { transform: 'translateY(0)' },
49
- },
50
- 'slide-left': {
51
- from: { transform: 'translateX(-100%)' },
52
- to: { transform: 'translateX(0)' },
53
- },
54
- 'slide-right': {
55
- from: { transform: 'translateX(100%)' },
56
- to: { transform: 'translateX(0)' },
57
- },
58
- 'bounce': {
59
- from: { opacity: 0, transform: 'translateY(-60px)' },
60
- to: { opacity: 1, transform: 'translateY(0)' },
61
- },
62
- 'rotate-in': {
63
- from: { opacity: 0, transform: 'rotate(-180deg) scale(0.5)' },
64
- to: { opacity: 1, transform: 'rotate(0deg) scale(1)' },
65
- },
66
- 'blur-in': {
67
- from: { opacity: 0, filter: 'blur(12px)' },
68
- to: { opacity: 1, filter: 'blur(0px)' },
69
- },
70
- 'skew-in': {
71
- from: { opacity: 0, transform: 'skewX(20deg) translateX(30px)' },
72
- to: { opacity: 1, transform: 'skewX(0deg) translateX(0)' },
73
- },
74
- 'scale-x': {
75
- from: { transform: 'scaleX(0)' },
76
- to: { transform: 'scaleX(1)' },
77
- },
78
- 'scale-y': {
79
- from: { transform: 'scaleY(0)' },
80
- to: { transform: 'scaleY(1)' },
81
- },
82
- 'shimmer': {
83
- from: { opacity: 0.5, filter: 'brightness(1)' },
84
- to: { opacity: 1, filter: 'brightness(1.5)' },
85
- },
86
- 'pulse': {
87
- from: { transform: 'scale(1)' },
88
- to: { transform: 'scale(1.05)' },
89
- },
90
- 'swing': {
91
- from: { transform: 'rotate(-10deg)' },
92
- to: { transform: 'rotate(10deg)' },
93
- },
94
- };
95
- function resolvePreset(animation) {
96
- var _a;
97
- if (typeof animation === 'string') {
98
- return (_a = PRESETS[animation]) !== null && _a !== void 0 ? _a : PRESETS['fade-in-up'];
99
- }
100
- if (Array.isArray(animation)) {
101
- const combined = { from: {}, to: {} };
102
- animation.forEach(name => {
103
- const preset = PRESETS[name];
104
- if (preset) {
105
- Object.entries(preset.from).forEach(([key, val]) => {
106
- if (key === 'transform' && combined.from[key]) {
107
- combined.from[key] = `${combined.from[key]} ${val}`;
108
- }
109
- else {
110
- combined.from[key] = val;
111
- }
112
- });
113
- Object.entries(preset.to).forEach(([key, val]) => {
114
- if (key === 'transform' && combined.to[key]) {
115
- combined.to[key] = `${combined.to[key]} ${val}`;
116
- }
117
- else {
118
- combined.to[key] = val;
119
- }
120
- });
121
- }
122
- });
123
- return combined;
124
- }
125
- return animation;
126
- }
127
- /** Easing to CSS cubic-bezier mapping */
128
- const EASING_MAP = {
129
- linear: 'linear',
130
- ease: 'ease',
131
- 'ease-in': 'ease-in',
132
- 'ease-out': 'ease-out',
133
- 'ease-in-out': 'ease-in-out',
134
- spring: 'cubic-bezier(0.34, 1.56, 0.64, 1)',
135
- };
136
- function resolveEasing(easing) {
137
- var _a;
138
- return (_a = EASING_MAP[easing]) !== null && _a !== void 0 ? _a : easing;
139
- }
140
-
141
- /**
142
- * use-scroll-animate - Core Implementation
143
- * Uses IntersectionObserver + Web Animations API for zero-dependency,
144
- * high-performance scroll-triggered animations.
145
- */
146
- const DEFAULT_CONFIG = {
147
- defaultAnimation: 'fade-in-up',
148
- defaultDuration: 600,
149
- defaultDelay: 0,
150
- defaultEasing: 'ease',
151
- defaultThreshold: 0.1,
152
- defaultRootMargin: '0px',
153
- defaultRepeat: false,
154
- defaultOnce: true,
155
- defaultOffset: 0,
156
- hiddenClass: 'sa-hidden',
157
- visibleClass: 'sa-visible',
158
- useClassNames: false,
159
- disabled: false,
160
- root: null,
161
- };
162
- const DEFAULT_OPTIONS = {
163
- stagger: 0,
164
- parallax: {},
165
- onStart: () => undefined,
166
- onComplete: () => undefined,
167
- onEnter: () => undefined,
168
- onLeave: () => undefined,
169
- onProgress: () => undefined,
170
- };
171
- function parseDataAttributes(el, config) {
172
- const dataset = el.dataset;
173
- const opts = {};
174
- if (dataset.saAnimation) {
175
- const anim = dataset.saAnimation;
176
- opts.animation = anim.includes(',')
177
- ? anim.split(',').map(s => s.trim())
178
- : anim;
179
- }
180
- if (dataset.saDuration)
181
- opts.duration = parseInt(dataset.saDuration, 10);
182
- if (dataset.saDelay)
183
- opts.delay = parseInt(dataset.saDelay, 10);
184
- if (dataset.saEasing)
185
- opts.easing = dataset.saEasing;
186
- if (dataset.saThreshold) {
187
- const t = dataset.saThreshold;
188
- opts.threshold = t.includes(',') ? t.split(',').map(parseFloat) : parseFloat(t);
189
- }
190
- if (dataset.saRootMargin)
191
- opts.rootMargin = dataset.saRootMargin;
192
- if (dataset.saRepeat !== undefined)
193
- opts.repeat = dataset.saRepeat !== 'false';
194
- if (dataset.saOnce !== undefined)
195
- opts.once = dataset.saOnce !== 'false';
196
- if (dataset.saOffset)
197
- opts.offset = parseInt(dataset.saOffset, 10);
198
- if (dataset.saStagger)
199
- opts.stagger = parseInt(dataset.saStagger, 10);
200
- if (dataset.saParallaxX || dataset.saParallaxY || dataset.saParallaxRotate || dataset.saParallaxScale) {
201
- opts.parallax = {
202
- x: dataset.saParallaxX,
203
- y: dataset.saParallaxY,
204
- rotate: dataset.saParallaxRotate ? parseFloat(dataset.saParallaxRotate) : undefined,
205
- scale: dataset.saParallaxScale ? parseFloat(dataset.saParallaxScale) : undefined,
206
- speed: dataset.saParallaxSpeed ? parseFloat(dataset.saParallaxSpeed) : 1,
207
- };
208
- }
209
- return mergeOptions(opts, config);
210
- }
211
- function mergeOptions(opts, config) {
212
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
213
- const repeat = (_a = opts.repeat) !== null && _a !== void 0 ? _a : config.defaultRepeat;
214
- return {
215
- animation: (_b = opts.animation) !== null && _b !== void 0 ? _b : config.defaultAnimation,
216
- duration: (_c = opts.duration) !== null && _c !== void 0 ? _c : config.defaultDuration,
217
- delay: (_d = opts.delay) !== null && _d !== void 0 ? _d : config.defaultDelay,
218
- easing: (_e = opts.easing) !== null && _e !== void 0 ? _e : config.defaultEasing,
219
- threshold: (_f = opts.threshold) !== null && _f !== void 0 ? _f : config.defaultThreshold,
220
- rootMargin: (_g = opts.rootMargin) !== null && _g !== void 0 ? _g : config.defaultRootMargin,
221
- repeat: repeat,
222
- once: (_h = opts.once) !== null && _h !== void 0 ? _h : (repeat ? false : config.defaultOnce),
223
- offset: (_j = opts.offset) !== null && _j !== void 0 ? _j : config.defaultOffset,
224
- stagger: (_k = opts.stagger) !== null && _k !== void 0 ? _k : DEFAULT_OPTIONS.stagger,
225
- parallax: (_l = opts.parallax) !== null && _l !== void 0 ? _l : DEFAULT_OPTIONS.parallax,
226
- onStart: (_m = opts.onStart) !== null && _m !== void 0 ? _m : DEFAULT_OPTIONS.onStart,
227
- onComplete: (_o = opts.onComplete) !== null && _o !== void 0 ? _o : DEFAULT_OPTIONS.onComplete,
228
- onEnter: (_p = opts.onEnter) !== null && _p !== void 0 ? _p : DEFAULT_OPTIONS.onEnter,
229
- onLeave: (_q = opts.onLeave) !== null && _q !== void 0 ? _q : DEFAULT_OPTIONS.onLeave,
230
- onProgress: (_r = opts.onProgress) !== null && _r !== void 0 ? _r : DEFAULT_OPTIONS.onProgress,
231
- };
232
- }
233
- function resolveTargets(target) {
234
- if (typeof target === 'string') {
235
- return Array.from(document.querySelectorAll(target));
236
- }
237
- if (target instanceof Element) {
238
- return [target];
239
- }
240
- if (target instanceof NodeList) {
241
- return Array.from(target);
242
- }
243
- if (Array.isArray(target)) {
244
- return target;
245
- }
246
- return [];
247
- }
248
- function prefersReducedMotion() {
249
- var _a, _b;
250
- return (_b = (_a = window.matchMedia) === null || _a === void 0 ? void 0 : _a.call(window, '(prefers-reduced-motion: reduce)').matches) !== null && _b !== void 0 ? _b : false;
251
- }
252
- function runAnimation(el, opts, config, staggerIndex = 0) {
253
- const { animation, duration, delay, easing, stagger, onStart, onComplete } = opts;
254
- const totalDelay = delay + staggerIndex * stagger;
255
- const preset = resolvePreset(animation);
256
- const easingValue = resolveEasing(easing);
257
- if (config.useClassNames) {
258
- if (totalDelay > 0) {
259
- el.style.animationDelay = `${totalDelay}ms`;
260
- }
261
- el.classList.remove(config.hiddenClass);
262
- el.classList.add(config.visibleClass);
263
- onStart(el);
264
- setTimeout(() => onComplete(el), duration + totalDelay);
265
- return;
266
- }
267
- const keyframes = [
268
- preset.from,
269
- preset.to,
270
- ];
271
- const timing = {
272
- duration,
273
- delay: totalDelay,
274
- easing: easingValue,
275
- fill: 'both',
276
- };
277
- // Check if Web Animations API is supported
278
- if (typeof el.animate === 'function') {
279
- const anim = el.animate(keyframes, timing);
280
- onStart(el);
281
- anim.onfinish = () => onComplete(el);
282
- }
283
- else {
284
- // Fallback for older browsers
285
- el.style.opacity = '1';
286
- el.style.transform = 'none';
287
- onStart(el);
288
- onComplete(el);
289
- }
290
- }
291
- function applyParallax(el, progress, parallax) {
292
- const { x = 0, y = 0, rotate = 0, scale = 1, speed = 1 } = parallax;
293
- const p = (progress - 0.5) * 2 * speed;
294
- let transform = '';
295
- if (x)
296
- transform += ` translateX(${typeof x === 'number' ? x * p + 'px' : 'calc(' + x + ' * ' + p + ')'})`;
297
- if (y)
298
- transform += ` translateY(${typeof y === 'number' ? y * p + 'px' : 'calc(' + y + ' * ' + p + ')'})`;
299
- if (rotate)
300
- transform += ` rotate(${rotate * p}deg)`;
301
- if (scale !== 1)
302
- transform += ` scale(${1 + (scale - 1) * p})`;
303
- el.style.transform = transform;
304
- }
305
- function hideElement(el, config) {
306
- if (config.useClassNames) {
307
- el.classList.add(config.hiddenClass);
308
- el.classList.remove(config.visibleClass);
309
- }
310
- else {
311
- el.style.opacity = '0';
312
- }
313
- }
314
- function createScrollAnimate(userConfig = {}) {
315
- let config = { ...DEFAULT_CONFIG, ...userConfig };
316
- const registry = new Map();
317
- function createObserver(opts) {
318
- // Handle offset by adjusting rootMargin
319
- const rootMargin = opts.offset !== 0
320
- ? `${opts.rootMargin.split(' ')[0]} 0px -${opts.offset}px 0px`
321
- : opts.rootMargin;
322
- return new IntersectionObserver((entries) => {
323
- entries.forEach((entry) => {
324
- var _a;
325
- const record = registry.get(entry.target);
326
- if (!record)
327
- return;
328
- if (entry.isIntersecting) {
329
- opts.onEnter(entry.target);
330
- if (!record.animated || opts.repeat) {
331
- const parent = entry.target.parentElement;
332
- let staggerIndex = 0;
333
- if (parent && opts.stagger > 0) {
334
- // BUG FIX: Use a more robust way to find index among siblings that are also observed
335
- const siblings = Array.from(parent.children).filter((c) => registry.has(c));
336
- staggerIndex = siblings.indexOf(entry.target);
337
- }
338
- if (!config.disabled && !prefersReducedMotion()) {
339
- runAnimation(entry.target, opts, config, staggerIndex);
340
- }
341
- else {
342
- entry.target.style.opacity = '1';
343
- entry.target.style.transform = '';
344
- }
345
- record.animated = true;
346
- // Handle 'once' functionality
347
- if (opts.once) {
348
- record.observer.unobserve(entry.target);
349
- (_a = record.progressObserver) === null || _a === void 0 ? void 0 : _a.unobserve(entry.target);
350
- // We don't delete from registry yet to allow other potential interactions
351
- }
352
- }
353
- }
354
- else {
355
- opts.onLeave(entry.target);
356
- if (opts.repeat && record.animated) {
357
- hideElement(entry.target, config);
358
- record.animated = false;
359
- }
360
- }
361
- });
362
- }, {
363
- threshold: typeof opts.threshold === 'number' ? opts.threshold : opts.threshold[0],
364
- rootMargin: rootMargin,
365
- root: config.root,
366
- });
367
- }
368
- function createProgressObserver(el, opts) {
369
- const thresholds = [];
370
- for (let i = 0; i <= 100; i++)
371
- thresholds.push(i / 100);
372
- return new IntersectionObserver((entries) => {
373
- entries.forEach((entry) => {
374
- const progress = entry.intersectionRatio;
375
- opts.onProgress(el, progress);
376
- if (Object.keys(opts.parallax).length > 0) {
377
- applyParallax(el, progress, opts.parallax);
378
- }
379
- });
380
- }, {
381
- threshold: thresholds,
382
- rootMargin: opts.rootMargin,
383
- root: config.root,
384
- });
385
- }
386
- function observeElement(el, opts) {
387
- if (registry.has(el))
388
- return;
389
- if (!config.useClassNames) {
390
- hideElement(el, config);
391
- }
392
- const observer = createObserver(opts);
393
- observer.observe(el);
394
- let progressObserver;
395
- if (Object.keys(opts.parallax).length > 0 || opts.onProgress !== DEFAULT_OPTIONS.onProgress) {
396
- progressObserver = createProgressObserver(el, opts);
397
- progressObserver.observe(el);
398
- }
399
- registry.set(el, {
400
- element: el,
401
- options: opts,
402
- observer,
403
- animated: false,
404
- progressObserver
405
- });
406
- }
407
- const instance = {
408
- observe(target, options = {}) {
409
- const elements = resolveTargets(target);
410
- const opts = mergeOptions(options, config);
411
- elements.forEach((el) => observeElement(el, opts));
412
- },
413
- unobserve(target) {
414
- const elements = resolveTargets(target);
415
- elements.forEach((el) => {
416
- var _a;
417
- const record = registry.get(el);
418
- if (record) {
419
- record.observer.disconnect(); // BUG FIX: Use disconnect for better cleanup
420
- (_a = record.progressObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
421
- registry.delete(el);
422
- }
423
- });
424
- },
425
- init(rootElement = document) {
426
- const elements = rootElement.querySelectorAll('[data-sa]');
427
- elements.forEach((el) => {
428
- const opts = parseDataAttributes(el, config);
429
- observeElement(el, opts);
430
- });
431
- },
432
- destroy() {
433
- registry.forEach((record) => {
434
- var _a;
435
- record.observer.disconnect();
436
- (_a = record.progressObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
437
- });
438
- registry.clear();
439
- },
440
- refresh() {
441
- const entries = Array.from(registry.entries());
442
- instance.destroy();
443
- entries.forEach(([el, record]) => {
444
- observeElement(el, record.options);
445
- });
446
- },
447
- animate(target, options = {}) {
448
- const elements = resolveTargets(target);
449
- const opts = mergeOptions(options, config);
450
- elements.forEach((el) => {
451
- runAnimation(el, opts, config, 0);
452
- });
453
- },
454
- getObservedElements() {
455
- return Array.from(registry.values());
456
- },
457
- configure(newConfig) {
458
- config = { ...config, ...newConfig };
459
- },
460
- };
461
- return instance;
462
- }
463
-
464
- /**
465
- * use-scroll-animate - React Integration
466
- * Provides useScrollAnimate and useScrollRef hooks for React applications.
467
- */
468
- function createReactHooks(React) {
469
- function useScrollAnimate(options = {}) {
470
- const ref = React.useRef(null);
471
- React.useEffect(() => {
472
- const el = ref.current;
473
- if (!el)
474
- return;
475
- const { animation = 'fade-in-up', duration = 600, delay = 0, easing = 'ease', threshold = 0.1, rootMargin = '0px', repeat = false, parallax = {}, onStart, onComplete, onEnter, onLeave, onProgress, } = options;
476
- const preset = resolvePreset(animation);
477
- const easingValue = resolveEasing(easing);
478
- let animated = false;
479
- el.style.opacity = '0';
480
- const observer = new IntersectionObserver((entries) => {
481
- entries.forEach((entry) => {
482
- if (entry.isIntersecting) {
483
- onEnter === null || onEnter === void 0 ? void 0 : onEnter(el);
484
- if (!animated || repeat) {
485
- const keyframes = [
486
- preset.from,
487
- preset.to,
488
- ];
489
- const anim = el.animate(keyframes, {
490
- duration,
491
- delay,
492
- easing: easingValue,
493
- fill: 'both',
494
- });
495
- onStart === null || onStart === void 0 ? void 0 : onStart(el);
496
- anim.onfinish = () => onComplete === null || onComplete === void 0 ? void 0 : onComplete(el);
497
- animated = true;
498
- if (!repeat && !Object.keys(parallax).length && !onProgress) {
499
- observer.unobserve(el);
500
- }
501
- }
502
- }
503
- else {
504
- onLeave === null || onLeave === void 0 ? void 0 : onLeave(el);
505
- if (repeat && animated) {
506
- el.style.opacity = '0';
507
- animated = false;
508
- }
509
- }
510
- });
511
- }, { threshold: typeof threshold === 'number' ? threshold : threshold[0], rootMargin });
512
- let progressObserver = null;
513
- if (Object.keys(parallax).length > 0 || onProgress) {
514
- const thresholds = [];
515
- for (let i = 0; i <= 100; i++)
516
- thresholds.push(i / 100);
517
- progressObserver = new IntersectionObserver((entries) => {
518
- entries.forEach((entry) => {
519
- const progress = entry.intersectionRatio;
520
- onProgress === null || onProgress === void 0 ? void 0 : onProgress(el, progress);
521
- if (Object.keys(parallax).length > 0) {
522
- const { x = 0, y = 0, rotate = 0, scale = 1, speed = 1 } = parallax;
523
- const p = (progress - 0.5) * 2 * speed;
524
- let transform = '';
525
- if (x)
526
- transform += ` translateX(${typeof x === 'number' ? x * p + 'px' : 'calc(' + x + ' * ' + p + ')'})`;
527
- if (y)
528
- transform += ` translateY(${typeof y === 'number' ? y * p + 'px' : 'calc(' + y + ' * ' + p + ')'})`;
529
- if (rotate)
530
- transform += ` rotate(${rotate * p}deg)`;
531
- if (scale !== 1)
532
- transform += ` scale(${1 + (scale - 1) * p})`;
533
- el.style.transform = transform;
534
- }
535
- });
536
- }, { threshold: thresholds, rootMargin });
537
- progressObserver.observe(el);
538
- }
539
- observer.observe(el);
540
- return () => {
541
- observer.disconnect();
542
- progressObserver === null || progressObserver === void 0 ? void 0 : progressObserver.disconnect();
543
- };
544
- }, []);
545
- return ref;
546
- }
547
- function useScrollStagger(options = {}) {
548
- const ref = React.useRef(null);
549
- React.useEffect(() => {
550
- const container = ref.current;
551
- if (!container)
552
- return;
553
- const { animation = 'fade-in-up', duration = 600, delay = 0, easing = 'ease', threshold = 0.1, rootMargin = '0px', stagger = 80, } = options;
554
- const children = Array.from(container.children);
555
- const preset = resolvePreset(animation);
556
- const easingValue = resolveEasing(easing);
557
- children.forEach((child) => {
558
- child.style.opacity = '0';
559
- });
560
- let animated = false;
561
- const observer = new IntersectionObserver((entries) => {
562
- entries.forEach((entry) => {
563
- if (entry.isIntersecting && !animated) {
564
- animated = true;
565
- children.forEach((child, i) => {
566
- child.animate([preset.from, preset.to], {
567
- duration,
568
- delay: delay + i * stagger,
569
- easing: easingValue,
570
- fill: 'both',
571
- });
572
- });
573
- observer.unobserve(container);
574
- }
575
- });
576
- }, { threshold: typeof threshold === 'number' ? threshold : threshold[0], rootMargin });
577
- observer.observe(container);
578
- return () => observer.disconnect();
579
- }, []);
580
- return ref;
581
- }
582
- return { useScrollAnimate, useScrollStagger };
583
- }
584
-
585
- /**
586
- * use-scroll-animate - Vue 3 Integration
587
- * Provides useScrollAnimate composable for Vue 3 applications.
588
- */
589
- function createVueComposables(Vue) {
590
- function useScrollAnimate(options = {}) {
591
- const animateRef = Vue.ref(null);
592
- let observer = null;
593
- let progressObserver = null;
594
- Vue.onMounted(() => {
595
- const el = animateRef.value;
596
- if (!el)
597
- return;
598
- const { animation = 'fade-in-up', duration = 600, delay = 0, easing = 'ease', threshold = 0.1, rootMargin = '0px', repeat = false, parallax = {}, onStart, onComplete, onEnter, onLeave, onProgress, } = options;
599
- const preset = resolvePreset(animation);
600
- const easingValue = resolveEasing(easing);
601
- let animated = false;
602
- el.style.opacity = '0';
603
- observer = new IntersectionObserver((entries) => {
604
- entries.forEach((entry) => {
605
- if (entry.isIntersecting) {
606
- onEnter === null || onEnter === void 0 ? void 0 : onEnter(el);
607
- if (!animated || repeat) {
608
- const anim = el.animate([preset.from, preset.to], {
609
- duration,
610
- delay,
611
- easing: easingValue,
612
- fill: 'both',
613
- });
614
- onStart === null || onStart === void 0 ? void 0 : onStart(el);
615
- anim.onfinish = () => onComplete === null || onComplete === void 0 ? void 0 : onComplete(el);
616
- animated = true;
617
- if (!repeat && !Object.keys(parallax).length && !onProgress) {
618
- observer === null || observer === void 0 ? void 0 : observer.unobserve(el);
619
- }
620
- }
621
- }
622
- else {
623
- onLeave === null || onLeave === void 0 ? void 0 : onLeave(el);
624
- if (repeat && animated) {
625
- el.style.opacity = '0';
626
- animated = false;
627
- }
628
- }
629
- });
630
- }, { threshold: typeof threshold === 'number' ? threshold : threshold[0], rootMargin });
631
- if (Object.keys(parallax).length > 0 || onProgress) {
632
- const thresholds = [];
633
- for (let i = 0; i <= 100; i++)
634
- thresholds.push(i / 100);
635
- progressObserver = new IntersectionObserver((entries) => {
636
- entries.forEach((entry) => {
637
- const progress = entry.intersectionRatio;
638
- onProgress === null || onProgress === void 0 ? void 0 : onProgress(el, progress);
639
- if (Object.keys(parallax).length > 0) {
640
- const { x = 0, y = 0, rotate = 0, scale = 1, speed = 1 } = parallax;
641
- const p = (progress - 0.5) * 2 * speed;
642
- let transform = '';
643
- if (x)
644
- transform += ` translateX(${typeof x === 'number' ? x * p + 'px' : 'calc(' + x + ' * ' + p + ')'})`;
645
- if (y)
646
- transform += ` translateY(${typeof y === 'number' ? y * p + 'px' : 'calc(' + y + ' * ' + p + ')'})`;
647
- if (rotate)
648
- transform += ` rotate(${rotate * p}deg)`;
649
- if (scale !== 1)
650
- transform += ` scale(${1 + (scale - 1) * p})`;
651
- el.style.transform = transform;
652
- }
653
- });
654
- }, { threshold: thresholds, rootMargin });
655
- progressObserver.observe(el);
656
- }
657
- observer.observe(el);
658
- });
659
- Vue.onUnmounted(() => {
660
- observer === null || observer === void 0 ? void 0 : observer.disconnect();
661
- progressObserver === null || progressObserver === void 0 ? void 0 : progressObserver.disconnect();
662
- });
663
- return { animateRef };
664
- }
665
- return { useScrollAnimate };
666
- }
667
-
668
- /**
669
- * use-scroll-animate
670
- *
671
- * A lightweight (~4KB gzipped), dependency-free scroll animation library
672
- * for modern web applications. Built with TypeScript, powered by
673
- * IntersectionObserver and the Web Animations API.
674
- *
675
- * @version 1.0.0
676
- * @license MIT
677
- * @see https://github.com/use-scroll-animate/use-scroll-animate
678
- */
679
- /**
680
- * Default singleton instance of ScrollAnimate.
681
- * Ready to use out of the box with sensible defaults.
682
- *
683
- * @example
684
- * ```js
685
- * import ScrollAnimate from 'use-scroll-animate';
686
- *
687
- * // Auto-initialize all elements with data-sa attribute
688
- * ScrollAnimate.init();
689
- *
690
- * // Or manually observe elements
691
- * ScrollAnimate.observe('.my-element', { animation: 'fade-in-up' });
692
- * ```
693
- */
694
- const ScrollAnimate = createScrollAnimate();
695
-
696
- export { EASING_MAP, PRESETS, createReactHooks, createScrollAnimate, createVueComposables, ScrollAnimate as default, resolveEasing, resolvePreset };
697
- //# sourceMappingURL=index.esm.js.map
1
+ /**
2
+ * use-scroll-animate - Animation Presets
3
+ * Defines keyframes for all built-in animation presets
4
+ */
5
+ const PRESETS = {
6
+ 'fade-in': {
7
+ from: { opacity: 0 },
8
+ to: { opacity: 1 },
9
+ },
10
+ 'fade-in-up': {
11
+ from: { opacity: 0, transform: 'translateY(40px)' },
12
+ to: { opacity: 1, transform: 'translateY(0px)' },
13
+ },
14
+ 'fade-in-down': {
15
+ from: { opacity: 0, transform: 'translateY(-40px)' },
16
+ to: { opacity: 1, transform: 'translateY(0px)' },
17
+ },
18
+ 'fade-in-left': {
19
+ from: { opacity: 0, transform: 'translateX(-40px)' },
20
+ to: { opacity: 1, transform: 'translateX(0px)' },
21
+ },
22
+ 'fade-in-right': {
23
+ from: { opacity: 0, transform: 'translateX(40px)' },
24
+ to: { opacity: 1, transform: 'translateX(0px)' },
25
+ },
26
+ 'zoom-in': {
27
+ from: { opacity: 0, transform: 'scale(0.8)' },
28
+ to: { opacity: 1, transform: 'scale(1)' },
29
+ },
30
+ 'zoom-out': {
31
+ from: { opacity: 0, transform: 'scale(1.2)' },
32
+ to: { opacity: 1, transform: 'scale(1)' },
33
+ },
34
+ 'flip-x': {
35
+ from: { opacity: 0, transform: 'rotateX(-90deg)' },
36
+ to: { opacity: 1, transform: 'rotateX(0deg)' },
37
+ },
38
+ 'flip-y': {
39
+ from: { opacity: 0, transform: 'rotateY(-90deg)' },
40
+ to: { opacity: 1, transform: 'rotateY(0deg)' },
41
+ },
42
+ 'slide-up': {
43
+ from: { transform: 'translateY(100%)' },
44
+ to: { transform: 'translateY(0px)' },
45
+ },
46
+ 'slide-down': {
47
+ from: { transform: 'translateY(-100%)' },
48
+ to: { transform: 'translateY(0px)' },
49
+ },
50
+ 'slide-left': {
51
+ from: { transform: 'translateX(-100%)' },
52
+ to: { transform: 'translateX(0px)' },
53
+ },
54
+ 'slide-right': {
55
+ from: { transform: 'translateX(100%)' },
56
+ to: { transform: 'translateX(0px)' },
57
+ },
58
+ 'bounce': {
59
+ from: { opacity: 0, transform: 'translateY(-60px)' },
60
+ to: { opacity: 1, transform: 'translateY(0px)' },
61
+ },
62
+ 'rotate-in': {
63
+ from: { opacity: 0, transform: 'rotate(-180deg) scale(0.5)' },
64
+ to: { opacity: 1, transform: 'rotate(0deg) scale(1)' },
65
+ },
66
+ 'blur-in': {
67
+ from: { opacity: 0, filter: 'blur(12px)' },
68
+ to: { opacity: 1, filter: 'blur(0px)' },
69
+ },
70
+ 'skew-in': {
71
+ from: { opacity: 0, transform: 'skewX(20deg) translateX(30px)' },
72
+ to: { opacity: 1, transform: 'skewX(0deg) translateX(0px)' },
73
+ },
74
+ 'scale-x': {
75
+ from: { transform: 'scaleX(0)' },
76
+ to: { transform: 'scaleX(1)' },
77
+ },
78
+ 'scale-y': {
79
+ from: { transform: 'scaleY(0)' },
80
+ to: { transform: 'scaleY(1)' },
81
+ },
82
+ 'shimmer': {
83
+ from: { opacity: 0.5, filter: 'brightness(1)' },
84
+ to: { opacity: 1, filter: 'brightness(1.5)' },
85
+ },
86
+ 'pulse': {
87
+ from: { transform: 'scale(1)' },
88
+ to: { transform: 'scale(1.05)' },
89
+ },
90
+ 'swing': {
91
+ from: { transform: 'rotate(-10deg)' },
92
+ to: { transform: 'rotate(10deg)' },
93
+ },
94
+ 'scale-up': {
95
+ from: { opacity: 0, transform: 'scale(0.5)' },
96
+ to: { opacity: 1, transform: 'scale(1)' },
97
+ },
98
+ 'blur-in-up': {
99
+ from: { opacity: 0, filter: 'blur(12px)', transform: 'translateY(40px)' },
100
+ to: { opacity: 1, filter: 'blur(0px)', transform: 'translateY(0px)' },
101
+ },
102
+ 'flip-up': {
103
+ from: { opacity: 0, transform: 'perspective(800px) rotateX(60deg)' },
104
+ to: { opacity: 1, transform: 'perspective(800px) rotateX(0deg)' },
105
+ },
106
+ 'flip-down': {
107
+ from: { opacity: 0, transform: 'perspective(800px) rotateX(-60deg)' },
108
+ to: { opacity: 1, transform: 'perspective(800px) rotateX(0deg)' },
109
+ },
110
+ 'rotate-left': {
111
+ from: { opacity: 0, transform: 'rotate(-15deg) translateX(-40px)' },
112
+ to: { opacity: 1, transform: 'rotate(0deg) translateX(0px)' },
113
+ },
114
+ 'rotate-right': {
115
+ from: { opacity: 0, transform: 'rotate(15deg) translateX(40px)' },
116
+ to: { opacity: 1, transform: 'rotate(0deg) translateX(0px)' },
117
+ },
118
+ // clip-path reveals: content is uncovered without moving or fading
119
+ 'clip-up': {
120
+ from: { clipPath: 'inset(100% 0% 0% 0%)' },
121
+ to: { clipPath: 'inset(0% 0% 0% 0%)' },
122
+ },
123
+ 'clip-down': {
124
+ from: { clipPath: 'inset(0% 0% 100% 0%)' },
125
+ to: { clipPath: 'inset(0% 0% 0% 0%)' },
126
+ },
127
+ 'clip-left': {
128
+ from: { clipPath: 'inset(0% 0% 0% 100%)' },
129
+ to: { clipPath: 'inset(0% 0% 0% 0%)' },
130
+ },
131
+ 'clip-right': {
132
+ from: { clipPath: 'inset(0% 100% 0% 0%)' },
133
+ to: { clipPath: 'inset(0% 0% 0% 0%)' },
134
+ },
135
+ 'clip-circle': {
136
+ from: { clipPath: 'circle(0% at 50% 50%)' },
137
+ to: { clipPath: 'circle(75% at 50% 50%)' },
138
+ },
139
+ };
140
+ function resolvePreset(animation) {
141
+ var _a;
142
+ if (typeof animation === 'string') {
143
+ return (_a = PRESETS[animation.trim()]) !== null && _a !== void 0 ? _a : PRESETS['fade-in-up'];
144
+ }
145
+ if (Array.isArray(animation)) {
146
+ const combined = { from: {}, to: {} };
147
+ animation.forEach(name => {
148
+ const preset = PRESETS[name.trim()];
149
+ if (preset) {
150
+ Object.entries(preset.from).forEach(([key, val]) => {
151
+ if (key === 'transform' && combined.from[key]) {
152
+ combined.from[key] = `${combined.from[key]} ${val}`;
153
+ }
154
+ else {
155
+ combined.from[key] = val;
156
+ }
157
+ });
158
+ Object.entries(preset.to).forEach(([key, val]) => {
159
+ if (key === 'transform' && combined.to[key]) {
160
+ combined.to[key] = `${combined.to[key]} ${val}`;
161
+ }
162
+ else {
163
+ combined.to[key] = val;
164
+ }
165
+ });
166
+ }
167
+ });
168
+ return combined;
169
+ }
170
+ return animation;
171
+ }
172
+ /** Easing to CSS cubic-bezier mapping */
173
+ const EASING_MAP = {
174
+ linear: 'linear',
175
+ ease: 'ease',
176
+ 'ease-in': 'ease-in',
177
+ 'ease-out': 'ease-out',
178
+ 'ease-in-out': 'ease-in-out',
179
+ spring: 'cubic-bezier(0.34, 1.56, 0.64, 1)',
180
+ 'soft-spring': 'cubic-bezier(0.175, 0.885, 0.32, 1.275)',
181
+ 'heavy-bounce': 'cubic-bezier(0.68, -0.55, 0.265, 1.55)',
182
+ };
183
+ function resolveEasing(easing) {
184
+ var _a;
185
+ if (typeof easing === 'string') {
186
+ return (_a = EASING_MAP[easing]) !== null && _a !== void 0 ? _a : easing;
187
+ }
188
+ if (Array.isArray(easing)) {
189
+ return `cubic-bezier(${easing.join(', ')})`;
190
+ }
191
+ if (typeof easing === 'function') {
192
+ // Functions cannot be expressed as a CSS easing string; the core samples
193
+ // them into a `linear()` easing (or keyframes on older browsers).
194
+ return 'linear';
195
+ }
196
+ return 'ease';
197
+ }
198
+
199
+ /**
200
+ * use-scroll-animate - Core Implementation
201
+ * Uses IntersectionObserver + Web Animations API for zero-dependency,
202
+ * high-performance scroll-triggered animations.
203
+ */
204
+ const DEFAULT_CONFIG = {
205
+ defaultAnimation: 'fade-in-up',
206
+ defaultDuration: 600,
207
+ defaultDelay: 0,
208
+ defaultEasing: 'ease',
209
+ defaultThreshold: 0.1,
210
+ defaultRootMargin: '0px',
211
+ defaultRepeat: false,
212
+ defaultOnce: true,
213
+ defaultOffset: 0,
214
+ hiddenClass: 'sa-hidden',
215
+ visibleClass: 'sa-visible',
216
+ useClassNames: false,
217
+ disabled: false,
218
+ root: null,
219
+ autoUnregister: true,
220
+ };
221
+ const noop = () => undefined;
222
+ /* ------------------------------------------------------------------ */
223
+ /* Environment helpers (all SSR-safe: never touch globals at import) */
224
+ /* ------------------------------------------------------------------ */
225
+ const hasDOM = () => typeof window !== 'undefined' && typeof document !== 'undefined';
226
+ /** @internal */
227
+ const supportsObserver = () => hasDOM() && typeof IntersectionObserver !== 'undefined';
228
+ let reducedMotionQuery;
229
+ /** @internal Whether the user asked the OS/browser to reduce motion. */
230
+ function prefersReducedMotion() {
231
+ if (!hasDOM())
232
+ return false;
233
+ if (reducedMotionQuery === undefined) {
234
+ reducedMotionQuery =
235
+ typeof window.matchMedia === 'function' ? window.matchMedia('(prefers-reduced-motion: reduce)') : null;
236
+ }
237
+ return !!reducedMotionQuery && reducedMotionQuery.matches;
238
+ }
239
+ /* ------------------------------------------------------------------ */
240
+ /* Option parsing */
241
+ /* ------------------------------------------------------------------ */
242
+ function num(value) {
243
+ if (value === undefined || value.trim() === '')
244
+ return undefined;
245
+ const n = parseFloat(value);
246
+ return Number.isFinite(n) ? n : undefined;
247
+ }
248
+ /** Numeric strings ("100") become numbers (px); strings with units stay as-is. */
249
+ function lengthValue(value) {
250
+ if (value === undefined || value.trim() === '')
251
+ return undefined;
252
+ const v = value.trim();
253
+ return /^-?(\d+\.?\d*|\.\d+)$/.test(v) ? parseFloat(v) : v;
254
+ }
255
+ const DEFAULT_PROGRESS_VAR = '--sa-progress';
256
+ /** `''` (bare attribute) -> default name; `sa-progress` -> `--sa-progress`. */
257
+ function normalizeVar(name) {
258
+ const v = name.trim();
259
+ if (!v)
260
+ return DEFAULT_PROGRESS_VAR;
261
+ return v.startsWith('--') ? v : `--${v}`;
262
+ }
263
+ function parseDataAttributes(el, config) {
264
+ var _a;
265
+ const dataset = el.dataset || {};
266
+ const opts = {};
267
+ if (dataset.saAnimation) {
268
+ const anim = dataset.saAnimation;
269
+ opts.animation = (anim.includes(',') ? anim.split(',').map((s) => s.trim()) : anim.trim());
270
+ }
271
+ opts.duration = num(dataset.saDuration);
272
+ opts.delay = num(dataset.saDelay);
273
+ if (dataset.saEasing) {
274
+ const e = dataset.saEasing.trim();
275
+ if (e.startsWith('[')) {
276
+ try {
277
+ opts.easing = JSON.parse(e);
278
+ }
279
+ catch (_b) {
280
+ // Malformed JSON: fall back to the default easing instead of throwing
281
+ }
282
+ }
283
+ else {
284
+ opts.easing = e;
285
+ }
286
+ }
287
+ if (dataset.saThreshold) {
288
+ const t = dataset.saThreshold;
289
+ opts.threshold = t.includes(',')
290
+ ? t.split(',').map(parseFloat).filter(Number.isFinite)
291
+ : num(t);
292
+ }
293
+ if (dataset.saRootMargin)
294
+ opts.rootMargin = dataset.saRootMargin;
295
+ if (dataset.saRepeat !== undefined)
296
+ opts.repeat = dataset.saRepeat !== 'false';
297
+ if (dataset.saOnce !== undefined)
298
+ opts.once = dataset.saOnce !== 'false';
299
+ opts.offset = num(dataset.saOffset);
300
+ opts.stagger = num(dataset.saStagger);
301
+ if (dataset.saProgressVar !== undefined)
302
+ opts.progressVar = normalizeVar(dataset.saProgressVar);
303
+ if (dataset.saProgress)
304
+ opts.progressMode = dataset.saProgress.trim() === 'scroll' ? 'scroll' : 'ratio';
305
+ if (dataset.saParallaxX || dataset.saParallaxY || dataset.saParallaxRotate || dataset.saParallaxScale) {
306
+ opts.parallax = {
307
+ x: lengthValue(dataset.saParallaxX),
308
+ y: lengthValue(dataset.saParallaxY),
309
+ rotate: num(dataset.saParallaxRotate),
310
+ scale: num(dataset.saParallaxScale),
311
+ speed: (_a = num(dataset.saParallaxSpeed)) !== null && _a !== void 0 ? _a : 1,
312
+ };
313
+ }
314
+ return mergeOptions(opts, config);
315
+ }
316
+ function mergeOptions(opts, config) {
317
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
318
+ const repeat = (_a = opts.repeat) !== null && _a !== void 0 ? _a : config.defaultRepeat;
319
+ const threshold = (_b = opts.threshold) !== null && _b !== void 0 ? _b : config.defaultThreshold;
320
+ return {
321
+ animation: (_c = opts.animation) !== null && _c !== void 0 ? _c : config.defaultAnimation,
322
+ duration: (_d = opts.duration) !== null && _d !== void 0 ? _d : config.defaultDuration,
323
+ delay: (_e = opts.delay) !== null && _e !== void 0 ? _e : config.defaultDelay,
324
+ easing: (_f = opts.easing) !== null && _f !== void 0 ? _f : config.defaultEasing,
325
+ threshold: Array.isArray(threshold) && threshold.length === 0 ? config.defaultThreshold : threshold,
326
+ rootMargin: (_g = opts.rootMargin) !== null && _g !== void 0 ? _g : config.defaultRootMargin,
327
+ repeat,
328
+ once: (_h = opts.once) !== null && _h !== void 0 ? _h : (repeat ? false : config.defaultOnce),
329
+ offset: (_j = opts.offset) !== null && _j !== void 0 ? _j : config.defaultOffset,
330
+ stagger: (_k = opts.stagger) !== null && _k !== void 0 ? _k : 0,
331
+ parallax: (_l = opts.parallax) !== null && _l !== void 0 ? _l : {},
332
+ onStart: (_m = opts.onStart) !== null && _m !== void 0 ? _m : noop,
333
+ onComplete: (_o = opts.onComplete) !== null && _o !== void 0 ? _o : noop,
334
+ onEnter: (_p = opts.onEnter) !== null && _p !== void 0 ? _p : noop,
335
+ onLeave: (_q = opts.onLeave) !== null && _q !== void 0 ? _q : noop,
336
+ onProgress: (_r = opts.onProgress) !== null && _r !== void 0 ? _r : noop,
337
+ progressMode: (_s = opts.progressMode) !== null && _s !== void 0 ? _s : 'ratio',
338
+ progressVar: opts.progressVar ? normalizeVar(opts.progressVar) : '',
339
+ };
340
+ }
341
+ function resolveTargets(target) {
342
+ if (!target || !hasDOM())
343
+ return [];
344
+ if (typeof target === 'string')
345
+ return Array.from(document.querySelectorAll(target));
346
+ if (target instanceof Element)
347
+ return [target];
348
+ if (Array.isArray(target) || target instanceof NodeList) {
349
+ return Array.from(target).filter((el) => el instanceof Element);
350
+ }
351
+ return [];
352
+ }
353
+ /**
354
+ * Apply `offset` to the bottom edge of a rootMargin, preserving the other
355
+ * three sides. `offset: 100` means "trigger 100px later" (bottom -100px).
356
+ * @internal
357
+ */
358
+ function applyOffset(rootMargin, offset) {
359
+ var _a, _b, _c;
360
+ if (!offset)
361
+ return rootMargin;
362
+ const parts = (rootMargin || '0px').trim().split(/\s+/);
363
+ const top = parts[0];
364
+ const right = (_a = parts[1]) !== null && _a !== void 0 ? _a : top;
365
+ const bottom = (_b = parts[2]) !== null && _b !== void 0 ? _b : top;
366
+ const left = (_c = parts[3]) !== null && _c !== void 0 ? _c : right;
367
+ const m = /^(-?\d*\.?\d+)(px)?$/.exec(bottom);
368
+ const base = m ? parseFloat(m[1]) : 0; // non-px bottoms (e.g. %) cannot be combined; offset wins
369
+ return `${top} ${right} ${base - offset}px ${left}`;
370
+ }
371
+ function hasParallax(p) {
372
+ return !!p && Object.keys(p).some((k) => p[k] !== undefined);
373
+ }
374
+ function needsProgress(opts) {
375
+ return hasParallax(opts.parallax) || opts.onProgress !== noop || !!opts.progressVar;
376
+ }
377
+ /**
378
+ * True scroll progress of `el` through the viewport (or `root`): 0 when its top
379
+ * edge reaches the bottom of the viewport, 1 when its bottom edge passes the top.
380
+ * Works for elements taller than the viewport. Returns 0 without a DOM.
381
+ */
382
+ function getScrollProgress(el, root) {
383
+ if (!hasDOM())
384
+ return 0;
385
+ const rect = el.getBoundingClientRect();
386
+ let top = 0;
387
+ let height = window.innerHeight || document.documentElement.clientHeight || 0;
388
+ if (root) {
389
+ const r = root.getBoundingClientRect();
390
+ top = r.top;
391
+ height = r.height;
392
+ }
393
+ const total = height + rect.height;
394
+ if (total <= 0)
395
+ return 0;
396
+ const p = (top + height - rect.top) / total;
397
+ return p < 0 ? 0 : p > 1 ? 1 : p;
398
+ }
399
+ /* ------------------------------------------------------------------ */
400
+ /* Animation */
401
+ /* ------------------------------------------------------------------ */
402
+ /** The animation currently running on an element, so it can be cancelled/replaced. */
403
+ const running = new WeakMap();
404
+ const timers = new WeakMap();
405
+ function cancelRunning(el) {
406
+ const anim = running.get(el);
407
+ if (anim) {
408
+ running.delete(el);
409
+ anim.onfinish = null;
410
+ anim.cancel();
411
+ }
412
+ const timer = timers.get(el);
413
+ if (timer !== undefined) {
414
+ clearTimeout(timer);
415
+ timers.delete(el);
416
+ }
417
+ }
418
+ function setStyles(el, styles) {
419
+ const style = el.style;
420
+ if (!style)
421
+ return;
422
+ Object.keys(styles).forEach((prop) => {
423
+ style[prop] = String(styles[prop]);
424
+ });
425
+ }
426
+ const NUM_UNIT = /(-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)([a-z%]*)/gi;
427
+ /**
428
+ * Interpolate two CSS values at `t`. Numbers interpolate directly; strings
429
+ * interpolate when they share the same structure (e.g. `translateY(40px)` ->
430
+ * `translateY(0px)`, or `scale(0.8)` -> `scale(1)`). Otherwise snaps at 0.5.
431
+ * @internal
432
+ */
433
+ function interpolateValue(from, to, t) {
434
+ if (typeof from === 'number' && typeof to === 'number')
435
+ return from + (to - from) * t;
436
+ const a = String(from);
437
+ const b = String(to);
438
+ const ta = [];
439
+ const tb = [];
440
+ const skA = a.replace(NUM_UNIT, (_, n, u) => (ta.push([parseFloat(n), u]), '#'));
441
+ const skB = b.replace(NUM_UNIT, (_, n, u) => (tb.push([parseFloat(n), u]), '#'));
442
+ if (skA !== skB || ta.length !== tb.length)
443
+ return t < 0.5 ? from : to;
444
+ let i = 0;
445
+ let ok = true;
446
+ const out = skA.replace(/#/g, () => {
447
+ const [na, ua] = ta[i];
448
+ const [nb, ub] = tb[i++];
449
+ if (ua !== ub && na !== 0 && nb !== 0 && ua && ub)
450
+ ok = false;
451
+ const unit = ua || ub;
452
+ return `${+(na + (nb - na) * t).toFixed(4)}${unit}`;
453
+ });
454
+ return ok ? out : t < 0.5 ? from : to;
455
+ }
456
+ const EASING_SAMPLES = 30;
457
+ let linearSupported;
458
+ function supportsLinearEasing() {
459
+ if (linearSupported === undefined) {
460
+ linearSupported =
461
+ typeof CSS !== 'undefined' &&
462
+ typeof CSS.supports === 'function' &&
463
+ CSS.supports('animation-timing-function', 'linear(0, 1)');
464
+ }
465
+ return linearSupported;
466
+ }
467
+ function sampleEasing(fn) {
468
+ const values = [];
469
+ for (let i = 0; i <= EASING_SAMPLES; i++) {
470
+ const v = fn(i / EASING_SAMPLES);
471
+ values.push(Number.isFinite(v) ? +v.toFixed(4) : i / EASING_SAMPLES);
472
+ }
473
+ return values;
474
+ }
475
+ function buildAnimation(preset, easing) {
476
+ if (typeof easing !== 'function') {
477
+ return { keyframes: [preset.from, preset.to], easing: resolveEasing(easing) };
478
+ }
479
+ const samples = sampleEasing(easing);
480
+ // Modern browsers: an exact, property-agnostic `linear()` easing curve.
481
+ if (supportsLinearEasing()) {
482
+ return { keyframes: [preset.from, preset.to], easing: `linear(${samples.join(', ')})` };
483
+ }
484
+ // Fallback: approximate the curve with interpolated keyframes.
485
+ const props = Object.keys(preset.from).filter((p) => p in preset.to);
486
+ const keyframes = samples.map((eased, i) => {
487
+ const frame = { offset: i / EASING_SAMPLES };
488
+ props.forEach((prop) => {
489
+ frame[prop] = interpolateValue(preset.from[prop], preset.to[prop], eased);
490
+ });
491
+ return frame;
492
+ });
493
+ return { keyframes, easing: 'linear' };
494
+ }
495
+ /** Make an element visible without animating (reduced motion / disabled / no WAAPI). */
496
+ function reveal(el, config) {
497
+ cancelRunning(el);
498
+ if (config.useClassNames) {
499
+ el.classList.remove(config.hiddenClass);
500
+ el.classList.add(config.visibleClass);
501
+ }
502
+ else {
503
+ const style = el.style;
504
+ if (style)
505
+ style.opacity = '';
506
+ }
507
+ }
508
+ /** @internal Cancel a running/pending animation and make the element visible. */
509
+ function stopAnimation(el, config = {}) {
510
+ reveal(el, { ...DEFAULT_CONFIG, ...config });
511
+ }
512
+ /** @internal Whether animations should be skipped entirely. */
513
+ function motionDisabled(config) {
514
+ return !!config.disabled || prefersReducedMotion();
515
+ }
516
+ function runAnimation(el, opts, config, staggerIndex = 0) {
517
+ const { duration, delay, stagger, onStart, onComplete } = opts;
518
+ const totalDelay = Math.max(0, delay + staggerIndex * stagger);
519
+ cancelRunning(el);
520
+ if (motionDisabled(config)) {
521
+ reveal(el, config);
522
+ onStart(el);
523
+ onComplete(el);
524
+ return;
525
+ }
526
+ if (config.useClassNames) {
527
+ if (totalDelay > 0)
528
+ el.style.animationDelay = `${totalDelay}ms`;
529
+ el.classList.remove(config.hiddenClass);
530
+ el.classList.add(config.visibleClass);
531
+ onStart(el);
532
+ timers.set(el, setTimeout(() => {
533
+ timers.delete(el);
534
+ onComplete(el);
535
+ }, duration + totalDelay));
536
+ return;
537
+ }
538
+ const preset = resolvePreset(opts.animation);
539
+ // Presets that don't animate opacity (slide-*, clip-*, scale-x, ...) would
540
+ // otherwise stay at the `opacity: 0` applied while waiting to enter.
541
+ if (!('opacity' in preset.to)) {
542
+ const style = el.style;
543
+ if (style && style.opacity === '0')
544
+ style.opacity = '';
545
+ }
546
+ if (typeof el.animate !== 'function') {
547
+ setStyles(el, preset.to);
548
+ onStart(el);
549
+ onComplete(el);
550
+ return;
551
+ }
552
+ const built = buildAnimation(preset, opts.easing);
553
+ const timing = { duration, delay: totalDelay, easing: built.easing, fill: 'both' };
554
+ let anim;
555
+ try {
556
+ anim = el.animate(built.keyframes, timing);
557
+ }
558
+ catch (_a) {
559
+ // Invalid user easing string (WAAPI throws a TypeError): fall back to 'ease'
560
+ anim = el.animate(built.keyframes, { ...timing, easing: 'ease' });
561
+ }
562
+ running.set(el, anim);
563
+ onStart(el);
564
+ anim.onfinish = () => {
565
+ if (running.get(el) === anim) {
566
+ running.delete(el);
567
+ // Persist the end state inline and drop the filling animation. This frees
568
+ // the Animation object and lets later inline styles (parallax, user code)
569
+ // take effect instead of being masked by `fill: forwards`.
570
+ try {
571
+ anim.commitStyles();
572
+ }
573
+ catch (_a) {
574
+ setStyles(el, preset.to);
575
+ }
576
+ anim.cancel();
577
+ }
578
+ onComplete(el);
579
+ };
580
+ }
581
+ function applyParallax(el, progress, parallax) {
582
+ const { x = 0, y = 0, rotate = 0, scale = 1, speed = 1 } = parallax;
583
+ const p = (progress - 0.5) * 2 * speed;
584
+ const axis = (v) => (typeof v === 'number' ? `${v * p}px` : `calc(${v} * ${p})`);
585
+ let transform = '';
586
+ if (x)
587
+ transform += ` translateX(${axis(x)})`;
588
+ if (y)
589
+ transform += ` translateY(${axis(y)})`;
590
+ if (rotate)
591
+ transform += ` rotate(${rotate * p}deg)`;
592
+ if (scale !== 1)
593
+ transform += ` scale(${1 + (scale - 1) * p})`;
594
+ el.style.transform = transform.trim();
595
+ }
596
+ function hideElement(el, config) {
597
+ cancelRunning(el);
598
+ if (config.useClassNames) {
599
+ el.classList.add(config.hiddenClass);
600
+ el.classList.remove(config.visibleClass);
601
+ }
602
+ else {
603
+ const style = el.style;
604
+ if (style)
605
+ style.opacity = '0';
606
+ }
607
+ }
608
+ /** @internal Hide an element before its entrance animation, unless motion is off. */
609
+ function prepareElement(el, config = {}) {
610
+ const full = { ...DEFAULT_CONFIG, ...config };
611
+ if (!motionDisabled(full))
612
+ hideElement(el, full);
613
+ }
614
+ let progressThresholds;
615
+ function getProgressThresholds() {
616
+ if (!progressThresholds) {
617
+ progressThresholds = [];
618
+ for (let i = 0; i <= 100; i++)
619
+ progressThresholds.push(i / 100);
620
+ }
621
+ return progressThresholds;
622
+ }
623
+ const PASSIVE = { passive: true };
624
+ /* ------------------------------------------------------------------ */
625
+ /* Instance */
626
+ /* ------------------------------------------------------------------ */
627
+ function createScrollAnimate(userConfig = {}) {
628
+ let config = { ...DEFAULT_CONFIG, ...userConfig };
629
+ const registry = new Map();
630
+ // `once` elements that finished and were dropped from the registry (autoUnregister).
631
+ let finished = new WeakSet();
632
+ // Elements in `progressMode: 'scroll'` that are currently inside the viewport.
633
+ const scrolling = new Set();
634
+ let frame = 0;
635
+ let listening = null;
636
+ // Active watch() MutationObservers, disconnected by destroy().
637
+ const watchers = new Set();
638
+ // Observers are shared between elements with the same root/threshold/rootMargin,
639
+ // instead of one (or two) IntersectionObservers per element.
640
+ const pools = new Map();
641
+ function pooled(root, key, create) {
642
+ let pool = pools.get(root);
643
+ if (!pool)
644
+ pools.set(root, (pool = new Map()));
645
+ let io = pool.get(key);
646
+ if (!io)
647
+ pool.set(key, (io = create()));
648
+ return io;
649
+ }
650
+ function teardown(el, restore) {
651
+ var _a;
652
+ const record = registry.get(el);
653
+ if (!record)
654
+ return;
655
+ record.observer.unobserve(el);
656
+ (_a = record.progressObserver) === null || _a === void 0 ? void 0 : _a.unobserve(el);
657
+ registry.delete(el);
658
+ untrack(el);
659
+ // An element that never animated would otherwise stay invisible forever.
660
+ if (restore && !record.animated)
661
+ reveal(el, config);
662
+ }
663
+ function pruneDetached() {
664
+ registry.forEach((record, el) => {
665
+ if (el.isConnected === false)
666
+ teardown(el, false);
667
+ });
668
+ }
669
+ function emitProgress(el, record, progress) {
670
+ const opts = record.options;
671
+ opts.onProgress(el, progress);
672
+ if (opts.progressVar) {
673
+ const style = el.style;
674
+ if (style)
675
+ style.setProperty(opts.progressVar, String(+progress.toFixed(4)));
676
+ }
677
+ if (hasParallax(opts.parallax) && !motionDisabled(config))
678
+ applyParallax(el, progress, opts.parallax);
679
+ }
680
+ function update() {
681
+ frame = 0;
682
+ scrolling.forEach((el) => {
683
+ const record = registry.get(el);
684
+ if (record)
685
+ emitProgress(el, record, getScrollProgress(el, config.root));
686
+ });
687
+ }
688
+ // rAF-throttled; IntersectionObserver-capable browsers all have rAF.
689
+ const schedule = () => frame || (frame = requestAnimationFrame(update));
690
+ function listen(on) {
691
+ if (on === !!listening)
692
+ return;
693
+ const method = on ? 'addEventListener' : 'removeEventListener';
694
+ const target = listening || config.root || window;
695
+ target[method]('scroll', schedule, PASSIVE);
696
+ window[method]('resize', schedule, PASSIVE);
697
+ listening = on ? target : null;
698
+ if (!on && frame) {
699
+ cancelAnimationFrame(frame);
700
+ frame = 0;
701
+ }
702
+ }
703
+ function untrack(el) {
704
+ if (scrolling.delete(el) && !scrolling.size)
705
+ listen(false);
706
+ }
707
+ function onScrollIntersect(entries) {
708
+ entries.forEach((entry) => {
709
+ const el = entry.target;
710
+ const record = registry.get(el);
711
+ if (!record)
712
+ return;
713
+ if (entry.isIntersecting) {
714
+ scrolling.add(el);
715
+ listen(true);
716
+ }
717
+ else {
718
+ untrack(el);
719
+ }
720
+ // Emit right away so the edges (0 / 1) are reported even on fast scrolls.
721
+ emitProgress(el, record, getScrollProgress(el, config.root));
722
+ });
723
+ }
724
+ function onIntersect(entries) {
725
+ const staggerCounts = new Map();
726
+ entries.forEach((entry) => {
727
+ var _a;
728
+ const el = entry.target;
729
+ const record = registry.get(el);
730
+ if (!record)
731
+ return;
732
+ const opts = record.options;
733
+ if (el.isConnected === false) {
734
+ teardown(el, false);
735
+ return;
736
+ }
737
+ if (entry.isIntersecting) {
738
+ opts.onEnter(el);
739
+ if (record.animated && !opts.repeat)
740
+ return;
741
+ // Stagger relative to siblings revealed in the same batch, so elements
742
+ // scrolled into view later don't inherit an ever-growing delay.
743
+ let staggerIndex = 0;
744
+ if (opts.stagger > 0) {
745
+ const parent = el.parentElement;
746
+ staggerIndex = (_a = staggerCounts.get(parent)) !== null && _a !== void 0 ? _a : 0;
747
+ staggerCounts.set(parent, staggerIndex + 1);
748
+ }
749
+ runAnimation(el, opts, config, staggerIndex);
750
+ record.animated = true;
751
+ if (opts.once && !opts.repeat) {
752
+ // Keep the progress observer: parallax/onProgress must keep working.
753
+ record.observer.unobserve(el);
754
+ if (config.autoUnregister && !record.progressObserver) {
755
+ // Nothing left to watch: free the record (the running animation
756
+ // keeps its own reference until it finishes).
757
+ finished.add(el);
758
+ teardown(el, false);
759
+ }
760
+ }
761
+ }
762
+ else {
763
+ opts.onLeave(el);
764
+ if (opts.repeat && record.animated) {
765
+ if (!motionDisabled(config))
766
+ hideElement(el, config);
767
+ record.animated = false;
768
+ }
769
+ }
770
+ });
771
+ }
772
+ function onProgress(entries) {
773
+ entries.forEach((entry) => {
774
+ const record = registry.get(entry.target);
775
+ if (!record)
776
+ return;
777
+ emitProgress(entry.target, record, entry.intersectionRatio);
778
+ });
779
+ }
780
+ function getObserver(opts) {
781
+ const rootMargin = applyOffset(opts.rootMargin, opts.offset);
782
+ const threshold = opts.threshold;
783
+ const root = config.root;
784
+ return pooled(root, `m|${rootMargin}|${String(threshold)}`, () => new IntersectionObserver(onIntersect, { threshold, rootMargin, root: root }));
785
+ }
786
+ function getProgressObserver(opts) {
787
+ const root = config.root;
788
+ if (opts.progressMode === 'scroll') {
789
+ // Only used to know when to start/stop measuring; progress itself comes
790
+ // from a single shared, rAF-throttled passive scroll listener.
791
+ return pooled(root, `s|${opts.rootMargin}`, () => new IntersectionObserver(onScrollIntersect, { threshold: 0, rootMargin: opts.rootMargin, root: root }));
792
+ }
793
+ return pooled(root, `p|${opts.rootMargin}`, () => new IntersectionObserver(onProgress, {
794
+ threshold: getProgressThresholds(),
795
+ rootMargin: opts.rootMargin,
796
+ root: root,
797
+ }));
798
+ }
799
+ function attach(el, record, observeMain) {
800
+ var _a;
801
+ record.observer = getObserver(record.options);
802
+ if (observeMain)
803
+ record.observer.observe(el);
804
+ record.progressObserver = needsProgress(record.options) ? getProgressObserver(record.options) : undefined;
805
+ (_a = record.progressObserver) === null || _a === void 0 ? void 0 : _a.observe(el);
806
+ }
807
+ function observeElement(el, opts) {
808
+ if (registry.has(el) || finished.has(el))
809
+ return;
810
+ if (!supportsObserver()) {
811
+ // No IntersectionObserver (very old browser): never leave content hidden.
812
+ reveal(el, config);
813
+ return;
814
+ }
815
+ if (!motionDisabled(config))
816
+ hideElement(el, config);
817
+ const record = { element: el, options: opts, animated: false };
818
+ registry.set(el, record);
819
+ attach(el, record, true);
820
+ }
821
+ function observeDataElement(el) {
822
+ if (!registry.has(el))
823
+ observeElement(el, parseDataAttributes(el, config));
824
+ }
825
+ const instance = {
826
+ observe(target, options = {}) {
827
+ pruneDetached();
828
+ const opts = mergeOptions(options, config);
829
+ resolveTargets(target).forEach((el) => observeElement(el, opts));
830
+ },
831
+ unobserve(target) {
832
+ resolveTargets(target).forEach((el) => {
833
+ finished.delete(el);
834
+ teardown(el, true);
835
+ });
836
+ },
837
+ init(rootElement) {
838
+ const scope = rootElement !== null && rootElement !== void 0 ? rootElement : (hasDOM() ? document : null);
839
+ if (!scope)
840
+ return;
841
+ pruneDetached();
842
+ scope.querySelectorAll('[data-sa]').forEach(observeDataElement);
843
+ },
844
+ watch(rootElement) {
845
+ const scope = rootElement !== null && rootElement !== void 0 ? rootElement : (hasDOM() ? document : null);
846
+ if (!scope || typeof MutationObserver === 'undefined')
847
+ return noop;
848
+ instance.init(scope);
849
+ const observeTree = (node) => {
850
+ if (node.hasAttribute('data-sa'))
851
+ observeDataElement(node);
852
+ node.querySelectorAll('[data-sa]').forEach(observeDataElement);
853
+ };
854
+ const mo = new MutationObserver((records) => {
855
+ let removed = false;
856
+ records.forEach((record) => {
857
+ if (record.type === 'attributes') {
858
+ const target = record.target;
859
+ if (target.isConnected !== false)
860
+ observeTree(target);
861
+ return;
862
+ }
863
+ record.addedNodes.forEach((node) => {
864
+ if (node instanceof Element && node.isConnected !== false)
865
+ observeTree(node);
866
+ });
867
+ if (record.removedNodes.length)
868
+ removed = true;
869
+ });
870
+ // Free elements that left the DOM (they can't animate any more).
871
+ if (removed)
872
+ pruneDetached();
873
+ });
874
+ mo.observe(scope, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-sa'] });
875
+ watchers.add(mo);
876
+ return () => {
877
+ mo.disconnect();
878
+ watchers.delete(mo);
879
+ };
880
+ },
881
+ destroy() {
882
+ watchers.forEach((mo) => mo.disconnect());
883
+ watchers.clear();
884
+ registry.forEach((record, el) => {
885
+ if (!record.animated)
886
+ reveal(el, config);
887
+ });
888
+ pools.forEach((pool) => pool.forEach((io) => io.disconnect()));
889
+ pools.clear();
890
+ registry.clear();
891
+ scrolling.clear();
892
+ listen(false);
893
+ finished = new WeakSet();
894
+ },
895
+ refresh() {
896
+ // Rebuild observers (e.g. after configure({ root })) without re-hiding or
897
+ // replaying elements that have already animated.
898
+ pools.forEach((pool) => pool.forEach((io) => io.disconnect()));
899
+ pools.clear();
900
+ scrolling.clear();
901
+ listen(false);
902
+ pruneDetached();
903
+ if (!supportsObserver())
904
+ return;
905
+ registry.forEach((record, el) => {
906
+ const done = record.animated && record.options.once && !record.options.repeat;
907
+ attach(el, record, !done);
908
+ });
909
+ },
910
+ animate(target, options = {}) {
911
+ const opts = mergeOptions(options, config);
912
+ resolveTargets(target).forEach((el) => runAnimation(el, opts, config, 0));
913
+ },
914
+ getObservedElements() {
915
+ return Array.from(registry.values());
916
+ },
917
+ configure(newConfig) {
918
+ config = { ...config, ...newConfig };
919
+ },
920
+ };
921
+ return instance;
922
+ }
923
+
924
+ /**
925
+ * use-scroll-animate - Staggered children
926
+ * Reveal a container's children one after another when the container scrolls
927
+ * into view, optionally also animating children that are added later.
928
+ */
929
+ let fallback$1 = null;
930
+ /**
931
+ * Animate the children of `container` with a stagger once it enters the
932
+ * viewport. Returns a cleanup function. SSR-safe (no-op without a DOM).
933
+ *
934
+ * @example
935
+ * const stop = staggerChildren(document.querySelector('ul'), { stagger: 60, observeChildren: true });
936
+ */
937
+ function staggerChildren(container, options = {}, instance) {
938
+ if (!container || !hasDOM() || !supportsObserver())
939
+ return () => undefined; // leave content visible
940
+ const sa = instance || fallback$1 || (fallback$1 = createScrollAnimate());
941
+ const { stagger = 80, delay = 0, threshold = 0.1, rootMargin = '0px', observeChildren = false, ...rest } = options;
942
+ let items = Array.from(container.children);
943
+ let revealed = false;
944
+ const late = [];
945
+ items.forEach((child) => prepareElement(child));
946
+ const io = new IntersectionObserver((entries) => {
947
+ if (revealed || !entries.some((entry) => entry.isIntersecting))
948
+ return;
949
+ revealed = true;
950
+ io.disconnect();
951
+ items.forEach((child, i) => {
952
+ if (child.parentNode === container)
953
+ sa.animate(child, { ...rest, delay: delay + i * stagger });
954
+ });
955
+ items = [];
956
+ }, { threshold, rootMargin });
957
+ io.observe(container);
958
+ let mo;
959
+ if (observeChildren && typeof MutationObserver !== 'undefined') {
960
+ mo = new MutationObserver((records) => {
961
+ records.forEach((record) => {
962
+ record.addedNodes.forEach((node) => {
963
+ if (!(node instanceof Element) || node.parentNode !== container)
964
+ return;
965
+ if (!revealed) {
966
+ prepareElement(node);
967
+ items.push(node);
968
+ }
969
+ else {
970
+ // The core engine staggers siblings relative to the batch that
971
+ // enters the viewport together.
972
+ late.push(node);
973
+ sa.observe(node, { ...rest, delay, stagger, threshold, rootMargin });
974
+ }
975
+ });
976
+ record.removedNodes.forEach((node) => {
977
+ if (!(node instanceof Element))
978
+ return;
979
+ items = items.filter((el) => el !== node);
980
+ const i = late.indexOf(node);
981
+ if (i >= 0) {
982
+ late.splice(i, 1);
983
+ sa.unobserve(node);
984
+ }
985
+ });
986
+ });
987
+ });
988
+ mo.observe(container, { childList: true });
989
+ }
990
+ return () => {
991
+ io.disconnect();
992
+ mo === null || mo === void 0 ? void 0 : mo.disconnect();
993
+ // Stopped before the container was revealed: never leave the children hidden.
994
+ if (!revealed) {
995
+ revealed = true;
996
+ items.forEach((child) => stopAnimation(child));
997
+ items = [];
998
+ }
999
+ late.forEach((el) => sa.unobserve(el));
1000
+ late.length = 0;
1001
+ };
1002
+ }
1003
+
1004
+ /**
1005
+ * use-scroll-animate - Sequence / timeline helper
1006
+ * Chain animations on several targets, one after another (or overlapping).
1007
+ */
1008
+ let fallback = null;
1009
+ function plan(steps, defaults) {
1010
+ const out = [];
1011
+ let cursor = 0;
1012
+ steps.forEach((step) => {
1013
+ var _a, _b;
1014
+ const { target, gap = 0, at, ...stepOpts } = step;
1015
+ const opts = { ...defaults, ...stepOpts };
1016
+ const duration = (_a = opts.duration) !== null && _a !== void 0 ? _a : 600;
1017
+ const start = Math.max(0, at !== null && at !== void 0 ? at : cursor + gap) + ((_b = opts.delay) !== null && _b !== void 0 ? _b : 0);
1018
+ let end = Math.max(cursor, start);
1019
+ resolveTargets(target).forEach((el, i) => {
1020
+ var _a;
1021
+ const delay = start + i * ((_a = opts.stagger) !== null && _a !== void 0 ? _a : 0);
1022
+ out.push({ el, opts: { ...opts, duration, delay, stagger: 0 }, end: delay + duration });
1023
+ end = Math.max(end, delay + duration);
1024
+ });
1025
+ cursor = end;
1026
+ });
1027
+ return out;
1028
+ }
1029
+ /**
1030
+ * Build a timeline of animations.
1031
+ *
1032
+ * @example
1033
+ * sequence([
1034
+ * { target: '.title', animation: 'fade-in-up' },
1035
+ * { target: '.subtitle', animation: 'blur-in', gap: -300 }, // overlap by 300ms
1036
+ * { target: '.card', animation: 'scale-up', stagger: 80 },
1037
+ * ], { trigger: '.hero' });
1038
+ */
1039
+ function sequence(steps, options = {}) {
1040
+ var _a, _b;
1041
+ const { trigger, instance, ...defaults } = options;
1042
+ const sa = () => instance || fallback || (fallback = createScrollAnimate());
1043
+ let io;
1044
+ let active = [];
1045
+ let settle;
1046
+ // Targets hidden while waiting for `trigger`; revealed if cancelled before it fires.
1047
+ let prepared = [];
1048
+ const controller = {
1049
+ play() {
1050
+ controller.cancel();
1051
+ if (!hasDOM())
1052
+ return Promise.resolve();
1053
+ active = plan(steps, defaults);
1054
+ return new Promise((resolve) => {
1055
+ let left = active.length;
1056
+ settle = () => {
1057
+ settle = undefined;
1058
+ resolve();
1059
+ };
1060
+ if (!left)
1061
+ return settle();
1062
+ const run = active;
1063
+ run.forEach(({ el, opts }) => {
1064
+ const done = opts.onComplete;
1065
+ sa().animate(el, {
1066
+ ...opts,
1067
+ onComplete: (node) => {
1068
+ done === null || done === void 0 ? void 0 : done(node);
1069
+ if (run === active && --left === 0)
1070
+ settle === null || settle === void 0 ? void 0 : settle();
1071
+ },
1072
+ });
1073
+ });
1074
+ });
1075
+ },
1076
+ cancel() {
1077
+ io === null || io === void 0 ? void 0 : io.disconnect();
1078
+ io = undefined;
1079
+ prepared.forEach((el) => stopAnimation(el));
1080
+ prepared = [];
1081
+ active.forEach(({ el }) => stopAnimation(el));
1082
+ active = [];
1083
+ settle === null || settle === void 0 ? void 0 : settle();
1084
+ },
1085
+ duration() {
1086
+ return plan(steps, defaults).reduce((max, p) => Math.max(max, p.end), 0);
1087
+ },
1088
+ };
1089
+ if (trigger && hasDOM() && supportsObserver()) {
1090
+ const el = resolveTargets(trigger)[0];
1091
+ if (el) {
1092
+ prepared = plan(steps, defaults).map(({ el: target }) => target);
1093
+ prepared.forEach((target) => prepareElement(target));
1094
+ io = new IntersectionObserver((entries) => {
1095
+ if (!entries.some((e) => e.isIntersecting))
1096
+ return;
1097
+ io === null || io === void 0 ? void 0 : io.disconnect();
1098
+ io = undefined;
1099
+ prepared = []; // play() takes over from here
1100
+ controller.play();
1101
+ }, { threshold: (_a = defaults.threshold) !== null && _a !== void 0 ? _a : 0.1, rootMargin: (_b = defaults.rootMargin) !== null && _b !== void 0 ? _b : '0px' });
1102
+ io.observe(el);
1103
+ }
1104
+ }
1105
+ return controller;
1106
+ }
1107
+
1108
+ /**
1109
+ * use-scroll-animate - React Integration
1110
+ * Provides useScrollAnimate and useScrollStagger hooks for React applications.
1111
+ * `useScrollStagger({ observeChildren: true })` also animates children added later.
1112
+ *
1113
+ * Both hooks are thin wrappers around the core engine, so they share its
1114
+ * behaviour: `once`, `offset`, custom easing functions, parallax,
1115
+ * `prefers-reduced-motion` support, and proper cleanup on unmount.
1116
+ */
1117
+ const CALLBACKS = ['onStart', 'onComplete', 'onEnter', 'onLeave', 'onProgress'];
1118
+ /**
1119
+ * Wrap the callbacks that exist at mount so they always call the latest
1120
+ * version from the most recent render (avoids stale closures without
1121
+ * re-creating observers on every render).
1122
+ * @internal
1123
+ */
1124
+ function withLatestCallbacks(latest) {
1125
+ const initial = latest.current || {};
1126
+ const opts = { ...initial };
1127
+ CALLBACKS.forEach((name) => {
1128
+ if (typeof initial[name] === 'function') {
1129
+ opts[name] = (...args) => { var _a, _b; return (_b = (_a = latest.current) === null || _a === void 0 ? void 0 : _a[name]) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); };
1130
+ }
1131
+ });
1132
+ return opts;
1133
+ }
1134
+ function createReactHooks(React) {
1135
+ // Created lazily on the client so importing on the server is side-effect free.
1136
+ let instance = null;
1137
+ const getInstance = () => instance || (instance = createScrollAnimate());
1138
+ function useScrollAnimate(options = {}) {
1139
+ const ref = React.useRef(null);
1140
+ const optionsRef = React.useRef(options);
1141
+ optionsRef.current = options;
1142
+ React.useEffect(() => {
1143
+ const el = ref.current;
1144
+ if (!el)
1145
+ return;
1146
+ const sa = getInstance();
1147
+ sa.observe(el, withLatestCallbacks(optionsRef));
1148
+ return () => sa.unobserve(el);
1149
+ }, []);
1150
+ return ref;
1151
+ }
1152
+ function useScrollStagger(options = {}) {
1153
+ const ref = React.useRef(null);
1154
+ const optionsRef = React.useRef(options);
1155
+ optionsRef.current = options;
1156
+ React.useEffect(() => {
1157
+ const container = ref.current;
1158
+ if (!container)
1159
+ return;
1160
+ return staggerChildren(container, withLatestCallbacks(optionsRef), getInstance());
1161
+ }, []);
1162
+ return ref;
1163
+ }
1164
+ return { useScrollAnimate, useScrollStagger };
1165
+ }
1166
+
1167
+ /**
1168
+ * use-scroll-animate - Vue 3 Integration
1169
+ * Provides useScrollAnimate and useScrollStagger composables for Vue 3 applications.
1170
+ *
1171
+ * A thin wrapper around the core engine, so it shares its behaviour: `once`,
1172
+ * `offset`, custom easing functions, parallax, `prefers-reduced-motion`
1173
+ * support, and cleanup on unmount.
1174
+ */
1175
+ /** Support refs on components (`$el`) as well as plain elements. */
1176
+ function unwrap(value) {
1177
+ if (value && typeof Element !== 'undefined' && !(value instanceof Element) && value.$el instanceof Element) {
1178
+ return value.$el;
1179
+ }
1180
+ return value || null;
1181
+ }
1182
+ function createVueComposables(Vue) {
1183
+ // Created lazily on the client so importing on the server is side-effect free.
1184
+ let instance = null;
1185
+ const getInstance = () => instance || (instance = createScrollAnimate());
1186
+ function useScrollAnimate(options = {}) {
1187
+ const animateRef = Vue.ref(null);
1188
+ let el = null;
1189
+ Vue.onMounted(() => {
1190
+ const target = unwrap(animateRef.value);
1191
+ if (!target)
1192
+ return;
1193
+ el = target;
1194
+ getInstance().observe(el, options);
1195
+ });
1196
+ Vue.onUnmounted(() => {
1197
+ if (el)
1198
+ getInstance().unobserve(el);
1199
+ el = null;
1200
+ });
1201
+ return { animateRef };
1202
+ }
1203
+ /** Stagger the children of `staggerRef`; `observeChildren: true` also animates children added later. */
1204
+ function useScrollStagger(options = {}) {
1205
+ const staggerRef = Vue.ref(null);
1206
+ let stop;
1207
+ Vue.onMounted(() => {
1208
+ const target = unwrap(staggerRef.value);
1209
+ if (target)
1210
+ stop = staggerChildren(target, options, getInstance());
1211
+ });
1212
+ Vue.onUnmounted(() => {
1213
+ stop === null || stop === void 0 ? void 0 : stop();
1214
+ stop = undefined;
1215
+ });
1216
+ return { staggerRef };
1217
+ }
1218
+ return { useScrollAnimate, useScrollStagger };
1219
+ }
1220
+
1221
+ /**
1222
+ * use-scroll-animate
1223
+ *
1224
+ * A lightweight, dependency-free scroll animation library for modern web
1225
+ * applications. Built with TypeScript, powered by IntersectionObserver and
1226
+ * the Web Animations API. Safe to import during SSR.
1227
+ *
1228
+ * @license MIT
1229
+ * @see https://github.com/HarrisonCN/use-scroll-animate
1230
+ */
1231
+ /**
1232
+ * Default singleton instance of ScrollAnimate.
1233
+ * Ready to use out of the box with sensible defaults.
1234
+ *
1235
+ * @example
1236
+ * ```js
1237
+ * import ScrollAnimate from 'use-scroll-animate';
1238
+ *
1239
+ * // Auto-initialize all elements with data-sa attribute
1240
+ * ScrollAnimate.init();
1241
+ *
1242
+ * // Or manually observe elements
1243
+ * ScrollAnimate.observe('.my-element', { animation: 'fade-in-up' });
1244
+ * ```
1245
+ */
1246
+ const ScrollAnimate = createScrollAnimate();
1247
+
1248
+ export { EASING_MAP, PRESETS, createReactHooks, createScrollAnimate, createVueComposables, ScrollAnimate as default, getScrollProgress, resolveEasing, resolvePreset, sequence, staggerChildren };
1249
+ //# sourceMappingURL=index.esm.js.map