use-scroll-animate 5.7.0 → 5.9.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/bin/usa-codemod-6.mjs +146 -0
  3. package/dist/components/angular.d.cts +2 -1
  4. package/dist/components/angular.d.ts +2 -1
  5. package/dist/components/click.cjs +23 -4
  6. package/dist/components/click.cjs.map +1 -1
  7. package/dist/components/click.d.cts +12 -7
  8. package/dist/components/click.d.ts +12 -7
  9. package/dist/components/click.js +28 -9
  10. package/dist/components/click.js.map +1 -1
  11. package/dist/components/effects.cjs +669 -2
  12. package/dist/components/effects.cjs.map +1 -1
  13. package/dist/components/effects.d.cts +176 -2
  14. package/dist/components/effects.d.ts +176 -2
  15. package/dist/components/effects.js +653 -5
  16. package/dist/components/effects.js.map +1 -1
  17. package/dist/components/fx.cjs +2 -2
  18. package/dist/components/fx.cjs.map +1 -1
  19. package/dist/components/fx.js +2 -2
  20. package/dist/components/fx.js.map +1 -1
  21. package/dist/components/lite.cjs +35 -14
  22. package/dist/components/lite.cjs.map +1 -1
  23. package/dist/components/lite.js +35 -14
  24. package/dist/components/lite.js.map +1 -1
  25. package/dist/components/page.cjs +2 -0
  26. package/dist/components/page.cjs.map +1 -1
  27. package/dist/components/page.js +3 -1
  28. package/dist/components/page.js.map +1 -1
  29. package/dist/components/solid.d.cts +2 -1
  30. package/dist/components/solid.d.ts +2 -1
  31. package/dist/components/svelte.d.cts +2 -1
  32. package/dist/components/svelte.d.ts +2 -1
  33. package/dist/components/vue.d.cts +2 -1
  34. package/dist/components/vue.d.ts +2 -1
  35. package/dist/components.cjs +5 -5
  36. package/dist/components.d.cts +12 -7
  37. package/dist/components.d.ts +12 -7
  38. package/dist/components.js +2 -2
  39. package/dist/components.umd.js +2 -2
  40. package/dist/components.umd.js.map +1 -1
  41. package/docs/ROADMAP.md +2 -2
  42. package/docs/components.md +46 -0
  43. package/docs/deprecations.md +4 -0
  44. package/docs/upgrading-6.md +32 -0
  45. package/package.json +3 -2
@@ -1,7 +1,7 @@
1
- import { playEffect, registerBuiltinEffects, registerEffects } from './fx.js';
2
- import { x as defineElement, p as prefersReducedMotion } from '../chunks/base-C3Sw9sAO.js';
3
- import '../chunks/core-DN3hHbHh.js';
4
- import './tokens.js';
1
+ import { playEffect, bindEffect, registerBuiltinEffects, registerEffects } from './fx.js';
2
+ import { x as defineElement, p as prefersReducedMotion, u as adoptStyles } from '../chunks/base-C3Sw9sAO.js';
3
+ import { applyMotionTokens, motionTokensToVars, mergeMotionTokens } from './tokens.js';
4
+ import { T as TIMELINE_PRESETS } from '../chunks/core-DN3hHbHh.js';
5
5
  import '../chunks/fx-ChjxrMBo.js';
6
6
 
7
7
  let layer = null;
@@ -1821,6 +1821,645 @@ function defineGestureFx(tag = 'usa-gesture-fx') {
1821
1821
  }, { id: 'usa-gesture-fx', text: 'usa-gesture-fx{display:inline-block;touch-action:none;user-select:none}' });
1822
1822
  }
1823
1823
 
1824
+ const saved = new WeakMap();
1825
+ /** Toggle `aria-pressed` (or set it) and return the new state. */
1826
+ function togglePressed(el, force) {
1827
+ const on = force ?? el.getAttribute('aria-pressed') !== 'true';
1828
+ el.setAttribute('aria-pressed', String(on));
1829
+ return on;
1830
+ }
1831
+ /** Swap `el`'s label for `ms` (polite live region), then restore it. */
1832
+ function swapLabel(el, text, ms) {
1833
+ if (!saved.has(el))
1834
+ saved.set(el, el.innerHTML);
1835
+ el.setAttribute('aria-live', 'polite');
1836
+ el.textContent = text;
1837
+ return new Promise((r) => setTimeout(() => {
1838
+ el.innerHTML = saved.get(el);
1839
+ saved.delete(el);
1840
+ el.removeAttribute('aria-live');
1841
+ r();
1842
+ }, ms));
1843
+ }
1844
+ /** Add `delta` to the number in `[data-count]` (or `el`), keeping it in `data-count`. Returns the new value. */
1845
+ function bumpCount(el, delta, ctx) {
1846
+ const t = el.querySelector('[data-count]') || el;
1847
+ const n = (Number(t.dataset.count ?? (t.textContent || '').replace(/[^\d.-]/g, '')) || 0) + delta;
1848
+ t.dataset.count = String(n);
1849
+ t.textContent = String(n);
1850
+ ctx?.animate(t, [{ transform: `translateY(${delta > 0 ? 60 : -60}%)`, opacity: 0 }, { transform: 'none', opacity: 1 }], { duration: 260, easing: 'cubic-bezier(.2,1.4,.4,1)' });
1851
+ return n;
1852
+ }
1853
+ const pop = (el, ctx, s = 1.25, d = 380) => ctx.animate(el, [{ transform: 'scale(1)' }, { transform: `scale(${s})`, offset: 0.4 }, { transform: 'scale(1)' }], { duration: d, easing: 'cubic-bezier(.2,1.4,.4,1)' });
1854
+ /** A few glyphs flying out of the pointer / centre. */
1855
+ function burst(el, ctx, glyph, color, n = 6, rise = false) {
1856
+ const { x, y } = origin(el, ctx);
1857
+ return all(Array.from({ length: n }, (_, i) => {
1858
+ const a = rise ? -Math.PI / 2 + rand(-0.6, 0.6) : (i / n) * Math.PI * 2;
1859
+ const d = rand(28, 56);
1860
+ return spawn(x - 7, y - 7, `font-size:14px;line-height:1;color:${color}`, ctx, [{ transform: 'translate(0,0) scale(.4)', opacity: 1 }, { transform: `translate(${Math.cos(a) * d}px,${Math.sin(a) * d}px) scale(1)`, opacity: 0 }], { duration: rand(500, 750), easing: 'cubic-bezier(.2,.8,.3,1)' }, glyph);
1861
+ }));
1862
+ }
1863
+ const click = (name, description, defaults, run) => ({ name, kind: 'click', description, defaults, run });
1864
+ const attn = (name, description, defaults, run) => ({ name, kind: 'attention', description, defaults, run });
1865
+ const MICRO_FX = [
1866
+ click('copy-success', 'Copies `text` (or `data-copy` / the target of `for`) to the clipboard and swaps the label to "Copied ✓".', { text: '', label: 'Copied ✓', ms: 1500 }, (el, o, ctx) => {
1867
+ const src = el.getAttribute('for') ? document.getElementById(el.getAttribute('for')) : null;
1868
+ const text = o.text || el.dataset.copy || src?.value || src?.textContent || '';
1869
+ navigator.clipboard?.writeText(text).catch(() => undefined);
1870
+ pop(el, ctx, 1.08);
1871
+ return swapLabel(el, o.label, o.ms);
1872
+ }),
1873
+ click('toggle-morph', 'Toggles `aria-pressed` with a squash-and-stretch morph.', {}, (el, _o, ctx) => {
1874
+ const on = togglePressed(el);
1875
+ return ctx.animate(el, [{ transform: 'scale(1,1)' }, { transform: `scale(${on ? 1.15 : 0.85},${on ? 0.85 : 1.15})`, offset: 0.35 }, { transform: 'scale(1,1)' }], { duration: 360, easing: 'ease-out' });
1876
+ }),
1877
+ click('password-reveal', 'Shows / hides the password input (`for` id, or the previous input) with an eye blink.', { show: 'Hide password', hide: 'Show password' }, (el, o, ctx) => {
1878
+ const input = (el.getAttribute('for') ? document.getElementById(el.getAttribute('for')) : el.previousElementSibling);
1879
+ if (!input || !('type' in input))
1880
+ return;
1881
+ const show = input.type === 'password';
1882
+ input.type = show ? 'text' : 'password';
1883
+ togglePressed(el, show);
1884
+ el.setAttribute('aria-label', show ? o.show : o.hide);
1885
+ return ctx.animate(el, [{ transform: 'scaleY(1)' }, { transform: 'scaleY(.1)', offset: 0.5 }, { transform: 'scaleY(1)' }], { duration: 240, easing: 'ease-in-out' });
1886
+ }),
1887
+ click('favorite-star', 'Toggles a favourite: the star pops and throws little stars (`color`).', { color: '#facc15' }, (el, o, ctx) => {
1888
+ const on = togglePressed(el);
1889
+ return Promise.all([pop(el, ctx, on ? 1.35 : 0.85)?.finished, on ? burst(el, ctx, '★', o.color) : null]);
1890
+ }),
1891
+ click('like-heart', 'Toggles a like: the heart beats and hearts float up (`color`).', { color: '#ff5c8a' }, (el, o, ctx) => {
1892
+ const on = togglePressed(el);
1893
+ return Promise.all([pop(el, ctx, on ? 1.3 : 0.9)?.finished, on ? burst(el, ctx, '♥', o.color, 5, true) : null]);
1894
+ }),
1895
+ click('bookmark-flip', 'Toggles a bookmark with a 3D flip.', {}, (el, _o, ctx) => {
1896
+ togglePressed(el);
1897
+ return ctx.animate(el, [{ transform: 'perspective(400px) rotateY(0)' }, { transform: 'perspective(400px) rotateY(180deg)' }, { transform: 'perspective(400px) rotateY(360deg)' }], { duration: 520, easing: 'ease-in-out' });
1898
+ }),
1899
+ click('download-progress', 'Fills a progress bar over `duration` ms, then shows "Done ✓" (`aria-busy` while running; fires `usa-done`).', { duration: 1600, label: 'Done ✓', color: '#34d399' }, (el, o, ctx) => {
1900
+ if (el.getAttribute('aria-busy') === 'true')
1901
+ return;
1902
+ el.setAttribute('aria-busy', 'true');
1903
+ const [bar, remove] = overlay(el, `background:${o.color}55;transform-origin:left;transform:scaleX(0)`);
1904
+ const a = ctx.animate(bar, [{ transform: 'scaleX(0)' }, { transform: 'scaleX(1)' }], { duration: o.duration, easing: 'linear', fill: 'forwards' });
1905
+ const done = a ? a.finished.catch(() => undefined) : Promise.resolve();
1906
+ return done.then(() => {
1907
+ remove();
1908
+ el.removeAttribute('aria-busy');
1909
+ el.dispatchEvent(new CustomEvent('usa-done', { bubbles: true }));
1910
+ return swapLabel(el, o.label, 1400);
1911
+ });
1912
+ }),
1913
+ click('submit-loading', 'Shows "Sending…" with pulsing dots for `duration` ms, then "Sent ✓" (`aria-busy`, `usa-done`).', { duration: 1200, loading: 'Sending…', label: 'Sent ✓' }, (el, o, ctx) => {
1914
+ if (el.getAttribute('aria-busy') === 'true')
1915
+ return;
1916
+ el.setAttribute('aria-busy', 'true');
1917
+ const t = swapLabel(el, o.loading, o.duration);
1918
+ const a = ctx.animate(el, [{ opacity: 1 }, { opacity: 0.55 }, { opacity: 1 }], { duration: 600, iterations: Math.max(1, Math.round(o.duration / 600)) });
1919
+ return t.then(() => {
1920
+ a?.cancel();
1921
+ el.removeAttribute('aria-busy');
1922
+ el.dispatchEvent(new CustomEvent('usa-done', { bubbles: true }));
1923
+ return swapLabel(el, o.label, 1400);
1924
+ });
1925
+ }),
1926
+ click('send-plane', 'A paper plane ✈ takes off from the button.', { color: '#22d3ee' }, (el, o, ctx) => {
1927
+ const r = el.getBoundingClientRect();
1928
+ pop(el, ctx, 0.92, 200);
1929
+ return spawn(r.left + r.width / 2 - 8, r.top + r.height / 2 - 8, `font-size:16px;color:${o.color}`, ctx, [{ transform: 'translate(0,0) rotate(0)', opacity: 1 }, { transform: 'translate(40px,-10px) rotate(-10deg)', opacity: 1, offset: 0.4 }, { transform: 'translate(160px,-90px) rotate(-25deg)', opacity: 0 }], { duration: 800, easing: 'ease-in' }, '✈')?.finished;
1930
+ }),
1931
+ click('add-to-cart', 'Bumps `[data-count]` by one and floats a "+1" (`text`).', { text: '+1', color: '#34d399' }, (el, o, ctx) => {
1932
+ bumpCount(el, 1, ctx);
1933
+ const { x, y } = origin(el, ctx);
1934
+ return spawn(x - 10, y - 10, `font:700 14px system-ui;color:${o.color}`, ctx, [{ transform: 'translateY(0)', opacity: 1 }, { transform: 'translateY(-40px)', opacity: 0 }], { duration: 700, easing: 'ease-out' }, o.text)?.finished;
1935
+ }),
1936
+ click('counter-bump', 'Adds `step` to `[data-count]` with a rolling number.', { step: 1 }, (el, o, ctx) => void bumpCount(el, Number(o.step) || 1, ctx)),
1937
+ click('upvote', 'Toggles an upvote: the arrow nudges up and `[data-count]` ±1.', {}, (el, _o, ctx) => {
1938
+ const on = togglePressed(el);
1939
+ bumpCount(el, on ? 1 : -1, ctx);
1940
+ return ctx.animate(el, [{ transform: 'translateY(0)' }, { transform: `translateY(${on ? -6 : 4}px)`, offset: 0.4 }, { transform: 'translateY(0)' }], { duration: 320, easing: 'cubic-bezier(.2,1.4,.4,1)' });
1941
+ }),
1942
+ click('clap', 'Counts claps in `[data-count]` with a 👏 burst on every press.', {}, (el, _o, ctx) => {
1943
+ bumpCount(el, 1, ctx);
1944
+ return Promise.all([pop(el, ctx, 1.15, 240)?.finished, burst(el, ctx, '👏', 'inherit', 3, true)]);
1945
+ }),
1946
+ click('emoji-react', 'Pops one `emoji` up from the pointer (reaction button).', { emoji: '🎉' }, (el, o, ctx) => burst(el, ctx, o.emoji, 'inherit', 1, true)),
1947
+ click('refresh-spin', 'Spins the icon one turn (`turns`).', { turns: 1 }, (el, o, ctx) => ctx.animate(el, [{ transform: 'rotate(0)' }, { transform: `rotate(${360 * o.turns}deg)` }], { duration: 600 * o.turns, easing: 'cubic-bezier(.4,0,.2,1)' })),
1948
+ click('trash-shake', 'Shakes, then drops and fades (`remove: true` removes the element afterwards).', { remove: false }, (el, o, ctx) => {
1949
+ const a = ctx.animate(el, [{ transform: 'none', opacity: 1 }, { transform: 'rotate(-6deg)', offset: 0.15 }, { transform: 'rotate(6deg)', offset: 0.3 }, { transform: 'rotate(0)', offset: 0.45, opacity: 1 }, { transform: 'translateY(30px) scale(.8)', opacity: 0 }], { duration: 650, easing: 'ease-in', fill: 'forwards' });
1950
+ const end = () => (o.remove ? el.remove() : a?.cancel());
1951
+ return a ? a.finished.then(end, end) : void end();
1952
+ }),
1953
+ click('check-toggle', 'Toggles a check mark (`aria-checked` for role=checkbox, else `aria-pressed`) that scales in.', {}, (el, _o, ctx) => {
1954
+ const attr = el.getAttribute('role') === 'checkbox' ? 'aria-checked' : 'aria-pressed';
1955
+ const on = el.getAttribute(attr) !== 'true';
1956
+ el.setAttribute(attr, String(on));
1957
+ return ctx.animate(el, on ? [{ transform: 'scale(.6)' }, { transform: 'scale(1.15)', offset: 0.6 }, { transform: 'scale(1)' }] : [{ transform: 'scale(1)' }, { transform: 'scale(.85)' }, { transform: 'scale(1)' }], { duration: 280, easing: 'ease-out' });
1958
+ }),
1959
+ attn('input-shake', 'Shakes an invalid field side to side and sets `aria-invalid` (`color` outline flash).', { color: '#ff5c8a' }, (el, o, ctx) => {
1960
+ el.setAttribute('aria-invalid', 'true');
1961
+ const prev = el.style.outline;
1962
+ el.style.outline = `2px solid ${o.color}`;
1963
+ setTimeout(() => (el.style.outline = prev), 900);
1964
+ return ctx.animate(el, [0, -8, 8, -6, 6, -3, 0].map((x) => ({ transform: `translateX(${x}px)` })), { duration: 420, easing: 'ease-out' });
1965
+ }),
1966
+ attn('error-flash', 'Flashes the element red once (no more than one flash per call).', { color: '#ff5c8a' }, (el, o, ctx) => ctx.animate(el, [{ boxShadow: `0 0 0 0 ${o.color}00` }, { boxShadow: `0 0 0 4px ${o.color}`, offset: 0.3 }, { boxShadow: `0 0 0 0 ${o.color}00` }], { duration: 700 })),
1967
+ attn('success-check', 'A green ✓ badge pops over the element and fades.', { color: '#34d399' }, (el, o, ctx) => {
1968
+ const [b, remove] = overlay(el, `display:grid;place-items:center;font:700 22px system-ui;color:#fff;background:${o.color}d0`);
1969
+ b.textContent = '✓';
1970
+ const a = ctx.animate(b, [{ opacity: 0, transform: 'scale(.6)' }, { opacity: 1, transform: 'scale(1)', offset: 0.3 }, { opacity: 1, offset: 0.75 }, { opacity: 0 }], { duration: 1100, easing: 'ease-out' });
1971
+ return a ? a.finished.then(remove, remove) : void setTimeout(remove, 900);
1972
+ }),
1973
+ attn('nudge-hint', 'A small sideways nudge that says "try me" (`distance`).', { distance: 6 }, (el, o, ctx) => ctx.animate(el, [0, o.distance, 0, o.distance / 2, 0].map((x) => ({ transform: `translateX(${x}px)` })), { duration: 700, easing: 'ease-in-out' })),
1974
+ attn('focus-pulse', 'A ring pulses around the element to draw focus to it (`color`).', { color: '#7c5cff' }, (el, o, ctx) => ctx.animate(el, [{ boxShadow: `0 0 0 0 ${o.color}aa` }, { boxShadow: `0 0 0 12px ${o.color}00` }], { duration: 900, iterations: 2, easing: 'ease-out' })),
1975
+ attn('notify-badge', 'Bumps the badge count (`[data-count]`, `step`) with a pop — for new notifications.', { step: 1 }, (el, o, ctx) => {
1976
+ bumpCount(el, Number(o.step) || 1, ctx);
1977
+ return pop(el, ctx, 1.3, 320);
1978
+ }),
1979
+ ];
1980
+
1981
+ const THEME_ROLES = ['enter', 'hover', 'click', 'attention', 'background'];
1982
+ const P = (enter, hover, click, attention, background) => ({
1983
+ enter: { effect: enter },
1984
+ hover: { effect: hover },
1985
+ click: { effect: click },
1986
+ attention: { effect: attention },
1987
+ background: { effect: background },
1988
+ });
1989
+ const THEMES = {
1990
+ neon: {
1991
+ name: 'neon',
1992
+ vars: { bg: '#07070c', fg: '#e8e8ff', accent: '#22d3ee', 'accent-2': '#ff2bd6', surface: '#11111c', border: '1px solid #22d3ee', radius: '10px', shadow: '0 0 18px #22d3ee66, inset 0 0 12px #ff2bd622', font: 'ui-monospace, SFMono-Regular, Menlo, monospace' },
1993
+ motion: { duration: { fast: 120, normal: 220 }, easing: { standard: 'cubic-bezier(0.2, 0, 0, 1)' } },
1994
+ presets: P('fade-up', 'neon-flicker', 'shockwave', 'neon-flicker', 'starfield'),
1995
+ },
1996
+ paper: {
1997
+ name: 'paper',
1998
+ vars: { bg: '#f6f1e7', fg: '#2b2721', accent: '#c2410c', 'accent-2': '#0f766e', surface: '#fffdf8', border: '1px solid #e3dccd', radius: '4px', shadow: '0 1px 0 #0000000d, 0 10px 24px -14px #00000040', font: 'Georgia, "Times New Roman", serif' },
1999
+ motion: { duration: { fast: 200, normal: 380, slow: 700 }, easing: { standard: 'cubic-bezier(0, 0, 0, 1)' } },
2000
+ presets: P('paper-fold', 'wiggle', 'ink-splash', 'nudge-hint', 'contours'),
2001
+ },
2002
+ glass: {
2003
+ name: 'glass',
2004
+ vars: { bg: 'linear-gradient(135deg, #1e1b4b, #0e7490)', fg: '#f8fafc', accent: '#a5f3fc', 'accent-2': '#c4b5fd', surface: '#ffffff1f', border: '1px solid #ffffff40', radius: '18px', shadow: '0 8px 32px #0000003d', font: 'system-ui, -apple-system, "Segoe UI", sans-serif' },
2005
+ motion: { duration: { normal: 320 }, easing: { standard: 'cubic-bezier(0.22, 1, 0.36, 1)' } },
2006
+ presets: P('blur', 'glass-shine', 'ripple', 'focus-pulse', 'mesh-gradient'),
2007
+ },
2008
+ retro: {
2009
+ name: 'retro',
2010
+ vars: { bg: '#1d1135', fg: '#ffe9a8', accent: '#ff6b35', 'accent-2': '#2ec4b6', surface: '#2a1b4d', border: '3px solid #ffe9a8', radius: '0', shadow: '4px 4px 0 #ff6b35', font: '"Courier New", ui-monospace, monospace' },
2011
+ motion: { duration: { normal: 300 }, easing: { standard: 'steps(6, end)' } },
2012
+ presets: P('clip-up', 'rubber-band', 'star-burst', 'tada', 'retro-scanlines'),
2013
+ },
2014
+ brutalist: {
2015
+ name: 'brutalist',
2016
+ vars: { bg: '#ffffff', fg: '#000000', accent: '#ff3b00', 'accent-2': '#0047ff', surface: '#fff200', border: '3px solid #000000', radius: '0', shadow: '6px 6px 0 #000000', font: '"Arial Black", Arial, sans-serif' },
2017
+ motion: { duration: { fast: 80, normal: 160 }, easing: { standard: 'linear' } },
2018
+ presets: P('drop-bounce', 'jelly', 'brutal-shift', 'shake', 'voronoi'),
2019
+ },
2020
+ };
2021
+ const THEME_NAMES = Object.keys(THEMES);
2022
+ const BASE_CSS = `[data-usa-theme]{background:var(--usa-theme-bg);color:var(--usa-theme-fg);font-family:var(--usa-theme-font)}
2023
+ [data-usa-theme] .usa-surface{background:var(--usa-theme-surface);border:var(--usa-theme-border);border-radius:var(--usa-theme-radius);box-shadow:var(--usa-theme-shadow)}
2024
+ [data-usa-theme] .usa-accent{color:var(--usa-theme-accent)}
2025
+ [data-usa-theme=glass] .usa-surface{-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}`;
2026
+ const pack = (t) => {
2027
+ const p = typeof t === 'string' ? THEMES[t] : t;
2028
+ if (!p)
2029
+ throw new Error(`[use-scroll-animate] unknown theme "${String(t)}" — ${THEME_NAMES.join(', ')}`);
2030
+ return p;
2031
+ };
2032
+ /** The CSS custom properties of a theme (design + motion tokens). */
2033
+ function themeVars(t) {
2034
+ const p = pack(t);
2035
+ const out = {};
2036
+ for (const [k, v] of Object.entries(p.vars))
2037
+ out[`--usa-theme-${k}`] = v;
2038
+ return { ...out, ...motionTokensToVars(mergeMotionTokens(p.motion)) };
2039
+ }
2040
+ /** A theme as a CSS rule (`selector` default `[data-usa-theme=<name>]`) — for SSR / static CSS. */
2041
+ function themeCss(t, selector) {
2042
+ const p = pack(t);
2043
+ return `${selector || `[data-usa-theme=${p.name}]`}{${Object.entries(themeVars(p)).map(([k, v]) => `${k}:${v}`).join(';')}}`;
2044
+ }
2045
+ /** Apply a theme to `root` (default `<html>`). Returns an undo. */
2046
+ function applyTheme(t, root) {
2047
+ const p = pack(t);
2048
+ const el = root || document.documentElement;
2049
+ adoptStyles('usa-theme', BASE_CSS);
2050
+ const prevAttr = el.getAttribute('data-usa-theme');
2051
+ el.setAttribute('data-usa-theme', p.name);
2052
+ const vars = Object.entries(p.vars).map(([k, v]) => [`--usa-theme-${k}`, v]);
2053
+ const old = vars.map(([k]) => [k, el.style.getPropertyValue(k)]);
2054
+ for (const [k, v] of vars)
2055
+ el.style.setProperty(k, v);
2056
+ let undoMotion;
2057
+ if (el === document.documentElement)
2058
+ undoMotion = applyMotionTokens(p.motion, el);
2059
+ else {
2060
+ const mv = Object.entries(motionTokensToVars(mergeMotionTokens(p.motion)));
2061
+ const mold = mv.map(([k]) => [k, el.style.getPropertyValue(k)]);
2062
+ for (const [k, v] of mv)
2063
+ el.style.setProperty(k, v);
2064
+ undoMotion = () => mold.forEach(([k, v]) => (v ? el.style.setProperty(k, v) : el.style.removeProperty(k)));
2065
+ }
2066
+ return () => {
2067
+ undoMotion();
2068
+ old.forEach(([k, v]) => (v ? el.style.setProperty(k, v) : el.style.removeProperty(k)));
2069
+ if (prevAttr === null)
2070
+ el.removeAttribute('data-usa-theme');
2071
+ else
2072
+ el.setAttribute('data-usa-theme', prevAttr);
2073
+ };
2074
+ }
2075
+ /** The effect preset of a theme for a role. */
2076
+ function themePreset(t, role) {
2077
+ return pack(t).presets[role];
2078
+ }
2079
+ /** Play the preset for `role` of the theme on the closest `[data-usa-theme]` (or `theme`). */
2080
+ function playThemeEffect(el, role, theme) {
2081
+ const name = theme || el.closest('[data-usa-theme]')?.getAttribute('data-usa-theme') || 'neon';
2082
+ const pr = themePreset(name, role);
2083
+ return playEffect(el, pr.effect, pr.options);
2084
+ }
2085
+ const THEME_FX = [
2086
+ {
2087
+ name: 'neon-flicker',
2088
+ kind: 'attention',
2089
+ description: 'A neon tube flickering on — dims (never blacks out) twice, well under 3 flashes per second.',
2090
+ defaults: { color: '#22d3ee' },
2091
+ run: (el, o, ctx) => ctx.animate(el, [{ opacity: 1, filter: 'none' }, { opacity: 0.55, offset: 0.2 }, { opacity: 1, filter: `drop-shadow(0 0 6px ${o.color})`, offset: 0.35 }, { opacity: 0.7, offset: 0.6 }, { opacity: 1, filter: `drop-shadow(0 0 10px ${o.color})` }], { duration: 900, easing: 'linear' }),
2092
+ },
2093
+ {
2094
+ name: 'paper-fold',
2095
+ kind: 'enter',
2096
+ description: 'Unfolds like a sheet of paper hinged at the top.',
2097
+ defaults: { duration: 600 },
2098
+ run: (el, o, ctx) => ctx.animate(el, [{ transform: 'perspective(800px) rotateX(-85deg)', transformOrigin: 'top', opacity: 0 }, { transform: 'perspective(800px) rotateX(12deg)', transformOrigin: 'top', opacity: 1, offset: 0.7 }, { transform: 'perspective(800px) rotateX(0)', transformOrigin: 'top', opacity: 1 }], { duration: o.duration, easing: 'ease-out', fill: 'backwards' }),
2099
+ },
2100
+ {
2101
+ name: 'glass-shine',
2102
+ kind: 'hover',
2103
+ description: 'A bright diagonal shine sweeps across frosted glass.',
2104
+ defaults: { duration: 700 },
2105
+ run: (el, o, ctx) => {
2106
+ const [s, remove] = overlay(el, 'overflow:hidden;background:linear-gradient(105deg,transparent 35%,#ffffff8c 50%,transparent 65%);background-size:250% 100%;background-position:120% 0');
2107
+ const a = ctx.animate(s, [{ backgroundPosition: '120% 0' }, { backgroundPosition: '-20% 0' }], { duration: o.duration, easing: 'ease-in-out' });
2108
+ return a ? a.finished.then(remove, remove) : void remove();
2109
+ },
2110
+ },
2111
+ {
2112
+ name: 'retro-scanlines',
2113
+ kind: 'background',
2114
+ description: 'CRT scanlines with a slow roll (static lines under reduced motion; persistent).',
2115
+ reduced: 'run',
2116
+ defaults: { opacity: 0.18 },
2117
+ run: (el, o, ctx) => {
2118
+ const [s, remove] = overlay(el, `opacity:${o.opacity};background:repeating-linear-gradient(0deg,#000 0 1px,transparent 1px 3px);mix-blend-mode:multiply`);
2119
+ const a = ctx.reduced ? null : ctx.animate(s, [{ backgroundPosition: '0 0' }, { backgroundPosition: '0 30px' }], { duration: 2400, iterations: Infinity, easing: 'linear' });
2120
+ return () => {
2121
+ a?.cancel();
2122
+ remove();
2123
+ };
2124
+ },
2125
+ },
2126
+ {
2127
+ name: 'brutal-shift',
2128
+ kind: 'click',
2129
+ description: 'Presses into its hard drop shadow and springs back (brutalist buttons).',
2130
+ defaults: { offset: 6 },
2131
+ run: (el, o, ctx) => ctx.animate(el, [{ transform: 'translate(0,0)' }, { transform: `translate(${o.offset}px,${o.offset}px)`, boxShadow: '0 0 0 #000', offset: 0.3 }, { transform: 'translate(0,0)' }], { duration: 260, easing: 'ease-out' }),
2132
+ },
2133
+ ];
2134
+ /** `<usa-theme name="neon | paper | glass | retro | brutalist">` — a themed subtree. */
2135
+ function defineTheme(tag = 'usa-theme') {
2136
+ return defineElement(tag, (Base) => class UsaTheme extends Base {
2137
+ static get observedAttributes() {
2138
+ return ['name'];
2139
+ }
2140
+ get theme() {
2141
+ const n = this.str('name', 'neon');
2142
+ return THEMES[n] ? n : 'neon';
2143
+ }
2144
+ mount() {
2145
+ this.onCleanup(applyTheme(this.theme, this));
2146
+ this.querySelectorAll('[data-theme-fx]').forEach((el) => {
2147
+ const role = (el.dataset.themeFx || 'click');
2148
+ if (!THEME_ROLES.includes(role))
2149
+ return;
2150
+ const pr = themePreset(this.theme, role);
2151
+ const trigger = role === 'attention' ? 'click' : role === 'background' ? 'load' : role;
2152
+ try {
2153
+ this.onCleanup(bindEffect(el, pr.effect, { ...(pr.options || {}), trigger }));
2154
+ }
2155
+ catch {
2156
+ /* effect not registered: call registerAllEffects() */
2157
+ }
2158
+ });
2159
+ }
2160
+ }, { id: 'usa-theme-el', text: 'usa-theme{display:block}' });
2161
+ }
2162
+
2163
+ /**
2164
+ * 5.9 — `<usa-player>`: plays JSON animations.
2165
+ *
2166
+ * Format `use-scroll-animate/animation` v1:
2167
+ *
2168
+ * ```json
2169
+ * { "format": "use-scroll-animate/animation", "version": 1, "name": "Hero",
2170
+ * "loop": false,
2171
+ * "tracks": [
2172
+ * { "target": "h1", "start": 0, "duration": 600, "preset": "fade-up" },
2173
+ * { "target": ".cta", "start": 500, "duration": 500, "keyframes": [{ "opacity": 0 }, { "opacity": 1 }], "easing": "ease-out" },
2174
+ * { "target": ".cta", "start": 1100, "effect": "jelly", "options": {} }
2175
+ * ] }
2176
+ * ```
2177
+ *
2178
+ * A track animates `target` (a selector inside the player; `:scope` for the
2179
+ * player itself) with a timeline preset, its own keyframes, or fires any
2180
+ * registered effect at `start`. Playground presets (format
2181
+ * `use-scroll-animate/playground`) are accepted too — their tracks map to the
2182
+ * player's children in order.
2183
+ *
2184
+ * Keyframe tracks are WAAPI animations driven by one clock, so the player can
2185
+ * play, pause, seek, change rate and be scrubbed by scroll
2186
+ * (`trigger="scroll"`). Reduced motion: jumps to the end state, effects skipped.
2187
+ */
2188
+ const ANIMATION_FORMAT = 'use-scroll-animate/animation';
2189
+ function decodePlayground(state) {
2190
+ try {
2191
+ const b64 = state.replace(/-/g, '+').replace(/_/g, '/');
2192
+ const json = decodeURIComponent(escape(atob(b64)));
2193
+ const t = (JSON.parse(json).t || []);
2194
+ return t.map(([preset, start, duration, label], i) => ({ target: `:scope > :nth-child(${i + 1})`, preset, start, duration, label }));
2195
+ }
2196
+ catch {
2197
+ return [];
2198
+ }
2199
+ }
2200
+ /** Validate / normalise an animation (object or JSON text). Throws on anything unusable. */
2201
+ function normalizeAnimation(input) {
2202
+ const d = typeof input === 'string' ? JSON.parse(input) : input;
2203
+ if (!d || typeof d !== 'object')
2204
+ throw new Error('[use-scroll-animate] animation: expected an object');
2205
+ let tracks;
2206
+ if (d.format === 'use-scroll-animate/playground')
2207
+ tracks = decodePlayground(String(d.state || ''));
2208
+ else if (Array.isArray(d.tracks))
2209
+ tracks = d.tracks;
2210
+ else
2211
+ throw new Error('[use-scroll-animate] animation: missing "tracks"');
2212
+ if (d.format && d.format !== ANIMATION_FORMAT && d.format !== 'use-scroll-animate/playground')
2213
+ throw new Error(`[use-scroll-animate] animation: unknown format "${d.format}"`);
2214
+ if (d.version && d.version > 1 && d.format === ANIMATION_FORMAT)
2215
+ throw new Error(`[use-scroll-animate] animation: version ${d.version} needs a newer use-scroll-animate`);
2216
+ const out = tracks
2217
+ .filter((t) => t && (t.effect || t.preset || Array.isArray(t.keyframes)))
2218
+ .map((t) => ({ ...t, target: t.target || ':scope', start: Math.max(0, Number(t.start) || 0), duration: t.effect ? 0 : Math.max(1, Number(t.duration) || 600) }));
2219
+ const end = out.reduce((m, t) => Math.max(m, t.start + t.duration), 0);
2220
+ return { tracks: out, duration: Math.max(end, Number(d.duration) || 0), loop: !!d.loop, name: String(d.name || 'animation') };
2221
+ }
2222
+ const pick = (root, sel) => {
2223
+ if (sel === ':scope')
2224
+ return [root];
2225
+ try {
2226
+ return Array.from(root.querySelectorAll(sel));
2227
+ }
2228
+ catch {
2229
+ return [];
2230
+ }
2231
+ };
2232
+ /** Bind an animation to `root` and return its controller (paused at 0 unless `autoplay`). */
2233
+ function createPlayer(root, animation, o = {}) {
2234
+ const a = normalizeAnimation(animation);
2235
+ const loop = o.loop ?? a.loop;
2236
+ const anims = [];
2237
+ const effects = [];
2238
+ for (const t of a.tracks) {
2239
+ const els = pick(root, t.target);
2240
+ if (t.effect)
2241
+ effects.push({ els, t, fired: false });
2242
+ else {
2243
+ const kf = t.keyframes || TIMELINE_PRESETS[t.preset] || TIMELINE_PRESETS.fade;
2244
+ for (const el of els) {
2245
+ if (typeof el.animate !== 'function')
2246
+ continue;
2247
+ const an = el.animate(kf, { duration: t.duration, delay: t.start, easing: t.easing || 'cubic-bezier(0.22, 1, 0.36, 1)', fill: 'both' });
2248
+ an.pause();
2249
+ an.currentTime = 0;
2250
+ anims.push(an);
2251
+ }
2252
+ }
2253
+ }
2254
+ let time = 0;
2255
+ let playing = false;
2256
+ let raf = 0;
2257
+ let last = 0;
2258
+ let resolve;
2259
+ let finished = new Promise((r) => (resolve = r));
2260
+ const set = (ms) => {
2261
+ time = Math.min(a.duration, Math.max(0, ms));
2262
+ for (const an of anims)
2263
+ an.currentTime = time;
2264
+ };
2265
+ const fireDue = () => {
2266
+ if (prefersReducedMotion())
2267
+ return;
2268
+ for (const e of effects)
2269
+ if (!e.fired && time >= e.t.start) {
2270
+ e.fired = true;
2271
+ for (const el of e.els)
2272
+ playEffect(el, e.t.effect, e.t.options || {}).catch(() => undefined);
2273
+ }
2274
+ };
2275
+ const done = () => {
2276
+ resolve();
2277
+ o.onFinish?.();
2278
+ finished = new Promise((r) => (resolve = r));
2279
+ };
2280
+ const frame = (now) => {
2281
+ raf = 0;
2282
+ if (!playing)
2283
+ return;
2284
+ set(time + (now - last) * player.rate);
2285
+ last = now;
2286
+ fireDue();
2287
+ if (time >= a.duration) {
2288
+ if (loop) {
2289
+ effects.forEach((e) => (e.fired = false));
2290
+ set(0);
2291
+ }
2292
+ else {
2293
+ playing = false;
2294
+ done();
2295
+ return;
2296
+ }
2297
+ }
2298
+ raf = requestAnimationFrame(frame);
2299
+ };
2300
+ const player = {
2301
+ get duration() {
2302
+ return a.duration;
2303
+ },
2304
+ get currentTime() {
2305
+ return time;
2306
+ },
2307
+ get playing() {
2308
+ return playing;
2309
+ },
2310
+ rate: o.rate ?? 1,
2311
+ get finished() {
2312
+ return finished;
2313
+ },
2314
+ play() {
2315
+ if (prefersReducedMotion()) {
2316
+ set(a.duration);
2317
+ effects.forEach((e) => (e.fired = true));
2318
+ done();
2319
+ return;
2320
+ }
2321
+ if (playing)
2322
+ return;
2323
+ if (time >= a.duration) {
2324
+ effects.forEach((e) => (e.fired = false));
2325
+ set(0);
2326
+ }
2327
+ playing = true;
2328
+ last = performance.now();
2329
+ fireDue();
2330
+ raf = requestAnimationFrame(frame);
2331
+ },
2332
+ pause() {
2333
+ playing = false;
2334
+ cancelAnimationFrame(raf);
2335
+ raf = 0;
2336
+ },
2337
+ seek(ms) {
2338
+ set(ms);
2339
+ effects.forEach((e) => (e.fired = e.t.start < time));
2340
+ },
2341
+ destroy() {
2342
+ player.pause();
2343
+ anims.forEach((an) => an.cancel());
2344
+ },
2345
+ };
2346
+ if (o.autoplay)
2347
+ player.play();
2348
+ return player;
2349
+ }
2350
+ /**
2351
+ * `<usa-player src="hero.json" | <script type="application/json"> child
2352
+ * trigger="load | view | scroll | click | manual" loop rate controls>`.
2353
+ * Emits `usa-player-ready` and `usa-player-finish`; sets `data-error` when the
2354
+ * animation cannot be loaded.
2355
+ */
2356
+ function definePlayer(tag = 'usa-player') {
2357
+ return defineElement(tag, (Base) => class UsaPlayer extends Base {
2358
+ constructor() {
2359
+ super(...arguments);
2360
+ this.player = null;
2361
+ this.json = null;
2362
+ }
2363
+ static get observedAttributes() {
2364
+ return ['src', 'trigger', 'loop', 'rate'];
2365
+ }
2366
+ load(animation) {
2367
+ this.json = animation;
2368
+ this.start();
2369
+ }
2370
+ play() {
2371
+ this.player?.play();
2372
+ }
2373
+ pause() {
2374
+ this.player?.pause();
2375
+ }
2376
+ seek(ms) {
2377
+ this.player?.seek(ms);
2378
+ }
2379
+ start() {
2380
+ this.player?.destroy();
2381
+ this.player = null;
2382
+ if (!this.json)
2383
+ return;
2384
+ try {
2385
+ this.player = createPlayer(this, this.json, {
2386
+ loop: this.hasAttribute('loop') ? true : undefined,
2387
+ rate: this.num('rate', 1),
2388
+ onFinish: () => this.dispatchEvent(new CustomEvent('usa-player-finish', { bubbles: true })),
2389
+ });
2390
+ this.removeAttribute('data-error');
2391
+ }
2392
+ catch (err) {
2393
+ this.setAttribute('data-error', String(err.message || err));
2394
+ return;
2395
+ }
2396
+ const p = this.player;
2397
+ this.dispatchEvent(new CustomEvent('usa-player-ready', { detail: { duration: p.duration }, bubbles: true }));
2398
+ const trig = this.str('trigger', 'view');
2399
+ if (trig === 'load')
2400
+ p.play();
2401
+ else if (trig === 'view')
2402
+ this.inView((v) => v && p.play(), { threshold: 0.25 });
2403
+ else if (trig === 'click')
2404
+ this.listen(this, 'click', () => (p.playing ? p.pause() : p.play()));
2405
+ else if (trig === 'scroll') {
2406
+ let f = 0;
2407
+ const upd = () => {
2408
+ f = 0;
2409
+ p.seek(storyProgress(this) * p.duration);
2410
+ };
2411
+ const kick = () => void (f || (f = requestAnimationFrame(upd)));
2412
+ this.listen(window, 'scroll', kick, { passive: true });
2413
+ this.listen(window, 'resize', kick);
2414
+ this.onCleanup(() => cancelAnimationFrame(f));
2415
+ upd();
2416
+ }
2417
+ if (this.flag('controls'))
2418
+ this.mountControls(p);
2419
+ }
2420
+ mountControls(p) {
2421
+ const b = document.createElement('button');
2422
+ b.type = 'button';
2423
+ b.setAttribute('data-player-toggle', '');
2424
+ b.textContent = '▶︎ / ❚❚';
2425
+ b.setAttribute('aria-label', 'Play / pause animation');
2426
+ this.listen(b, 'click', (e) => {
2427
+ e.stopPropagation();
2428
+ if (p.playing)
2429
+ p.pause();
2430
+ else
2431
+ p.play();
2432
+ b.setAttribute('aria-pressed', String(p.playing));
2433
+ });
2434
+ this.append(b);
2435
+ this.onCleanup(() => b.remove());
2436
+ }
2437
+ changed(name) {
2438
+ if (name === 'src')
2439
+ this.json = null;
2440
+ super.changed(name);
2441
+ }
2442
+ mount() {
2443
+ this.onCleanup(() => {
2444
+ this.player?.destroy();
2445
+ this.player = null;
2446
+ });
2447
+ const inline = this.querySelector('script[type="application/json"]');
2448
+ const src = this.str('src');
2449
+ if (inline && !this.json)
2450
+ this.json = inline.textContent || '';
2451
+ if (src && !this.json) {
2452
+ fetch(src)
2453
+ .then((r) => (r.ok ? r.text() : Promise.reject(new Error(`HTTP ${r.status}`))))
2454
+ .then((t) => this.isConnected && this.load(t))
2455
+ .catch((err) => this.setAttribute('data-error', String(err.message || err)));
2456
+ return;
2457
+ }
2458
+ this.start();
2459
+ }
2460
+ }, { id: 'usa-player', text: 'usa-player{display:block;position:relative}usa-player>script{display:none}usa-player [data-player-toggle]{position:absolute;right:8px;bottom:8px}' });
2461
+ }
2462
+
1824
2463
  /**
1825
2464
  * use-scroll-animate/components/effects — the 5.x effect packs, all
1826
2465
  * registered through `registerEffect()` (5.0) and playable with
@@ -1841,6 +2480,8 @@ const EFFECT_PACKS = {
1841
2480
  generative: GENERATIVE_FX,
1842
2481
  audio: AUDIO_FX,
1843
2482
  cursor: CURSOR_FX,
2483
+ micro: MICRO_FX,
2484
+ themes: THEME_FX,
1844
2485
  };
1845
2486
  /** 5.1: card & click effects 2.0. */
1846
2487
  function registerCardClickEffects() {
@@ -1866,11 +2507,18 @@ function registerAudioEffects() {
1866
2507
  function registerCursorEffects() {
1867
2508
  registerEffects(EFFECT_PACKS.cursor);
1868
2509
  }
2510
+ /** 5.8: micro-interactions + theme-pack effects. */
2511
+ function registerMicroEffects() {
2512
+ registerEffects(EFFECT_PACKS.micro);
2513
+ registerEffects(EFFECT_PACKS.themes);
2514
+ }
1869
2515
  /** Define the 5.x elements of this entry (`<usa-story>`, …) under their default tags. */
1870
2516
  function defineEffectElements() {
1871
2517
  defineStory();
1872
2518
  defineAudio();
1873
2519
  defineGestureFx();
2520
+ defineTheme();
2521
+ definePlayer();
1874
2522
  }
1875
2523
  /** Register the built-ins and every pack (idempotent). */
1876
2524
  function registerAllEffects() {
@@ -1879,5 +2527,5 @@ function registerAllEffects() {
1879
2527
  registerEffects(defs);
1880
2528
  }
1881
2529
 
1882
- export { AUDIO_FX, CARD_FX, CLICK_FX, CURSOR_FX, EFFECT_PACKS, GENERATIVE_FX, GESTURES, PAGE_FX, PHYSICS_FX, STORY_TEMPLATES, angleDelta, bindBeat, bindGesture, bounceKeyframes, canvasBackground, createBeatDetector, defineAudio, defineEffectElements, defineGestureFx, defineStory, disableAudio, enableAudio, flingVelocity, formatCount, fxLayer, getAudio, hexRgb, noise2, onBeat, registerAllEffects, registerAudioEffects, registerCardClickEffects, registerCursorEffects, registerGenerativeEffects, registerPageEffects, registerPhysicsEffects, solveSpring, springKeyframes, storyProgress };
2530
+ export { ANIMATION_FORMAT, AUDIO_FX, CARD_FX, CLICK_FX, CURSOR_FX, EFFECT_PACKS, GENERATIVE_FX, GESTURES, MICRO_FX, PAGE_FX, PHYSICS_FX, STORY_TEMPLATES, THEMES, THEME_FX, THEME_NAMES, THEME_ROLES, angleDelta, applyTheme, bindBeat, bindGesture, bounceKeyframes, bumpCount, canvasBackground, createBeatDetector, createPlayer, defineAudio, defineEffectElements, defineGestureFx, definePlayer, defineStory, defineTheme, disableAudio, enableAudio, flingVelocity, formatCount, fxLayer, getAudio, hexRgb, noise2, normalizeAnimation, onBeat, playThemeEffect, registerAllEffects, registerAudioEffects, registerCardClickEffects, registerCursorEffects, registerGenerativeEffects, registerMicroEffects, registerPageEffects, registerPhysicsEffects, solveSpring, springKeyframes, storyProgress, swapLabel, themeCss, themePreset, themeVars, togglePressed };
1883
2531
  //# sourceMappingURL=effects.js.map