xjs.js 72 KB

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