animal.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  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);
  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. // --- JS Interpolator (anime.js-ish, simplified) ---
  402. class JsAnimation {
  403. constructor(target, propValues, opts = {}, callbacks = {}) {
  404. this.target = target;
  405. this.propValues = propValues;
  406. this.duration = opts.duration ?? 1000;
  407. this.delay = opts.delay ?? 0;
  408. this.direction = opts.direction ?? 'normal';
  409. this.loop = opts.loop ?? 1;
  410. this.endDelay = opts.endDelay ?? 0;
  411. this.easing = opts.easing ?? 'linear';
  412. this.autoplay = opts.autoplay !== false;
  413. this.update = callbacks.update;
  414. this.begin = callbacks.begin;
  415. this.complete = callbacks.complete;
  416. this._resolve = null;
  417. this.finished = new Promise((res) => (this._resolve = res));
  418. this._started = false;
  419. this._running = false;
  420. this._paused = false;
  421. this._cancelled = false;
  422. this._startTime = 0;
  423. this._progress = 0;
  424. this._didBegin = false;
  425. this._ease = resolveJsEasing(this.easing, opts.springValues);
  426. this._tween = this._buildTween();
  427. this.tick = this.tick.bind(this);
  428. if (this.autoplay) this.play();
  429. }
  430. _readCurrentValue(k) {
  431. const t = this.target;
  432. // JS object
  433. if (!isEl(t) && !isSVG(t)) return t[k];
  434. // scroll
  435. if (k === 'scrollTop' || k === 'scrollLeft') return t[k];
  436. // CSS var
  437. if (isEl(t) && isCssVar(k)) {
  438. const cs = getComputedStyle(t);
  439. return (cs.getPropertyValue(k) || t.style.getPropertyValue(k) || '').trim();
  440. }
  441. // style
  442. if (isEl(t)) {
  443. const cs = getComputedStyle(t);
  444. // Prefer computed style (kebab) because many props aren't direct keys on cs
  445. const v = cs.getPropertyValue(toKebab(k));
  446. if (v && v.trim()) return v.trim();
  447. // Fallback to inline style access
  448. if (k in t.style) return t.style[k];
  449. }
  450. // SVG attribute
  451. if (isSVG(t)) {
  452. const attr = toKebab(k);
  453. if (t.hasAttribute(attr)) return t.getAttribute(attr);
  454. if (t.hasAttribute(k)) return t.getAttribute(k);
  455. }
  456. // Generic property
  457. return t[k];
  458. }
  459. _writeValue(k, v) {
  460. const t = this.target;
  461. // JS object
  462. if (!isEl(t) && !isSVG(t)) {
  463. t[k] = v;
  464. return;
  465. }
  466. // scroll
  467. if (k === 'scrollTop' || k === 'scrollLeft') {
  468. t[k] = v;
  469. return;
  470. }
  471. // CSS var
  472. if (isEl(t) && isCssVar(k)) {
  473. t.style.setProperty(k, v);
  474. return;
  475. }
  476. // style
  477. if (isEl(t) && (k in t.style)) {
  478. t.style[k] = v;
  479. return;
  480. }
  481. // SVG attribute
  482. if (isSVG(t)) {
  483. const attr = toKebab(k);
  484. t.setAttribute(attr, v);
  485. return;
  486. }
  487. // Generic property
  488. t[k] = v;
  489. }
  490. _buildTween() {
  491. const tween = {};
  492. Object.keys(this.propValues).forEach((k) => {
  493. const raw = this.propValues[k];
  494. const fromRaw = isArr(raw) ? raw[0] : this._readCurrentValue(k);
  495. const toRaw = isArr(raw) ? raw[1] : raw;
  496. const fromStr = isNil(fromRaw) ? '0' : ('' + fromRaw).trim();
  497. const toStr = isNil(toRaw) ? '0' : ('' + toRaw).trim();
  498. const fromNum = parseFloat(fromStr);
  499. const toNum = parseFloat(toStr);
  500. const fromNumOk = !Number.isNaN(fromNum);
  501. const toNumOk = !Number.isNaN(toNum);
  502. // numeric tween (with unit preservation)
  503. if (fromNumOk && toNumOk) {
  504. const unit = getUnit(toStr, k) ?? getUnit(fromStr, k) ?? '';
  505. tween[k] = { type: 'number', from: fromNum, to: toNum, unit };
  506. } else {
  507. // Non-numeric: fall back to "switch" (still useful for seek endpoints)
  508. tween[k] = { type: 'discrete', from: fromStr, to: toStr };
  509. }
  510. });
  511. return tween;
  512. }
  513. _apply(progress, time) {
  514. this._progress = clamp01(progress);
  515. Object.keys(this._tween).forEach((k) => {
  516. const t = this._tween[k];
  517. if (t.type === 'number') {
  518. const eased = this._ease ? this._ease(this._progress) : this._progress;
  519. const val = t.from + (t.to - t.from) * eased;
  520. if (!isEl(this.target) && !isSVG(this.target) && t.unit === '') {
  521. this._writeValue(k, val);
  522. } else {
  523. this._writeValue(k, (val + t.unit));
  524. }
  525. } else {
  526. const val = this._progress >= 1 ? t.to : t.from;
  527. this._writeValue(k, val);
  528. }
  529. });
  530. if (this.update) this.update({ target: this.target, progress: this._progress, time });
  531. }
  532. seek(progress) {
  533. // Seek does not auto-play; it's intended for scroll-linked or manual control.
  534. const t = (typeof performance !== 'undefined' ? performance.now() : 0);
  535. this._apply(progress, t);
  536. }
  537. play() {
  538. if (this._cancelled) return;
  539. if (!this._started) {
  540. this._started = true;
  541. this._startTime = performance.now() + this.delay - (this._progress * this.duration);
  542. // begin fired on first active tick to avoid firing during delay.
  543. }
  544. this._paused = false;
  545. if (!this._running) {
  546. this._running = true;
  547. rafEngine.add(this);
  548. }
  549. }
  550. pause() {
  551. this._paused = true;
  552. }
  553. cancel() {
  554. this._cancelled = true;
  555. this._running = false;
  556. rafEngine.remove(this);
  557. // Resolve to avoid hanging awaits
  558. if (this._resolve) this._resolve();
  559. }
  560. finish() {
  561. this.seek(1);
  562. this._running = false;
  563. rafEngine.remove(this);
  564. if (this.complete) this.complete(this.target);
  565. if (this._resolve) this._resolve();
  566. }
  567. tick(now) {
  568. if (this._cancelled) return false;
  569. if (this._paused) return true;
  570. if (!this._started) {
  571. this._started = true;
  572. this._startTime = now + this.delay;
  573. }
  574. if (now < this._startTime) return true;
  575. if (!this._didBegin) {
  576. this._didBegin = true;
  577. if (this.begin) this.begin(this.target);
  578. }
  579. const totalDur = this.duration + (this.endDelay || 0);
  580. const elapsed = now - this._startTime;
  581. const iter = totalDur > 0 ? Math.floor(elapsed / totalDur) : 0;
  582. const inIter = totalDur > 0 ? (elapsed - iter * totalDur) : elapsed;
  583. const iterations = this.loop === true ? Infinity : this.loop;
  584. if (iterations !== Infinity && iter >= iterations) {
  585. this._apply(this._mapDirection(1, iterations - 1));
  586. this._running = false;
  587. if (this.complete) this.complete(this.target);
  588. if (this._resolve) this._resolve();
  589. return false;
  590. }
  591. // if we're in endDelay portion, hold the end state
  592. let p = clamp01(inIter / this.duration);
  593. if (this.duration <= 0) p = 1;
  594. if (this.endDelay && inIter > this.duration) p = 1;
  595. this._apply(this._mapDirection(p, iter), now);
  596. // Keep running until loops exhausted
  597. return true;
  598. }
  599. _mapDirection(p, iterIndex) {
  600. const dir = this.direction;
  601. const flip = (dir === 'reverse') || (dir === 'alternate-reverse');
  602. const isAlt = (dir === 'alternate') || (dir === 'alternate-reverse');
  603. let t = flip ? (1 - p) : p;
  604. if (isAlt && (iterIndex % 2 === 1)) t = 1 - t;
  605. return t;
  606. }
  607. }
  608. // --- Controls (Motion One-ish, chainable / thenable) ---
  609. class Controls {
  610. constructor({ waapi = [], js = [], finished }) {
  611. this.animations = waapi; // backward compat with old `.animations` usage
  612. this.jsAnimations = js;
  613. this.finished = finished || Promise.resolve();
  614. }
  615. then(onFulfilled, onRejected) { return this.finished.then(onFulfilled, onRejected); }
  616. catch(onRejected) { return this.finished.catch(onRejected); }
  617. finally(onFinally) { return this.finished.finally(onFinally); }
  618. play() {
  619. if (this._onPlay) this._onPlay.forEach((fn) => fn && fn());
  620. if (this._ensureWaapiUpdate) this._ensureWaapiUpdate();
  621. this.animations.forEach((a) => a && a.play && a.play());
  622. this.jsAnimations.forEach((a) => a && a.play && a.play());
  623. return this;
  624. }
  625. pause() {
  626. this.animations.forEach((a) => a && a.pause && a.pause());
  627. this.jsAnimations.forEach((a) => a && a.pause && a.pause());
  628. return this;
  629. }
  630. cancel() {
  631. this.animations.forEach((a) => a && a.cancel && a.cancel());
  632. this.jsAnimations.forEach((a) => a && a.cancel && a.cancel());
  633. return this;
  634. }
  635. finish() {
  636. this.animations.forEach((a) => a && a.finish && a.finish());
  637. this.jsAnimations.forEach((a) => a && a.finish && a.finish());
  638. return this;
  639. }
  640. seek(progress) {
  641. const p = clamp01(progress);
  642. const t = (typeof performance !== 'undefined' ? performance.now() : 0);
  643. this.animations.forEach((anim) => {
  644. if (anim && anim.effect) {
  645. let timing = this._waapiTimingByAnim && this._waapiTimingByAnim.get(anim);
  646. if (!timing) {
  647. timing = readWaapiEffectTiming(anim.effect);
  648. if (this._waapiTimingByAnim) this._waapiTimingByAnim.set(anim, timing);
  649. }
  650. const dur = timing.duration || 0;
  651. if (!dur) return;
  652. anim.currentTime = dur * p;
  653. const target = this._waapiTargetByAnim && this._waapiTargetByAnim.get(anim);
  654. if (this._fireUpdate && target) this._fireUpdate({ target, progress: p, time: t });
  655. }
  656. });
  657. this.jsAnimations.forEach((a) => a && a.seek && a.seek(p));
  658. return this;
  659. }
  660. }
  661. // --- Main Animation Logic ---
  662. function animate(targets, params) {
  663. const elements = toArray(targets);
  664. const safeParams = params || {};
  665. const optionsNamespace = (safeParams.options && typeof safeParams.options === 'object') ? safeParams.options : {};
  666. // `params.options` provides a safe namespace for config keys without risking them being treated as animated props.
  667. // Top-level keys still win for backward compatibility.
  668. const merged = { ...optionsNamespace, ...safeParams };
  669. const {
  670. duration = 1000,
  671. delay = 0,
  672. easing = 'ease-out',
  673. direction = 'normal',
  674. fill = 'forwards',
  675. loop = 1,
  676. endDelay = 0,
  677. autoplay = true,
  678. springFrames = 120,
  679. update, // callback
  680. begin, // callback
  681. complete // callback
  682. } = merged;
  683. let isSpring = false;
  684. let springValuesRaw = null;
  685. let springValuesSampled = null;
  686. let springDurationMs = null;
  687. if (typeof easing === 'object' && !Array.isArray(easing)) {
  688. isSpring = true;
  689. springValuesRaw = getSpringValues(easing);
  690. const frames = (typeof springFrames === 'number' && springFrames > 1) ? Math.floor(springFrames) : 120;
  691. springValuesSampled = downsample(springValuesRaw, frames);
  692. springDurationMs = springValuesRaw.length * 1000 / 60;
  693. }
  694. // Callback aggregation (avoid double-calling when WAAPI+JS both run)
  695. const cbState = typeof WeakMap !== 'undefined' ? new WeakMap() : null;
  696. const getState = (t) => {
  697. if (!cbState) return { begun: false, completed: false, lastUpdateBucket: -1 };
  698. let s = cbState.get(t);
  699. if (!s) {
  700. s = { begun: false, completed: false, lastUpdateBucket: -1 };
  701. cbState.set(t, s);
  702. }
  703. return s;
  704. };
  705. const fireBegin = (t) => {
  706. if (!begin) return;
  707. const s = getState(t);
  708. if (s.begun) return;
  709. s.begun = true;
  710. begin(t);
  711. };
  712. const fireComplete = (t) => {
  713. if (!complete) return;
  714. const s = getState(t);
  715. if (s.completed) return;
  716. s.completed = true;
  717. complete(t);
  718. };
  719. const fireUpdate = (payload) => {
  720. if (!update) return;
  721. const t = payload && payload.target;
  722. const time = payload && payload.time;
  723. if (!t) return update(payload);
  724. const s = getState(t);
  725. const bucket = Math.floor(((typeof time === 'number' ? time : (typeof performance !== 'undefined' ? performance.now() : 0))) / 16);
  726. if (bucket === s.lastUpdateBucket) return;
  727. s.lastUpdateBucket = bucket;
  728. update(payload);
  729. };
  730. const propEntries = [];
  731. Object.keys(safeParams).forEach((key) => {
  732. if (key === 'options') return;
  733. if (isAnimOptionKey(key)) return;
  734. propEntries.push({ key, canonical: ALIASES[key] || key, val: safeParams[key] });
  735. });
  736. // Create animations but don't play if autoplay is false
  737. const waapiAnimations = [];
  738. const jsAnimations = [];
  739. const engineInfo = {
  740. isSpring,
  741. waapiKeys: [],
  742. jsKeys: []
  743. };
  744. const waapiKeySet = new Set();
  745. const jsKeySet = new Set();
  746. const onPlayHooks = [];
  747. const waapiUpdateItems = [];
  748. const waapiTargetByAnim = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
  749. const waapiTimingByAnim = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
  750. let waapiUpdateStarted = false;
  751. const ensureWaapiUpdate = () => {
  752. if (waapiUpdateStarted) return;
  753. waapiUpdateStarted = true;
  754. waapiUpdateItems.forEach((item) => waapiUpdateSampler.add(item));
  755. };
  756. const promises = elements.map((el) => {
  757. // Route props per target (fix mixed HTML/SVG/object target arrays).
  758. const waapiProps = {};
  759. const jsProps = {};
  760. propEntries.forEach(({ key, canonical, val }) => {
  761. const isTransform = TRANSFORMS.includes(canonical) || TRANSFORMS.includes(key);
  762. if (!el || (!isEl(el) && !isSVG(el))) {
  763. jsProps[key] = val;
  764. jsKeySet.add(key);
  765. return;
  766. }
  767. const isSvgTarget = isSVG(el);
  768. if (isSvgTarget) {
  769. if (isTransform || key === 'opacity' || key === 'filter') {
  770. waapiProps[canonical] = val;
  771. waapiKeySet.add(canonical);
  772. } else {
  773. jsProps[key] = val;
  774. jsKeySet.add(key);
  775. }
  776. return;
  777. }
  778. // HTML element
  779. if (isCssVar(key)) {
  780. jsProps[key] = val;
  781. jsKeySet.add(key);
  782. return;
  783. }
  784. const isCssLike = isTransform || key === 'opacity' || key === 'filter' || (isEl(el) && (key in el.style));
  785. if (isCssLike) {
  786. waapiProps[canonical] = val;
  787. waapiKeySet.add(canonical);
  788. } else {
  789. jsProps[key] = val;
  790. jsKeySet.add(key);
  791. }
  792. });
  793. // 1. WAAPI Animation
  794. let waapiAnim = null;
  795. let waapiPromise = Promise.resolve();
  796. if (Object.keys(waapiProps).length > 0) {
  797. const buildFrames = (propValues) => {
  798. // Spring: share sampled progress; per-target we only compute start/end once per prop.
  799. if (isSpring && springValuesSampled && springValuesSampled.length) {
  800. const cs = (isEl(el) && typeof getComputedStyle !== 'undefined') ? getComputedStyle(el) : null;
  801. const metas = Object.keys(propValues).map((k) => {
  802. const raw = propValues[k];
  803. const rawFrom = Array.isArray(raw) ? raw[0] : undefined;
  804. const rawTo = Array.isArray(raw) ? raw[1] : raw;
  805. const toNum = parseFloat(('' + rawTo).trim());
  806. const fromNumExplicit = Array.isArray(raw) ? parseFloat(('' + rawFrom).trim()) : NaN;
  807. const isT = TRANSFORMS.includes(ALIASES[k] || k) || TRANSFORMS.includes(k);
  808. const unit = getUnit(('' + rawTo), k) ?? getUnit(('' + rawFrom), k) ?? getDefaultUnit(k);
  809. let fromNum = 0;
  810. if (Number.isFinite(fromNumExplicit)) {
  811. fromNum = fromNumExplicit;
  812. } else if (k.startsWith('scale')) {
  813. fromNum = 1;
  814. } else if (k === 'opacity' && cs) {
  815. const n = parseFloat(cs.opacity);
  816. if (!Number.isNaN(n)) fromNum = n;
  817. } else if (!isT && cs) {
  818. const cssVal = cs.getPropertyValue(toKebab(k));
  819. const n = parseFloat(cssVal);
  820. if (!Number.isNaN(n)) fromNum = n;
  821. }
  822. const to = Number.isFinite(toNum) ? toNum : 0;
  823. return { k, isT, unit: unit ?? '', from: fromNum, to };
  824. });
  825. const frames = new Array(springValuesSampled.length);
  826. for (let i = 0; i < springValuesSampled.length; i++) {
  827. const v = springValuesSampled[i];
  828. const frame = {};
  829. let transformStr = '';
  830. for (let j = 0; j < metas.length; j++) {
  831. const m = metas[j];
  832. const current = m.from + (m.to - m.from) * v;
  833. const outVal = (m.unit === '' ? ('' + current) : (current + m.unit));
  834. if (m.isT) transformStr += `${m.k}(${outVal}) `;
  835. else frame[m.k] = outVal;
  836. }
  837. if (transformStr) frame.transform = transformStr.trim();
  838. frames[i] = frame;
  839. }
  840. if (frames[0] && Object.keys(frames[0]).length === 0) frames.shift();
  841. return frames;
  842. }
  843. // Non-spring: 2-keyframe path
  844. const frame0 = {};
  845. const frame1 = {};
  846. let transform0 = '';
  847. let transform1 = '';
  848. Object.keys(propValues).forEach((k) => {
  849. const val = propValues[k];
  850. const isT = TRANSFORMS.includes(ALIASES[k] || k) || TRANSFORMS.includes(k);
  851. if (Array.isArray(val)) {
  852. const from = isT ? normalizeTransformPartValue(k, val[0]) : val[0];
  853. const to = isT ? normalizeTransformPartValue(k, val[1]) : val[1];
  854. if (isT) {
  855. transform0 += `${k}(${from}) `;
  856. transform1 += `${k}(${to}) `;
  857. } else {
  858. frame0[k] = from;
  859. frame1[k] = to;
  860. }
  861. } else {
  862. if (isT) transform1 += `${k}(${normalizeTransformPartValue(k, val)}) `;
  863. else frame1[k] = val;
  864. }
  865. });
  866. if (transform0) frame0.transform = transform0.trim();
  867. if (transform1) frame1.transform = transform1.trim();
  868. const out = [frame0, frame1];
  869. if (Object.keys(out[0]).length === 0) out.shift();
  870. return out;
  871. };
  872. const finalFrames = buildFrames(waapiProps);
  873. const opts = {
  874. duration: isSpring ? springDurationMs : duration,
  875. delay,
  876. fill,
  877. iterations: loop,
  878. easing: isSpring ? 'linear' : easing,
  879. direction,
  880. endDelay
  881. };
  882. const animation = el.animate(finalFrames, opts);
  883. if (!autoplay) animation.pause();
  884. waapiAnim = animation;
  885. waapiPromise = animation.finished;
  886. waapiAnimations.push(waapiAnim);
  887. if (waapiTargetByAnim) waapiTargetByAnim.set(waapiAnim, el);
  888. if (waapiTimingByAnim) waapiTimingByAnim.set(waapiAnim, readWaapiEffectTiming(waapiAnim.effect));
  889. if (begin) {
  890. // Fire begin when play starts (and also for autoplay on next frame)
  891. onPlayHooks.push(() => fireBegin(el));
  892. if (autoplay && typeof requestAnimationFrame !== 'undefined') requestAnimationFrame(() => fireBegin(el));
  893. }
  894. if (complete) {
  895. waapiAnim.addEventListener?.('finish', () => fireComplete(el));
  896. }
  897. if (update) {
  898. const timing = (waapiTimingByAnim && waapiTimingByAnim.get(waapiAnim)) || readWaapiEffectTiming(waapiAnim.effect);
  899. const item = { anim: waapiAnim, target: el, update: fireUpdate, _lastP: null, _dur: timing.duration || 0 };
  900. waapiUpdateItems.push(item);
  901. // Ensure removal on finish/cancel
  902. waapiAnim.addEventListener?.('finish', () => waapiUpdateSampler.remove(item));
  903. waapiAnim.addEventListener?.('cancel', () => waapiUpdateSampler.remove(item));
  904. // Start sampler only when needed (autoplay or explicit play)
  905. if (autoplay) ensureWaapiUpdate();
  906. }
  907. }
  908. // 2. JS Animation (Fallback / Attributes)
  909. let jsPromise = Promise.resolve();
  910. if (Object.keys(jsProps).length > 0) {
  911. const jsAnim = new JsAnimation(
  912. el,
  913. jsProps,
  914. { duration, delay, easing, autoplay, direction, loop, endDelay, springValues: isSpring ? springValuesRaw : null },
  915. { update: fireUpdate, begin: fireBegin, complete: fireComplete }
  916. );
  917. jsAnimations.push(jsAnim);
  918. jsPromise = jsAnim.finished;
  919. }
  920. return Promise.all([waapiPromise, jsPromise]);
  921. });
  922. const finished = Promise.all(promises);
  923. const controls = new Controls({ waapi: waapiAnimations, js: jsAnimations, finished });
  924. controls.engine = engineInfo;
  925. controls._onPlay = onPlayHooks;
  926. controls._fireUpdate = fireUpdate;
  927. controls._waapiTargetByAnim = waapiTargetByAnim;
  928. controls._waapiTimingByAnim = waapiTimingByAnim;
  929. controls._ensureWaapiUpdate = update ? ensureWaapiUpdate : null;
  930. if (!autoplay) controls.pause();
  931. engineInfo.waapiKeys = Array.from(waapiKeySet);
  932. engineInfo.jsKeys = Array.from(jsKeySet);
  933. return controls;
  934. }
  935. // --- SVG Draw ---
  936. function svgDraw(targets, params = {}) {
  937. const elements = toArray(targets);
  938. elements.forEach(el => {
  939. if (!isSVG(el)) return;
  940. const len = el.getTotalLength ? el.getTotalLength() : 0;
  941. el.style.strokeDasharray = len;
  942. el.style.strokeDashoffset = len;
  943. animate(el, {
  944. strokeDashoffset: [len, 0],
  945. ...params
  946. });
  947. });
  948. }
  949. // --- In View ---
  950. function inViewAnimate(targets, params, options = {}) {
  951. const elements = toArray(targets);
  952. const observer = new IntersectionObserver((entries) => {
  953. entries.forEach(entry => {
  954. if (entry.isIntersecting) {
  955. animate(entry.target, params);
  956. if (options.once !== false) observer.unobserve(entry.target);
  957. }
  958. });
  959. }, { threshold: options.threshold || 0.1 });
  960. elements.forEach(el => observer.observe(el));
  961. // Return cleanup so callers can disconnect observers in long-lived pages (esp. once:false).
  962. return () => {
  963. try {
  964. elements.forEach((el) => observer.unobserve(el));
  965. observer.disconnect();
  966. } catch (e) {
  967. // ignore
  968. }
  969. };
  970. }
  971. // --- Scroll Linked ---
  972. function scroll(animationPromise, options = {}) {
  973. // options: container (default window), range [start, end] (default viewport logic)
  974. const container = options.container || window;
  975. const target = options.target || document.body; // Element to track for progress
  976. // If passing an animation promise, we control its WAAPI animations
  977. const controls = animationPromise;
  978. // Back-compat: old return value was a Promise with `.animations`
  979. const hasSeek = controls && isFunc(controls.seek);
  980. const anims = (controls && controls.animations) || (animationPromise && animationPromise.animations) || [];
  981. const jsAnims = (controls && controls.jsAnimations) || [];
  982. if (!hasSeek && !anims.length && !jsAnims.length) return;
  983. // Cache WAAPI timing per animation to avoid repeated getComputedTiming() during scroll.
  984. const timingCache = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
  985. const getEndTime = (anim) => {
  986. if (!anim || !anim.effect) return 0;
  987. if (timingCache) {
  988. const cached = timingCache.get(anim);
  989. if (cached) return cached;
  990. }
  991. const timing = readWaapiEffectTiming(anim.effect);
  992. const end = timing.duration || 0;
  993. if (timingCache && end) timingCache.set(anim, end);
  994. return end;
  995. };
  996. const updateScroll = () => {
  997. let progress = 0;
  998. if (container === window) {
  999. const scrollY = window.scrollY;
  1000. const winH = window.innerHeight;
  1001. const docH = document.body.scrollHeight;
  1002. // Simple progress: how far down the page (0 to 1)
  1003. // Or element based?
  1004. // Motion One defaults to element entering view.
  1005. if (options.target) {
  1006. const rect = options.target.getBoundingClientRect();
  1007. const start = winH;
  1008. const end = -rect.height;
  1009. // progress 0 when rect.top == start (just entering)
  1010. // progress 1 when rect.top == end (just left)
  1011. const totalDistance = start - end;
  1012. const currentDistance = start - rect.top;
  1013. progress = currentDistance / totalDistance;
  1014. } else {
  1015. // Whole page scroll
  1016. progress = scrollY / (docH - winH);
  1017. }
  1018. } else if (container && (typeof Element !== 'undefined') && (container instanceof Element)) {
  1019. // Scroll container progress
  1020. const el = container;
  1021. const scrollTop = el.scrollTop;
  1022. const max = (el.scrollHeight - el.clientHeight) || 1;
  1023. if (options.target) {
  1024. const containerRect = el.getBoundingClientRect();
  1025. const rect = options.target.getBoundingClientRect();
  1026. const start = containerRect.height;
  1027. const end = -rect.height;
  1028. const totalDistance = start - end;
  1029. const currentDistance = start - (rect.top - containerRect.top);
  1030. progress = currentDistance / totalDistance;
  1031. } else {
  1032. progress = scrollTop / max;
  1033. }
  1034. }
  1035. // Clamp
  1036. progress = clamp01(progress);
  1037. if (hasSeek) {
  1038. controls.seek(progress);
  1039. return;
  1040. }
  1041. anims.forEach((anim) => {
  1042. if (anim.effect) {
  1043. const end = getEndTime(anim);
  1044. if (!end) return;
  1045. anim.currentTime = end * progress;
  1046. }
  1047. });
  1048. };
  1049. let rafId = 0;
  1050. const onScroll = () => {
  1051. if (rafId) return;
  1052. rafId = requestAnimationFrame(() => {
  1053. rafId = 0;
  1054. updateScroll();
  1055. });
  1056. };
  1057. const eventTarget = (container && container.addEventListener) ? container : window;
  1058. eventTarget.addEventListener('scroll', onScroll, { passive: true });
  1059. updateScroll(); // Initial
  1060. return () => {
  1061. if (rafId) cancelAnimationFrame(rafId);
  1062. eventTarget.removeEventListener('scroll', onScroll);
  1063. };
  1064. }
  1065. // --- Timeline ---
  1066. function timeline(defaults = {}) {
  1067. const steps = [];
  1068. const api = {
  1069. currentTime: 0,
  1070. add: (targets, params, offset) => {
  1071. const animParams = { ...defaults, ...params };
  1072. let start = api.currentTime;
  1073. if (offset !== undefined) {
  1074. if (isStr(offset) && offset.startsWith('-=')) start -= parseFloat(offset.slice(2));
  1075. else if (isStr(offset) && offset.startsWith('+=')) start += parseFloat(offset.slice(2));
  1076. else if (typeof offset === 'number') start = offset;
  1077. }
  1078. const dur = animParams.duration || 1000;
  1079. const step = { targets, animParams, start, _scheduled: false };
  1080. steps.push(step);
  1081. // Backward compatible: schedule immediately (existing docs rely on this)
  1082. if (start <= 0) {
  1083. animate(targets, animParams);
  1084. step._scheduled = true;
  1085. } else {
  1086. setTimeout(() => {
  1087. animate(targets, animParams);
  1088. }, start);
  1089. step._scheduled = true;
  1090. }
  1091. api.currentTime = Math.max(api.currentTime, start + dur);
  1092. return api;
  1093. },
  1094. // Optional: if you create a timeline and want to defer scheduling yourself
  1095. play: () => {
  1096. steps.forEach((s) => {
  1097. if (s._scheduled) return;
  1098. if (s.start <= 0) animate(s.targets, s.animParams);
  1099. else setTimeout(() => animate(s.targets, s.animParams), s.start);
  1100. s._scheduled = true;
  1101. });
  1102. return api;
  1103. }
  1104. };
  1105. return api;
  1106. }
  1107. // --- Export ---
  1108. // transform `$` to be the main export `animal`, with statics attached
  1109. const animal = $;
  1110. // Extend $ behavior to act as a global selector and property accessor
  1111. Object.assign(animal, {
  1112. animate,
  1113. timeline,
  1114. draw: svgDraw,
  1115. svgDraw,
  1116. inViewAnimate,
  1117. spring,
  1118. scroll,
  1119. $: animal // Self-reference for backward compatibility
  1120. });
  1121. // Expose Layer if available or allow lazy loading
  1122. Object.defineProperty(animal, 'Layer', {
  1123. get: () => {
  1124. return (typeof window !== 'undefined' && window.Layer) ? window.Layer :
  1125. (typeof globalThis !== 'undefined' && globalThis.Layer) ? globalThis.Layer :
  1126. (typeof Layer !== 'undefined' ? Layer : null);
  1127. }
  1128. });
  1129. // Shortcut for Layer.fire or new Layer()
  1130. // Allows $.fire({ title: 'Hi' }) or $.layer({ title: 'Hi' })
  1131. animal.fire = (options) => {
  1132. const L = animal.Layer;
  1133. if (L) return (L.fire ? L.fire(options) : new L(options).fire());
  1134. console.warn('Layer module not loaded.');
  1135. return Promise.reject('Layer module not loaded');
  1136. };
  1137. // 'layer' alias for static usage
  1138. animal.layer = animal.fire;
  1139. return animal;
  1140. })));