use-scroll-animate 5.2.0 → 5.4.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.
@@ -1,5 +1,5 @@
1
1
  import { registerBuiltinEffects, registerEffects } from './fx.js';
2
- import '../chunks/base-C3Sw9sAO.js';
2
+ import { x as defineElement } from '../chunks/base-C3Sw9sAO.js';
3
3
  import '../chunks/core-DN3hHbHh.js';
4
4
  import './tokens.js';
5
5
  import '../chunks/fx-ChjxrMBo.js';
@@ -437,6 +437,396 @@ const PHYSICS_FX = [
437
437
  },
438
438
  ];
439
439
 
440
+ /** A full-viewport, aria-hidden, pointer-blocking (while covering) transition layer. */
441
+ function screen(css = '') {
442
+ const s = document.createElement('div');
443
+ s.setAttribute('aria-hidden', 'true');
444
+ s.setAttribute('data-usa-page-fx', '');
445
+ s.style.cssText = `position:fixed;inset:0;z-index:2147483001;pointer-events:auto;${css}`;
446
+ document.body.appendChild(s);
447
+ return s;
448
+ }
449
+ const wait = (a) => (a ? a.finished.catch(() => undefined) : Promise.resolve());
450
+ const call = async (fn) => {
451
+ if (typeof fn === 'function')
452
+ await fn();
453
+ };
454
+ /** Reduced-motion version of every transition: a quick cross-fade through the cover colour. */
455
+ async function crossFade(o, ctx) {
456
+ const s = screen(`background:${o.color};opacity:0`);
457
+ await wait(ctx.animate(s, [{ opacity: 0 }, { opacity: 1 }], { duration: 150, fill: 'forwards' }));
458
+ await call(o.onCovered);
459
+ await wait(ctx.animate(s, [{ opacity: 1 }, { opacity: 0 }], { duration: 150, fill: 'forwards' }));
460
+ s.remove();
461
+ }
462
+ /** Build a transition from a cover layer and cover / reveal animations of its parts. */
463
+ function transition(build) {
464
+ return async (el, o, ctx) => {
465
+ if (ctx.reduced)
466
+ return crossFade(o, ctx);
467
+ const s = screen('pointer-events:auto');
468
+ const { parts, cover, delay } = build(s, o, ctx, el);
469
+ const frames = (i) => (typeof cover === 'function' ? cover(i) : cover);
470
+ const half = o.duration / 2;
471
+ await Promise.all(parts.map((p, i) => wait(ctx.animate(p, frames(i), { duration: half, delay: delay?.(i) ?? 0, easing: 'cubic-bezier(0.65, 0, 0.35, 1)', fill: 'both' }))));
472
+ await call(o.onCovered);
473
+ if (o.hold)
474
+ await new Promise((r) => setTimeout(r, o.hold));
475
+ await Promise.all(parts.map((p, i) => wait(ctx.animate(p, [...frames(i)].reverse(), { duration: half, delay: delay?.(i) ?? 0, easing: 'cubic-bezier(0.65, 0, 0.35, 1)', fill: 'both' }))));
476
+ s.remove();
477
+ };
478
+ }
479
+ const part = (s, css) => {
480
+ const p = document.createElement('div');
481
+ p.style.cssText = `position:absolute;${css}`;
482
+ s.appendChild(p);
483
+ return p;
484
+ };
485
+ const TRANSITION_DEFAULTS = { color: '#0f0f1a', duration: 1000, hold: 0, onCovered: undefined };
486
+ const PAGE_FX = [
487
+ {
488
+ name: 'curtain',
489
+ kind: 'page',
490
+ description: 'Two curtain panels close from the sides, call onCovered(), then open.',
491
+ reduced: 'run',
492
+ defaults: TRANSITION_DEFAULTS,
493
+ run: transition((s, o) => ({
494
+ parts: [part(s, `top:0;bottom:0;left:0;width:50.5%;background:${o.color}`), part(s, `top:0;bottom:0;right:0;width:50.5%;background:${o.color}`)],
495
+ cover: (i) => [{ transform: `translateX(${i ? 100 : -100}%)` }, { transform: 'translateX(0)' }],
496
+ })),
497
+ },
498
+ {
499
+ name: 'iris',
500
+ kind: 'page',
501
+ description: 'A circle closes on the click point (or the element’s center), calls onCovered(), then opens.',
502
+ reduced: 'run',
503
+ defaults: TRANSITION_DEFAULTS,
504
+ run: transition((s, o, ctx, el) => {
505
+ const { x, y } = origin(el, ctx);
506
+ const r = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y)) + 2;
507
+ // a huge box-shadow ring around a hole: the hole shrinks to 0 to cover
508
+ const p = part(s, `left:${x}px;top:${y}px;width:0;height:0;border-radius:50%;box-shadow:0 0 0 ${Math.ceil(r)}px ${o.color}`);
509
+ s.style.background = 'transparent';
510
+ return { parts: [p], cover: [{ width: `${r * 2}px`, height: `${r * 2}px`, margin: `${-r}px 0 0 ${-r}px` }, { width: '0px', height: '0px', margin: '0px 0 0 0px' }] };
511
+ }),
512
+ },
513
+ {
514
+ name: 'pixel-dissolve',
515
+ kind: 'page',
516
+ description: 'The screen fills with pixels in random order, calls onCovered(), then dissolves (`cols` × `rows`).',
517
+ reduced: 'run',
518
+ defaults: { ...TRANSITION_DEFAULTS, cols: 16, rows: 10 },
519
+ run: transition((s, o) => {
520
+ const n = o.cols * o.rows;
521
+ const order = Array.from({ length: n }, (_, i) => i).sort(() => Math.random() - 0.5);
522
+ const parts = Array.from({ length: n }, (_, i) => part(s, `left:${((i % o.cols) * 100) / o.cols}%;top:${(Math.floor(i / o.cols) * 100) / o.rows}%;width:${100 / o.cols + 0.2}%;height:${100 / o.rows + 0.2}%;background:${o.color};opacity:0`));
523
+ return { parts, cover: [{ opacity: 0 }, { opacity: 1 }], delay: (i) => (order[i] / n) * (o.duration / 2) * 0.6 };
524
+ }),
525
+ },
526
+ {
527
+ name: 'blinds',
528
+ kind: 'page',
529
+ description: 'Horizontal slats rotate shut like venetian blinds, call onCovered(), then open (`slats`).',
530
+ reduced: 'run',
531
+ defaults: { ...TRANSITION_DEFAULTS, slats: 8 },
532
+ run: transition((s, o) => ({
533
+ parts: Array.from({ length: o.slats }, (_, i) => part(s, `left:0;right:0;top:${(i * 100) / o.slats}%;height:${100 / o.slats + 0.3}%;background:${o.color};transform-origin:top`)),
534
+ cover: [{ transform: 'scaleY(0)' }, { transform: 'scaleY(1)' }],
535
+ delay: (i) => i * 30,
536
+ })),
537
+ },
538
+ {
539
+ name: 'velocity-skew',
540
+ kind: 'scroll',
541
+ description: 'Skews the element with scroll velocity and eases back when scrolling stops (persistent).',
542
+ defaults: { max: 8, factor: 0.25 },
543
+ run: (el, o, ctx) => {
544
+ if (ctx.reduced)
545
+ return;
546
+ let last = scrollY;
547
+ let skew = 0;
548
+ let raf = 0;
549
+ const tick = () => {
550
+ const y = scrollY;
551
+ const target = Math.max(-o.max, Math.min(o.max, (y - last) * o.factor));
552
+ last = y;
553
+ skew += (target - skew) * 0.2;
554
+ el.style.transform = `skewY(${skew.toFixed(3)}deg)`;
555
+ raf = Math.abs(skew) > 0.01 || Math.abs(target) > 0.01 ? requestAnimationFrame(tick) : 0;
556
+ if (!raf)
557
+ el.style.transform = '';
558
+ };
559
+ const onScroll = () => {
560
+ if (!raf)
561
+ raf = requestAnimationFrame(tick);
562
+ };
563
+ addEventListener('scroll', onScroll, { passive: true });
564
+ return () => {
565
+ removeEventListener('scroll', onScroll);
566
+ cancelAnimationFrame(raf);
567
+ el.style.transform = '';
568
+ };
569
+ },
570
+ },
571
+ {
572
+ name: 'spotlight',
573
+ kind: 'cursor',
574
+ description: 'Dims the page except a soft circle that follows the pointer (persistent; `radius`, `dim`).',
575
+ defaults: { radius: 180, dim: 0.72 },
576
+ run: (_el, o, ctx) => {
577
+ if (ctx.reduced)
578
+ return;
579
+ const s = screen(`pointer-events:none;background:radial-gradient(circle ${o.radius}px at var(--x,50%) var(--y,50%),transparent 0,transparent 60%,rgba(0,0,0,${o.dim}) 100%)`);
580
+ const move = (e) => {
581
+ s.style.setProperty('--x', `${e.clientX}px`);
582
+ s.style.setProperty('--y', `${e.clientY}px`);
583
+ };
584
+ addEventListener('pointermove', move, { passive: true });
585
+ return () => {
586
+ removeEventListener('pointermove', move);
587
+ s.remove();
588
+ };
589
+ },
590
+ },
591
+ {
592
+ name: 'edge-glow',
593
+ kind: 'scroll',
594
+ description: 'A soft glow lights the top / bottom edge of the viewport while scrolling in that direction (persistent).',
595
+ defaults: { color: '#7c5cff', size: 90 },
596
+ run: (_el, o, ctx) => {
597
+ if (ctx.reduced)
598
+ return;
599
+ const s = screen('pointer-events:none;opacity:0;transition:opacity .35s ease-out');
600
+ let last = scrollY;
601
+ let t = 0;
602
+ const onScroll = () => {
603
+ const down = scrollY >= last;
604
+ last = scrollY;
605
+ s.style.background = `linear-gradient(${down ? 'to top' : 'to bottom'},${o.color}55,transparent ${o.size}px)`;
606
+ s.style.opacity = '1';
607
+ clearTimeout(t);
608
+ t = setTimeout(() => (s.style.opacity = '0'), 160);
609
+ };
610
+ addEventListener('scroll', onScroll, { passive: true });
611
+ return () => {
612
+ removeEventListener('scroll', onScroll);
613
+ clearTimeout(t);
614
+ s.remove();
615
+ };
616
+ },
617
+ },
618
+ ];
619
+
620
+ /**
621
+ * 5.4 — `<usa-story template="…">` scroll-storytelling templates.
622
+ *
623
+ * - `pin` — a sticky `[data-stage]` while `[data-step]` sections scroll past; the
624
+ * step in view gets `data-active`, the stage gets `data-active-step="<index>"`.
625
+ * - `gallery` — a horizontal `[data-track]` slides sideways as you scroll down.
626
+ * - `zoom` — the `[data-stage]` zooms toward the viewer (`zoom="6"`) and fades.
627
+ * - `compare` — before / after (`[data-before]`, `[data-after]`) wipe driven by
628
+ * scroll, plus a draggable, keyboard-accessible handle (`role="slider"`).
629
+ * - `counter` — `[data-count="1234"]` numbers count up when they enter view.
630
+ * - `highlight` — paragraphs dim except the one crossing the viewport center.
631
+ *
632
+ * Every template sets `--usa-story-progress` (0–1) on the host and dispatches
633
+ * `usa-story-step` (`detail: { index }`). Reduced motion: no sliding / zooming
634
+ * (the gallery stacks vertically), counters show final values, the rest is
635
+ * class changes only.
636
+ */
637
+ const STORY_TEMPLATES = ['pin', 'gallery', 'zoom', 'compare', 'counter', 'highlight'];
638
+ const CSS = `usa-story{display:block;position:relative}
639
+ usa-story[template=pin] [data-stage],usa-story[template=gallery] [data-sticky],usa-story[template=zoom] [data-stage],usa-story[template=compare] [data-sticky]{position:sticky;top:0}
640
+ usa-story[template=pin] [data-stage]{align-self:start}
641
+ usa-story[template=pin] [data-step]{min-height:80vh;opacity:.35;transition:opacity .3s}
642
+ usa-story[template=pin] [data-step][data-active]{opacity:1}
643
+ usa-story[template=gallery] [data-sticky]{height:100vh;overflow:hidden;display:flex;align-items:center}
644
+ usa-story[template=gallery] [data-track]{display:flex;gap:24px;will-change:transform}
645
+ usa-story[template=gallery][data-static] [data-sticky]{position:static;height:auto;overflow:visible}
646
+ usa-story[template=gallery][data-static] [data-track]{flex-direction:column;transform:none!important}
647
+ usa-story[template=zoom] [data-stage]{height:100vh;overflow:hidden;display:grid;place-items:center}
648
+ usa-story[template=compare] [data-sticky]{height:var(--usa-story-h,70vh);overflow:hidden}
649
+ usa-story[template=compare] [data-before],usa-story[template=compare] [data-after]{position:absolute;inset:0}
650
+ usa-story[template=compare] [data-after]{clip-path:inset(0 0 0 var(--usa-split,50%))}
651
+ usa-story [data-handle]{position:absolute;top:0;bottom:0;left:var(--usa-split,50%);width:4px;margin-left:-2px;background:#fff;box-shadow:0 0 0 1px #0003;cursor:ew-resize;touch-action:none}
652
+ usa-story [data-handle]:focus-visible{outline:3px solid #7c5cff;outline-offset:2px}
653
+ usa-story[template=highlight] p,usa-story[template=highlight] [data-step]{opacity:.3;transition:opacity .25s}
654
+ usa-story[template=highlight] [data-active]{opacity:1}`;
655
+ const clamp = (v, a = 0, b = 1) => Math.min(b, Math.max(a, v));
656
+ /** Progress of `el` through the viewport: 0 when its top hits the viewport top, 1 when its bottom hits the viewport bottom. */
657
+ function storyProgress(el, vh = typeof innerHeight === 'number' ? innerHeight : 800) {
658
+ const r = el.getBoundingClientRect();
659
+ const span = r.height - vh;
660
+ return span > 0 ? clamp(-r.top / span) : clamp((vh - r.top) / (vh + r.height));
661
+ }
662
+ /** Format a counted value like the target (`1,234`, `12.5`, prefix / suffix kept). */
663
+ function formatCount(target, t) {
664
+ const m = target.match(/^(\D*)([\d,]*\.?\d+)(.*)$/);
665
+ if (!m)
666
+ return target;
667
+ const [, pre, num, post] = m;
668
+ const n = parseFloat(num.replace(/,/g, ''));
669
+ const dec = (num.split('.')[1] || '').length;
670
+ let s = (n * t).toFixed(dec);
671
+ if (num.includes(','))
672
+ s = Number(s).toLocaleString('en-US', { minimumFractionDigits: dec, maximumFractionDigits: dec });
673
+ return pre + s + post;
674
+ }
675
+ function defineStory(tag = 'usa-story') {
676
+ return defineElement(tag, (Base) => class UsaStory extends Base {
677
+ constructor() {
678
+ super(...arguments);
679
+ this.progress = 0;
680
+ this.step = -1;
681
+ this.frame = 0;
682
+ }
683
+ static get observedAttributes() {
684
+ return ['template', 'zoom'];
685
+ }
686
+ get template() {
687
+ const t = this.str('template', 'pin');
688
+ return STORY_TEMPLATES.includes(t) ? t : 'pin';
689
+ }
690
+ steps() {
691
+ const own = Array.from(this.querySelectorAll('[data-step]:not([data-stage])'));
692
+ return own.length || this.template !== 'highlight' ? own : Array.from(this.querySelectorAll('p'));
693
+ }
694
+ setStep(i) {
695
+ if (i === this.step)
696
+ return;
697
+ this.step = i;
698
+ this.steps().forEach((s, k) => s.toggleAttribute('data-active', k === i));
699
+ const stage = this.querySelector('[data-stage]');
700
+ if (stage)
701
+ stage.dataset.activeStep = String(i);
702
+ this.dispatchEvent(new CustomEvent('usa-story-step', { detail: { index: i }, bubbles: true }));
703
+ }
704
+ /** Recompute from the current scroll position (called on scroll / resize). */
705
+ update() {
706
+ this.frame = 0;
707
+ const p = (this.progress = storyProgress(this));
708
+ this.style.setProperty('--usa-story-progress', p.toFixed(4));
709
+ const t = this.template;
710
+ const vh = innerHeight || 800;
711
+ if (t === 'pin' || t === 'highlight') {
712
+ const mid = vh / 2;
713
+ let best = -1;
714
+ let bestD = Infinity;
715
+ this.steps().forEach((s, i) => {
716
+ const r = s.getBoundingClientRect();
717
+ const d = r.top <= mid && r.bottom >= mid ? 0 : Math.min(Math.abs(r.top - mid), Math.abs(r.bottom - mid));
718
+ if (d < bestD)
719
+ (bestD = d), (best = i);
720
+ });
721
+ this.setStep(best);
722
+ }
723
+ else if (t === 'gallery' && !this.reduced) {
724
+ const track = this.querySelector('[data-track]');
725
+ const box = this.querySelector('[data-sticky]');
726
+ if (track && box)
727
+ track.style.transform = `translateX(${(-p * Math.max(0, track.scrollWidth - box.clientWidth)).toFixed(1)}px)`;
728
+ }
729
+ else if (t === 'zoom' && !this.reduced) {
730
+ const inner = this.querySelector('[data-stage] > *');
731
+ if (inner) {
732
+ inner.style.transform = `scale(${(1 + p * (this.num('zoom', 6) - 1)).toFixed(3)})`;
733
+ inner.style.opacity = String(clamp(1.4 - p * 1.4).toFixed(3));
734
+ }
735
+ }
736
+ else if (t === 'compare' && !this.hasAttribute('data-dragged')) {
737
+ this.setSplit(p * 100);
738
+ }
739
+ else if (t === 'counter') {
740
+ this.querySelectorAll('[data-count]:not([data-counted])').forEach((el) => {
741
+ const r = el.getBoundingClientRect();
742
+ if (r.top < vh * 0.9 && r.bottom > 0)
743
+ this.count(el);
744
+ });
745
+ }
746
+ }
747
+ setSplit(pct) {
748
+ const v = clamp(pct, 0, 100);
749
+ this.style.setProperty('--usa-split', `${v.toFixed(2)}%`);
750
+ const h = this.querySelector('[data-handle]');
751
+ if (h)
752
+ h.setAttribute('aria-valuenow', String(Math.round(v)));
753
+ }
754
+ count(el) {
755
+ el.dataset.counted = '';
756
+ const target = el.dataset.count || el.textContent || '0';
757
+ el.setAttribute('aria-label', target);
758
+ if (this.reduced) {
759
+ el.textContent = target;
760
+ return;
761
+ }
762
+ const dur = Number(el.dataset.duration) || 1600;
763
+ const t0 = performance.now();
764
+ const tick = (now) => {
765
+ const k = clamp((now - t0) / dur);
766
+ el.textContent = formatCount(target, 1 - (1 - k) ** 3);
767
+ if (k < 1)
768
+ requestAnimationFrame(tick);
769
+ };
770
+ requestAnimationFrame(tick);
771
+ }
772
+ mount() {
773
+ this.toggleAttribute('data-static', this.reduced);
774
+ if (this.template === 'compare')
775
+ this.mountCompare();
776
+ const kick = () => {
777
+ if (!this.frame)
778
+ this.frame = requestAnimationFrame(() => this.update());
779
+ };
780
+ this.listen(window, 'scroll', kick, { passive: true });
781
+ this.listen(window, 'resize', kick);
782
+ this.onCleanup(() => cancelAnimationFrame(this.frame));
783
+ this.update();
784
+ }
785
+ mountCompare() {
786
+ const box = this.querySelector('[data-sticky]') || this;
787
+ let h = this.querySelector('[data-handle]');
788
+ if (!h) {
789
+ h = document.createElement('div');
790
+ h.setAttribute('data-handle', '');
791
+ box.appendChild(h);
792
+ this.onCleanup(() => h.remove());
793
+ }
794
+ h.tabIndex = 0;
795
+ h.setAttribute('role', 'slider');
796
+ h.setAttribute('aria-label', this.str('label', 'Before / after'));
797
+ h.setAttribute('aria-valuemin', '0');
798
+ h.setAttribute('aria-valuemax', '100');
799
+ const at = (e) => {
800
+ const r = box.getBoundingClientRect();
801
+ this.dataset.dragged = '';
802
+ this.setSplit(((e.clientX - r.left) / (r.width || 1)) * 100);
803
+ };
804
+ let drag = false;
805
+ this.listen(h, 'pointerdown', (e) => {
806
+ drag = true;
807
+ h.setPointerCapture?.(e.pointerId);
808
+ });
809
+ this.listen(h, 'pointermove', (e) => drag && at(e));
810
+ this.listen(h, 'pointerup', () => (drag = false));
811
+ this.listen(h, 'keydown', (e) => {
812
+ const cur = parseFloat(h.getAttribute('aria-valuenow') || '50');
813
+ const step = e.shiftKey ? 10 : 2;
814
+ const next = e.key === 'ArrowLeft' || e.key === 'ArrowDown' ? cur - step : e.key === 'ArrowRight' || e.key === 'ArrowUp' ? cur + step : e.key === 'Home' ? 0 : e.key === 'End' ? 100 : null;
815
+ if (next == null)
816
+ return;
817
+ e.preventDefault();
818
+ this.dataset.dragged = '';
819
+ this.setSplit(next);
820
+ });
821
+ this.setSplit(50);
822
+ }
823
+ unmount() {
824
+ this.step = -1;
825
+ delete this.dataset.dragged;
826
+ }
827
+ }, { id: 'usa-story', text: CSS });
828
+ }
829
+
440
830
  /**
441
831
  * use-scroll-animate/components/effects — the 5.x effect packs, all
442
832
  * registered through `registerEffect()` (5.0) and playable with
@@ -453,6 +843,7 @@ const PHYSICS_FX = [
453
843
  const EFFECT_PACKS = {
454
844
  'cards-click': [...CARD_FX, ...CLICK_FX],
455
845
  physics: PHYSICS_FX,
846
+ page: PAGE_FX,
456
847
  };
457
848
  /** 5.1: card & click effects 2.0. */
458
849
  function registerCardClickEffects() {
@@ -462,6 +853,14 @@ function registerCardClickEffects() {
462
853
  function registerPhysicsEffects() {
463
854
  registerEffects(EFFECT_PACKS.physics);
464
855
  }
856
+ /** 5.3: page-wide transitions and effects. */
857
+ function registerPageEffects() {
858
+ registerEffects(EFFECT_PACKS.page);
859
+ }
860
+ /** Define the 5.x elements of this entry (`<usa-story>`, …) under their default tags. */
861
+ function defineEffectElements() {
862
+ defineStory();
863
+ }
465
864
  /** Register the built-ins and every pack (idempotent). */
466
865
  function registerAllEffects() {
467
866
  registerBuiltinEffects();
@@ -469,5 +868,5 @@ function registerAllEffects() {
469
868
  registerEffects(defs);
470
869
  }
471
870
 
472
- export { CARD_FX, CLICK_FX, EFFECT_PACKS, PHYSICS_FX, bounceKeyframes, fxLayer, registerAllEffects, registerCardClickEffects, registerPhysicsEffects, solveSpring, springKeyframes };
871
+ export { CARD_FX, CLICK_FX, EFFECT_PACKS, PAGE_FX, PHYSICS_FX, STORY_TEMPLATES, bounceKeyframes, defineEffectElements, defineStory, formatCount, fxLayer, registerAllEffects, registerCardClickEffects, registerPageEffects, registerPhysicsEffects, solveSpring, springKeyframes, storyProgress };
473
872
  //# sourceMappingURL=effects.js.map