animal.js 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global.animal = factory());
  5. }(this, (function () {
  6. 'use strict';
  7. // --- Utils ---
  8. const isArr = (a) => Array.isArray(a);
  9. const isStr = (s) => typeof s === 'string';
  10. const isFunc = (f) => typeof f === 'function';
  11. const isNil = (v) => v === undefined || v === null;
  12. const isSVG = (el) => (typeof SVGElement !== 'undefined' && el instanceof SVGElement) || ((typeof Element !== 'undefined') && (el instanceof Element) && el.namespaceURI === 'http://www.w3.org/2000/svg');
  13. const isEl = (v) => (typeof Element !== 'undefined') && (v instanceof Element);
  14. const clamp01 = (n) => Math.max(0, Math.min(1, n));
  15. const toKebab = (s) => s.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
  16. const toArray = (targets) => {
  17. if (isArr(targets)) return targets;
  18. if (isStr(targets)) {
  19. if (typeof document === 'undefined') return [];
  20. return Array.from(document.querySelectorAll(targets));
  21. }
  22. if ((typeof NodeList !== 'undefined') && (targets instanceof NodeList)) return Array.from(targets);
  23. if ((typeof Element !== 'undefined') && (targets instanceof Element)) return [targets];
  24. if ((typeof Window !== 'undefined') && (targets instanceof Window)) return [targets];
  25. // Plain objects (for anime.js-style object tweening)
  26. if (!isNil(targets) && (typeof targets === 'object' || isFunc(targets))) return [targets];
  27. return [];
  28. };
  29. // Selection helper (chainable, still Array-compatible)
  30. const _layerHandlerByEl = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
  31. class Selection extends Array {
  32. animate(params) { return animate(this, params); }
  33. draw(params = {}) { return svgDraw(this, params); }
  34. inViewAnimate(params, options = {}) { return inViewAnimate(this, params, options); }
  35. // Layer.js plugin-style helper:
  36. // const $ = animal.$;
  37. // $('.btn').layer({ title: 'Hi' });
  38. // Clicking the element will open Layer.
  39. layer(options) {
  40. const LayerCtor =
  41. (typeof window !== 'undefined' && window.Layer) ? window.Layer :
  42. (typeof globalThis !== 'undefined' && globalThis.Layer) ? globalThis.Layer :
  43. (typeof Layer !== 'undefined' ? Layer : null);
  44. if (!LayerCtor) return this;
  45. this.forEach((el) => {
  46. if (!isEl(el)) return;
  47. // De-dupe / replace previous binding
  48. if (_layerHandlerByEl) {
  49. const prev = _layerHandlerByEl.get(el);
  50. if (prev) el.removeEventListener('click', prev);
  51. }
  52. const handler = () => {
  53. let opts = options;
  54. if (isFunc(options)) {
  55. opts = options(el);
  56. } else if (isNil(options)) {
  57. opts = null;
  58. }
  59. // If no explicit options, allow data-* configuration
  60. if (!opts || (typeof opts === 'object' && Object.keys(opts).length === 0)) {
  61. const d = el.dataset || {};
  62. opts = {
  63. title: d.layerTitle || el.getAttribute('data-layer-title') || (el.textContent || '').trim(),
  64. text: d.layerText || el.getAttribute('data-layer-text') || '',
  65. icon: d.layerIcon || el.getAttribute('data-layer-icon') || null,
  66. showCancelButton: (d.layerCancel === 'true') || (el.getAttribute('data-layer-cancel') === 'true')
  67. };
  68. }
  69. // Prefer builder API if present, fallback to static fire.
  70. if (LayerCtor.$ && isFunc(LayerCtor.$)) return LayerCtor.$(opts).fire();
  71. if (LayerCtor.fire && isFunc(LayerCtor.fire)) return LayerCtor.fire(opts);
  72. };
  73. if (_layerHandlerByEl) _layerHandlerByEl.set(el, handler);
  74. el.addEventListener('click', handler);
  75. });
  76. return this;
  77. }
  78. // Remove click bindings added by `.layer()`
  79. unlayer() {
  80. this.forEach((el) => {
  81. if (!isEl(el)) return;
  82. if (!_layerHandlerByEl) return;
  83. const prev = _layerHandlerByEl.get(el);
  84. if (prev) el.removeEventListener('click', prev);
  85. _layerHandlerByEl.delete(el);
  86. });
  87. return this;
  88. }
  89. }
  90. const $ = (targets) => Selection.from(toArray(targets));
  91. const UNITLESS_KEYS = ['opacity', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'zIndex', 'fontWeight', 'strokeDashoffset', 'strokeDasharray', 'strokeWidth'];
  92. const getUnit = (val, prop) => {
  93. if (UNITLESS_KEYS.includes(prop)) return '';
  94. const split = /[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(val);
  95. return split ? split[1] : undefined;
  96. };
  97. const isCssVar = (k) => isStr(k) && k.startsWith('--');
  98. // Keep this intentionally broad so "unknown" config keys don't accidentally become animated props.
  99. // Prefer putting non-anim-prop config under `params.options`.
  100. const isAnimOptionKey = (k) => [
  101. 'options',
  102. 'duration', 'delay', 'easing', 'direction', 'fill', 'loop', 'endDelay', 'autoplay',
  103. 'update', 'begin', 'complete',
  104. // WAAPI-ish common keys (ignored unless we explicitly support them)
  105. 'iterations', 'iterationStart', 'iterationComposite', 'composite', 'playbackRate',
  106. // Spring helpers
  107. 'springFrames'
  108. ].includes(k);
  109. const isEasingFn = (e) => typeof e === 'function';
  110. // Minimal cubic-bezier implementation (for JS engine easing)
  111. function cubicBezier(x1, y1, x2, y2) {
  112. // Inspired by https://github.com/gre/bezier-easing (simplified)
  113. const NEWTON_ITERATIONS = 4;
  114. const NEWTON_MIN_SLOPE = 0.001;
  115. const SUBDIVISION_PRECISION = 0.0000001;
  116. const SUBDIVISION_MAX_ITERATIONS = 10;
  117. const kSplineTableSize = 11;
  118. const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
  119. const float32ArraySupported = typeof Float32Array === 'function';
  120. function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; }
  121. function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; }
  122. function C(aA1) { return 3.0 * aA1; }
  123. function calcBezier(aT, aA1, aA2) {
  124. return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
  125. }
  126. function getSlope(aT, aA1, aA2) {
  127. return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
  128. }
  129. function binarySubdivide(aX, aA, aB) {
  130. let currentX, currentT, i = 0;
  131. do {
  132. currentT = aA + (aB - aA) / 2.0;
  133. currentX = calcBezier(currentT, x1, x2) - aX;
  134. if (currentX > 0.0) aB = currentT;
  135. else aA = currentT;
  136. } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
  137. return currentT;
  138. }
  139. function newtonRaphsonIterate(aX, aGuessT) {
  140. for (let i = 0; i < NEWTON_ITERATIONS; ++i) {
  141. const currentSlope = getSlope(aGuessT, x1, x2);
  142. if (currentSlope === 0.0) return aGuessT;
  143. const currentX = calcBezier(aGuessT, x1, x2) - aX;
  144. aGuessT -= currentX / currentSlope;
  145. }
  146. return aGuessT;
  147. }
  148. const sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
  149. for (let i = 0; i < kSplineTableSize; ++i) {
  150. sampleValues[i] = calcBezier(i * kSampleStepSize, x1, x2);
  151. }
  152. function getTForX(aX) {
  153. let intervalStart = 0.0;
  154. let currentSample = 1;
  155. const lastSample = kSplineTableSize - 1;
  156. for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
  157. intervalStart += kSampleStepSize;
  158. }
  159. --currentSample;
  160. const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
  161. const guessForT = intervalStart + dist * kSampleStepSize;
  162. const initialSlope = getSlope(guessForT, x1, x2);
  163. if (initialSlope >= NEWTON_MIN_SLOPE) return newtonRaphsonIterate(aX, guessForT);
  164. if (initialSlope === 0.0) return guessForT;
  165. return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);
  166. }
  167. return (x) => {
  168. if (x === 0 || x === 1) return x;
  169. return calcBezier(getTForX(x), y1, y2);
  170. };
  171. }
  172. function resolveJsEasing(easing, springValues) {
  173. if (isEasingFn(easing)) return easing;
  174. if (typeof easing === 'object' && easing && !Array.isArray(easing)) {
  175. // Spring: map linear progress -> simulated spring curve (0..1)
  176. const values = springValues || getSpringValues(easing);
  177. const last = Math.max(0, values.length - 1);
  178. return (t) => {
  179. const p = clamp01(t);
  180. const idx = p * last;
  181. const i0 = Math.floor(idx);
  182. const i1 = Math.min(last, i0 + 1);
  183. const frac = idx - i0;
  184. const v0 = values[i0] ?? p;
  185. const v1 = values[i1] ?? p;
  186. return v0 + (v1 - v0) * frac;
  187. };
  188. }
  189. if (Array.isArray(easing) && easing.length === 4) {
  190. return cubicBezier(easing[0], easing[1], easing[2], easing[3]);
  191. }
  192. // Common named easings
  193. switch (easing) {
  194. case 'linear': return (t) => t;
  195. case 'ease': return cubicBezier(0.25, 0.1, 0.25, 1);
  196. case 'ease-in': return cubicBezier(0.42, 0, 1, 1);
  197. case 'ease-out': return cubicBezier(0, 0, 0.58, 1);
  198. case 'ease-in-out': return cubicBezier(0.42, 0, 0.58, 1);
  199. default: return (t) => t;
  200. }
  201. }
  202. // --- Spring Physics (Simplified) ---
  203. // Returns an array of [time, value] or just value for WAAPI linear easing
  204. function spring({ stiffness = 100, damping = 10, mass = 1, velocity = 0, precision = 0.01 } = {}) {
  205. const values = [];
  206. let t = 0;
  207. const timeStep = 1 / 60; // 60fps simulation
  208. let current = 0;
  209. let v = velocity;
  210. const target = 1;
  211. let running = true;
  212. while (running && t < 10) { // Safety break at 10s
  213. const fSpring = -stiffness * (current - target);
  214. const fDamper = -damping * v;
  215. const a = (fSpring + fDamper) / mass;
  216. v += a * timeStep;
  217. current += v * timeStep;
  218. values.push(current);
  219. t += timeStep;
  220. if (Math.abs(current - target) < precision && Math.abs(v) < precision) {
  221. running = false;
  222. }
  223. }
  224. if (values[values.length - 1] !== 1) values.push(1);
  225. return values;
  226. }
  227. // Cache spring curves by config (perf: avoid recomputing for many targets)
  228. // LRU-ish capped cache to avoid unbounded growth in long-lived apps.
  229. const SPRING_CACHE_MAX = 50;
  230. const springCache = new Map();
  231. function springCacheGet(key) {
  232. const v = springCache.get(key);
  233. if (!v) return v;
  234. // refresh LRU
  235. springCache.delete(key);
  236. springCache.set(key, v);
  237. return v;
  238. }
  239. function springCacheSet(key, values) {
  240. if (springCache.has(key)) springCache.delete(key);
  241. springCache.set(key, values);
  242. if (springCache.size > SPRING_CACHE_MAX) {
  243. const firstKey = springCache.keys().next().value;
  244. if (firstKey !== undefined) springCache.delete(firstKey);
  245. }
  246. }
  247. function getSpringValues(config = {}) {
  248. const {
  249. stiffness = 100,
  250. damping = 10,
  251. mass = 1,
  252. velocity = 0,
  253. precision = 0.01
  254. } = config || {};
  255. const key = `${stiffness}|${damping}|${mass}|${velocity}|${precision}`;
  256. const cached = springCacheGet(key);
  257. if (cached) return cached;
  258. const values = spring({ stiffness, damping, mass, velocity, precision });
  259. springCacheSet(key, values);
  260. return values;
  261. }
  262. function downsample(values, maxFrames = 120) {
  263. if (!values || values.length <= maxFrames) return values || [];
  264. const out = [];
  265. const lastIndex = values.length - 1;
  266. const step = lastIndex / (maxFrames - 1);
  267. for (let i = 0; i < maxFrames; i++) {
  268. const idx = i * step;
  269. const i0 = Math.floor(idx);
  270. const i1 = Math.min(lastIndex, i0 + 1);
  271. const frac = idx - i0;
  272. const v0 = values[i0];
  273. const v1 = values[i1];
  274. out.push(v0 + (v1 - v0) * frac);
  275. }
  276. if (out[out.length - 1] !== 1) out[out.length - 1] = 1;
  277. return out;
  278. }
  279. // --- WAAPI Core ---
  280. const TRANSFORMS = ['translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'perspective', 'x', 'y'];
  281. const ALIASES = {
  282. x: 'translateX',
  283. y: 'translateY',
  284. z: 'translateZ'
  285. };
  286. // Basic rAF loop for non-WAAPI props or fallback
  287. class RafEngine {
  288. constructor() {
  289. this.animations = [];
  290. this.tick = this.tick.bind(this);
  291. this.running = false;
  292. }
  293. add(anim) {
  294. this.animations.push(anim);
  295. if (!this.running) {
  296. this.running = true;
  297. requestAnimationFrame(this.tick);
  298. }
  299. }
  300. remove(anim) {
  301. this.animations = this.animations.filter(a => a !== anim);
  302. }
  303. tick(t) {
  304. const now = t;
  305. this.animations = this.animations.filter(anim => {
  306. return anim.tick(now); // return true to keep
  307. });
  308. if (this.animations.length) {
  309. requestAnimationFrame(this.tick);
  310. } else {
  311. this.running = false;
  312. }
  313. }
  314. }
  315. const rafEngine = new RafEngine();
  316. // --- WAAPI update sampler (only used when update callback is provided) ---
  317. class WaapiUpdateSampler {
  318. constructor() {
  319. this.items = new Set();
  320. this._running = false;
  321. this._tick = this._tick.bind(this);
  322. }
  323. add(item) {
  324. this.items.add(item);
  325. if (!this._running) {
  326. this._running = true;
  327. requestAnimationFrame(this._tick);
  328. }
  329. }
  330. remove(item) {
  331. this.items.delete(item);
  332. }
  333. _tick(t) {
  334. if (!this.items.size) {
  335. this._running = false;
  336. return;
  337. }
  338. let anyActive = false;
  339. let anyChanged = false;
  340. this.items.forEach((item) => {
  341. const { anim, target, update } = item;
  342. if (!anim || !anim.effect) return;
  343. let dur = item._dur || 0;
  344. if (!dur) {
  345. const timing = readWaapiEffectTiming(anim.effect);
  346. dur = timing.duration || 0;
  347. item._dur = dur;
  348. }
  349. if (!dur) return;
  350. const p = clamp01((anim.currentTime || 0) / dur);
  351. if (anim.playState === 'running') anyActive = true;
  352. if (item._lastP !== p) {
  353. anyChanged = true;
  354. item._lastP = p;
  355. update({ target, progress: p, time: t });
  356. }
  357. if (anim.playState === 'finished' || anim.playState === 'idle') {
  358. this.items.delete(item);
  359. }
  360. });
  361. if (this.items.size && (anyActive || anyChanged)) {
  362. requestAnimationFrame(this._tick);
  363. } else {
  364. this._running = false;
  365. }
  366. }
  367. }
  368. const waapiUpdateSampler = new WaapiUpdateSampler();
  369. function readWaapiEffectTiming(effect) {
  370. // We compute this once per animation and cache it to avoid per-frame getComputedTiming().
  371. // We primarily cache `duration` to preserve existing behavior (progress maps to one iteration).
  372. let duration = 0;
  373. let endTime = 0;
  374. if (!effect) return { duration, endTime };
  375. try {
  376. const ct = effect.getComputedTiming ? effect.getComputedTiming() : null;
  377. if (ct) {
  378. if (typeof ct.duration === 'number' && Number.isFinite(ct.duration)) duration = ct.duration;
  379. if (typeof ct.endTime === 'number' && Number.isFinite(ct.endTime)) endTime = ct.endTime;
  380. }
  381. } catch (e) {
  382. // ignore
  383. }
  384. if (!endTime) endTime = duration || 0;
  385. return { duration, endTime };
  386. }
  387. function getDefaultUnit(prop) {
  388. if (!prop) return '';
  389. if (UNITLESS_KEYS.includes(prop)) return '';
  390. if (prop.startsWith('scale')) return '';
  391. if (prop === 'opacity') return '';
  392. if (prop.startsWith('rotate') || prop.startsWith('skew')) return 'deg';
  393. return 'px';
  394. }
  395. function normalizeTransformPartValue(prop, v) {
  396. if (typeof v !== 'number') return v;
  397. if (prop && prop.startsWith('scale')) return '' + v;
  398. if (prop && (prop.startsWith('rotate') || prop.startsWith('skew'))) return v + 'deg';
  399. return v + 'px';
  400. }
  401. // String number template: interpolate numeric tokens inside a string.
  402. // Useful for SVG path `d`, `points`, and other attributes that contain many numbers.
  403. const _PURE_NUMBER_RE = /^[+-]?(?:\d*\.)?\d+(?:[eE][+-]?\d+)?(?:%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/;
  404. function isPureNumberLike(str) {
  405. return _PURE_NUMBER_RE.test(String(str || '').trim());
  406. }
  407. function countDecimals(numStr) {
  408. const s = String(numStr || '');
  409. const dot = s.indexOf('.');
  410. if (dot < 0) return 0;
  411. // Strip exponent part for decimal count
  412. const e = s.search(/[eE]/);
  413. const end = e >= 0 ? e : s.length;
  414. const frac = s.slice(dot + 1, end);
  415. // Ignore trailing zeros for display
  416. const trimmed = frac.replace(/0+$/, '');
  417. return Math.min(6, trimmed.length);
  418. }
  419. function parseNumberTemplate(str) {
  420. const s = String(str ?? '');
  421. const nums = [];
  422. const parts = [];
  423. let last = 0;
  424. const re = /[+-]?(?:\d*\.)?\d+(?:[eE][+-]?\d+)?/g;
  425. let m;
  426. while ((m = re.exec(s))) {
  427. const start = m.index;
  428. const end = start + m[0].length;
  429. parts.push(s.slice(last, start));
  430. nums.push(parseFloat(m[0]));
  431. last = end;
  432. }
  433. parts.push(s.slice(last));
  434. return { nums, parts };
  435. }
  436. function extractNumberStrings(str) {
  437. // Use a fresh regex to avoid any `lastIndex` surprises.
  438. return String(str ?? '').match(/[+-]?(?:\d*\.)?\d+(?:[eE][+-]?\d+)?/g) || [];
  439. }
  440. function formatInterpolatedNumber(n, decimals) {
  441. let v = n;
  442. if (!Number.isFinite(v)) v = 0;
  443. if (Math.abs(v) < 1e-12) v = 0;
  444. if (!decimals) return String(Math.round(v));
  445. // Use fixed, then strip trailing zeros/dot to keep strings compact.
  446. return v.toFixed(decimals).replace(/\.?0+$/, '');
  447. }
  448. // --- JS Interpolator (anime.js-ish, simplified) ---
  449. class JsAnimation {
  450. constructor(target, propValues, opts = {}, callbacks = {}) {
  451. this.target = target;
  452. this.propValues = propValues;
  453. this.duration = opts.duration ?? 1000;
  454. this.delay = opts.delay ?? 0;
  455. this.direction = opts.direction ?? 'normal';
  456. this.loop = opts.loop ?? 1;
  457. this.endDelay = opts.endDelay ?? 0;
  458. this.easing = opts.easing ?? 'linear';
  459. this.autoplay = opts.autoplay !== false;
  460. this.update = callbacks.update;
  461. this.begin = callbacks.begin;
  462. this.complete = callbacks.complete;
  463. this._resolve = null;
  464. this.finished = new Promise((res) => (this._resolve = res));
  465. this._started = false;
  466. this._running = false;
  467. this._paused = false;
  468. this._cancelled = false;
  469. this._startTime = 0;
  470. this._progress = 0;
  471. this._didBegin = false;
  472. this._ease = resolveJsEasing(this.easing, opts.springValues);
  473. this._tween = this._buildTween();
  474. this.tick = this.tick.bind(this);
  475. if (this.autoplay) this.play();
  476. }
  477. _readCurrentValue(k) {
  478. const t = this.target;
  479. // JS object
  480. if (!isEl(t) && !isSVG(t)) return t[k];
  481. // scroll
  482. if (k === 'scrollTop' || k === 'scrollLeft') return t[k];
  483. // CSS var
  484. if (isEl(t) && isCssVar(k)) {
  485. const cs = getComputedStyle(t);
  486. return (cs.getPropertyValue(k) || t.style.getPropertyValue(k) || '').trim();
  487. }
  488. // style
  489. if (isEl(t)) {
  490. const cs = getComputedStyle(t);
  491. // Prefer computed style (kebab) because many props aren't direct keys on cs
  492. const v = cs.getPropertyValue(toKebab(k));
  493. if (v && v.trim()) return v.trim();
  494. // Fallback to inline style access
  495. if (k in t.style) return t.style[k];
  496. }
  497. // SVG attribute
  498. if (isSVG(t)) {
  499. const attr = toKebab(k);
  500. if (t.hasAttribute(attr)) return t.getAttribute(attr);
  501. if (t.hasAttribute(k)) return t.getAttribute(k);
  502. }
  503. // Generic property
  504. return t[k];
  505. }
  506. _writeValue(k, v) {
  507. const t = this.target;
  508. // JS object
  509. if (!isEl(t) && !isSVG(t)) {
  510. t[k] = v;
  511. return;
  512. }
  513. // scroll
  514. if (k === 'scrollTop' || k === 'scrollLeft') {
  515. t[k] = v;
  516. return;
  517. }
  518. // CSS var
  519. if (isEl(t) && isCssVar(k)) {
  520. t.style.setProperty(k, v);
  521. return;
  522. }
  523. // style
  524. if (isEl(t) && (k in t.style)) {
  525. t.style[k] = v;
  526. return;
  527. }
  528. // SVG attribute
  529. if (isSVG(t)) {
  530. const attr = toKebab(k);
  531. t.setAttribute(attr, v);
  532. return;
  533. }
  534. // Fallback for path/d/points even if isSVG check somehow failed
  535. if ((k === 'd' || k === 'points') && isEl(t)) {
  536. t.setAttribute(k, v);
  537. return;
  538. }
  539. // Generic property
  540. t[k] = v;
  541. }
  542. _buildTween() {
  543. const tween = {};
  544. Object.keys(this.propValues).forEach((k) => {
  545. const raw = this.propValues[k];
  546. const fromRaw = isArr(raw) ? raw[0] : this._readCurrentValue(k);
  547. const toRaw = isArr(raw) ? raw[1] : raw;
  548. const fromStr = isNil(fromRaw) ? '0' : ('' + fromRaw).trim();
  549. const toStr = isNil(toRaw) ? '0' : ('' + toRaw).trim();
  550. const fromScalar = isPureNumberLike(fromStr);
  551. const toScalar = isPureNumberLike(toStr);
  552. // numeric tween (with unit preservation) — only when BOTH sides are pure scalars.
  553. if (fromScalar && toScalar) {
  554. const fromNum = parseFloat(fromStr);
  555. const toNum = parseFloat(toStr);
  556. const unit = getUnit(toStr, k) ?? getUnit(fromStr, k) ?? '';
  557. tween[k] = { type: 'number', from: fromNum, to: toNum, unit };
  558. return;
  559. }
  560. // string number-template tween (SVG path `d`, `points`, etc.)
  561. // Requires both strings to have the same count of numeric tokens (>= 2).
  562. const a = parseNumberTemplate(fromStr);
  563. const b = parseNumberTemplate(toStr);
  564. if (a.nums.length >= 2 && a.nums.length === b.nums.length && a.parts.length === b.parts.length) {
  565. const aStrs = extractNumberStrings(fromStr);
  566. const bStrs = extractNumberStrings(toStr);
  567. const decs = a.nums.map((_, i) => Math.max(countDecimals(aStrs[i]), countDecimals(bStrs[i])));
  568. tween[k] = { type: 'number-template', fromNums: a.nums, toNums: b.nums, parts: b.parts, decimals: decs };
  569. return;
  570. } else if ((k === 'd' || k === 'points') && (a.nums.length > 0 || b.nums.length > 0)) {
  571. console.warn(`[Animal.js] Morph mismatch for property "${k}".\nValues must have matching number count.`,
  572. { from: a.nums.length, to: b.nums.length, fromVal: fromStr, toVal: toStr }
  573. );
  574. }
  575. // Non-numeric: fall back to "switch" (still useful for seek endpoints)
  576. tween[k] = { type: 'discrete', from: fromStr, to: toStr };
  577. });
  578. return tween;
  579. }
  580. _apply(progress, time) {
  581. this._progress = clamp01(progress);
  582. Object.keys(this._tween).forEach((k) => {
  583. const t = this._tween[k];
  584. if (t.type === 'number') {
  585. const eased = this._ease ? this._ease(this._progress) : this._progress;
  586. const val = t.from + (t.to - t.from) * eased;
  587. if (!isEl(this.target) && !isSVG(this.target) && t.unit === '') {
  588. this._writeValue(k, val);
  589. } else {
  590. this._writeValue(k, (val + t.unit));
  591. }
  592. } else if (t.type === 'number-template') {
  593. const eased = this._ease ? this._ease(this._progress) : this._progress;
  594. const { fromNums, toNums, parts, decimals } = t;
  595. let out = parts[0] || '';
  596. for (let i = 0; i < fromNums.length; i++) {
  597. const v = fromNums[i] + (toNums[i] - fromNums[i]) * eased;
  598. out += formatInterpolatedNumber(v, decimals ? decimals[i] : 0);
  599. out += parts[i + 1] || '';
  600. }
  601. this._writeValue(k, out);
  602. } else {
  603. const val = this._progress >= 1 ? t.to : t.from;
  604. this._writeValue(k, val);
  605. }
  606. });
  607. if (this.update) this.update({ target: this.target, progress: this._progress, time });
  608. }
  609. seek(progress) {
  610. // Seek does not auto-play; it's intended for scroll-linked or manual control.
  611. const t = (typeof performance !== 'undefined' ? performance.now() : 0);
  612. this._apply(progress, t);
  613. }
  614. play() {
  615. if (this._cancelled) return;
  616. if (!this._started) {
  617. this._started = true;
  618. this._startTime = performance.now() + this.delay - (this._progress * this.duration);
  619. // begin fired on first active tick to avoid firing during delay.
  620. }
  621. this._paused = false;
  622. if (!this._running) {
  623. this._running = true;
  624. rafEngine.add(this);
  625. }
  626. }
  627. pause() {
  628. this._paused = true;
  629. }
  630. cancel() {
  631. this._cancelled = true;
  632. this._running = false;
  633. rafEngine.remove(this);
  634. // Resolve to avoid hanging awaits
  635. if (this._resolve) this._resolve();
  636. }
  637. finish() {
  638. this.seek(1);
  639. this._running = false;
  640. rafEngine.remove(this);
  641. if (this.complete) this.complete(this.target);
  642. if (this._resolve) this._resolve();
  643. }
  644. tick(now) {
  645. if (this._cancelled) return false;
  646. if (this._paused) return true;
  647. if (!this._started) {
  648. this._started = true;
  649. this._startTime = now + this.delay;
  650. }
  651. if (now < this._startTime) return true;
  652. if (!this._didBegin) {
  653. this._didBegin = true;
  654. if (this.begin) this.begin(this.target);
  655. }
  656. const totalDur = this.duration + (this.endDelay || 0);
  657. const elapsed = now - this._startTime;
  658. const iter = totalDur > 0 ? Math.floor(elapsed / totalDur) : 0;
  659. const inIter = totalDur > 0 ? (elapsed - iter * totalDur) : elapsed;
  660. const iterations = this.loop === true ? Infinity : this.loop;
  661. if (iterations !== Infinity && iter >= iterations) {
  662. this._apply(this._mapDirection(1, iterations - 1));
  663. this._running = false;
  664. if (this.complete) this.complete(this.target);
  665. if (this._resolve) this._resolve();
  666. return false;
  667. }
  668. // if we're in endDelay portion, hold the end state
  669. let p = clamp01(inIter / this.duration);
  670. if (this.duration <= 0) p = 1;
  671. if (this.endDelay && inIter > this.duration) p = 1;
  672. this._apply(this._mapDirection(p, iter), now);
  673. // Keep running until loops exhausted
  674. return true;
  675. }
  676. _mapDirection(p, iterIndex) {
  677. const dir = this.direction;
  678. const flip = (dir === 'reverse') || (dir === 'alternate-reverse');
  679. const isAlt = (dir === 'alternate') || (dir === 'alternate-reverse');
  680. let t = flip ? (1 - p) : p;
  681. if (isAlt && (iterIndex % 2 === 1)) t = 1 - t;
  682. return t;
  683. }
  684. }
  685. // --- Controls (Motion One-ish, chainable / thenable) ---
  686. class Controls {
  687. constructor({ waapi = [], js = [], finished }) {
  688. this.animations = waapi; // backward compat with old `.animations` usage
  689. this.jsAnimations = js;
  690. this.finished = finished || Promise.resolve();
  691. }
  692. then(onFulfilled, onRejected) { return this.finished.then(onFulfilled, onRejected); }
  693. catch(onRejected) { return this.finished.catch(onRejected); }
  694. finally(onFinally) { return this.finished.finally(onFinally); }
  695. play() {
  696. if (this._onPlay) this._onPlay.forEach((fn) => fn && fn());
  697. if (this._ensureWaapiUpdate) this._ensureWaapiUpdate();
  698. this.animations.forEach((a) => a && a.play && a.play());
  699. this.jsAnimations.forEach((a) => a && a.play && a.play());
  700. return this;
  701. }
  702. pause() {
  703. this.animations.forEach((a) => a && a.pause && a.pause());
  704. this.jsAnimations.forEach((a) => a && a.pause && a.pause());
  705. return this;
  706. }
  707. cancel() {
  708. this.animations.forEach((a) => a && a.cancel && a.cancel());
  709. this.jsAnimations.forEach((a) => a && a.cancel && a.cancel());
  710. return this;
  711. }
  712. finish() {
  713. this.animations.forEach((a) => a && a.finish && a.finish());
  714. this.jsAnimations.forEach((a) => a && a.finish && a.finish());
  715. return this;
  716. }
  717. seek(progress) {
  718. const p = clamp01(progress);
  719. const t = (typeof performance !== 'undefined' ? performance.now() : 0);
  720. this.animations.forEach((anim) => {
  721. if (anim && anim.effect) {
  722. let timing = this._waapiTimingByAnim && this._waapiTimingByAnim.get(anim);
  723. if (!timing) {
  724. timing = readWaapiEffectTiming(anim.effect);
  725. if (this._waapiTimingByAnim) this._waapiTimingByAnim.set(anim, timing);
  726. }
  727. const dur = timing.duration || 0;
  728. if (!dur) return;
  729. anim.currentTime = dur * p;
  730. const target = this._waapiTargetByAnim && this._waapiTargetByAnim.get(anim);
  731. if (this._fireUpdate && target) this._fireUpdate({ target, progress: p, time: t });
  732. }
  733. });
  734. this.jsAnimations.forEach((a) => a && a.seek && a.seek(p));
  735. return this;
  736. }
  737. }
  738. // --- Main Animation Logic ---
  739. function animate(targets, params) {
  740. const elements = toArray(targets);
  741. const safeParams = params || {};
  742. const optionsNamespace = (safeParams.options && typeof safeParams.options === 'object') ? safeParams.options : {};
  743. // `params.options` provides a safe namespace for config keys without risking them being treated as animated props.
  744. // Top-level keys still win for backward compatibility.
  745. const merged = { ...optionsNamespace, ...safeParams };
  746. const {
  747. duration = 1000,
  748. delay = 0,
  749. easing = 'ease-out',
  750. direction = 'normal',
  751. fill = 'forwards',
  752. loop = 1,
  753. endDelay = 0,
  754. autoplay = true,
  755. springFrames = 120,
  756. update, // callback
  757. begin, // callback
  758. complete // callback
  759. } = merged;
  760. let isSpring = false;
  761. let springValuesRaw = null;
  762. let springValuesSampled = null;
  763. let springDurationMs = null;
  764. if (typeof easing === 'object' && !Array.isArray(easing)) {
  765. isSpring = true;
  766. springValuesRaw = getSpringValues(easing);
  767. const frames = (typeof springFrames === 'number' && springFrames > 1) ? Math.floor(springFrames) : 120;
  768. springValuesSampled = downsample(springValuesRaw, frames);
  769. springDurationMs = springValuesRaw.length * 1000 / 60;
  770. }
  771. // Callback aggregation (avoid double-calling when WAAPI+JS both run)
  772. const cbState = typeof WeakMap !== 'undefined' ? new WeakMap() : null;
  773. const getState = (t) => {
  774. if (!cbState) return { begun: false, completed: false, lastUpdateBucket: -1 };
  775. let s = cbState.get(t);
  776. if (!s) {
  777. s = { begun: false, completed: false, lastUpdateBucket: -1 };
  778. cbState.set(t, s);
  779. }
  780. return s;
  781. };
  782. const fireBegin = (t) => {
  783. if (!begin) return;
  784. const s = getState(t);
  785. if (s.begun) return;
  786. s.begun = true;
  787. begin(t);
  788. };
  789. const fireComplete = (t) => {
  790. if (!complete) return;
  791. const s = getState(t);
  792. if (s.completed) return;
  793. s.completed = true;
  794. complete(t);
  795. };
  796. const fireUpdate = (payload) => {
  797. if (!update) return;
  798. const t = payload && payload.target;
  799. const time = payload && payload.time;
  800. if (!t) return update(payload);
  801. const s = getState(t);
  802. const bucket = Math.floor(((typeof time === 'number' ? time : (typeof performance !== 'undefined' ? performance.now() : 0))) / 16);
  803. if (bucket === s.lastUpdateBucket) return;
  804. s.lastUpdateBucket = bucket;
  805. update(payload);
  806. };
  807. const propEntries = [];
  808. Object.keys(safeParams).forEach((key) => {
  809. if (key === 'options') return;
  810. if (isAnimOptionKey(key)) return;
  811. propEntries.push({ key, canonical: ALIASES[key] || key, val: safeParams[key] });
  812. });
  813. // Create animations but don't play if autoplay is false
  814. const waapiAnimations = [];
  815. const jsAnimations = [];
  816. const engineInfo = {
  817. isSpring,
  818. waapiKeys: [],
  819. jsKeys: []
  820. };
  821. const waapiKeySet = new Set();
  822. const jsKeySet = new Set();
  823. const onPlayHooks = [];
  824. const waapiUpdateItems = [];
  825. const waapiTargetByAnim = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
  826. const waapiTimingByAnim = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
  827. let waapiUpdateStarted = false;
  828. const ensureWaapiUpdate = () => {
  829. if (waapiUpdateStarted) return;
  830. waapiUpdateStarted = true;
  831. waapiUpdateItems.forEach((item) => waapiUpdateSampler.add(item));
  832. };
  833. const promises = elements.map((el) => {
  834. // Route props per target (fix mixed HTML/SVG/object target arrays).
  835. const waapiProps = {};
  836. const jsProps = {};
  837. propEntries.forEach(({ key, canonical, val }) => {
  838. const isTransform = TRANSFORMS.includes(canonical) || TRANSFORMS.includes(key);
  839. if (!el || (!isEl(el) && !isSVG(el))) {
  840. jsProps[key] = val;
  841. jsKeySet.add(key);
  842. return;
  843. }
  844. const isSvgTarget = isSVG(el);
  845. if (isSvgTarget) {
  846. if (isTransform || key === 'opacity' || key === 'filter') {
  847. waapiProps[canonical] = val;
  848. waapiKeySet.add(canonical);
  849. } else {
  850. jsProps[key] = val;
  851. jsKeySet.add(key);
  852. }
  853. return;
  854. }
  855. // HTML element
  856. if (isCssVar(key)) {
  857. jsProps[key] = val;
  858. jsKeySet.add(key);
  859. return;
  860. }
  861. const isCssLike = isTransform || key === 'opacity' || key === 'filter' || (isEl(el) && (key in el.style));
  862. if (isCssLike) {
  863. waapiProps[canonical] = val;
  864. waapiKeySet.add(canonical);
  865. } else {
  866. jsProps[key] = val;
  867. jsKeySet.add(key);
  868. }
  869. });
  870. // 1. WAAPI Animation
  871. let waapiAnim = null;
  872. let waapiPromise = Promise.resolve();
  873. if (Object.keys(waapiProps).length > 0) {
  874. const buildFrames = (propValues) => {
  875. // Spring: share sampled progress; per-target we only compute start/end once per prop.
  876. if (isSpring && springValuesSampled && springValuesSampled.length) {
  877. const cs = (isEl(el) && typeof getComputedStyle !== 'undefined') ? getComputedStyle(el) : null;
  878. const metas = Object.keys(propValues).map((k) => {
  879. const raw = propValues[k];
  880. const rawFrom = Array.isArray(raw) ? raw[0] : undefined;
  881. const rawTo = Array.isArray(raw) ? raw[1] : raw;
  882. const toNum = parseFloat(('' + rawTo).trim());
  883. const fromNumExplicit = Array.isArray(raw) ? parseFloat(('' + rawFrom).trim()) : NaN;
  884. const isT = TRANSFORMS.includes(ALIASES[k] || k) || TRANSFORMS.includes(k);
  885. const unit = getUnit(('' + rawTo), k) ?? getUnit(('' + rawFrom), k) ?? getDefaultUnit(k);
  886. let fromNum = 0;
  887. if (Number.isFinite(fromNumExplicit)) {
  888. fromNum = fromNumExplicit;
  889. } else if (k.startsWith('scale')) {
  890. fromNum = 1;
  891. } else if (k === 'opacity' && cs) {
  892. const n = parseFloat(cs.opacity);
  893. if (!Number.isNaN(n)) fromNum = n;
  894. } else if (!isT && cs) {
  895. const cssVal = cs.getPropertyValue(toKebab(k));
  896. const n = parseFloat(cssVal);
  897. if (!Number.isNaN(n)) fromNum = n;
  898. }
  899. const to = Number.isFinite(toNum) ? toNum : 0;
  900. return { k, isT, unit: unit ?? '', from: fromNum, to };
  901. });
  902. const frames = new Array(springValuesSampled.length);
  903. for (let i = 0; i < springValuesSampled.length; i++) {
  904. const v = springValuesSampled[i];
  905. const frame = {};
  906. let transformStr = '';
  907. for (let j = 0; j < metas.length; j++) {
  908. const m = metas[j];
  909. const current = m.from + (m.to - m.from) * v;
  910. const outVal = (m.unit === '' ? ('' + current) : (current + m.unit));
  911. if (m.isT) transformStr += `${m.k}(${outVal}) `;
  912. else frame[m.k] = outVal;
  913. }
  914. if (transformStr) frame.transform = transformStr.trim();
  915. frames[i] = frame;
  916. }
  917. if (frames[0] && Object.keys(frames[0]).length === 0) frames.shift();
  918. return frames;
  919. }
  920. // Non-spring: 2-keyframe path
  921. const frame0 = {};
  922. const frame1 = {};
  923. let transform0 = '';
  924. let transform1 = '';
  925. Object.keys(propValues).forEach((k) => {
  926. const val = propValues[k];
  927. const isT = TRANSFORMS.includes(ALIASES[k] || k) || TRANSFORMS.includes(k);
  928. if (Array.isArray(val)) {
  929. const from = isT ? normalizeTransformPartValue(k, val[0]) : val[0];
  930. const to = isT ? normalizeTransformPartValue(k, val[1]) : val[1];
  931. if (isT) {
  932. transform0 += `${k}(${from}) `;
  933. transform1 += `${k}(${to}) `;
  934. } else {
  935. frame0[k] = from;
  936. frame1[k] = to;
  937. }
  938. } else {
  939. if (isT) transform1 += `${k}(${normalizeTransformPartValue(k, val)}) `;
  940. else frame1[k] = val;
  941. }
  942. });
  943. if (transform0) frame0.transform = transform0.trim();
  944. if (transform1) frame1.transform = transform1.trim();
  945. const out = [frame0, frame1];
  946. if (Object.keys(out[0]).length === 0) out.shift();
  947. return out;
  948. };
  949. const finalFrames = buildFrames(waapiProps);
  950. const opts = {
  951. duration: isSpring ? springDurationMs : duration,
  952. delay,
  953. fill,
  954. iterations: loop,
  955. easing: isSpring ? 'linear' : easing,
  956. direction,
  957. endDelay
  958. };
  959. const animation = el.animate(finalFrames, opts);
  960. if (!autoplay) animation.pause();
  961. waapiAnim = animation;
  962. waapiPromise = animation.finished;
  963. waapiAnimations.push(waapiAnim);
  964. if (waapiTargetByAnim) waapiTargetByAnim.set(waapiAnim, el);
  965. if (waapiTimingByAnim) waapiTimingByAnim.set(waapiAnim, readWaapiEffectTiming(waapiAnim.effect));
  966. if (begin) {
  967. // Fire begin when play starts (and also for autoplay on next frame)
  968. onPlayHooks.push(() => fireBegin(el));
  969. if (autoplay && typeof requestAnimationFrame !== 'undefined') requestAnimationFrame(() => fireBegin(el));
  970. }
  971. if (complete) {
  972. waapiAnim.addEventListener?.('finish', () => fireComplete(el));
  973. }
  974. if (update) {
  975. const timing = (waapiTimingByAnim && waapiTimingByAnim.get(waapiAnim)) || readWaapiEffectTiming(waapiAnim.effect);
  976. const item = { anim: waapiAnim, target: el, update: fireUpdate, _lastP: null, _dur: timing.duration || 0 };
  977. waapiUpdateItems.push(item);
  978. // Ensure removal on finish/cancel
  979. waapiAnim.addEventListener?.('finish', () => waapiUpdateSampler.remove(item));
  980. waapiAnim.addEventListener?.('cancel', () => waapiUpdateSampler.remove(item));
  981. // Start sampler only when needed (autoplay or explicit play)
  982. if (autoplay) ensureWaapiUpdate();
  983. }
  984. }
  985. // 2. JS Animation (Fallback / Attributes)
  986. let jsPromise = Promise.resolve();
  987. if (Object.keys(jsProps).length > 0) {
  988. const jsAnim = new JsAnimation(
  989. el,
  990. jsProps,
  991. { duration, delay, easing, autoplay, direction, loop, endDelay, springValues: isSpring ? springValuesRaw : null },
  992. { update: fireUpdate, begin: fireBegin, complete: fireComplete }
  993. );
  994. jsAnimations.push(jsAnim);
  995. jsPromise = jsAnim.finished;
  996. }
  997. return Promise.all([waapiPromise, jsPromise]);
  998. });
  999. const finished = Promise.all(promises);
  1000. const controls = new Controls({ waapi: waapiAnimations, js: jsAnimations, finished });
  1001. controls.engine = engineInfo;
  1002. controls._onPlay = onPlayHooks;
  1003. controls._fireUpdate = fireUpdate;
  1004. controls._waapiTargetByAnim = waapiTargetByAnim;
  1005. controls._waapiTimingByAnim = waapiTimingByAnim;
  1006. controls._ensureWaapiUpdate = update ? ensureWaapiUpdate : null;
  1007. if (!autoplay) controls.pause();
  1008. engineInfo.waapiKeys = Array.from(waapiKeySet);
  1009. engineInfo.jsKeys = Array.from(jsKeySet);
  1010. return controls;
  1011. }
  1012. // --- SVG Draw ---
  1013. function svgDraw(targets, params = {}) {
  1014. const elements = toArray(targets);
  1015. elements.forEach(el => {
  1016. if (!isSVG(el)) return;
  1017. const len = el.getTotalLength ? el.getTotalLength() : 0;
  1018. el.style.strokeDasharray = len;
  1019. el.style.strokeDashoffset = len;
  1020. animate(el, {
  1021. strokeDashoffset: [len, 0],
  1022. ...params
  1023. });
  1024. });
  1025. }
  1026. // --- In View ---
  1027. function inViewAnimate(targets, params, options = {}) {
  1028. const elements = toArray(targets);
  1029. const observer = new IntersectionObserver((entries) => {
  1030. entries.forEach(entry => {
  1031. if (entry.isIntersecting) {
  1032. animate(entry.target, params);
  1033. if (options.once !== false) observer.unobserve(entry.target);
  1034. }
  1035. });
  1036. }, { threshold: options.threshold || 0.1 });
  1037. elements.forEach(el => observer.observe(el));
  1038. // Return cleanup so callers can disconnect observers in long-lived pages (esp. once:false).
  1039. return () => {
  1040. try {
  1041. elements.forEach((el) => observer.unobserve(el));
  1042. observer.disconnect();
  1043. } catch (e) {
  1044. // ignore
  1045. }
  1046. };
  1047. }
  1048. // --- Scroll Linked ---
  1049. function scroll(animationPromise, options = {}) {
  1050. // options: container (default window), range [start, end] (default viewport logic)
  1051. const container = options.container || window;
  1052. const target = options.target || document.body; // Element to track for progress
  1053. // If passing an animation promise, we control its WAAPI animations
  1054. const controls = animationPromise;
  1055. // Back-compat: old return value was a Promise with `.animations`
  1056. const hasSeek = controls && isFunc(controls.seek);
  1057. const anims = (controls && controls.animations) || (animationPromise && animationPromise.animations) || [];
  1058. const jsAnims = (controls && controls.jsAnimations) || [];
  1059. if (!hasSeek && !anims.length && !jsAnims.length) return;
  1060. // Cache WAAPI timing per animation to avoid repeated getComputedTiming() during scroll.
  1061. const timingCache = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
  1062. const getEndTime = (anim) => {
  1063. if (!anim || !anim.effect) return 0;
  1064. if (timingCache) {
  1065. const cached = timingCache.get(anim);
  1066. if (cached) return cached;
  1067. }
  1068. const timing = readWaapiEffectTiming(anim.effect);
  1069. const end = timing.duration || 0;
  1070. if (timingCache && end) timingCache.set(anim, end);
  1071. return end;
  1072. };
  1073. const updateScroll = () => {
  1074. let progress = 0;
  1075. if (container === window) {
  1076. const scrollY = window.scrollY;
  1077. const winH = window.innerHeight;
  1078. const docH = document.body.scrollHeight;
  1079. // Simple progress: how far down the page (0 to 1)
  1080. // Or element based?
  1081. // Motion One defaults to element entering view.
  1082. if (options.target) {
  1083. const rect = options.target.getBoundingClientRect();
  1084. const start = winH;
  1085. const end = -rect.height;
  1086. // progress 0 when rect.top == start (just entering)
  1087. // progress 1 when rect.top == end (just left)
  1088. const totalDistance = start - end;
  1089. const currentDistance = start - rect.top;
  1090. progress = currentDistance / totalDistance;
  1091. } else {
  1092. // Whole page scroll
  1093. progress = scrollY / (docH - winH);
  1094. }
  1095. } else if (container && (typeof Element !== 'undefined') && (container instanceof Element)) {
  1096. // Scroll container progress
  1097. const el = container;
  1098. const scrollTop = el.scrollTop;
  1099. const max = (el.scrollHeight - el.clientHeight) || 1;
  1100. if (options.target) {
  1101. const containerRect = el.getBoundingClientRect();
  1102. const rect = options.target.getBoundingClientRect();
  1103. const start = containerRect.height;
  1104. const end = -rect.height;
  1105. const totalDistance = start - end;
  1106. const currentDistance = start - (rect.top - containerRect.top);
  1107. progress = currentDistance / totalDistance;
  1108. } else {
  1109. progress = scrollTop / max;
  1110. }
  1111. }
  1112. // Clamp
  1113. progress = clamp01(progress);
  1114. if (hasSeek) {
  1115. controls.seek(progress);
  1116. return;
  1117. }
  1118. anims.forEach((anim) => {
  1119. if (anim.effect) {
  1120. const end = getEndTime(anim);
  1121. if (!end) return;
  1122. anim.currentTime = end * progress;
  1123. }
  1124. });
  1125. };
  1126. let rafId = 0;
  1127. const onScroll = () => {
  1128. if (rafId) return;
  1129. rafId = requestAnimationFrame(() => {
  1130. rafId = 0;
  1131. updateScroll();
  1132. });
  1133. };
  1134. const eventTarget = (container && container.addEventListener) ? container : window;
  1135. eventTarget.addEventListener('scroll', onScroll, { passive: true });
  1136. updateScroll(); // Initial
  1137. return () => {
  1138. if (rafId) cancelAnimationFrame(rafId);
  1139. eventTarget.removeEventListener('scroll', onScroll);
  1140. };
  1141. }
  1142. // --- Timeline ---
  1143. function timeline(defaults = {}) {
  1144. const steps = [];
  1145. const api = {
  1146. currentTime: 0,
  1147. add: (targets, params, offset) => {
  1148. const animParams = { ...defaults, ...params };
  1149. let start = api.currentTime;
  1150. if (offset !== undefined) {
  1151. if (isStr(offset) && offset.startsWith('-=')) start -= parseFloat(offset.slice(2));
  1152. else if (isStr(offset) && offset.startsWith('+=')) start += parseFloat(offset.slice(2));
  1153. else if (typeof offset === 'number') start = offset;
  1154. }
  1155. const dur = animParams.duration || 1000;
  1156. const step = { targets, animParams, start, _scheduled: false };
  1157. steps.push(step);
  1158. // Backward compatible: schedule immediately (existing docs rely on this)
  1159. if (start <= 0) {
  1160. animate(targets, animParams);
  1161. step._scheduled = true;
  1162. } else {
  1163. setTimeout(() => {
  1164. animate(targets, animParams);
  1165. }, start);
  1166. step._scheduled = true;
  1167. }
  1168. api.currentTime = Math.max(api.currentTime, start + dur);
  1169. return api;
  1170. },
  1171. // Optional: if you create a timeline and want to defer scheduling yourself
  1172. play: () => {
  1173. steps.forEach((s) => {
  1174. if (s._scheduled) return;
  1175. if (s.start <= 0) animate(s.targets, s.animParams);
  1176. else setTimeout(() => animate(s.targets, s.animParams), s.start);
  1177. s._scheduled = true;
  1178. });
  1179. return api;
  1180. }
  1181. };
  1182. return api;
  1183. }
  1184. // --- Export ---
  1185. // transform `$` to be the main export `animal`, with statics attached
  1186. const animal = $;
  1187. // Extend $ behavior to act as a global selector and property accessor
  1188. Object.assign(animal, {
  1189. animate,
  1190. timeline,
  1191. draw: svgDraw,
  1192. svgDraw,
  1193. inViewAnimate,
  1194. spring,
  1195. scroll,
  1196. $: animal // Self-reference for backward compatibility
  1197. });
  1198. // Expose Layer if available or allow lazy loading
  1199. Object.defineProperty(animal, 'Layer', {
  1200. get: () => {
  1201. return (typeof window !== 'undefined' && window.Layer) ? window.Layer :
  1202. (typeof globalThis !== 'undefined' && globalThis.Layer) ? globalThis.Layer :
  1203. (typeof Layer !== 'undefined' ? Layer : null);
  1204. }
  1205. });
  1206. // Shortcut for Layer.fire or new Layer()
  1207. // Allows $.fire({ title: 'Hi' }) or $.layer({ title: 'Hi' })
  1208. animal.fire = (options) => {
  1209. const L = animal.Layer;
  1210. if (L) return (L.fire ? L.fire(options) : new L(options).fire());
  1211. console.warn('Layer module not loaded.');
  1212. return Promise.reject('Layer module not loaded');
  1213. };
  1214. // 'layer' alias for static usage
  1215. animal.layer = animal.fire;
  1216. return animal;
  1217. })));