xjs.js 58 KB

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