animal.js 53 KB

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