xjs.js 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  1. // xjs.js - combined single-file build (animal + layer)
  2. // Generated by `go run main.go build`.
  3. // NOTE: Do not edit this file directly in development.
  4. // Edit animal.js / layer.js instead.
  5. /* --- layer.js --- */
  6. (function (global, factory) {
  7. const LayerClass = factory();
  8. // Allow usage as `Layer({...})` or `new Layer()`
  9. // But Layer is a class. We can wrap it in a proxy or factory function.
  10. function LayerFactory(options) {
  11. if (options && typeof options === 'object') {
  12. return LayerClass.$(options);
  13. }
  14. return new LayerClass();
  15. }
  16. // Copy static methods (including non-enumerable class statics like `fire` / `$`)
  17. // Class static methods are non-enumerable by default, so Object.assign() would miss them.
  18. const copyStatic = (to, from) => {
  19. try {
  20. Object.getOwnPropertyNames(from).forEach((k) => {
  21. if (k === 'prototype' || k === 'name' || k === 'length') return;
  22. const desc = Object.getOwnPropertyDescriptor(from, k);
  23. if (!desc) return;
  24. Object.defineProperty(to, k, desc);
  25. });
  26. } catch (e) {
  27. // Best-effort fallback
  28. try { Object.assign(to, from); } catch {}
  29. }
  30. };
  31. copyStatic(LayerFactory, LayerClass);
  32. // Also copy prototype for instanceof checks if needed (though tricky with factory)
  33. LayerFactory.prototype = LayerClass.prototype;
  34. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = LayerFactory :
  35. typeof define === 'function' && define.amd ? define(() => LayerFactory) :
  36. (global.Layer = LayerFactory);
  37. }(this, (function () {
  38. 'use strict';
  39. const PREFIX = 'layer-';
  40. // Theme & Styles
  41. const css = `
  42. .${PREFIX}overlay {
  43. position: fixed;
  44. top: 0;
  45. left: 0;
  46. width: 100%;
  47. height: 100%;
  48. background: rgba(0, 0, 0, 0.4);
  49. display: flex;
  50. justify-content: center;
  51. align-items: center;
  52. z-index: 1000;
  53. opacity: 0;
  54. transition: opacity 0.3s;
  55. }
  56. .${PREFIX}overlay.show {
  57. opacity: 1;
  58. }
  59. .${PREFIX}popup {
  60. background: #fff;
  61. border-radius: 8px;
  62. box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  63. width: 32em;
  64. max-width: 90%;
  65. padding: 1.5em;
  66. display: flex;
  67. flex-direction: column;
  68. align-items: center;
  69. position: relative;
  70. z-index: 1;
  71. transform: scale(0.92);
  72. transition: transform 0.26s ease;
  73. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  74. }
  75. .${PREFIX}overlay.show .${PREFIX}popup {
  76. transform: scale(1);
  77. }
  78. .${PREFIX}title {
  79. font-size: 1.8em;
  80. font-weight: 600;
  81. color: #333;
  82. margin: 0 0 0.5em;
  83. text-align: center;
  84. }
  85. .${PREFIX}content {
  86. font-size: 1.125em;
  87. color: #545454;
  88. margin-bottom: 1.5em;
  89. text-align: center;
  90. line-height: 1.5;
  91. }
  92. .${PREFIX}actions {
  93. display: flex;
  94. justify-content: center;
  95. gap: 1em;
  96. width: 100%;
  97. }
  98. .${PREFIX}button {
  99. border: none;
  100. border-radius: 4px;
  101. padding: 0.6em 1.2em;
  102. font-size: 1em;
  103. cursor: pointer;
  104. transition: background-color 0.2s, box-shadow 0.2s;
  105. color: #fff;
  106. }
  107. .${PREFIX}confirm {
  108. background-color: #3085d6;
  109. }
  110. .${PREFIX}confirm:hover {
  111. background-color: #2b77c0;
  112. }
  113. .${PREFIX}cancel {
  114. background-color: #aaa;
  115. }
  116. .${PREFIX}cancel:hover {
  117. background-color: #999;
  118. }
  119. .${PREFIX}icon {
  120. position: relative;
  121. box-sizing: content-box;
  122. width: 5em;
  123. height: 5em;
  124. margin: 2.5em auto 0.6em;
  125. border: 0.25em solid rgba(0, 0, 0, 0);
  126. border-radius: 50%;
  127. font-family: inherit;
  128. line-height: 5em;
  129. cursor: default;
  130. user-select: none;
  131. }
  132. /* SVG mark content (kept), sits above the ring */
  133. .${PREFIX}icon svg {
  134. width: 100%;
  135. height: 100%;
  136. display: block;
  137. overflow: visible;
  138. position: relative;
  139. z-index: 3;
  140. }
  141. .${PREFIX}svg-ring,
  142. .${PREFIX}svg-mark {
  143. fill: none;
  144. stroke-linecap: round;
  145. stroke-linejoin: round;
  146. }
  147. .${PREFIX}svg-ring {
  148. stroke-width: 4.5;
  149. opacity: 0.95;
  150. }
  151. .${PREFIX}svg-mark {
  152. stroke-width: 6;
  153. }
  154. .${PREFIX}svg-dot {
  155. transform-box: fill-box;
  156. transform-origin: center;
  157. }
  158. /* =========================================
  159. "success-like" ring (shared by all icons)
  160. - we reuse the success ring pieces/rotation for every icon type
  161. - color is driven by currentColor
  162. ========================================= */
  163. .${PREFIX}icon.success { border-color: #a5dc86; color: #a5dc86; }
  164. .${PREFIX}icon.error { border-color: #f27474; color: #f27474; }
  165. .${PREFIX}icon.warning { border-color: #f8bb86; color: #f8bb86; }
  166. .${PREFIX}icon.info { border-color: #3fc3ee; color: #3fc3ee; }
  167. .${PREFIX}icon.question { border-color: #b18cff; color: #b18cff; }
  168. .${PREFIX}icon .${PREFIX}success-ring {
  169. position: absolute;
  170. z-index: 2;
  171. top: -0.25em;
  172. left: -0.25em;
  173. box-sizing: content-box;
  174. width: 100%;
  175. height: 100%;
  176. border: 0.25em solid currentColor;
  177. opacity: 0.3;
  178. border-radius: 50%;
  179. }
  180. .${PREFIX}icon .${PREFIX}success-fix {
  181. position: absolute;
  182. z-index: 1;
  183. top: 0.5em;
  184. left: 1.625em;
  185. width: 0.4375em;
  186. height: 5.625em;
  187. transform: rotate(-45deg);
  188. background-color: #fff; /* adjusted at runtime to popup bg */
  189. }
  190. .${PREFIX}icon .${PREFIX}success-circular-line-left,
  191. .${PREFIX}icon .${PREFIX}success-circular-line-right {
  192. position: absolute;
  193. width: 3.75em;
  194. height: 7.5em;
  195. border-radius: 50%;
  196. background-color: #fff; /* adjusted at runtime to popup bg */
  197. }
  198. .${PREFIX}icon .${PREFIX}success-circular-line-left {
  199. top: -0.4375em;
  200. left: -2.0635em;
  201. transform: rotate(-45deg);
  202. transform-origin: 3.75em 3.75em;
  203. border-radius: 7.5em 0 0 7.5em;
  204. }
  205. .${PREFIX}icon .${PREFIX}success-circular-line-right {
  206. top: -0.6875em;
  207. left: 1.875em;
  208. transform: rotate(-45deg);
  209. transform-origin: 0 3.75em;
  210. border-radius: 0 7.5em 7.5em 0;
  211. }
  212. .${PREFIX}icon .${PREFIX}success-line-tip,
  213. .${PREFIX}icon .${PREFIX}success-line-long {
  214. display: block;
  215. position: absolute;
  216. z-index: 2;
  217. height: 0.3125em;
  218. border-radius: 0.125em;
  219. background-color: currentColor;
  220. }
  221. .${PREFIX}icon .${PREFIX}success-line-tip {
  222. top: 2.875em;
  223. left: 0.8125em;
  224. width: 1.5625em;
  225. transform: rotate(45deg);
  226. }
  227. .${PREFIX}icon .${PREFIX}success-line-long {
  228. top: 2.375em;
  229. right: 0.5em;
  230. width: 2.9375em;
  231. transform: rotate(-45deg);
  232. }
  233. /* Triggered when icon has .${PREFIX}icon-show */
  234. .${PREFIX}icon.${PREFIX}icon-show .${PREFIX}success-line-tip {
  235. animation: ${PREFIX}animate-success-line-tip 0.75s;
  236. }
  237. .${PREFIX}icon.${PREFIX}icon-show .${PREFIX}success-line-long {
  238. animation: ${PREFIX}animate-success-line-long 0.75s;
  239. }
  240. .${PREFIX}icon.${PREFIX}icon-show .${PREFIX}success-circular-line-right {
  241. animation: ${PREFIX}rotate-success-circular-line 4.25s ease-in;
  242. }
  243. /* Warning needs a shorter arc (45deg) */
  244. .${PREFIX}icon.warning.${PREFIX}icon-show .${PREFIX}success-circular-line-right {
  245. animation: ${PREFIX}rotate-warning-circular-line 4.25s ease-in;
  246. }
  247. @keyframes ${PREFIX}animate-success-line-tip {
  248. 0% {
  249. top: 1.1875em;
  250. left: 0.0625em;
  251. width: 0;
  252. }
  253. 54% {
  254. top: 1.0625em;
  255. left: 0.125em;
  256. width: 0;
  257. }
  258. 70% {
  259. top: 2.1875em;
  260. left: -0.375em;
  261. width: 3.125em;
  262. }
  263. 84% {
  264. top: 3em;
  265. left: 1.3125em;
  266. width: 1.0625em;
  267. }
  268. 100% {
  269. top: 2.8125em;
  270. left: 0.8125em;
  271. width: 1.5625em;
  272. }
  273. }
  274. @keyframes ${PREFIX}animate-success-line-long {
  275. 0% {
  276. top: 3.375em;
  277. right: 2.875em;
  278. width: 0;
  279. }
  280. 65% {
  281. top: 3.375em;
  282. right: 2.875em;
  283. width: 0;
  284. }
  285. 84% {
  286. top: 2.1875em;
  287. right: 0;
  288. width: 3.4375em;
  289. }
  290. 100% {
  291. top: 2.375em;
  292. right: 0.5em;
  293. width: 2.9375em;
  294. }
  295. }
  296. @keyframes ${PREFIX}rotate-success-circular-line {
  297. 0% { transform: rotate(-45deg); }
  298. 5% { transform: rotate(-45deg); }
  299. 12% { transform: rotate(-405deg); }
  300. 100% { transform: rotate(-405deg); }
  301. }
  302. @keyframes ${PREFIX}rotate-warning-circular-line {
  303. 0% { transform: rotate(-45deg); }
  304. 5% { transform: rotate(-45deg); }
  305. 12% { transform: rotate(-180deg); }
  306. 100% { transform: rotate(-180deg); } /* match 12% so it "sweeps then stops" like success */
  307. }
  308. /* (Other icon shapes stay SVG-driven; only the ring animation is unified above) */
  309. `;
  310. // Inject Styles
  311. const injectStyles = () => {
  312. if (document.getElementById(`${PREFIX}styles`)) return;
  313. const styleSheet = document.createElement('style');
  314. styleSheet.id = `${PREFIX}styles`;
  315. styleSheet.textContent = css;
  316. document.head.appendChild(styleSheet);
  317. };
  318. class Layer {
  319. constructor() {
  320. injectStyles();
  321. this.params = {};
  322. this.dom = {};
  323. this.promise = null;
  324. this.resolve = null;
  325. this.reject = null;
  326. this._onKeydown = null;
  327. }
  328. // Constructor helper when called as function: const popup = Layer({...})
  329. static get isProxy() { return true; }
  330. // Static entry point
  331. static fire(options) {
  332. const instance = new Layer();
  333. return instance._fire(options);
  334. }
  335. // Chainable entry point (builder-style)
  336. // Example:
  337. // Layer.$({ title: 'Hi' }).fire().then(...)
  338. // Layer.$().config({ title: 'Hi' }).fire()
  339. static $(options) {
  340. const instance = new Layer();
  341. if (options !== undefined) instance.config(options);
  342. return instance;
  343. }
  344. // Chainable config helper (does not render until `.fire()` is called)
  345. config(options = {}) {
  346. // Support the same shorthand as Layer.fire(title, text, icon)
  347. if (typeof options === 'string') {
  348. options = { title: options };
  349. if (arguments[1]) options.text = arguments[1];
  350. if (arguments[2]) options.icon = arguments[2];
  351. }
  352. this.params = { ...(this.params || {}), ...options };
  353. return this;
  354. }
  355. // Instance entry point (chainable)
  356. fire(options) {
  357. const merged = (options === undefined) ? (this.params || {}) : options;
  358. return this._fire(merged);
  359. }
  360. _fire(options = {}) {
  361. if (typeof options === 'string') {
  362. options = { title: options };
  363. if (arguments[1]) options.text = arguments[1];
  364. if (arguments[2]) options.icon = arguments[2];
  365. }
  366. this.params = {
  367. title: '',
  368. text: '',
  369. icon: null,
  370. iconSize: null, // e.g. '6em' / '72px'
  371. confirmButtonText: 'OK',
  372. cancelButtonText: 'Cancel',
  373. showCancelButton: false,
  374. confirmButtonColor: '#3085d6',
  375. cancelButtonColor: '#aaa',
  376. closeOnClickOutside: true,
  377. closeOnEsc: true,
  378. iconAnimation: true,
  379. popupAnimation: true,
  380. ...options
  381. };
  382. this.promise = new Promise((resolve, reject) => {
  383. this.resolve = resolve;
  384. this.reject = reject;
  385. });
  386. this._render();
  387. return this.promise;
  388. }
  389. static _getXjs() {
  390. // Prefer xjs, fallback to animal (compat)
  391. const g = (typeof window !== 'undefined') ? window : (typeof globalThis !== 'undefined' ? globalThis : null);
  392. if (!g) return null;
  393. const x = g.xjs || g.animal;
  394. return (typeof x === 'function') ? x : null;
  395. }
  396. _render() {
  397. // Remove existing if any
  398. const existing = document.querySelector(`.${PREFIX}overlay`);
  399. if (existing) existing.remove();
  400. // Create Overlay
  401. this.dom.overlay = document.createElement('div');
  402. this.dom.overlay.className = `${PREFIX}overlay`;
  403. // Create Popup
  404. this.dom.popup = document.createElement('div');
  405. this.dom.popup.className = `${PREFIX}popup`;
  406. this.dom.overlay.appendChild(this.dom.popup);
  407. // Icon
  408. if (this.params.icon) {
  409. this.dom.icon = this._createIcon(this.params.icon);
  410. this.dom.popup.appendChild(this.dom.icon);
  411. }
  412. // Title
  413. if (this.params.title) {
  414. this.dom.title = document.createElement('h2');
  415. this.dom.title.className = `${PREFIX}title`;
  416. this.dom.title.textContent = this.params.title;
  417. this.dom.popup.appendChild(this.dom.title);
  418. }
  419. // Content (Text / HTML / Element)
  420. if (this.params.text || this.params.html || this.params.content) {
  421. this.dom.content = document.createElement('div');
  422. this.dom.content.className = `${PREFIX}content`;
  423. if (this.params.content) {
  424. // DOM Element or Selector
  425. let el = this.params.content;
  426. if (typeof el === 'string') el = document.querySelector(el);
  427. if (el instanceof Element) this.dom.content.appendChild(el);
  428. } else if (this.params.html) {
  429. this.dom.content.innerHTML = this.params.html;
  430. } else {
  431. this.dom.content.textContent = this.params.text;
  432. }
  433. this.dom.popup.appendChild(this.dom.content);
  434. }
  435. // Actions
  436. this.dom.actions = document.createElement('div');
  437. this.dom.actions.className = `${PREFIX}actions`;
  438. // Cancel Button
  439. if (this.params.showCancelButton) {
  440. this.dom.cancelBtn = document.createElement('button');
  441. this.dom.cancelBtn.className = `${PREFIX}button ${PREFIX}cancel`;
  442. this.dom.cancelBtn.textContent = this.params.cancelButtonText;
  443. this.dom.cancelBtn.style.backgroundColor = this.params.cancelButtonColor;
  444. this.dom.cancelBtn.onclick = () => this._close(false);
  445. this.dom.actions.appendChild(this.dom.cancelBtn);
  446. }
  447. // Confirm Button
  448. this.dom.confirmBtn = document.createElement('button');
  449. this.dom.confirmBtn.className = `${PREFIX}button ${PREFIX}confirm`;
  450. this.dom.confirmBtn.textContent = this.params.confirmButtonText;
  451. this.dom.confirmBtn.style.backgroundColor = this.params.confirmButtonColor;
  452. this.dom.confirmBtn.onclick = () => this._close(true);
  453. this.dom.actions.appendChild(this.dom.confirmBtn);
  454. this.dom.popup.appendChild(this.dom.actions);
  455. // Event Listeners
  456. if (this.params.closeOnClickOutside) {
  457. this.dom.overlay.addEventListener('click', (e) => {
  458. if (e.target === this.dom.overlay) {
  459. this._close(null); // Dismiss
  460. }
  461. });
  462. }
  463. document.body.appendChild(this.dom.overlay);
  464. // Animation
  465. requestAnimationFrame(() => {
  466. this.dom.overlay.classList.add('show');
  467. this._didOpen();
  468. });
  469. }
  470. _createIcon(type) {
  471. const icon = document.createElement('div');
  472. icon.className = `${PREFIX}icon ${type}`;
  473. const applyIconSize = (mode) => {
  474. if (!(this.params && this.params.iconSize)) return;
  475. try {
  476. const raw = this.params.iconSize;
  477. const s = String(raw).trim();
  478. if (!s) return;
  479. // For SweetAlert2-style success icon, scale via font-size so all `em`-based
  480. // parts remain proportional.
  481. if (mode === 'font') {
  482. const m = s.match(/^(-?\d*\.?\d+)\s*(px|em|rem)$/i);
  483. if (m) {
  484. const n = parseFloat(m[1]);
  485. const unit = m[2];
  486. if (Number.isFinite(n) && n > 0) {
  487. icon.style.fontSize = (n / 5) + unit; // icon is 5em wide/tall
  488. return;
  489. }
  490. }
  491. }
  492. // Fallback: directly size the box (works great for SVG icons)
  493. icon.style.width = s;
  494. icon.style.height = s;
  495. } catch {}
  496. };
  497. const svgNs = 'http://www.w3.org/2000/svg';
  498. if (type === 'success') {
  499. // SweetAlert2-compatible DOM structure (circle + tick) for exact style parity
  500. // <div class="...success-circular-line-left"></div>
  501. // <span class="...success-line-tip"></span>
  502. // <span class="...success-line-long"></span>
  503. // <div class="...success-ring"></div>
  504. // <div class="...success-fix"></div>
  505. // <div class="...success-circular-line-right"></div>
  506. const left = document.createElement('div');
  507. left.className = `${PREFIX}success-circular-line-left`;
  508. const tip = document.createElement('span');
  509. tip.className = `${PREFIX}success-line-tip`;
  510. const long = document.createElement('span');
  511. long.className = `${PREFIX}success-line-long`;
  512. const ring = document.createElement('div');
  513. ring.className = `${PREFIX}success-ring`;
  514. const fix = document.createElement('div');
  515. fix.className = `${PREFIX}success-fix`;
  516. const right = document.createElement('div');
  517. right.className = `${PREFIX}success-circular-line-right`;
  518. icon.appendChild(left);
  519. icon.appendChild(tip);
  520. icon.appendChild(long);
  521. icon.appendChild(ring);
  522. icon.appendChild(fix);
  523. icon.appendChild(right);
  524. applyIconSize('font');
  525. return icon;
  526. }
  527. if (type === 'error' || type === 'warning' || type === 'info' || type === 'question') {
  528. // Use the same "success-like" ring parts for every icon
  529. const left = document.createElement('div');
  530. left.className = `${PREFIX}success-circular-line-left`;
  531. const ring = document.createElement('div');
  532. ring.className = `${PREFIX}success-ring`;
  533. const fix = document.createElement('div');
  534. fix.className = `${PREFIX}success-fix`;
  535. const right = document.createElement('div');
  536. right.className = `${PREFIX}success-circular-line-right`;
  537. icon.appendChild(left);
  538. icon.appendChild(ring);
  539. icon.appendChild(fix);
  540. icon.appendChild(right);
  541. applyIconSize('font');
  542. // SVG only draws the inner symbol (no SVG ring)
  543. const svg = document.createElementNS(svgNs, 'svg');
  544. svg.setAttribute('viewBox', '0 0 80 80');
  545. svg.setAttribute('aria-hidden', 'true');
  546. svg.setAttribute('focusable', 'false');
  547. const addPath = (d, extraClass) => {
  548. const p = document.createElementNS(svgNs, 'path');
  549. p.setAttribute('d', d);
  550. p.setAttribute('class', `${PREFIX}svg-mark ${PREFIX}svg-draw${extraClass ? ' ' + extraClass : ''}`);
  551. p.setAttribute('stroke', 'currentColor');
  552. svg.appendChild(p);
  553. return p;
  554. };
  555. if (type === 'error') {
  556. addPath('M28 28 L52 52', `${PREFIX}svg-error-left`);
  557. addPath('M52 28 L28 52', `${PREFIX}svg-error-right`);
  558. } else if (type === 'warning') {
  559. addPath('M40 20 L40 46', `${PREFIX}svg-warning-line`);
  560. const dot = document.createElementNS(svgNs, 'circle');
  561. dot.setAttribute('class', `${PREFIX}svg-dot`);
  562. dot.setAttribute('cx', '40');
  563. dot.setAttribute('cy', '58');
  564. dot.setAttribute('r', '3.2');
  565. dot.setAttribute('fill', 'currentColor');
  566. svg.appendChild(dot);
  567. } else if (type === 'info') {
  568. addPath('M40 34 L40 56', `${PREFIX}svg-info-line`);
  569. const dot = document.createElementNS(svgNs, 'circle');
  570. dot.setAttribute('class', `${PREFIX}svg-dot`);
  571. dot.setAttribute('cx', '40');
  572. dot.setAttribute('cy', '25');
  573. dot.setAttribute('r', '3.2');
  574. dot.setAttribute('fill', 'currentColor');
  575. svg.appendChild(dot);
  576. } else if (type === 'question') {
  577. addPath('M30 30 C30 23 35 19 42 19 C49 19 54 23 54 30 C54 36 50 39 46 41 C43 42 42 44 42 48 L42 52', `${PREFIX}svg-question`);
  578. const dot = document.createElementNS(svgNs, 'circle');
  579. dot.setAttribute('class', `${PREFIX}svg-dot`);
  580. dot.setAttribute('cx', '42');
  581. dot.setAttribute('cy', '61');
  582. dot.setAttribute('r', '3.2');
  583. dot.setAttribute('fill', 'currentColor');
  584. svg.appendChild(dot);
  585. }
  586. icon.appendChild(svg);
  587. return icon;
  588. }
  589. // Default to SVG icons for other/custom types
  590. applyIconSize('box');
  591. const svg = document.createElementNS(svgNs, 'svg');
  592. svg.setAttribute('viewBox', '0 0 80 80');
  593. svg.setAttribute('aria-hidden', 'true');
  594. svg.setAttribute('focusable', 'false');
  595. const ring = document.createElementNS(svgNs, 'circle');
  596. ring.setAttribute('class', `${PREFIX}svg-ring ${PREFIX}svg-draw`);
  597. ring.setAttribute('cx', '40');
  598. ring.setAttribute('cy', '40');
  599. ring.setAttribute('r', '34');
  600. ring.setAttribute('stroke', 'currentColor');
  601. svg.appendChild(ring);
  602. const addPath = (d, extraClass) => {
  603. const p = document.createElementNS(svgNs, 'path');
  604. p.setAttribute('d', d);
  605. p.setAttribute('class', `${PREFIX}svg-mark ${PREFIX}svg-draw${extraClass ? ' ' + extraClass : ''}`);
  606. p.setAttribute('stroke', 'currentColor');
  607. svg.appendChild(p);
  608. return p;
  609. };
  610. if (type === 'error') {
  611. addPath('M28 28 L52 52', `${PREFIX}svg-error-left`);
  612. addPath('M52 28 L28 52', `${PREFIX}svg-error-right`);
  613. } else if (type === 'warning') {
  614. addPath('M40 20 L40 46', `${PREFIX}svg-warning-line`);
  615. const dot = document.createElementNS(svgNs, 'circle');
  616. dot.setAttribute('class', `${PREFIX}svg-dot`);
  617. dot.setAttribute('cx', '40');
  618. dot.setAttribute('cy', '58');
  619. dot.setAttribute('r', '3.2');
  620. dot.setAttribute('fill', 'currentColor');
  621. svg.appendChild(dot);
  622. } else if (type === 'info') {
  623. addPath('M40 34 L40 56', `${PREFIX}svg-info-line`);
  624. const dot = document.createElementNS(svgNs, 'circle');
  625. dot.setAttribute('class', `${PREFIX}svg-dot`);
  626. dot.setAttribute('cx', '40');
  627. dot.setAttribute('cy', '25');
  628. dot.setAttribute('r', '3.2');
  629. dot.setAttribute('fill', 'currentColor');
  630. svg.appendChild(dot);
  631. } else if (type === 'question') {
  632. // Question mark (single stroke + dot)
  633. addPath('M30 30 C30 23 35 19 42 19 C49 19 54 23 54 30 C54 36 50 39 46 41 C43 42 42 44 42 48 L42 52', `${PREFIX}svg-question`);
  634. const dot = document.createElementNS(svgNs, 'circle');
  635. dot.setAttribute('class', `${PREFIX}svg-dot`);
  636. dot.setAttribute('cx', '42');
  637. dot.setAttribute('cy', '61');
  638. dot.setAttribute('r', '3.2');
  639. dot.setAttribute('fill', 'currentColor');
  640. svg.appendChild(dot);
  641. } else {
  642. // Fallback: ring only
  643. }
  644. icon.appendChild(svg);
  645. return icon;
  646. }
  647. _adjustRingBackgroundColor() {
  648. try {
  649. const icon = this.dom && this.dom.icon;
  650. const popup = this.dom && this.dom.popup;
  651. if (!icon || !popup) return;
  652. const bg = getComputedStyle(popup).backgroundColor;
  653. const parts = icon.querySelectorAll(`.${PREFIX}success-circular-line-left, .${PREFIX}success-circular-line-right, .${PREFIX}success-fix`);
  654. parts.forEach((el) => {
  655. try { el.style.backgroundColor = bg; } catch {}
  656. });
  657. } catch {}
  658. }
  659. _didOpen() {
  660. // Keyboard close (ESC)
  661. if (this.params.closeOnEsc) {
  662. this._onKeydown = (e) => {
  663. if (!e) return;
  664. if (e.key === 'Escape') this._close(null);
  665. };
  666. document.addEventListener('keydown', this._onKeydown);
  667. }
  668. // Keep the "success-like" ring perfectly blended with popup bg
  669. this._adjustRingBackgroundColor();
  670. // Popup animation (optional)
  671. if (this.params.popupAnimation) {
  672. const X = Layer._getXjs();
  673. if (X && this.dom.popup) {
  674. // Override the CSS scale transition with a spring-ish entrance.
  675. try {
  676. this.dom.popup.style.transition = 'none';
  677. this.dom.popup.style.transform = 'scale(0.92)';
  678. X(this.dom.popup).animate({
  679. scale: [0.92, 1],
  680. y: [-6, 0],
  681. duration: 520,
  682. easing: { stiffness: 260, damping: 16 }
  683. });
  684. } catch {}
  685. }
  686. }
  687. // Icon SVG draw animation
  688. if (this.params.iconAnimation) {
  689. this._animateIcon();
  690. }
  691. // User hook (SweetAlert-ish naming)
  692. try {
  693. if (typeof this.params.didOpen === 'function') this.params.didOpen(this.dom.popup);
  694. } catch {}
  695. }
  696. _animateIcon() {
  697. const icon = this.dom.icon;
  698. if (!icon) return;
  699. const type = (this.params && this.params.icon) || '';
  700. const ringTypes = new Set(['success', 'error', 'warning', 'info', 'question']);
  701. // Ring animation (same as success) for all built-in icons
  702. if (ringTypes.has(type)) this._adjustRingBackgroundColor();
  703. try { icon.classList.remove(`${PREFIX}icon-show`); } catch {}
  704. requestAnimationFrame(() => {
  705. try { icon.classList.add(`${PREFIX}icon-show`); } catch {}
  706. });
  707. // Success tick is CSS-driven; others still draw their SVG mark after the ring starts.
  708. if (type === 'success') return;
  709. const X = Layer._getXjs();
  710. if (!X) return;
  711. const svg = icon.querySelector('svg');
  712. if (!svg) return;
  713. const marks = Array.from(svg.querySelectorAll(`.${PREFIX}svg-mark`));
  714. const dot = svg.querySelector(`.${PREFIX}svg-dot`);
  715. // If this is a built-in icon, we unify the "ring first, then mark" order.
  716. const baseDelay = ringTypes.has(type) ? 180 : 0;
  717. if (type === 'error') {
  718. const left = marks[0];
  719. const right = marks[1];
  720. try { if (left) X(left).draw({ duration: 320, easing: 'ease-out', delay: baseDelay }); } catch {}
  721. try { if (right) X(right).draw({ duration: 320, easing: 'ease-out', delay: baseDelay + 70 }); } catch {}
  722. } else {
  723. // warning / info / question (single stroke) or custom SVG symbols
  724. marks.forEach((m, i) => {
  725. try { X(m).draw({ duration: 420, easing: 'ease-out', delay: baseDelay + i * 60 }); } catch {}
  726. });
  727. }
  728. if (dot) {
  729. try {
  730. dot.style.opacity = '0';
  731. // Keep dot pop after the ring begins
  732. const d = baseDelay + 140;
  733. if (type === 'info') {
  734. X(dot).animate({ opacity: [0, 1], y: [-8, 0], scale: [0.2, 1], duration: 420, delay: d, easing: { stiffness: 300, damping: 14 } });
  735. } else {
  736. X(dot).animate({ opacity: [0, 1], scale: [0.2, 1], duration: 320, delay: d, easing: { stiffness: 320, damping: 18 } });
  737. }
  738. } catch {}
  739. }
  740. }
  741. _close(isConfirmed) {
  742. this.dom.overlay.classList.remove('show');
  743. setTimeout(() => {
  744. if (this.dom.overlay && this.dom.overlay.parentNode) {
  745. this.dom.overlay.parentNode.removeChild(this.dom.overlay);
  746. }
  747. }, 300);
  748. if (this._onKeydown) {
  749. try { document.removeEventListener('keydown', this._onKeydown); } catch {}
  750. this._onKeydown = null;
  751. }
  752. try {
  753. if (typeof this.params.willClose === 'function') this.params.willClose(this.dom.popup);
  754. } catch {}
  755. try {
  756. if (typeof this.params.didClose === 'function') this.params.didClose();
  757. } catch {}
  758. if (isConfirmed === true) {
  759. this.resolve({ isConfirmed: true, isDenied: false, isDismissed: false });
  760. } else if (isConfirmed === false) {
  761. this.resolve({ isConfirmed: false, isDenied: false, isDismissed: true, dismiss: 'cancel' });
  762. } else {
  763. this.resolve({ isConfirmed: false, isDenied: false, isDismissed: true, dismiss: 'backdrop' });
  764. }
  765. }
  766. }
  767. return Layer;
  768. })));
  769. /* --- animal.js --- */
  770. (function (global, factory) {
  771. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  772. typeof define === 'function' && define.amd ? define(factory) :
  773. (global.animal = factory());
  774. }(this, (function () {
  775. 'use strict';
  776. // --- Utils ---
  777. const isArr = (a) => Array.isArray(a);
  778. const isStr = (s) => typeof s === 'string';
  779. const isFunc = (f) => typeof f === 'function';
  780. const isNil = (v) => v === undefined || v === null;
  781. const isSVG = (el) => (typeof SVGElement !== 'undefined' && el instanceof SVGElement) || ((typeof Element !== 'undefined') && (el instanceof Element) && el.namespaceURI === 'http://www.w3.org/2000/svg');
  782. const isEl = (v) => (typeof Element !== 'undefined') && (v instanceof Element);
  783. const clamp01 = (n) => Math.max(0, Math.min(1, n));
  784. const toKebab = (s) => s.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
  785. const toArray = (targets) => {
  786. if (isArr(targets)) return targets;
  787. if (isStr(targets)) {
  788. if (typeof document === 'undefined') return [];
  789. return Array.from(document.querySelectorAll(targets));
  790. }
  791. if ((typeof NodeList !== 'undefined') && (targets instanceof NodeList)) return Array.from(targets);
  792. if ((typeof Element !== 'undefined') && (targets instanceof Element)) return [targets];
  793. if ((typeof Window !== 'undefined') && (targets instanceof Window)) return [targets];
  794. // Plain objects (for anime.js-style object tweening)
  795. if (!isNil(targets) && (typeof targets === 'object' || isFunc(targets))) return [targets];
  796. return [];
  797. };
  798. // Selection helper (chainable, still Array-compatible)
  799. const _layerHandlerByEl = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
  800. class Selection extends Array {
  801. animate(params) { return animate(this, params); }
  802. draw(params = {}) { return svgDraw(this, params); }
  803. inViewAnimate(params, options = {}) { return inViewAnimate(this, params, options); }
  804. // Layer.js plugin-style helper:
  805. // const $ = animal.$;
  806. // $('.btn').layer({ title: 'Hi' });
  807. // Clicking the element will open Layer.
  808. layer(options) {
  809. const LayerCtor =
  810. (typeof window !== 'undefined' && window.Layer) ? window.Layer :
  811. (typeof globalThis !== 'undefined' && globalThis.Layer) ? globalThis.Layer :
  812. (typeof Layer !== 'undefined' ? Layer : null);
  813. if (!LayerCtor) return this;
  814. this.forEach((el) => {
  815. if (!isEl(el)) return;
  816. // De-dupe / replace previous binding
  817. if (_layerHandlerByEl) {
  818. const prev = _layerHandlerByEl.get(el);
  819. if (prev) el.removeEventListener('click', prev);
  820. }
  821. const handler = () => {
  822. let opts = options;
  823. if (isFunc(options)) {
  824. opts = options(el);
  825. } else if (isNil(options)) {
  826. opts = null;
  827. }
  828. // If no explicit options, allow data-* configuration
  829. if (!opts || (typeof opts === 'object' && Object.keys(opts).length === 0)) {
  830. const d = el.dataset || {};
  831. opts = {
  832. title: d.layerTitle || el.getAttribute('data-layer-title') || (el.textContent || '').trim(),
  833. text: d.layerText || el.getAttribute('data-layer-text') || '',
  834. icon: d.layerIcon || el.getAttribute('data-layer-icon') || null,
  835. showCancelButton: (d.layerCancel === 'true') || (el.getAttribute('data-layer-cancel') === 'true')
  836. };
  837. }
  838. // Prefer builder API if present, fallback to static fire.
  839. if (LayerCtor.$ && isFunc(LayerCtor.$)) return LayerCtor.$(opts).fire();
  840. if (LayerCtor.fire && isFunc(LayerCtor.fire)) return LayerCtor.fire(opts);
  841. };
  842. if (_layerHandlerByEl) _layerHandlerByEl.set(el, handler);
  843. el.addEventListener('click', handler);
  844. });
  845. return this;
  846. }
  847. // Remove click bindings added by `.layer()`
  848. unlayer() {
  849. this.forEach((el) => {
  850. if (!isEl(el)) return;
  851. if (!_layerHandlerByEl) return;
  852. const prev = _layerHandlerByEl.get(el);
  853. if (prev) el.removeEventListener('click', prev);
  854. _layerHandlerByEl.delete(el);
  855. });
  856. return this;
  857. }
  858. }
  859. const $ = (targets) => Selection.from(toArray(targets));
  860. const UNITLESS_KEYS = ['opacity', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'zIndex', 'fontWeight', 'strokeDashoffset', 'strokeDasharray', 'strokeWidth'];
  861. const getUnit = (val, prop) => {
  862. if (UNITLESS_KEYS.includes(prop)) return '';
  863. 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);
  864. return split ? split[1] : undefined;
  865. };
  866. const isCssVar = (k) => isStr(k) && k.startsWith('--');
  867. // Keep this intentionally broad so "unknown" config keys don't accidentally become animated props.
  868. // Prefer putting non-anim-prop config under `params.options`.
  869. const isAnimOptionKey = (k) => [
  870. 'options',
  871. 'duration', 'delay', 'easing', 'direction', 'fill', 'loop', 'endDelay', 'autoplay',
  872. 'update', 'begin', 'complete',
  873. // WAAPI-ish common keys (ignored unless we explicitly support them)
  874. 'iterations', 'iterationStart', 'iterationComposite', 'composite', 'playbackRate',
  875. // Spring helpers
  876. 'springFrames'
  877. ].includes(k);
  878. const isEasingFn = (e) => typeof e === 'function';
  879. // Minimal cubic-bezier implementation (for JS engine easing)
  880. function cubicBezier(x1, y1, x2, y2) {
  881. // Inspired by https://github.com/gre/bezier-easing (simplified)
  882. const NEWTON_ITERATIONS = 4;
  883. const NEWTON_MIN_SLOPE = 0.001;
  884. const SUBDIVISION_PRECISION = 0.0000001;
  885. const SUBDIVISION_MAX_ITERATIONS = 10;
  886. const kSplineTableSize = 11;
  887. const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
  888. const float32ArraySupported = typeof Float32Array === 'function';
  889. function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; }
  890. function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; }
  891. function C(aA1) { return 3.0 * aA1; }
  892. function calcBezier(aT, aA1, aA2) {
  893. return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
  894. }
  895. function getSlope(aT, aA1, aA2) {
  896. return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
  897. }
  898. function binarySubdivide(aX, aA, aB) {
  899. let currentX, currentT, i = 0;
  900. do {
  901. currentT = aA + (aB - aA) / 2.0;
  902. currentX = calcBezier(currentT, x1, x2) - aX;
  903. if (currentX > 0.0) aB = currentT;
  904. else aA = currentT;
  905. } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
  906. return currentT;
  907. }
  908. function newtonRaphsonIterate(aX, aGuessT) {
  909. for (let i = 0; i < NEWTON_ITERATIONS; ++i) {
  910. const currentSlope = getSlope(aGuessT, x1, x2);
  911. if (currentSlope === 0.0) return aGuessT;
  912. const currentX = calcBezier(aGuessT, x1, x2) - aX;
  913. aGuessT -= currentX / currentSlope;
  914. }
  915. return aGuessT;
  916. }
  917. const sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
  918. for (let i = 0; i < kSplineTableSize; ++i) {
  919. sampleValues[i] = calcBezier(i * kSampleStepSize, x1, x2);
  920. }
  921. function getTForX(aX) {
  922. let intervalStart = 0.0;
  923. let currentSample = 1;
  924. const lastSample = kSplineTableSize - 1;
  925. for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
  926. intervalStart += kSampleStepSize;
  927. }
  928. --currentSample;
  929. const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
  930. const guessForT = intervalStart + dist * kSampleStepSize;
  931. const initialSlope = getSlope(guessForT, x1, x2);
  932. if (initialSlope >= NEWTON_MIN_SLOPE) return newtonRaphsonIterate(aX, guessForT);
  933. if (initialSlope === 0.0) return guessForT;
  934. return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);
  935. }
  936. return (x) => {
  937. if (x === 0 || x === 1) return x;
  938. return calcBezier(getTForX(x), y1, y2);
  939. };
  940. }
  941. function resolveJsEasing(easing, springValues) {
  942. if (isEasingFn(easing)) return easing;
  943. if (typeof easing === 'object' && easing && !Array.isArray(easing)) {
  944. // Spring: map linear progress -> simulated spring curve (0..1)
  945. const values = springValues || getSpringValues(easing);
  946. const last = Math.max(0, values.length - 1);
  947. return (t) => {
  948. const p = clamp01(t);
  949. const idx = p * last;
  950. const i0 = Math.floor(idx);
  951. const i1 = Math.min(last, i0 + 1);
  952. const frac = idx - i0;
  953. const v0 = values[i0] ?? p;
  954. const v1 = values[i1] ?? p;
  955. return v0 + (v1 - v0) * frac;
  956. };
  957. }
  958. if (Array.isArray(easing) && easing.length === 4) {
  959. return cubicBezier(easing[0], easing[1], easing[2], easing[3]);
  960. }
  961. // Common named easings
  962. switch (easing) {
  963. case 'linear': return (t) => t;
  964. case 'ease': return cubicBezier(0.25, 0.1, 0.25, 1);
  965. case 'ease-in': return cubicBezier(0.42, 0, 1, 1);
  966. case 'ease-out': return cubicBezier(0, 0, 0.58, 1);
  967. case 'ease-in-out': return cubicBezier(0.42, 0, 0.58, 1);
  968. default: return (t) => t;
  969. }
  970. }
  971. // --- Spring Physics (Simplified) ---
  972. // Returns an array of [time, value] or just value for WAAPI linear easing
  973. function spring({ stiffness = 100, damping = 10, mass = 1, velocity = 0, precision = 0.01 } = {}) {
  974. const values = [];
  975. let t = 0;
  976. const timeStep = 1 / 60; // 60fps simulation
  977. let current = 0;
  978. let v = velocity;
  979. const target = 1;
  980. let running = true;
  981. while (running && t < 10) { // Safety break at 10s
  982. const fSpring = -stiffness * (current - target);
  983. const fDamper = -damping * v;
  984. const a = (fSpring + fDamper) / mass;
  985. v += a * timeStep;
  986. current += v * timeStep;
  987. values.push(current);
  988. t += timeStep;
  989. if (Math.abs(current - target) < precision && Math.abs(v) < precision) {
  990. running = false;
  991. }
  992. }
  993. if (values[values.length - 1] !== 1) values.push(1);
  994. return values;
  995. }
  996. // Cache spring curves by config (perf: avoid recomputing for many targets)
  997. // LRU-ish capped cache to avoid unbounded growth in long-lived apps.
  998. const SPRING_CACHE_MAX = 50;
  999. const springCache = new Map();
  1000. function springCacheGet(key) {
  1001. const v = springCache.get(key);
  1002. if (!v) return v;
  1003. // refresh LRU
  1004. springCache.delete(key);
  1005. springCache.set(key, v);
  1006. return v;
  1007. }
  1008. function springCacheSet(key, values) {
  1009. if (springCache.has(key)) springCache.delete(key);
  1010. springCache.set(key, values);
  1011. if (springCache.size > SPRING_CACHE_MAX) {
  1012. const firstKey = springCache.keys().next().value;
  1013. if (firstKey !== undefined) springCache.delete(firstKey);
  1014. }
  1015. }
  1016. function getSpringValues(config = {}) {
  1017. const {
  1018. stiffness = 100,
  1019. damping = 10,
  1020. mass = 1,
  1021. velocity = 0,
  1022. precision = 0.01
  1023. } = config || {};
  1024. const key = `${stiffness}|${damping}|${mass}|${velocity}|${precision}`;
  1025. const cached = springCacheGet(key);
  1026. if (cached) return cached;
  1027. const values = spring({ stiffness, damping, mass, velocity, precision });
  1028. springCacheSet(key, values);
  1029. return values;
  1030. }
  1031. function downsample(values, maxFrames = 120) {
  1032. if (!values || values.length <= maxFrames) return values || [];
  1033. const out = [];
  1034. const lastIndex = values.length - 1;
  1035. const step = lastIndex / (maxFrames - 1);
  1036. for (let i = 0; i < maxFrames; i++) {
  1037. const idx = i * step;
  1038. const i0 = Math.floor(idx);
  1039. const i1 = Math.min(lastIndex, i0 + 1);
  1040. const frac = idx - i0;
  1041. const v0 = values[i0];
  1042. const v1 = values[i1];
  1043. out.push(v0 + (v1 - v0) * frac);
  1044. }
  1045. if (out[out.length - 1] !== 1) out[out.length - 1] = 1;
  1046. return out;
  1047. }
  1048. // --- WAAPI Core ---
  1049. const TRANSFORMS = ['translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'perspective', 'x', 'y'];
  1050. const ALIASES = {
  1051. x: 'translateX',
  1052. y: 'translateY',
  1053. z: 'translateZ'
  1054. };
  1055. // Basic rAF loop for non-WAAPI props or fallback
  1056. class RafEngine {
  1057. constructor() {
  1058. this.animations = [];
  1059. this.tick = this.tick.bind(this);
  1060. this.running = false;
  1061. }
  1062. add(anim) {
  1063. this.animations.push(anim);
  1064. if (!this.running) {
  1065. this.running = true;
  1066. requestAnimationFrame(this.tick);
  1067. }
  1068. }
  1069. remove(anim) {
  1070. this.animations = this.animations.filter(a => a !== anim);
  1071. }
  1072. tick(t) {
  1073. const now = t;
  1074. this.animations = this.animations.filter(anim => {
  1075. return anim.tick(now); // return true to keep
  1076. });
  1077. if (this.animations.length) {
  1078. requestAnimationFrame(this.tick);
  1079. } else {
  1080. this.running = false;
  1081. }
  1082. }
  1083. }
  1084. const rafEngine = new RafEngine();
  1085. // --- WAAPI update sampler (only used when update callback is provided) ---
  1086. class WaapiUpdateSampler {
  1087. constructor() {
  1088. this.items = new Set();
  1089. this._running = false;
  1090. this._tick = this._tick.bind(this);
  1091. }
  1092. add(item) {
  1093. this.items.add(item);
  1094. if (!this._running) {
  1095. this._running = true;
  1096. requestAnimationFrame(this._tick);
  1097. }
  1098. }
  1099. remove(item) {
  1100. this.items.delete(item);
  1101. }
  1102. _tick(t) {
  1103. if (!this.items.size) {
  1104. this._running = false;
  1105. return;
  1106. }
  1107. let anyActive = false;
  1108. let anyChanged = false;
  1109. this.items.forEach((item) => {
  1110. const { anim, target, update } = item;
  1111. if (!anim || !anim.effect) return;
  1112. let dur = item._dur || 0;
  1113. if (!dur) {
  1114. const timing = readWaapiEffectTiming(anim.effect);
  1115. dur = timing.duration || 0;
  1116. item._dur = dur;
  1117. }
  1118. if (!dur) return;
  1119. const p = clamp01((anim.currentTime || 0) / dur);
  1120. if (anim.playState === 'running') anyActive = true;
  1121. if (item._lastP !== p) {
  1122. anyChanged = true;
  1123. item._lastP = p;
  1124. update({ target, progress: p, time: t });
  1125. }
  1126. if (anim.playState === 'finished' || anim.playState === 'idle') {
  1127. this.items.delete(item);
  1128. }
  1129. });
  1130. if (this.items.size && (anyActive || anyChanged)) {
  1131. requestAnimationFrame(this._tick);
  1132. } else {
  1133. this._running = false;
  1134. }
  1135. }
  1136. }
  1137. const waapiUpdateSampler = new WaapiUpdateSampler();
  1138. function readWaapiEffectTiming(effect) {
  1139. // We compute this once per animation and cache it to avoid per-frame getComputedTiming().
  1140. // We primarily cache `duration` to preserve existing behavior (progress maps to one iteration).
  1141. let duration = 0;
  1142. let endTime = 0;
  1143. if (!effect) return { duration, endTime };
  1144. try {
  1145. const ct = effect.getComputedTiming ? effect.getComputedTiming() : null;
  1146. if (ct) {
  1147. if (typeof ct.duration === 'number' && Number.isFinite(ct.duration)) duration = ct.duration;
  1148. if (typeof ct.endTime === 'number' && Number.isFinite(ct.endTime)) endTime = ct.endTime;
  1149. }
  1150. } catch (e) {
  1151. // ignore
  1152. }
  1153. if (!endTime) endTime = duration || 0;
  1154. return { duration, endTime };
  1155. }
  1156. function getDefaultUnit(prop) {
  1157. if (!prop) return '';
  1158. if (UNITLESS_KEYS.includes(prop)) return '';
  1159. if (prop.startsWith('scale')) return '';
  1160. if (prop === 'opacity') return '';
  1161. if (prop.startsWith('rotate') || prop.startsWith('skew')) return 'deg';
  1162. return 'px';
  1163. }
  1164. function normalizeTransformPartValue(prop, v) {
  1165. if (typeof v !== 'number') return v;
  1166. if (prop && prop.startsWith('scale')) return '' + v;
  1167. if (prop && (prop.startsWith('rotate') || prop.startsWith('skew'))) return v + 'deg';
  1168. return v + 'px';
  1169. }
  1170. // String number template: interpolate numeric tokens inside a string.
  1171. // Useful for SVG path `d`, `points`, and other attributes that contain many numbers.
  1172. const _PURE_NUMBER_RE = /^[+-]?(?:\d*\.)?\d+(?:[eE][+-]?\d+)?(?:%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/;
  1173. function isPureNumberLike(str) {
  1174. return _PURE_NUMBER_RE.test(String(str || '').trim());
  1175. }
  1176. function countDecimals(numStr) {
  1177. const s = String(numStr || '');
  1178. const dot = s.indexOf('.');
  1179. if (dot < 0) return 0;
  1180. // Strip exponent part for decimal count
  1181. const e = s.search(/[eE]/);
  1182. const end = e >= 0 ? e : s.length;
  1183. const frac = s.slice(dot + 1, end);
  1184. // Ignore trailing zeros for display
  1185. const trimmed = frac.replace(/0+$/, '');
  1186. return Math.min(6, trimmed.length);
  1187. }
  1188. function parseNumberTemplate(str) {
  1189. const s = String(str ?? '');
  1190. const nums = [];
  1191. const parts = [];
  1192. let last = 0;
  1193. const re = /[+-]?(?:\d*\.)?\d+(?:[eE][+-]?\d+)?/g;
  1194. let m;
  1195. while ((m = re.exec(s))) {
  1196. const start = m.index;
  1197. const end = start + m[0].length;
  1198. parts.push(s.slice(last, start));
  1199. nums.push(parseFloat(m[0]));
  1200. last = end;
  1201. }
  1202. parts.push(s.slice(last));
  1203. return { nums, parts };
  1204. }
  1205. function extractNumberStrings(str) {
  1206. // Use a fresh regex to avoid any `lastIndex` surprises.
  1207. return String(str ?? '').match(/[+-]?(?:\d*\.)?\d+(?:[eE][+-]?\d+)?/g) || [];
  1208. }
  1209. function formatInterpolatedNumber(n, decimals) {
  1210. let v = n;
  1211. if (!Number.isFinite(v)) v = 0;
  1212. if (Math.abs(v) < 1e-12) v = 0;
  1213. if (!decimals) return String(Math.round(v));
  1214. // Use fixed, then strip trailing zeros/dot to keep strings compact.
  1215. return v.toFixed(decimals).replace(/\.?0+$/, '');
  1216. }
  1217. // --- JS Interpolator (anime.js-ish, simplified) ---
  1218. class JsAnimation {
  1219. constructor(target, propValues, opts = {}, callbacks = {}) {
  1220. this.target = target;
  1221. this.propValues = propValues;
  1222. this.duration = opts.duration ?? 1000;
  1223. this.delay = opts.delay ?? 0;
  1224. this.direction = opts.direction ?? 'normal';
  1225. this.loop = opts.loop ?? 1;
  1226. this.endDelay = opts.endDelay ?? 0;
  1227. this.easing = opts.easing ?? 'linear';
  1228. this.autoplay = opts.autoplay !== false;
  1229. this.update = callbacks.update;
  1230. this.begin = callbacks.begin;
  1231. this.complete = callbacks.complete;
  1232. this._resolve = null;
  1233. this.finished = new Promise((res) => (this._resolve = res));
  1234. this._started = false;
  1235. this._running = false;
  1236. this._paused = false;
  1237. this._cancelled = false;
  1238. this._startTime = 0;
  1239. this._progress = 0;
  1240. this._didBegin = false;
  1241. this._ease = resolveJsEasing(this.easing, opts.springValues);
  1242. this._tween = this._buildTween();
  1243. this.tick = this.tick.bind(this);
  1244. if (this.autoplay) this.play();
  1245. }
  1246. _readCurrentValue(k) {
  1247. const t = this.target;
  1248. // JS object
  1249. if (!isEl(t) && !isSVG(t)) return t[k];
  1250. // scroll
  1251. if (k === 'scrollTop' || k === 'scrollLeft') return t[k];
  1252. // CSS var
  1253. if (isEl(t) && isCssVar(k)) {
  1254. const cs = getComputedStyle(t);
  1255. return (cs.getPropertyValue(k) || t.style.getPropertyValue(k) || '').trim();
  1256. }
  1257. // style
  1258. if (isEl(t)) {
  1259. const cs = getComputedStyle(t);
  1260. // Prefer computed style (kebab) because many props aren't direct keys on cs
  1261. const v = cs.getPropertyValue(toKebab(k));
  1262. if (v && v.trim()) return v.trim();
  1263. // Fallback to inline style access
  1264. if (k in t.style) return t.style[k];
  1265. }
  1266. // SVG
  1267. // For many SVG presentation attributes (e.g. strokeDashoffset), style overrides attribute.
  1268. // Prefer computed style / inline style when available, and fallback to attributes.
  1269. if (isSVG(t)) {
  1270. // Geometry attrs must remain attrs (not style)
  1271. if (k === 'd' || k === 'points') {
  1272. const attr = toKebab(k);
  1273. if (t.hasAttribute(attr)) return t.getAttribute(attr);
  1274. if (t.hasAttribute(k)) return t.getAttribute(k);
  1275. return t.getAttribute(k);
  1276. }
  1277. try {
  1278. const cs = getComputedStyle(t);
  1279. const v = cs.getPropertyValue(toKebab(k));
  1280. if (v && v.trim()) return v.trim();
  1281. } catch (_) {}
  1282. try {
  1283. if (k in t.style) return t.style[k];
  1284. } catch (_) {}
  1285. const attr = toKebab(k);
  1286. if (t.hasAttribute(attr)) return t.getAttribute(attr);
  1287. if (t.hasAttribute(k)) return t.getAttribute(k);
  1288. }
  1289. // Generic property
  1290. return t[k];
  1291. }
  1292. _writeValue(k, v) {
  1293. const t = this.target;
  1294. // JS object
  1295. if (!isEl(t) && !isSVG(t)) {
  1296. t[k] = v;
  1297. return;
  1298. }
  1299. // scroll
  1300. if (k === 'scrollTop' || k === 'scrollLeft') {
  1301. t[k] = v;
  1302. return;
  1303. }
  1304. // CSS var
  1305. if (isEl(t) && isCssVar(k)) {
  1306. t.style.setProperty(k, v);
  1307. return;
  1308. }
  1309. // style
  1310. if (isEl(t) && (k in t.style)) {
  1311. t.style[k] = v;
  1312. return;
  1313. }
  1314. // SVG
  1315. // Prefer style for presentation attrs so it can animate when svgDraw initialized styles.
  1316. if (isSVG(t)) {
  1317. if (k === 'd' || k === 'points') {
  1318. t.setAttribute(k, v);
  1319. return;
  1320. }
  1321. try {
  1322. if (k in t.style) {
  1323. t.style[k] = v;
  1324. return;
  1325. }
  1326. } catch (_) {}
  1327. const attr = toKebab(k);
  1328. t.setAttribute(attr, v);
  1329. return;
  1330. }
  1331. // Fallback for path/d/points even if isSVG check somehow failed
  1332. if ((k === 'd' || k === 'points') && isEl(t)) {
  1333. t.setAttribute(k, v);
  1334. return;
  1335. }
  1336. // Generic property
  1337. t[k] = v;
  1338. }
  1339. _buildTween() {
  1340. const tween = {};
  1341. Object.keys(this.propValues).forEach((k) => {
  1342. const raw = this.propValues[k];
  1343. const fromRaw = isArr(raw) ? raw[0] : this._readCurrentValue(k);
  1344. const toRaw = isArr(raw) ? raw[1] : raw;
  1345. const fromStr = isNil(fromRaw) ? '0' : ('' + fromRaw).trim();
  1346. const toStr = isNil(toRaw) ? '0' : ('' + toRaw).trim();
  1347. const fromScalar = isPureNumberLike(fromStr);
  1348. const toScalar = isPureNumberLike(toStr);
  1349. // numeric tween (with unit preservation) — only when BOTH sides are pure scalars.
  1350. if (fromScalar && toScalar) {
  1351. const fromNum = parseFloat(fromStr);
  1352. const toNum = parseFloat(toStr);
  1353. const unit = getUnit(toStr, k) ?? getUnit(fromStr, k) ?? '';
  1354. tween[k] = { type: 'number', from: fromNum, to: toNum, unit };
  1355. return;
  1356. }
  1357. // string number-template tween (SVG path `d`, `points`, etc.)
  1358. // Requires both strings to have the same count of numeric tokens (>= 2).
  1359. const a = parseNumberTemplate(fromStr);
  1360. const b = parseNumberTemplate(toStr);
  1361. if (a.nums.length >= 2 && a.nums.length === b.nums.length && a.parts.length === b.parts.length) {
  1362. const aStrs = extractNumberStrings(fromStr);
  1363. const bStrs = extractNumberStrings(toStr);
  1364. const decs = a.nums.map((_, i) => Math.max(countDecimals(aStrs[i]), countDecimals(bStrs[i])));
  1365. tween[k] = { type: 'number-template', fromNums: a.nums, toNums: b.nums, parts: b.parts, decimals: decs };
  1366. return;
  1367. } else if ((k === 'd' || k === 'points') && (a.nums.length > 0 || b.nums.length > 0)) {
  1368. console.warn(`[Animal.js] Morph mismatch for property "${k}".\nValues must have matching number count.`,
  1369. { from: a.nums.length, to: b.nums.length, fromVal: fromStr, toVal: toStr }
  1370. );
  1371. }
  1372. // Non-numeric: fall back to "switch" (still useful for seek endpoints)
  1373. tween[k] = { type: 'discrete', from: fromStr, to: toStr };
  1374. });
  1375. return tween;
  1376. }
  1377. _apply(progress, time) {
  1378. this._progress = clamp01(progress);
  1379. Object.keys(this._tween).forEach((k) => {
  1380. const t = this._tween[k];
  1381. if (t.type === 'number') {
  1382. const eased = this._ease ? this._ease(this._progress) : this._progress;
  1383. const val = t.from + (t.to - t.from) * eased;
  1384. if (!isEl(this.target) && !isSVG(this.target) && t.unit === '') {
  1385. this._writeValue(k, val);
  1386. } else {
  1387. this._writeValue(k, (val + t.unit));
  1388. }
  1389. } else if (t.type === 'number-template') {
  1390. const eased = this._ease ? this._ease(this._progress) : this._progress;
  1391. const { fromNums, toNums, parts, decimals } = t;
  1392. let out = parts[0] || '';
  1393. for (let i = 0; i < fromNums.length; i++) {
  1394. const v = fromNums[i] + (toNums[i] - fromNums[i]) * eased;
  1395. out += formatInterpolatedNumber(v, decimals ? decimals[i] : 0);
  1396. out += parts[i + 1] || '';
  1397. }
  1398. this._writeValue(k, out);
  1399. } else {
  1400. const val = this._progress >= 1 ? t.to : t.from;
  1401. this._writeValue(k, val);
  1402. }
  1403. });
  1404. if (this.update) this.update({ target: this.target, progress: this._progress, time });
  1405. }
  1406. seek(progress) {
  1407. // Seek does not auto-play; it's intended for scroll-linked or manual control.
  1408. const t = (typeof performance !== 'undefined' ? performance.now() : 0);
  1409. this._apply(progress, t);
  1410. }
  1411. play() {
  1412. if (this._cancelled) return;
  1413. if (!this._started) {
  1414. this._started = true;
  1415. this._startTime = performance.now() + this.delay - (this._progress * this.duration);
  1416. // begin fired on first active tick to avoid firing during delay.
  1417. }
  1418. this._paused = false;
  1419. if (!this._running) {
  1420. this._running = true;
  1421. rafEngine.add(this);
  1422. }
  1423. }
  1424. pause() {
  1425. this._paused = true;
  1426. }
  1427. cancel() {
  1428. this._cancelled = true;
  1429. this._running = false;
  1430. rafEngine.remove(this);
  1431. // Resolve to avoid hanging awaits
  1432. if (this._resolve) this._resolve();
  1433. }
  1434. finish() {
  1435. this.seek(1);
  1436. this._running = false;
  1437. rafEngine.remove(this);
  1438. if (this.complete) this.complete(this.target);
  1439. if (this._resolve) this._resolve();
  1440. }
  1441. tick(now) {
  1442. if (this._cancelled) return false;
  1443. if (this._paused) return true;
  1444. if (!this._started) {
  1445. this._started = true;
  1446. this._startTime = now + this.delay;
  1447. }
  1448. if (now < this._startTime) return true;
  1449. if (!this._didBegin) {
  1450. this._didBegin = true;
  1451. if (this.begin) this.begin(this.target);
  1452. }
  1453. const totalDur = this.duration + (this.endDelay || 0);
  1454. const elapsed = now - this._startTime;
  1455. const iter = totalDur > 0 ? Math.floor(elapsed / totalDur) : 0;
  1456. const inIter = totalDur > 0 ? (elapsed - iter * totalDur) : elapsed;
  1457. const iterations = this.loop === true ? Infinity : this.loop;
  1458. if (iterations !== Infinity && iter >= iterations) {
  1459. this._apply(this._mapDirection(1, iterations - 1));
  1460. this._running = false;
  1461. if (this.complete) this.complete(this.target);
  1462. if (this._resolve) this._resolve();
  1463. return false;
  1464. }
  1465. // if we're in endDelay portion, hold the end state
  1466. let p = clamp01(inIter / this.duration);
  1467. if (this.duration <= 0) p = 1;
  1468. if (this.endDelay && inIter > this.duration) p = 1;
  1469. this._apply(this._mapDirection(p, iter), now);
  1470. // Keep running until loops exhausted
  1471. return true;
  1472. }
  1473. _mapDirection(p, iterIndex) {
  1474. const dir = this.direction;
  1475. const flip = (dir === 'reverse') || (dir === 'alternate-reverse');
  1476. const isAlt = (dir === 'alternate') || (dir === 'alternate-reverse');
  1477. let t = flip ? (1 - p) : p;
  1478. if (isAlt && (iterIndex % 2 === 1)) t = 1 - t;
  1479. return t;
  1480. }
  1481. }
  1482. // --- Controls (Motion One-ish, chainable / thenable) ---
  1483. class Controls {
  1484. constructor({ waapi = [], js = [], finished }) {
  1485. this.animations = waapi; // backward compat with old `.animations` usage
  1486. this.jsAnimations = js;
  1487. this.finished = finished || Promise.resolve();
  1488. }
  1489. then(onFulfilled, onRejected) { return this.finished.then(onFulfilled, onRejected); }
  1490. catch(onRejected) { return this.finished.catch(onRejected); }
  1491. finally(onFinally) { return this.finished.finally(onFinally); }
  1492. play() {
  1493. if (this._onPlay) this._onPlay.forEach((fn) => fn && fn());
  1494. if (this._ensureWaapiUpdate) this._ensureWaapiUpdate();
  1495. this.animations.forEach((a) => a && a.play && a.play());
  1496. this.jsAnimations.forEach((a) => a && a.play && a.play());
  1497. return this;
  1498. }
  1499. pause() {
  1500. this.animations.forEach((a) => a && a.pause && a.pause());
  1501. this.jsAnimations.forEach((a) => a && a.pause && a.pause());
  1502. return this;
  1503. }
  1504. cancel() {
  1505. this.animations.forEach((a) => a && a.cancel && a.cancel());
  1506. this.jsAnimations.forEach((a) => a && a.cancel && a.cancel());
  1507. return this;
  1508. }
  1509. finish() {
  1510. this.animations.forEach((a) => a && a.finish && a.finish());
  1511. this.jsAnimations.forEach((a) => a && a.finish && a.finish());
  1512. return this;
  1513. }
  1514. seek(progress) {
  1515. const p = clamp01(progress);
  1516. const t = (typeof performance !== 'undefined' ? performance.now() : 0);
  1517. this.animations.forEach((anim) => {
  1518. if (anim && anim.effect) {
  1519. let timing = this._waapiTimingByAnim && this._waapiTimingByAnim.get(anim);
  1520. if (!timing) {
  1521. timing = readWaapiEffectTiming(anim.effect);
  1522. if (this._waapiTimingByAnim) this._waapiTimingByAnim.set(anim, timing);
  1523. }
  1524. const dur = timing.duration || 0;
  1525. if (!dur) return;
  1526. anim.currentTime = dur * p;
  1527. const target = this._waapiTargetByAnim && this._waapiTargetByAnim.get(anim);
  1528. if (this._fireUpdate && target) this._fireUpdate({ target, progress: p, time: t });
  1529. }
  1530. });
  1531. this.jsAnimations.forEach((a) => a && a.seek && a.seek(p));
  1532. return this;
  1533. }
  1534. }
  1535. // --- Main Animation Logic ---
  1536. function animate(targets, params) {
  1537. const elements = toArray(targets);
  1538. const safeParams = params || {};
  1539. const optionsNamespace = (safeParams.options && typeof safeParams.options === 'object') ? safeParams.options : {};
  1540. // `params.options` provides a safe namespace for config keys without risking them being treated as animated props.
  1541. // Top-level keys still win for backward compatibility.
  1542. const merged = { ...optionsNamespace, ...safeParams };
  1543. const {
  1544. duration = 1000,
  1545. delay = 0,
  1546. easing = 'ease-out',
  1547. direction = 'normal',
  1548. fill = 'forwards',
  1549. loop = 1,
  1550. endDelay = 0,
  1551. autoplay = true,
  1552. springFrames = 120,
  1553. update, // callback
  1554. begin, // callback
  1555. complete // callback
  1556. } = merged;
  1557. let isSpring = false;
  1558. let springValuesRaw = null;
  1559. let springValuesSampled = null;
  1560. let springDurationMs = null;
  1561. if (typeof easing === 'object' && !Array.isArray(easing)) {
  1562. isSpring = true;
  1563. springValuesRaw = getSpringValues(easing);
  1564. const frames = (typeof springFrames === 'number' && springFrames > 1) ? Math.floor(springFrames) : 120;
  1565. springValuesSampled = downsample(springValuesRaw, frames);
  1566. springDurationMs = springValuesRaw.length * 1000 / 60;
  1567. }
  1568. // Callback aggregation (avoid double-calling when WAAPI+JS both run)
  1569. const cbState = typeof WeakMap !== 'undefined' ? new WeakMap() : null;
  1570. const getState = (t) => {
  1571. if (!cbState) return { begun: false, completed: false, lastUpdateBucket: -1 };
  1572. let s = cbState.get(t);
  1573. if (!s) {
  1574. s = { begun: false, completed: false, lastUpdateBucket: -1 };
  1575. cbState.set(t, s);
  1576. }
  1577. return s;
  1578. };
  1579. const fireBegin = (t) => {
  1580. if (!begin) return;
  1581. const s = getState(t);
  1582. if (s.begun) return;
  1583. s.begun = true;
  1584. begin(t);
  1585. };
  1586. const fireComplete = (t) => {
  1587. if (!complete) return;
  1588. const s = getState(t);
  1589. if (s.completed) return;
  1590. s.completed = true;
  1591. complete(t);
  1592. };
  1593. const fireUpdate = (payload) => {
  1594. if (!update) return;
  1595. const t = payload && payload.target;
  1596. const time = payload && payload.time;
  1597. if (!t) return update(payload);
  1598. const s = getState(t);
  1599. const bucket = Math.floor(((typeof time === 'number' ? time : (typeof performance !== 'undefined' ? performance.now() : 0))) / 16);
  1600. if (bucket === s.lastUpdateBucket) return;
  1601. s.lastUpdateBucket = bucket;
  1602. update(payload);
  1603. };
  1604. const propEntries = [];
  1605. Object.keys(safeParams).forEach((key) => {
  1606. if (key === 'options') return;
  1607. if (isAnimOptionKey(key)) return;
  1608. propEntries.push({ key, canonical: ALIASES[key] || key, val: safeParams[key] });
  1609. });
  1610. // Create animations but don't play if autoplay is false
  1611. const waapiAnimations = [];
  1612. const jsAnimations = [];
  1613. const engineInfo = {
  1614. isSpring,
  1615. waapiKeys: [],
  1616. jsKeys: []
  1617. };
  1618. const waapiKeySet = new Set();
  1619. const jsKeySet = new Set();
  1620. const onPlayHooks = [];
  1621. const waapiUpdateItems = [];
  1622. const waapiTargetByAnim = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
  1623. const waapiTimingByAnim = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
  1624. let waapiUpdateStarted = false;
  1625. const ensureWaapiUpdate = () => {
  1626. if (waapiUpdateStarted) return;
  1627. waapiUpdateStarted = true;
  1628. waapiUpdateItems.forEach((item) => waapiUpdateSampler.add(item));
  1629. };
  1630. const promises = elements.map((el) => {
  1631. // Route props per target (fix mixed HTML/SVG/object target arrays).
  1632. const waapiProps = {};
  1633. const jsProps = {};
  1634. propEntries.forEach(({ key, canonical, val }) => {
  1635. const isTransform = TRANSFORMS.includes(canonical) || TRANSFORMS.includes(key);
  1636. if (!el || (!isEl(el) && !isSVG(el))) {
  1637. jsProps[key] = val;
  1638. jsKeySet.add(key);
  1639. return;
  1640. }
  1641. const isSvgTarget = isSVG(el);
  1642. if (isSvgTarget) {
  1643. if (isTransform || key === 'opacity' || key === 'filter') {
  1644. waapiProps[canonical] = val;
  1645. waapiKeySet.add(canonical);
  1646. } else {
  1647. jsProps[key] = val;
  1648. jsKeySet.add(key);
  1649. }
  1650. return;
  1651. }
  1652. // HTML element
  1653. if (isCssVar(key)) {
  1654. jsProps[key] = val;
  1655. jsKeySet.add(key);
  1656. return;
  1657. }
  1658. const isCssLike = isTransform || key === 'opacity' || key === 'filter' || (isEl(el) && (key in el.style));
  1659. if (isCssLike) {
  1660. waapiProps[canonical] = val;
  1661. waapiKeySet.add(canonical);
  1662. } else {
  1663. jsProps[key] = val;
  1664. jsKeySet.add(key);
  1665. }
  1666. });
  1667. // 1. WAAPI Animation
  1668. let waapiAnim = null;
  1669. let waapiPromise = Promise.resolve();
  1670. if (Object.keys(waapiProps).length > 0) {
  1671. const buildFrames = (propValues) => {
  1672. // Spring: share sampled progress; per-target we only compute start/end once per prop.
  1673. if (isSpring && springValuesSampled && springValuesSampled.length) {
  1674. const cs = (isEl(el) && typeof getComputedStyle !== 'undefined') ? getComputedStyle(el) : null;
  1675. const metas = Object.keys(propValues).map((k) => {
  1676. const raw = propValues[k];
  1677. const rawFrom = Array.isArray(raw) ? raw[0] : undefined;
  1678. const rawTo = Array.isArray(raw) ? raw[1] : raw;
  1679. const toNum = parseFloat(('' + rawTo).trim());
  1680. const fromNumExplicit = Array.isArray(raw) ? parseFloat(('' + rawFrom).trim()) : NaN;
  1681. const isT = TRANSFORMS.includes(ALIASES[k] || k) || TRANSFORMS.includes(k);
  1682. const unit = getUnit(('' + rawTo), k) ?? getUnit(('' + rawFrom), k) ?? getDefaultUnit(k);
  1683. let fromNum = 0;
  1684. if (Number.isFinite(fromNumExplicit)) {
  1685. fromNum = fromNumExplicit;
  1686. } else if (k.startsWith('scale')) {
  1687. fromNum = 1;
  1688. } else if (k === 'opacity' && cs) {
  1689. const n = parseFloat(cs.opacity);
  1690. if (!Number.isNaN(n)) fromNum = n;
  1691. } else if (!isT && cs) {
  1692. const cssVal = cs.getPropertyValue(toKebab(k));
  1693. const n = parseFloat(cssVal);
  1694. if (!Number.isNaN(n)) fromNum = n;
  1695. }
  1696. const to = Number.isFinite(toNum) ? toNum : 0;
  1697. return { k, isT, unit: unit ?? '', from: fromNum, to };
  1698. });
  1699. const frames = new Array(springValuesSampled.length);
  1700. for (let i = 0; i < springValuesSampled.length; i++) {
  1701. const v = springValuesSampled[i];
  1702. const frame = {};
  1703. let transformStr = '';
  1704. for (let j = 0; j < metas.length; j++) {
  1705. const m = metas[j];
  1706. const current = m.from + (m.to - m.from) * v;
  1707. const outVal = (m.unit === '' ? ('' + current) : (current + m.unit));
  1708. if (m.isT) transformStr += `${m.k}(${outVal}) `;
  1709. else frame[m.k] = outVal;
  1710. }
  1711. if (transformStr) frame.transform = transformStr.trim();
  1712. frames[i] = frame;
  1713. }
  1714. if (frames[0] && Object.keys(frames[0]).length === 0) frames.shift();
  1715. return frames;
  1716. }
  1717. // Non-spring: 2-keyframe path
  1718. const frame0 = {};
  1719. const frame1 = {};
  1720. let transform0 = '';
  1721. let transform1 = '';
  1722. Object.keys(propValues).forEach((k) => {
  1723. const val = propValues[k];
  1724. const isT = TRANSFORMS.includes(ALIASES[k] || k) || TRANSFORMS.includes(k);
  1725. if (Array.isArray(val)) {
  1726. const from = isT ? normalizeTransformPartValue(k, val[0]) : val[0];
  1727. const to = isT ? normalizeTransformPartValue(k, val[1]) : val[1];
  1728. if (isT) {
  1729. transform0 += `${k}(${from}) `;
  1730. transform1 += `${k}(${to}) `;
  1731. } else {
  1732. frame0[k] = from;
  1733. frame1[k] = to;
  1734. }
  1735. } else {
  1736. if (isT) transform1 += `${k}(${normalizeTransformPartValue(k, val)}) `;
  1737. else frame1[k] = val;
  1738. }
  1739. });
  1740. if (transform0) frame0.transform = transform0.trim();
  1741. if (transform1) frame1.transform = transform1.trim();
  1742. const out = [frame0, frame1];
  1743. if (Object.keys(out[0]).length === 0) out.shift();
  1744. return out;
  1745. };
  1746. const finalFrames = buildFrames(waapiProps);
  1747. const opts = {
  1748. duration: isSpring ? springDurationMs : duration,
  1749. delay,
  1750. fill,
  1751. iterations: loop,
  1752. easing: isSpring ? 'linear' : easing,
  1753. direction,
  1754. endDelay
  1755. };
  1756. const animation = el.animate(finalFrames, opts);
  1757. if (!autoplay) animation.pause();
  1758. waapiAnim = animation;
  1759. waapiPromise = animation.finished;
  1760. waapiAnimations.push(waapiAnim);
  1761. if (waapiTargetByAnim) waapiTargetByAnim.set(waapiAnim, el);
  1762. if (waapiTimingByAnim) waapiTimingByAnim.set(waapiAnim, readWaapiEffectTiming(waapiAnim.effect));
  1763. if (begin) {
  1764. // Fire begin when play starts (and also for autoplay on next frame)
  1765. onPlayHooks.push(() => fireBegin(el));
  1766. if (autoplay && typeof requestAnimationFrame !== 'undefined') requestAnimationFrame(() => fireBegin(el));
  1767. }
  1768. if (complete) {
  1769. waapiAnim.addEventListener?.('finish', () => fireComplete(el));
  1770. }
  1771. if (update) {
  1772. const timing = (waapiTimingByAnim && waapiTimingByAnim.get(waapiAnim)) || readWaapiEffectTiming(waapiAnim.effect);
  1773. const item = { anim: waapiAnim, target: el, update: fireUpdate, _lastP: null, _dur: timing.duration || 0 };
  1774. waapiUpdateItems.push(item);
  1775. // Ensure removal on finish/cancel
  1776. waapiAnim.addEventListener?.('finish', () => waapiUpdateSampler.remove(item));
  1777. waapiAnim.addEventListener?.('cancel', () => waapiUpdateSampler.remove(item));
  1778. // Start sampler only when needed (autoplay or explicit play)
  1779. if (autoplay) ensureWaapiUpdate();
  1780. }
  1781. }
  1782. // 2. JS Animation (Fallback / Attributes)
  1783. let jsPromise = Promise.resolve();
  1784. if (Object.keys(jsProps).length > 0) {
  1785. const jsAnim = new JsAnimation(
  1786. el,
  1787. jsProps,
  1788. { duration, delay, easing, autoplay, direction, loop, endDelay, springValues: isSpring ? springValuesRaw : null },
  1789. { update: fireUpdate, begin: fireBegin, complete: fireComplete }
  1790. );
  1791. jsAnimations.push(jsAnim);
  1792. jsPromise = jsAnim.finished;
  1793. }
  1794. return Promise.all([waapiPromise, jsPromise]);
  1795. });
  1796. const finished = Promise.all(promises);
  1797. const controls = new Controls({ waapi: waapiAnimations, js: jsAnimations, finished });
  1798. controls.engine = engineInfo;
  1799. controls._onPlay = onPlayHooks;
  1800. controls._fireUpdate = fireUpdate;
  1801. controls._waapiTargetByAnim = waapiTargetByAnim;
  1802. controls._waapiTimingByAnim = waapiTimingByAnim;
  1803. controls._ensureWaapiUpdate = update ? ensureWaapiUpdate : null;
  1804. if (!autoplay) controls.pause();
  1805. engineInfo.waapiKeys = Array.from(waapiKeySet);
  1806. engineInfo.jsKeys = Array.from(jsKeySet);
  1807. return controls;
  1808. }
  1809. // --- SVG Draw ---
  1810. function svgDraw(targets, params = {}) {
  1811. const elements = toArray(targets);
  1812. elements.forEach(el => {
  1813. if (!isSVG(el)) return;
  1814. const len = el.getTotalLength ? el.getTotalLength() : 0;
  1815. el.style.strokeDasharray = len;
  1816. el.style.strokeDashoffset = len;
  1817. animate(el, {
  1818. strokeDashoffset: [len, 0],
  1819. ...params
  1820. });
  1821. });
  1822. }
  1823. // --- In View ---
  1824. function inViewAnimate(targets, params, options = {}) {
  1825. const elements = toArray(targets);
  1826. const observer = new IntersectionObserver((entries) => {
  1827. entries.forEach(entry => {
  1828. if (entry.isIntersecting) {
  1829. animate(entry.target, params);
  1830. if (options.once !== false) observer.unobserve(entry.target);
  1831. }
  1832. });
  1833. }, { threshold: options.threshold || 0.1 });
  1834. elements.forEach(el => observer.observe(el));
  1835. // Return cleanup so callers can disconnect observers in long-lived pages (esp. once:false).
  1836. return () => {
  1837. try {
  1838. elements.forEach((el) => observer.unobserve(el));
  1839. observer.disconnect();
  1840. } catch (e) {
  1841. // ignore
  1842. }
  1843. };
  1844. }
  1845. // --- Scroll Linked ---
  1846. function scroll(animationPromise, options = {}) {
  1847. // options: container (default window), range [start, end] (default viewport logic)
  1848. const container = options.container || window;
  1849. const target = options.target || document.body; // Element to track for progress
  1850. // If passing an animation promise, we control its WAAPI animations
  1851. const controls = animationPromise;
  1852. // Back-compat: old return value was a Promise with `.animations`
  1853. const hasSeek = controls && isFunc(controls.seek);
  1854. const anims = (controls && controls.animations) || (animationPromise && animationPromise.animations) || [];
  1855. const jsAnims = (controls && controls.jsAnimations) || [];
  1856. if (!hasSeek && !anims.length && !jsAnims.length) return;
  1857. // Cache WAAPI timing per animation to avoid repeated getComputedTiming() during scroll.
  1858. const timingCache = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
  1859. const getEndTime = (anim) => {
  1860. if (!anim || !anim.effect) return 0;
  1861. if (timingCache) {
  1862. const cached = timingCache.get(anim);
  1863. if (cached) return cached;
  1864. }
  1865. const timing = readWaapiEffectTiming(anim.effect);
  1866. const end = timing.duration || 0;
  1867. if (timingCache && end) timingCache.set(anim, end);
  1868. return end;
  1869. };
  1870. const updateScroll = () => {
  1871. let progress = 0;
  1872. if (container === window) {
  1873. const scrollY = window.scrollY;
  1874. const winH = window.innerHeight;
  1875. const docH = document.body.scrollHeight;
  1876. // Simple progress: how far down the page (0 to 1)
  1877. // Or element based?
  1878. // Motion One defaults to element entering view.
  1879. if (options.target) {
  1880. const rect = options.target.getBoundingClientRect();
  1881. const start = winH;
  1882. const end = -rect.height;
  1883. // progress 0 when rect.top == start (just entering)
  1884. // progress 1 when rect.top == end (just left)
  1885. const totalDistance = start - end;
  1886. const currentDistance = start - rect.top;
  1887. progress = currentDistance / totalDistance;
  1888. } else {
  1889. // Whole page scroll
  1890. progress = scrollY / (docH - winH);
  1891. }
  1892. } else if (container && (typeof Element !== 'undefined') && (container instanceof Element)) {
  1893. // Scroll container progress
  1894. const el = container;
  1895. const scrollTop = el.scrollTop;
  1896. const max = (el.scrollHeight - el.clientHeight) || 1;
  1897. if (options.target) {
  1898. const containerRect = el.getBoundingClientRect();
  1899. const rect = options.target.getBoundingClientRect();
  1900. const start = containerRect.height;
  1901. const end = -rect.height;
  1902. const totalDistance = start - end;
  1903. const currentDistance = start - (rect.top - containerRect.top);
  1904. progress = currentDistance / totalDistance;
  1905. } else {
  1906. progress = scrollTop / max;
  1907. }
  1908. }
  1909. // Clamp
  1910. progress = clamp01(progress);
  1911. if (hasSeek) {
  1912. controls.seek(progress);
  1913. return;
  1914. }
  1915. anims.forEach((anim) => {
  1916. if (anim.effect) {
  1917. const end = getEndTime(anim);
  1918. if (!end) return;
  1919. anim.currentTime = end * progress;
  1920. }
  1921. });
  1922. };
  1923. let rafId = 0;
  1924. const onScroll = () => {
  1925. if (rafId) return;
  1926. rafId = requestAnimationFrame(() => {
  1927. rafId = 0;
  1928. updateScroll();
  1929. });
  1930. };
  1931. const eventTarget = (container && container.addEventListener) ? container : window;
  1932. eventTarget.addEventListener('scroll', onScroll, { passive: true });
  1933. updateScroll(); // Initial
  1934. return () => {
  1935. if (rafId) cancelAnimationFrame(rafId);
  1936. eventTarget.removeEventListener('scroll', onScroll);
  1937. };
  1938. }
  1939. // --- Timeline ---
  1940. function timeline(defaults = {}) {
  1941. const steps = [];
  1942. const api = {
  1943. currentTime: 0,
  1944. add: (targets, params, offset) => {
  1945. const animParams = { ...defaults, ...params };
  1946. let start = api.currentTime;
  1947. if (offset !== undefined) {
  1948. if (isStr(offset) && offset.startsWith('-=')) start -= parseFloat(offset.slice(2));
  1949. else if (isStr(offset) && offset.startsWith('+=')) start += parseFloat(offset.slice(2));
  1950. else if (typeof offset === 'number') start = offset;
  1951. }
  1952. const dur = animParams.duration || 1000;
  1953. const step = { targets, animParams, start, _scheduled: false };
  1954. steps.push(step);
  1955. // Backward compatible: schedule immediately (existing docs rely on this)
  1956. if (start <= 0) {
  1957. animate(targets, animParams);
  1958. step._scheduled = true;
  1959. } else {
  1960. setTimeout(() => {
  1961. animate(targets, animParams);
  1962. }, start);
  1963. step._scheduled = true;
  1964. }
  1965. api.currentTime = Math.max(api.currentTime, start + dur);
  1966. return api;
  1967. },
  1968. // Optional: if you create a timeline and want to defer scheduling yourself
  1969. play: () => {
  1970. steps.forEach((s) => {
  1971. if (s._scheduled) return;
  1972. if (s.start <= 0) animate(s.targets, s.animParams);
  1973. else setTimeout(() => animate(s.targets, s.animParams), s.start);
  1974. s._scheduled = true;
  1975. });
  1976. return api;
  1977. }
  1978. };
  1979. return api;
  1980. }
  1981. // --- Export ---
  1982. // transform `$` to be the main export `animal`, with statics attached
  1983. const animal = $;
  1984. // Extend $ behavior to act as a global selector and property accessor
  1985. Object.assign(animal, {
  1986. animate,
  1987. timeline,
  1988. draw: svgDraw,
  1989. svgDraw,
  1990. inViewAnimate,
  1991. spring,
  1992. scroll,
  1993. $: animal // Self-reference for backward compatibility
  1994. });
  1995. // Expose Layer if available or allow lazy loading
  1996. Object.defineProperty(animal, 'Layer', {
  1997. get: () => {
  1998. return (typeof window !== 'undefined' && window.Layer) ? window.Layer :
  1999. (typeof globalThis !== 'undefined' && globalThis.Layer) ? globalThis.Layer :
  2000. (typeof Layer !== 'undefined' ? Layer : null);
  2001. }
  2002. });
  2003. // Shortcut for Layer.fire or new Layer()
  2004. // Allows $.fire({ title: 'Hi' }) or $.layer({ title: 'Hi' })
  2005. animal.fire = (options) => {
  2006. const L = animal.Layer;
  2007. if (L) return (L.fire ? L.fire(options) : new L(options).fire());
  2008. console.warn('Layer module not loaded.');
  2009. return Promise.reject('Layer module not loaded');
  2010. };
  2011. // 'layer' alias for static usage
  2012. animal.layer = animal.fire;
  2013. return animal;
  2014. })));
  2015. ;(function(g){
  2016. try { if (g && g.animal && !g.xjs) g.xjs = g.animal; } catch {}
  2017. try { if (g && g.XJS_GLOBAL_DOLLAR && !g.$ && g.xjs) g.$ = g.xjs; } catch {}
  2018. })(typeof window !== 'undefined' ? window : (typeof globalThis !== 'undefined' ? globalThis : this));