layer.js 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415
  1. (function (global, factory) {
  2. const LayerClass = factory();
  3. // Allow usage as `Layer({...})` or `new Layer()`
  4. // But Layer is a class. We can wrap it in a proxy or factory function.
  5. function LayerFactory(options) {
  6. if (options && typeof options === 'object') {
  7. return LayerClass.$(options);
  8. }
  9. return new LayerClass();
  10. }
  11. // Copy static methods (including non-enumerable class statics like `fire` / `$`)
  12. // Class static methods are non-enumerable by default, so Object.assign() would miss them.
  13. const copyStatic = (to, from) => {
  14. try {
  15. Object.getOwnPropertyNames(from).forEach((k) => {
  16. if (k === 'prototype' || k === 'name' || k === 'length') return;
  17. const desc = Object.getOwnPropertyDescriptor(from, k);
  18. if (!desc) return;
  19. Object.defineProperty(to, k, desc);
  20. });
  21. } catch (e) {
  22. // Best-effort fallback
  23. try { Object.assign(to, from); } catch {}
  24. }
  25. };
  26. copyStatic(LayerFactory, LayerClass);
  27. // Also copy prototype for instanceof checks if needed (though tricky with factory)
  28. LayerFactory.prototype = LayerClass.prototype;
  29. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = LayerFactory :
  30. typeof define === 'function' && define.amd ? define(() => LayerFactory) :
  31. (global.Layer = LayerFactory);
  32. }(this, (function () {
  33. 'use strict';
  34. const PREFIX = 'layer-';
  35. const RING_TYPES = new Set(['success', 'error', 'warning', 'info', 'question']);
  36. const RING_BG_PARTS_SELECTOR = `.${PREFIX}success-circular-line-left, .${PREFIX}success-circular-line-right, .${PREFIX}success-fix`;
  37. const SVGANI_PREFIX = 'svg:';
  38. const BG_SVG_PREFIX = 'svg(';
  39. const BG_CSS_PREFIX = 'css(';
  40. const THEME_VALUES = new Set(['auto', 'dark', 'light']);
  41. const normalizeTheme = (value) => {
  42. if (typeof value !== 'string') return 'auto';
  43. const v = value.trim().toLowerCase();
  44. return THEME_VALUES.has(v) ? v : 'auto';
  45. };
  46. const normalizeOptions = (options, text, icon) => {
  47. if (typeof options !== 'string') return options || {};
  48. const o = { title: options };
  49. if (text) o.text = text;
  50. if (icon) o.icon = icon;
  51. return o;
  52. };
  53. const el = (tag, className, text) => {
  54. const node = document.createElement(tag);
  55. if (className) node.className = className;
  56. if (text !== undefined) node.textContent = text;
  57. return node;
  58. };
  59. const svgEl = (tag) => document.createElementNS('http://www.w3.org/2000/svg', tag);
  60. // Ensure library CSS is loaded (xjs.css)
  61. // - CSS is centralized in xjs.css (no runtime <style> injection).
  62. // - We still auto-load it for convenience/compat, since consumers may forget the <link>.
  63. let _xjsCssReady = null; // Promise<void>
  64. const waitForStylesheet = (link) => new Promise((resolve) => {
  65. if (!link) return resolve();
  66. if (link.sheet) return resolve();
  67. let done = false;
  68. const finish = () => {
  69. if (done) return;
  70. done = true;
  71. resolve();
  72. };
  73. try { link.addEventListener('load', finish, { once: true }); } catch {}
  74. try { link.addEventListener('error', finish, { once: true }); } catch {}
  75. // Fallback timeout: avoid blocking forever if the load event is missed.
  76. setTimeout(finish, 200);
  77. });
  78. const ensureXjsCss = () => {
  79. try {
  80. if (_xjsCssReady) return _xjsCssReady;
  81. if (typeof document === 'undefined') return Promise.resolve();
  82. if (!document.head) return Promise.resolve();
  83. const existingLink = Array.from(document.querySelectorAll('link[rel="stylesheet"]'))
  84. .find((l) => /(^|\/)xjs\.css(\?|#|$)/.test((l.getAttribute('href') || '').trim()));
  85. if (existingLink) return (_xjsCssReady = waitForStylesheet(existingLink));
  86. const id = 'xjs-css';
  87. const existing = document.getElementById(id);
  88. if (existing) return (_xjsCssReady = waitForStylesheet(existing));
  89. const scripts = Array.from(document.getElementsByTagName('script'));
  90. const scriptSrc = scripts
  91. .map((s) => s && s.src)
  92. .find((src) => /(^|\/)(xjs|layer)\.js(\?|#|$)/.test(String(src || '')));
  93. let href = 'xjs.css';
  94. if (scriptSrc) {
  95. href = String(scriptSrc)
  96. .replace(/(^|\/)xjs\.js(\?|#|$)/, '$1xjs.css$2')
  97. .replace(/(^|\/)layer\.js(\?|#|$)/, '$1xjs.css$2');
  98. }
  99. const link = document.createElement('link');
  100. link.id = id;
  101. link.rel = 'stylesheet';
  102. link.href = href;
  103. _xjsCssReady = waitForStylesheet(link);
  104. document.head.appendChild(link);
  105. return _xjsCssReady;
  106. } catch {
  107. // ignore
  108. return Promise.resolve();
  109. }
  110. };
  111. // SvgAni (svg.js) lazy loader for "svg:*" icon type
  112. let _svgAniReady = null;
  113. let _svgAniPrefetchScheduled = false;
  114. const isSvgAniIcon = (icon) => {
  115. if (typeof icon !== 'string') return false;
  116. const s = icon.trim();
  117. return s.startsWith(SVGANI_PREFIX);
  118. };
  119. const getSvgAniIconName = (icon) => {
  120. if (!isSvgAniIcon(icon)) return '';
  121. let name = String(icon || '').trim().slice(SVGANI_PREFIX.length).trim();
  122. if (name === 'loadding') name = 'loading';
  123. return name;
  124. };
  125. const normalizeSvgAniName = (raw) => {
  126. let name = String(raw || '').trim();
  127. if (!name) return '';
  128. if (name.startsWith(SVGANI_PREFIX)) name = getSvgAniIconName(name);
  129. if (name === 'loadding') name = 'loading';
  130. return name;
  131. };
  132. const getLayerScriptBase = () => {
  133. try {
  134. if (typeof document === 'undefined') return '';
  135. const scripts = Array.from(document.getElementsByTagName('script'));
  136. const src = scripts
  137. .map((s) => s && s.src)
  138. .find((s) => /(^|\/)(xjs|layer)\.js(\?|#|$)/.test(String(s || '')));
  139. if (!src) return '';
  140. return String(src)
  141. .replace(/[#?].*$/, '')
  142. .replace(/\/[^\/]*$/, '/');
  143. } catch {
  144. return '';
  145. }
  146. };
  147. const resolveSvgAniScriptUrl = () => {
  148. const base = getLayerScriptBase();
  149. return base ? (base + 'svg/svg.js') : 'svg/svg.js';
  150. };
  151. const resolveSvgAniJsonUrl = (name) => {
  152. const raw = String(name || '').trim();
  153. if (!raw) return '';
  154. if (/^(https?:)?\/\//.test(raw)) return raw;
  155. if (raw.startsWith('/') || raw.startsWith('./') || raw.startsWith('../')) return raw;
  156. const base = getLayerScriptBase();
  157. const file = raw.endsWith('.json') ? raw : (raw + '.json');
  158. return (base ? base : '') + 'svg/' + file;
  159. };
  160. const ensureSvgAniLib = () => {
  161. try {
  162. if (typeof window === 'undefined') return Promise.resolve(null);
  163. if (window.lottie) return Promise.resolve(window.lottie);
  164. if (typeof document === 'undefined' || !document.head) return Promise.resolve(null);
  165. if (_svgAniReady) return _svgAniReady;
  166. const existing = document.getElementById('layer-svgani-lib');
  167. _svgAniReady = new Promise((resolve) => {
  168. const finish = () => resolve(window.lottie || null);
  169. if (existing) {
  170. try { existing.addEventListener('load', finish, { once: true }); } catch {}
  171. try { existing.addEventListener('error', finish, { once: true }); } catch {}
  172. setTimeout(finish, 1200);
  173. return;
  174. }
  175. const script = document.createElement('script');
  176. script.id = 'layer-svgani-lib';
  177. script.async = true;
  178. script.src = resolveSvgAniScriptUrl();
  179. try { script.addEventListener('load', finish, { once: true }); } catch {}
  180. try { script.addEventListener('error', finish, { once: true }); } catch {}
  181. setTimeout(finish, 1800);
  182. document.head.appendChild(script);
  183. });
  184. return _svgAniReady;
  185. } catch {
  186. return Promise.resolve(null);
  187. }
  188. };
  189. const scheduleSvgAniPrefetch = () => {
  190. if (_svgAniPrefetchScheduled) return;
  191. _svgAniPrefetchScheduled = true;
  192. try {
  193. if (typeof window === 'undefined') return;
  194. const start = () => {
  195. setTimeout(() => {
  196. try { ensureSvgAniLib(); } catch {}
  197. }, 0);
  198. };
  199. if (document.readyState === 'complete') start();
  200. else window.addEventListener('load', start, { once: true });
  201. } catch {}
  202. };
  203. const waitForConnected = (el) => new Promise((resolve) => {
  204. if (!el) return resolve(false);
  205. if (el.isConnected) return resolve(true);
  206. let done = false;
  207. const finish = () => {
  208. if (done) return;
  209. done = true;
  210. resolve(!!el.isConnected);
  211. };
  212. try {
  213. requestAnimationFrame(() => requestAnimationFrame(finish));
  214. } catch {
  215. setTimeout(finish, 0);
  216. return;
  217. }
  218. setTimeout(finish, 120);
  219. });
  220. class Layer {
  221. constructor() {
  222. this._cssReady = ensureXjsCss();
  223. this.params = {};
  224. this.dom = {};
  225. this.promise = null;
  226. this.resolve = null;
  227. this.reject = null;
  228. this._onKeydown = null;
  229. this._mounted = null; // { kind, originalEl, placeholder, parent, nextSibling, prevHidden, prevInlineDisplay }
  230. this._isClosing = false;
  231. this._isReplace = false;
  232. // Step/flow support
  233. this._flowSteps = null; // Array<options>
  234. this._flowIndex = 0;
  235. this._flowValues = [];
  236. this._flowBase = null; // base options merged into each step
  237. this._flowResolved = null; // resolved merged steps
  238. this._flowMountedList = []; // mounted DOM records for move-mode steps
  239. this._flowAutoForm = null; // { enabled: true } when using step container shorthand
  240. this._backgroundSpec = null;
  241. }
  242. // Constructor helper when called as function: const popup = Layer({...})
  243. static get isProxy() { return true; }
  244. // Static entry point
  245. static run(options) {
  246. const instance = new Layer();
  247. return instance.run(options);
  248. }
  249. // Chainable entry point (builder-style)
  250. // Example:
  251. // Layer.$({ title: 'Hi' }).run().then(...)
  252. // Layer.$().config({ title: 'Hi' }).run()
  253. static $(options) {
  254. const instance = new Layer();
  255. if (options !== undefined) instance.config(options);
  256. return instance;
  257. }
  258. // Chainable config helper (does not render until `.run()` is called)
  259. config(options = {}) {
  260. // Support the same shorthand as Layer.run(title, text, icon)
  261. options = normalizeOptions(options, arguments[1], arguments[2]);
  262. this.params = { ...(this.params || {}), ...options };
  263. return this;
  264. }
  265. // Add a single step (chainable)
  266. // Usage:
  267. // Layer.$().step({ title:'A', dom:'#step1' }).step({ title:'B', dom:'#step2' }).run()
  268. step(options = {}) {
  269. if (!this._flowSteps) this._flowSteps = [];
  270. this._flowSteps.push(normalizeOptions(options, arguments[1], arguments[2]));
  271. return this;
  272. }
  273. // Add multiple steps at once (chainable)
  274. steps(steps = []) {
  275. if (!Array.isArray(steps)) return this;
  276. if (!this._flowSteps) this._flowSteps = [];
  277. steps.forEach((s) => this.step(s));
  278. return this;
  279. }
  280. // Convenience static helper: Layer.flow([steps], baseOptions?)
  281. static flow(steps = [], baseOptions = {}) {
  282. return Layer.$(baseOptions).steps(steps).run();
  283. }
  284. // Instance entry point (chainable)
  285. run(options) {
  286. const hasArgs = (options !== undefined && options !== null);
  287. const normalized = hasArgs ? normalizeOptions(options, arguments[1], arguments[2]) : null;
  288. const merged = hasArgs ? normalized : (this.params || {});
  289. // If no explicit steps yet, allow shorthand: { step: '#container', stepItem: '.item' }
  290. if (!this._flowSteps || !this._flowSteps.length) {
  291. const didInit = this._initFlowFromStepContainer(merged);
  292. if (didInit) {
  293. this.params = { ...(this.params || {}), ...this._stripStepOptions(merged) };
  294. }
  295. }
  296. // Flow mode: if configured via .step()/.steps() or step container shorthand, ignore per-call options and use steps
  297. if (this._flowSteps && this._flowSteps.length) {
  298. if (hasArgs) {
  299. // allow providing base options at fire-time
  300. this.params = { ...(this.params || {}), ...this._stripStepOptions(merged) };
  301. }
  302. return this._fireFlow();
  303. }
  304. return this._fire(merged);
  305. }
  306. _fire(options = {}) {
  307. options = normalizeOptions(options, arguments[1], arguments[2]);
  308. this.params = {
  309. title: '',
  310. text: '',
  311. icon: null,
  312. iconSize: null, // e.g. '6em' / '72px'
  313. iconLoop: null, // svgAni only: true/false/null (auto)
  314. confirmButtonText: 'OK',
  315. cancelButtonText: 'Cancel',
  316. showCancelButton: false,
  317. closeOnClickOutside: true,
  318. closeOnEsc: true,
  319. iconAnimation: true,
  320. popupAnimation: true,
  321. theme: 'auto',
  322. background: null,
  323. width: null,
  324. height: null,
  325. iwidth: null,
  326. iheight: null,
  327. nextIcon: null, // flow-only: icon for Next button
  328. prevIcon: null, // flow-only: icon for Back button
  329. // Content:
  330. // - text: plain text
  331. // - html: innerHTML
  332. // - dom: selector / Element / <template> (preferred)
  333. // - content: backward compat for selector/Element OR advanced { dom, mode, clone }
  334. dom: null,
  335. domMode: 'move', // 'move' (default) | 'clone'
  336. // Hook for confirming (also used in flow steps)
  337. // Return false to prevent close / next.
  338. // Return a value to be attached as `value`.
  339. // May return Promise.
  340. preConfirm: null,
  341. ...options
  342. };
  343. this.promise = new Promise((resolve, reject) => {
  344. this.resolve = resolve;
  345. this.reject = reject;
  346. });
  347. this._render();
  348. return this.promise;
  349. }
  350. _fireFlow() {
  351. this._flowIndex = 0;
  352. this._flowValues = [];
  353. // In flow mode:
  354. // - keep iconAnimation off by default (avoids jitter)
  355. // - BUT allow popupAnimation by default so the first step has the same entrance feel
  356. const base = { ...(this.params || {}) };
  357. if (!('popupAnimation' in base)) base.popupAnimation = true;
  358. if (!('iconAnimation' in base)) base.iconAnimation = false;
  359. this._flowBase = base;
  360. this.promise = new Promise((resolve, reject) => {
  361. this.resolve = resolve;
  362. this.reject = reject;
  363. });
  364. this._flowResolved = (this._flowSteps || []).map((_, i) => this._getFlowStepOptions(i));
  365. const first = this._flowResolved[0] || this._getFlowStepOptions(0);
  366. this.params = first;
  367. this._render({ flow: true });
  368. return this.promise;
  369. }
  370. static _getXjs() {
  371. // Prefer $ (main), fallback to xjs/animal (compat)
  372. const g = (typeof window !== 'undefined') ? window : (typeof globalThis !== 'undefined' ? globalThis : null);
  373. if (!g) return null;
  374. const x = g.$ || g.xjs || g.animal;
  375. return (typeof x === 'function') ? x : null;
  376. }
  377. _stripStepOptions(options) {
  378. const out = { ...(options || {}) };
  379. try { delete out.step; } catch {}
  380. try { delete out.stepItem; } catch {}
  381. return out;
  382. }
  383. _parseStepSizeAttr(raw) {
  384. if (raw === undefined || raw === null) return null;
  385. const s = String(raw).trim();
  386. if (!s) return null;
  387. if (/^-?\d+(\.\d+)?$/.test(s)) return parseFloat(s);
  388. return s;
  389. }
  390. _readStepAttr(item, container, names) {
  391. const list = Array.isArray(names) ? names : [names];
  392. const readFrom = (el) => {
  393. if (!el || !el.getAttribute) return '';
  394. for (let i = 0; i < list.length; i++) {
  395. const v = el.getAttribute(list[i]);
  396. if (v != null && String(v).trim() !== '') return String(v).trim();
  397. }
  398. return '';
  399. };
  400. return readFrom(item) || readFrom(container) || '';
  401. }
  402. _normalizeStepContainer(options) {
  403. const opts = options || {};
  404. const raw = opts.step;
  405. if (!raw || typeof document === 'undefined') return null;
  406. const container = (typeof raw === 'string') ? document.querySelector(raw) : raw;
  407. if (!container || (typeof Element !== 'undefined' && !(container instanceof Element))) return null;
  408. const itemSelector = opts.stepItem;
  409. let items = [];
  410. if (typeof itemSelector === 'string' && itemSelector.trim()) {
  411. try { items = Array.from(container.querySelectorAll(itemSelector)); } catch {}
  412. } else {
  413. try { items = Array.from(container.children || []); } catch {}
  414. }
  415. return { container, items };
  416. }
  417. _initFlowFromStepContainer(options) {
  418. const spec = this._normalizeStepContainer(options);
  419. if (!spec) return false;
  420. const { items, container } = spec;
  421. if (!items || !items.length) {
  422. try { console.warn('Layer step container has no items.'); } catch {}
  423. return false;
  424. }
  425. this._flowSteps = items.map((item) => {
  426. const step = { dom: item, __fromContainer: true };
  427. try {
  428. const title =
  429. (item.getAttribute('data-step-title') || item.getAttribute('data-layer-title') || item.getAttribute('title') || '').trim();
  430. if (title) step.title = title;
  431. } catch {}
  432. try {
  433. const background = this._readStepAttr(item, container, ['data-step-background', 'data-layer-background', 'data-background']);
  434. if (background) step.background = background;
  435. const icon = this._readStepAttr(item, container, ['data-step-icon', 'data-layer-icon', 'data-icon']);
  436. if (icon) step.icon = icon;
  437. const theme = this._readStepAttr(item, container, ['data-step-theme', 'data-layer-theme', 'data-theme']);
  438. if (theme) step.theme = theme;
  439. const width = this._readStepAttr(item, container, ['data-step-width', 'data-layer-width', 'data-width']);
  440. const height = this._readStepAttr(item, container, ['data-step-height', 'data-layer-height', 'data-height']);
  441. const iwidth = this._readStepAttr(item, container, ['data-step-iwidth', 'data-layer-iwidth', 'data-iwidth']);
  442. const iheight = this._readStepAttr(item, container, ['data-step-iheight', 'data-layer-iheight', 'data-iheight']);
  443. const w = this._parseStepSizeAttr(width);
  444. const h = this._parseStepSizeAttr(height);
  445. const iw = this._parseStepSizeAttr(iwidth);
  446. const ih = this._parseStepSizeAttr(iheight);
  447. if (w != null) step.width = w;
  448. if (h != null) step.height = h;
  449. if (iw != null) step.iwidth = iw;
  450. if (ih != null) step.iheight = ih;
  451. } catch {}
  452. return step;
  453. });
  454. this._flowAutoForm = { enabled: true };
  455. return true;
  456. }
  457. _clearPopup() {
  458. const popup = this.dom && this.dom.popup;
  459. if (!popup) return null;
  460. while (popup.firstChild) popup.removeChild(popup.firstChild);
  461. return popup;
  462. }
  463. _bindOverlayClick(handler) {
  464. const overlay = this.dom && this.dom.overlay;
  465. if (!overlay) return;
  466. try {
  467. if (overlay._layerOnClick) {
  468. overlay.removeEventListener('click', overlay._layerOnClick);
  469. }
  470. } catch {}
  471. overlay._layerOnClick = null;
  472. if (!handler) return;
  473. overlay._layerOnClick = handler;
  474. overlay.addEventListener('click', handler);
  475. }
  476. _mountOverlay() {
  477. const overlay = this.dom && this.dom.overlay;
  478. if (!overlay) return;
  479. // Avoid first-open overlay "flash": wait for CSS before inserting into DOM,
  480. // then show on a clean frame so opacity transitions are smooth.
  481. const ready = this._cssReady && typeof this._cssReady.then === 'function' ? this._cssReady : Promise.resolve();
  482. ready.then(() => {
  483. try { overlay.style.visibility = ''; } catch {}
  484. if (!overlay.parentNode) {
  485. document.body.appendChild(overlay);
  486. }
  487. // Double-rAF gives the browser a chance to apply styles before animating.
  488. requestAnimationFrame(() => {
  489. requestAnimationFrame(() => {
  490. overlay.classList.add('show');
  491. this._didOpen();
  492. });
  493. });
  494. });
  495. }
  496. _applyPopupBasics(options, { forceBackground = false } = {}) {
  497. this._applyPopupSize(options);
  498. this._applyPopupTheme(options);
  499. this._applyBackgroundForOptions(options, { force: forceBackground });
  500. }
  501. _buildActions({ flow = false } = {}) {
  502. this.dom.actions = el('div', `${PREFIX}actions`);
  503. this.dom.popup.appendChild(this.dom.actions);
  504. if (flow) {
  505. this._updateFlowActions();
  506. return;
  507. }
  508. // Cancel Button
  509. if (this.params.showCancelButton) {
  510. this.dom.cancelBtn = el('button', `${PREFIX}button ${PREFIX}cancel`, '');
  511. this._setButtonContent(this.dom.cancelBtn, this.params.cancelButtonText);
  512. this.dom.cancelBtn.onclick = () => this._handleCancel();
  513. this.dom.actions.appendChild(this.dom.cancelBtn);
  514. }
  515. // Confirm Button
  516. this.dom.confirmBtn = el('button', `${PREFIX}button ${PREFIX}confirm`, '');
  517. this._setButtonContent(this.dom.confirmBtn, this.params.confirmButtonText);
  518. this.dom.confirmBtn.onclick = () => this._handleConfirm();
  519. this.dom.actions.appendChild(this.dom.confirmBtn);
  520. }
  521. _render(meta = null) {
  522. this._destroySvgAniIcon();
  523. // Remove existing if any (but first, try to restore any mounted DOM from the previous instance)
  524. const existing = document.querySelector(`.${PREFIX}overlay`);
  525. const wantReplace = !!(this.params && this.params.replace);
  526. this._isReplace = false;
  527. if (existing && wantReplace) {
  528. try {
  529. const prev = existing._layerInstance;
  530. if (prev && typeof prev._forceDestroy === 'function') prev._forceDestroy('replace');
  531. } catch {}
  532. try {
  533. if (existing._layerCloseTimer) {
  534. clearTimeout(existing._layerCloseTimer);
  535. existing._layerCloseTimer = null;
  536. }
  537. } catch {}
  538. try {
  539. if (existing._layerOnClick) {
  540. existing.removeEventListener('click', existing._layerOnClick);
  541. existing._layerOnClick = null;
  542. }
  543. } catch {}
  544. try {
  545. while (existing.firstChild) existing.removeChild(existing.firstChild);
  546. } catch {}
  547. try {
  548. existing.style.visibility = '';
  549. existing.classList.add('show');
  550. // Reset any inline fade state from the previous close
  551. existing.style.transition = 'none';
  552. existing.style.opacity = '1';
  553. requestAnimationFrame(() => {
  554. try { existing.style.transition = ''; } catch {}
  555. });
  556. } catch {}
  557. this.dom.overlay = existing;
  558. this.dom.overlay._layerInstance = this;
  559. this._isReplace = true;
  560. } else {
  561. if (existing) {
  562. try {
  563. const prev = existing._layerInstance;
  564. if (prev && typeof prev._forceDestroy === 'function') prev._forceDestroy('replace');
  565. } catch {}
  566. try { existing.remove(); } catch {}
  567. }
  568. // Create Overlay
  569. this.dom.overlay = el('div', `${PREFIX}overlay`);
  570. this.dom.overlay._layerInstance = this;
  571. }
  572. // Create Popup
  573. this.dom.popup = el('div', `${PREFIX}popup`);
  574. this.dom.overlay.appendChild(this.dom.popup);
  575. this._applyPopupBasics(this.params, { forceBackground: true });
  576. // Flow mode: pre-mount all steps and switch by hide/show (DOM continuity, less jitter)
  577. if (meta && meta.flow) {
  578. this._renderFlowUI();
  579. return;
  580. }
  581. // Icon
  582. if (this.params.icon) {
  583. this.dom.icon = this._createIcon(this.params.icon);
  584. this.dom.popup.appendChild(this.dom.icon);
  585. }
  586. // Title
  587. if (this.params.title) {
  588. this.dom.title = el('h2', `${PREFIX}title`, this.params.title);
  589. this.dom.popup.appendChild(this.dom.title);
  590. }
  591. // Content (Text / HTML / Element)
  592. if (this.params.text || this.params.html || this.params.content || this.params.dom) {
  593. this.dom.content = el('div', `${PREFIX}content`);
  594. // DOM content (preferred: dom, backward: content)
  595. const domSpec = this._normalizeDomSpec(this.params);
  596. if (domSpec) {
  597. this._mountDomContent(domSpec);
  598. } else if (this.params.html) {
  599. this.dom.content.innerHTML = this.params.html;
  600. } else {
  601. this.dom.content.textContent = this.params.text;
  602. }
  603. this.dom.popup.appendChild(this.dom.content);
  604. }
  605. // Actions
  606. this._buildActions();
  607. // Event Listeners
  608. if (this.params.closeOnClickOutside) {
  609. this._bindOverlayClick((e) => {
  610. if (e.target === this.dom.overlay) this._close(null); // Dismiss
  611. });
  612. } else {
  613. this._bindOverlayClick(null);
  614. }
  615. this._mountOverlay();
  616. }
  617. _renderFlowUI() {
  618. this._destroySvgAniIcon();
  619. // Icon/title/content/actions are stable; steps are pre-mounted and toggled.
  620. const popup = this.dom.popup;
  621. if (!popup) return;
  622. // Clear popup
  623. this._clearPopup();
  624. this._applyPopupBasics(this.params, { forceBackground: true });
  625. // Icon (in flow: suppressed by default unless question or summary)
  626. this.dom.icon = null;
  627. if (this.params.icon) {
  628. this.dom.icon = this._createIcon(this.params.icon);
  629. popup.appendChild(this.dom.icon);
  630. }
  631. // Title (always present for flow)
  632. this.dom.title = el('h2', `${PREFIX}title`, this.params.title || '');
  633. popup.appendChild(this.dom.title);
  634. // Content container
  635. this.dom.content = el('div', `${PREFIX}content`);
  636. // In flow, stretch content so slide distance is visible.
  637. this.dom.content.style.alignSelf = 'stretch';
  638. this.dom.content.style.width = '100%';
  639. // Stack container: keep panes absolute so we can cross-fade without layout thrash
  640. this.dom.stepStack = el('div', `${PREFIX}step-stack`);
  641. this.dom.stepStack.style.position = 'relative';
  642. this.dom.stepStack.style.width = '100%';
  643. this.dom.stepPanes = [];
  644. this._flowMountedList = [];
  645. const steps = this._flowResolved || (this._flowSteps || []).map((_, i) => this._getFlowStepOptions(i));
  646. steps.forEach((opt, i) => {
  647. const pane = el('div', `${PREFIX}step-pane`);
  648. pane.style.width = '100%';
  649. pane.style.boxSizing = 'border-box';
  650. pane.style.display = (i === this._flowIndex) ? '' : 'none';
  651. // Fill pane: dom/html/text
  652. const domSpec = this._normalizeDomSpec(opt);
  653. if (domSpec) {
  654. this._mountDomContentInto(pane, domSpec, { collectFlow: true });
  655. } else if (opt.html) {
  656. pane.innerHTML = opt.html;
  657. } else if (opt.text) {
  658. pane.textContent = opt.text;
  659. }
  660. this.dom.stepStack.appendChild(pane);
  661. this.dom.stepPanes.push(pane);
  662. });
  663. this.dom.content.appendChild(this.dom.stepStack);
  664. popup.appendChild(this.dom.content);
  665. // Actions
  666. this._buildActions({ flow: true });
  667. // Event Listeners
  668. if (this.params.closeOnClickOutside) {
  669. this._bindOverlayClick((e) => {
  670. if (e.target === this.dom.overlay) this._close(null, 'backdrop');
  671. });
  672. } else {
  673. this._bindOverlayClick(null);
  674. }
  675. this._mountOverlay();
  676. }
  677. _updateFlowActions() {
  678. const actions = this.dom && this.dom.actions;
  679. if (!actions) return;
  680. while (actions.firstChild) actions.removeChild(actions.firstChild);
  681. this.dom.cancelBtn = null;
  682. const total = (this._flowSteps && this._flowSteps.length) ? this._flowSteps.length : 0;
  683. const isLast = total > 0 ? (this._flowIndex >= (total - 1)) : true;
  684. if (this.params.showCancelButton) {
  685. const prevIcon = (this._flowIndex > 0) ? this.params.prevIcon : null;
  686. this.dom.cancelBtn = el('button', `${PREFIX}button ${PREFIX}cancel`, '');
  687. this._setButtonContent(this.dom.cancelBtn, this.params.cancelButtonText, prevIcon, 'start');
  688. this.dom.cancelBtn.onclick = () => this._handleCancel();
  689. actions.appendChild(this.dom.cancelBtn);
  690. }
  691. const nextIcon = (!isLast) ? this.params.nextIcon : null;
  692. this.dom.confirmBtn = el('button', `${PREFIX}button ${PREFIX}confirm`, '');
  693. this._setButtonContent(this.dom.confirmBtn, this.params.confirmButtonText, nextIcon, 'end');
  694. this.dom.confirmBtn.onclick = () => this._handleConfirm();
  695. actions.appendChild(this.dom.confirmBtn);
  696. }
  697. _createIcon(type) {
  698. const rawType = String(type || '').trim();
  699. const icon = el('div', `${PREFIX}icon ${rawType}`);
  700. const applyIconBoxSize = () => {
  701. if (!this.params) return;
  702. const w = this._normalizeSizeValue(this.params.iwidth);
  703. const h = this._normalizeSizeValue(this.params.iheight);
  704. if (w) icon.style.width = w;
  705. if (h) icon.style.height = h;
  706. };
  707. const applyIconSize = (mode) => {
  708. if (!(this.params && this.params.iconSize)) return;
  709. try {
  710. const s = String(this.params.iconSize).trim();
  711. if (!s) return;
  712. // For SweetAlert2-style success icon, scale via font-size so all `em`-based parts remain proportional.
  713. if (mode === 'font') {
  714. const m = s.match(/^(-?\d*\.?\d+)\s*(px|em|rem)$/i);
  715. if (m) {
  716. const n = parseFloat(m[1]);
  717. const unit = m[2];
  718. if (Number.isFinite(n) && n > 0) {
  719. icon.style.fontSize = (n / 5) + unit; // icon is 5em wide/tall
  720. return;
  721. }
  722. }
  723. }
  724. // Fallback: directly size the box (works great for SVG icons)
  725. icon.style.width = s;
  726. icon.style.height = s;
  727. } catch {}
  728. };
  729. const appendRingParts = () => {
  730. // Use the same "success-like" ring parts for every built-in icon
  731. icon.appendChild(el('div', `${PREFIX}success-circular-line-left`));
  732. icon.appendChild(el('div', `${PREFIX}success-ring`));
  733. icon.appendChild(el('div', `${PREFIX}success-fix`));
  734. icon.appendChild(el('div', `${PREFIX}success-circular-line-right`));
  735. };
  736. const createInnerMarkSvg = () => {
  737. const svg = svgEl('svg');
  738. svg.setAttribute('viewBox', '0 0 80 80');
  739. svg.setAttribute('aria-hidden', 'true');
  740. svg.setAttribute('focusable', 'false');
  741. return svg;
  742. };
  743. const addMarkPath = (svg, d, extraClass) => {
  744. const p = svgEl('path');
  745. p.setAttribute('d', d);
  746. p.setAttribute('class', `${PREFIX}svg-mark ${PREFIX}svg-draw${extraClass ? ' ' + extraClass : ''}`);
  747. p.setAttribute('stroke', 'currentColor');
  748. svg.appendChild(p);
  749. return p;
  750. };
  751. const addDot = (svg, cx, cy) => {
  752. const dot = svgEl('circle');
  753. dot.setAttribute('class', `${PREFIX}svg-dot`);
  754. dot.setAttribute('cx', String(cx));
  755. dot.setAttribute('cy', String(cy));
  756. dot.setAttribute('r', '3.2');
  757. dot.setAttribute('fill', 'currentColor');
  758. svg.appendChild(dot);
  759. return dot;
  760. };
  761. const appendBuiltInInnerMark = (svg) => {
  762. if (rawType === 'error') {
  763. addMarkPath(svg, 'M28 28 L52 52', `${PREFIX}svg-error-left`);
  764. addMarkPath(svg, 'M52 28 L28 52', `${PREFIX}svg-error-right`);
  765. } else if (rawType === 'warning') {
  766. addMarkPath(svg, 'M40 20 L40 46', `${PREFIX}svg-warning-line`);
  767. addDot(svg, 40, 58);
  768. } else if (rawType === 'info') {
  769. addMarkPath(svg, 'M40 34 L40 56', `${PREFIX}svg-info-line`);
  770. addDot(svg, 40, 25);
  771. } else if (rawType === 'question') {
  772. addMarkPath(svg, '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`);
  773. addDot(svg, 42, 61);
  774. }
  775. };
  776. if (isSvgAniIcon(rawType)) {
  777. // SvgAni animation icon: svg:<name>
  778. const name = getSvgAniIconName(rawType);
  779. icon.className = `${PREFIX}icon ${PREFIX}icon-svgAni`;
  780. icon.dataset.svgani = name;
  781. const container = el('div', `${PREFIX}svgAni`);
  782. icon.appendChild(container);
  783. applyIconSize('box');
  784. applyIconBoxSize();
  785. scheduleSvgAniPrefetch();
  786. this._initSvgAniIcon(icon, name);
  787. return icon;
  788. }
  789. if (rawType === 'success') {
  790. // SweetAlert2-compatible DOM structure (circle + tick) for exact style parity
  791. // <div class="...success-circular-line-left"></div>
  792. // <div class="...success-mark"><span class="...success-line-tip"></span><span class="...success-line-long"></span></div>
  793. // <div class="...success-ring"></div>
  794. // <div class="...success-fix"></div>
  795. // <div class="...success-circular-line-right"></div>
  796. icon.appendChild(el('div', `${PREFIX}success-circular-line-left`));
  797. const mark = el('div', `${PREFIX}success-mark`);
  798. mark.appendChild(el('span', `${PREFIX}success-line-tip`));
  799. mark.appendChild(el('span', `${PREFIX}success-line-long`));
  800. icon.appendChild(mark);
  801. icon.appendChild(el('div', `${PREFIX}success-ring`));
  802. icon.appendChild(el('div', `${PREFIX}success-fix`));
  803. icon.appendChild(el('div', `${PREFIX}success-circular-line-right`));
  804. applyIconSize('font');
  805. return icon;
  806. }
  807. if (rawType === 'error' || rawType === 'warning' || rawType === 'info' || rawType === 'question') {
  808. // Use the same "success-like" ring parts for every icon
  809. appendRingParts();
  810. applyIconSize('font');
  811. applyIconBoxSize();
  812. // SVG only draws the inner symbol (no SVG ring)
  813. const svg = createInnerMarkSvg();
  814. appendBuiltInInnerMark(svg);
  815. icon.appendChild(svg);
  816. return icon;
  817. }
  818. // Default to SVG icons for other/custom types
  819. applyIconSize('box');
  820. applyIconBoxSize();
  821. const svg = createInnerMarkSvg();
  822. const ring = svgEl('circle');
  823. ring.setAttribute('class', `${PREFIX}svg-ring ${PREFIX}svg-draw`);
  824. ring.setAttribute('cx', '40');
  825. ring.setAttribute('cy', '40');
  826. ring.setAttribute('r', '34');
  827. ring.setAttribute('stroke', 'currentColor');
  828. svg.appendChild(ring);
  829. // For custom types, we draw ring only by default (no inner mark).
  830. icon.appendChild(svg);
  831. return icon;
  832. }
  833. _normalizeSizeValue(v) {
  834. if (v === undefined || v === null) return null;
  835. if (typeof v === 'number' && Number.isFinite(v)) return v + 'px';
  836. if (typeof v === 'string') {
  837. const s = v.trim();
  838. return s ? s : null;
  839. }
  840. return null;
  841. }
  842. _applyPopupSize(options) {
  843. const popup = this.dom && this.dom.popup;
  844. if (!popup) return;
  845. const w = this._normalizeSizeValue(options && options.width);
  846. const h = this._normalizeSizeValue(options && options.height);
  847. if (!w && !h) {
  848. popup.style.width = '';
  849. popup.style.height = '';
  850. popup.style.maxWidth = '';
  851. popup.style.overflow = '';
  852. return;
  853. }
  854. if (w) {
  855. popup.style.width = w;
  856. // If width is explicitly set, remove default CSS max-width clamp.
  857. popup.style.maxWidth = 'none';
  858. } else {
  859. popup.style.width = '';
  860. popup.style.maxWidth = '';
  861. }
  862. if (h) popup.style.height = h;
  863. else popup.style.height = '';
  864. popup.style.overflow = 'auto';
  865. }
  866. _applyPopupTheme(options) {
  867. const popup = this.dom && this.dom.popup;
  868. if (!popup) return;
  869. const theme = normalizeTheme(options && options.theme);
  870. try {
  871. popup.classList.remove(`${PREFIX}theme-auto`, `${PREFIX}theme-light`, `${PREFIX}theme-dark`);
  872. } catch {}
  873. try {
  874. popup.classList.add(`${PREFIX}theme-${theme}`);
  875. } catch {}
  876. }
  877. _normalizeBackgroundSpec(raw) {
  878. if (!raw || typeof raw !== 'string') return null;
  879. const s = raw.trim();
  880. if (!s) return null;
  881. if (s.startsWith(BG_SVG_PREFIX) && s.endsWith(')')) {
  882. const name = normalizeSvgAniName(s.slice(BG_SVG_PREFIX.length, -1));
  883. if (!name) return null;
  884. return { type: 'svg', name, key: `svg:${name}` };
  885. }
  886. if (s.startsWith(SVGANI_PREFIX)) {
  887. const name = normalizeSvgAniName(s);
  888. if (!name) return null;
  889. return { type: 'svg', name, key: `svg:${name}` };
  890. }
  891. if (/^url\(/i.test(s)) {
  892. return { type: 'image', value: s, key: s };
  893. }
  894. if (s.startsWith(BG_CSS_PREFIX) && s.endsWith(')')) {
  895. const css = s.slice(BG_CSS_PREFIX.length, -1).trim();
  896. if (!css) return null;
  897. return { type: 'css', css, key: `css:${css}` };
  898. }
  899. // Fallback: treat as raw css string
  900. return { type: 'css', css: s, key: `css:${s}` };
  901. }
  902. _isSameBackgroundSpec(a, b) {
  903. if (!a && !b) return true;
  904. if (!a || !b) return false;
  905. return a.key === b.key;
  906. }
  907. _insertBackgroundEl(bgEl) {
  908. const popup = this.dom && this.dom.popup;
  909. if (!popup || !bgEl) return;
  910. if (popup.firstChild) popup.insertBefore(bgEl, popup.firstChild);
  911. else popup.appendChild(bgEl);
  912. }
  913. _createBackgroundEl(spec) {
  914. const bg = el('div', `${PREFIX}bg`);
  915. bg.dataset.bgKey = spec.key;
  916. if (spec.type === 'image') {
  917. bg.style.backgroundImage = spec.value;
  918. } else if (spec.type === 'css') {
  919. try { bg.style.cssText += ';' + spec.css; } catch {}
  920. } else if (spec.type === 'svg') {
  921. const container = el('div', `${PREFIX}svgAni`);
  922. bg.appendChild(container);
  923. this._initSvgAniBackground(bg, spec.name);
  924. }
  925. return bg;
  926. }
  927. _applyBackgroundForOptions(options, { force = false } = {}) {
  928. const popup = this.dom && this.dom.popup;
  929. if (!popup) return;
  930. const spec = this._normalizeBackgroundSpec(options && options.background);
  931. if (!spec) {
  932. if (this.dom.background) {
  933. this._destroySvgAniBackground(this.dom.background);
  934. try { this.dom.background.remove(); } catch {}
  935. }
  936. this.dom.background = null;
  937. this._backgroundSpec = null;
  938. popup.style.background = '';
  939. return;
  940. }
  941. if (!force && this._isSameBackgroundSpec(this._backgroundSpec, spec)) return;
  942. if (this.dom.background) {
  943. this._destroySvgAniBackground(this.dom.background);
  944. try { this.dom.background.remove(); } catch {}
  945. }
  946. const bgEl = this._createBackgroundEl(spec);
  947. this.dom.background = bgEl;
  948. this._backgroundSpec = spec;
  949. popup.style.background = 'transparent';
  950. this._insertBackgroundEl(bgEl);
  951. }
  952. async _transitionBackground(nextSpec, direction) {
  953. const popup = this.dom && this.dom.popup;
  954. if (!popup) return;
  955. if (this._isSameBackgroundSpec(this._backgroundSpec, nextSpec)) return;
  956. const fromEl = this.dom.background;
  957. let toEl = null;
  958. if (nextSpec) {
  959. toEl = this._createBackgroundEl(nextSpec);
  960. this._insertBackgroundEl(toEl);
  961. popup.style.background = 'transparent';
  962. } else {
  963. popup.style.background = '';
  964. }
  965. const isNext = direction !== 'prev';
  966. const enterFrom = isNext ? 100 : -100;
  967. const exitTo = isNext ? -100 : 100;
  968. const duration = 320;
  969. if (toEl) {
  970. toEl.style.transform = `translateX(${enterFrom}%)`;
  971. toEl.style.opacity = '0.2';
  972. }
  973. if (fromEl) {
  974. fromEl.style.transform = 'translateX(0%)';
  975. fromEl.style.opacity = '1';
  976. }
  977. let fromAnim = null;
  978. let toAnim = null;
  979. try {
  980. if (fromEl && fromEl.animate) {
  981. fromAnim = fromEl.animate(
  982. [
  983. { transform: 'translateX(0%)', opacity: 1 },
  984. { transform: `translateX(${exitTo}%)`, opacity: 0.1 }
  985. ],
  986. { duration, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' }
  987. );
  988. }
  989. } catch {}
  990. try {
  991. if (toEl && toEl.animate) {
  992. toAnim = toEl.animate(
  993. [
  994. { transform: `translateX(${enterFrom}%)`, opacity: 0.2 },
  995. { transform: 'translateX(0%)', opacity: 1 }
  996. ],
  997. { duration, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' }
  998. );
  999. }
  1000. } catch {}
  1001. try {
  1002. await Promise.all([
  1003. fromAnim && fromAnim.finished ? fromAnim.finished.catch(() => {}) : Promise.resolve(),
  1004. toAnim && toAnim.finished ? toAnim.finished.catch(() => {}) : Promise.resolve()
  1005. ]);
  1006. } catch {}
  1007. if (fromEl) {
  1008. this._destroySvgAniBackground(fromEl);
  1009. try { fromEl.remove(); } catch {}
  1010. }
  1011. if (toEl) {
  1012. toEl.style.transform = '';
  1013. toEl.style.opacity = '';
  1014. }
  1015. this.dom.background = toEl;
  1016. this._backgroundSpec = nextSpec || null;
  1017. }
  1018. _destroySvgAniBackground(bgEl) {
  1019. if (!bgEl) return;
  1020. const inst = bgEl._svgAniInstance;
  1021. if (inst && typeof inst.destroy === 'function') {
  1022. try { inst.destroy(); } catch {}
  1023. }
  1024. try { bgEl._svgAniInstance = null; } catch {}
  1025. }
  1026. _initSvgAniBackground(bgEl, name) {
  1027. if (!bgEl) return;
  1028. const container = bgEl.querySelector(`.${PREFIX}svgAni`);
  1029. if (!container) return;
  1030. const cleanName = normalizeSvgAniName(name);
  1031. if (!cleanName) return;
  1032. const url = resolveSvgAniJsonUrl(cleanName);
  1033. if (!url) return;
  1034. const showError = (msg) => {
  1035. try {
  1036. container.textContent = String(msg || '');
  1037. container.classList.add(`${PREFIX}svgAni-error`);
  1038. } catch {}
  1039. };
  1040. const loadData = () => new Promise((resolve, reject) => {
  1041. try {
  1042. if (typeof fetch === 'function') {
  1043. fetch(url).then((res) => {
  1044. if (!res || !res.ok) throw new Error('fetch failed');
  1045. return res.json();
  1046. }).then(resolve).catch(reject);
  1047. return;
  1048. }
  1049. const xhr = new XMLHttpRequest();
  1050. xhr.open('GET', url, true);
  1051. xhr.responseType = 'json';
  1052. xhr.onload = () => {
  1053. if (xhr.status >= 200 && xhr.status < 300) {
  1054. const data = xhr.response || (xhr.responseText ? JSON.parse(xhr.responseText) : null);
  1055. resolve(data);
  1056. } else {
  1057. reject(new Error('xhr failed'));
  1058. }
  1059. };
  1060. xhr.onerror = () => reject(new Error('xhr failed'));
  1061. xhr.send();
  1062. } catch (e) {
  1063. reject(e);
  1064. }
  1065. });
  1066. const boot = async () => {
  1067. const svgAniLib = await ensureSvgAniLib();
  1068. if (!svgAniLib) {
  1069. showError('SvgAni lib not available');
  1070. return;
  1071. }
  1072. try {
  1073. const data = await loadData();
  1074. if (!data) throw new Error('empty json');
  1075. try { container.textContent = ''; } catch {}
  1076. const anim = svgAniLib.loadAnimation({
  1077. container,
  1078. renderer: 'svg',
  1079. loop: true,
  1080. autoplay: true,
  1081. animationData: data,
  1082. // Fill background container even if aspect ratio differs
  1083. rendererSettings: { preserveAspectRatio: 'xMidYMid slice' }
  1084. });
  1085. bgEl._svgAniInstance = anim;
  1086. } catch (e) {
  1087. showError('SvgAni load failed');
  1088. }
  1089. };
  1090. boot();
  1091. }
  1092. _adjustRingBackgroundColor() {
  1093. try {
  1094. const icon = this.dom && this.dom.icon;
  1095. const popup = this.dom && this.dom.popup;
  1096. if (!icon || !popup) return;
  1097. const bg = getComputedStyle(popup).backgroundColor;
  1098. const parts = icon.querySelectorAll(RING_BG_PARTS_SELECTOR);
  1099. parts.forEach((el) => {
  1100. try { el.style.backgroundColor = bg; } catch {}
  1101. });
  1102. } catch {}
  1103. }
  1104. _didOpen() {
  1105. // Keyboard close (ESC)
  1106. if (this.params.closeOnEsc) {
  1107. this._onKeydown = (e) => {
  1108. if (!e) return;
  1109. if (e.key === 'Escape') this._close(null, 'esc');
  1110. };
  1111. document.addEventListener('keydown', this._onKeydown);
  1112. }
  1113. // Keep the "success-like" ring perfectly blended with popup bg
  1114. this._adjustRingBackgroundColor();
  1115. // Popup animation (optional)
  1116. if (this.params.popupAnimation) {
  1117. if (this.dom.popup) {
  1118. // Use WAAPI directly to guarantee the slide+fade effect is visible,
  1119. // independent from xjs.animate implementation details.
  1120. try {
  1121. const popup = this.dom.popup;
  1122. try { popup.classList.add(`${PREFIX}popup-anim-slide`); } catch {}
  1123. const rect = popup.getBoundingClientRect();
  1124. // Default entrance: from above center by "more than half" of popup height.
  1125. // Clamp to viewport so very tall popups don't start far off-screen.
  1126. const vh = (typeof window !== 'undefined' && window && window.innerHeight) ? window.innerHeight : rect.height;
  1127. const baseH = Math.min(rect.height, vh);
  1128. const y0 = -Math.round(Math.max(18, baseH * 0.75));
  1129. // Disable CSS transform transition so it won't fight with WAAPI.
  1130. popup.style.transition = 'none';
  1131. popup.style.willChange = 'transform, opacity';
  1132. // If WAAPI is available, prefer it (most consistent).
  1133. if (popup.animate) {
  1134. const anim = popup.animate(
  1135. [
  1136. { transform: `translateY(${y0}px) scale(0.92)`, opacity: 0 },
  1137. { transform: 'translateY(0px) scale(1)', opacity: 1 }
  1138. ],
  1139. {
  1140. duration: 220,
  1141. easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)',
  1142. fill: 'forwards'
  1143. }
  1144. );
  1145. anim.finished
  1146. .catch(() => {})
  1147. .finally(() => {
  1148. try { popup.style.willChange = ''; } catch {}
  1149. });
  1150. } else {
  1151. // Fallback: try xjs.animate if WAAPI isn't available.
  1152. const X = Layer._getXjs();
  1153. if (X) {
  1154. popup.style.opacity = '0';
  1155. popup.style.transform = `translateY(${y0}px) scale(0.92)`;
  1156. X(popup).animate({
  1157. y: [y0, 0],
  1158. scale: [0.92, 1],
  1159. opacity: [0, 1],
  1160. duration: 220,
  1161. easing: 'ease-out'
  1162. });
  1163. }
  1164. setTimeout(() => {
  1165. try { popup.style.willChange = ''; } catch {}
  1166. }, 260);
  1167. }
  1168. } catch {}
  1169. }
  1170. }
  1171. // When popupAnimation is disabled, use a subtle scale-pop fade-in at current position.
  1172. if (!this.params.popupAnimation && !this._isReplace && this.dom.popup) {
  1173. try {
  1174. const popup = this.dom.popup;
  1175. popup.style.transition = 'none';
  1176. popup.style.willChange = 'transform, opacity';
  1177. if (popup.animate) {
  1178. const anim = popup.animate(
  1179. [
  1180. { transform: 'scale(0.8)', opacity: 0, offset: 0, easing: 'ease-out' },
  1181. { transform: 'scale(1.1)', opacity: 1, offset: 0.67, easing: 'ease-in-out' },
  1182. { transform: 'scale(1)', opacity: 1, offset: 1 }
  1183. ],
  1184. {
  1185. duration: 240,
  1186. fill: 'forwards'
  1187. }
  1188. );
  1189. anim.finished
  1190. .catch(() => {})
  1191. .finally(() => {
  1192. try { popup.style.willChange = ''; } catch {}
  1193. try { popup.style.transition = ''; } catch {}
  1194. try { popup.style.opacity = ''; } catch {}
  1195. try { popup.style.transform = ''; } catch {}
  1196. });
  1197. } else {
  1198. const X = Layer._getXjs();
  1199. if (X) {
  1200. popup.style.opacity = '0';
  1201. popup.style.transform = 'scale(0.8)';
  1202. X(popup).animate({
  1203. scale: [0.8, 1.1],
  1204. opacity: [0, 1],
  1205. duration: 160,
  1206. easing: 'ease-out'
  1207. });
  1208. setTimeout(() => {
  1209. try {
  1210. X(popup).animate({
  1211. scale: [1.1, 1],
  1212. duration: 80,
  1213. easing: 'ease-in-out'
  1214. });
  1215. } catch {}
  1216. }, 160);
  1217. setTimeout(() => {
  1218. try { popup.style.willChange = ''; } catch {}
  1219. try { popup.style.transition = ''; } catch {}
  1220. try { popup.style.opacity = ''; } catch {}
  1221. try { popup.style.transform = ''; } catch {}
  1222. }, 270);
  1223. } else {
  1224. setTimeout(() => {
  1225. try { popup.style.willChange = ''; } catch {}
  1226. try { popup.style.transition = ''; } catch {}
  1227. }, 260);
  1228. }
  1229. }
  1230. } catch {}
  1231. }
  1232. // Replace mode: if popupAnimation is off, do a soft fade+scale to avoid a hard cut.
  1233. if (!this.params.popupAnimation && this._isReplace && this.dom.popup) {
  1234. try {
  1235. const popup = this.dom.popup;
  1236. popup.style.transition = 'none';
  1237. popup.style.opacity = '0';
  1238. popup.style.transform = 'scale(0.98)';
  1239. requestAnimationFrame(() => {
  1240. popup.style.transition = 'opacity 0.22s ease, transform 0.22s ease';
  1241. popup.style.opacity = '1';
  1242. popup.style.transform = 'scale(1)';
  1243. setTimeout(() => {
  1244. try { popup.style.transition = ''; } catch {}
  1245. try { popup.style.opacity = ''; } catch {}
  1246. try { popup.style.transform = ''; } catch {}
  1247. }, 260);
  1248. });
  1249. } catch {}
  1250. }
  1251. // Icon SVG draw animation
  1252. if (this.params.iconAnimation) {
  1253. this._animateIcon();
  1254. }
  1255. // User hook (SweetAlert-ish naming)
  1256. try {
  1257. if (typeof this.params.didOpen === 'function') this.params.didOpen(this.dom.popup);
  1258. } catch {}
  1259. }
  1260. _animateIcon() {
  1261. const icon = this.dom.icon;
  1262. if (!icon) return;
  1263. const type = (this.params && this.params.icon) || '';
  1264. if (isSvgAniIcon(type)) return;
  1265. // Ring animation (same as success) for all built-in icons
  1266. if (RING_TYPES.has(type)) this._adjustRingBackgroundColor();
  1267. try { icon.classList.remove(`${PREFIX}icon-show`); } catch {}
  1268. requestAnimationFrame(() => {
  1269. try { icon.classList.add(`${PREFIX}icon-show`); } catch {}
  1270. });
  1271. // Success tick is CSS-driven; others still draw their SVG mark after the ring starts.
  1272. if (type === 'success') return;
  1273. const X = Layer._getXjs();
  1274. if (!X) return;
  1275. const svg = icon.querySelector('svg');
  1276. if (!svg) return;
  1277. const marks = Array.from(svg.querySelectorAll(`.${PREFIX}svg-mark`));
  1278. const dot = svg.querySelector(`.${PREFIX}svg-dot`);
  1279. // If this is a built-in icon, keep the SweetAlert-like order:
  1280. // ring sweep first (~0.51s), then draw the inner mark.
  1281. const baseDelay = RING_TYPES.has(type) ? 520 : 0;
  1282. if (type === 'error') {
  1283. // Draw order: left-top -> right-bottom, then right-top -> left-bottom
  1284. // NOTE: A tiny delay (like 70ms) looks simultaneous; make it strictly sequential.
  1285. const a = svg.querySelector(`.${PREFIX}svg-error-left`) || marks[0]; // M28 28 L52 52
  1286. const b = svg.querySelector(`.${PREFIX}svg-error-right`) || marks[1]; // M52 28 L28 52
  1287. const dur = 320;
  1288. const gap = 60;
  1289. try { if (a) X(a).draw({ duration: dur, easing: 'ease-out', delay: baseDelay }); } catch {}
  1290. try { if (b) X(b).draw({ duration: dur, easing: 'ease-out', delay: baseDelay + dur + gap }); } catch {}
  1291. } else {
  1292. // warning / info / question (single stroke) or custom SVG symbols
  1293. marks.forEach((m, i) => {
  1294. try { X(m).draw({ duration: 420, easing: 'ease-out', delay: baseDelay + i * 60 }); } catch {}
  1295. });
  1296. }
  1297. if (dot) {
  1298. try {
  1299. dot.style.opacity = '0';
  1300. // Keep dot pop after the ring begins
  1301. const d = baseDelay + 140;
  1302. if (type === 'info') {
  1303. X(dot).animate({ opacity: [0, 1], y: [-8, 0], scale: [0.2, 1], duration: 420, delay: d, easing: { stiffness: 300, damping: 14 } });
  1304. } else {
  1305. X(dot).animate({ opacity: [0, 1], scale: [0.2, 1], duration: 320, delay: d, easing: { stiffness: 320, damping: 18 } });
  1306. }
  1307. } catch {}
  1308. }
  1309. }
  1310. _forceDestroy(reason = 'replace') {
  1311. try { this._destroySvgAniIcon(); } catch {}
  1312. try { this._destroySvgAniBackground(this.dom && this.dom.background); } catch {}
  1313. // Restore mounted DOM (if any) and cleanup listeners; also resolve the promise so it doesn't hang.
  1314. try {
  1315. if (this._flowSteps && this._flowSteps.length) this._unmountFlowMounted();
  1316. else this._unmountDomContent();
  1317. } catch {}
  1318. if (this._onKeydown) {
  1319. try { document.removeEventListener('keydown', this._onKeydown); } catch {}
  1320. this._onKeydown = null;
  1321. }
  1322. try {
  1323. if (this.resolve) {
  1324. this.resolve({ isConfirmed: false, isDenied: false, isDismissed: true, dismiss: reason });
  1325. }
  1326. } catch {}
  1327. }
  1328. _close(isConfirmed, reason) {
  1329. if (this._isClosing) return;
  1330. this._isClosing = true;
  1331. try { this._destroySvgAniIcon(); } catch {}
  1332. try { this._destroySvgAniBackground(this.dom && this.dom.background); } catch {}
  1333. const shouldDelayUnmount = !!(
  1334. (this._mounted && this._mounted.kind === 'move') ||
  1335. (this._flowSteps && this._flowSteps.length && this._flowMountedList && this._flowMountedList.length)
  1336. ) || !this.params.popupAnimation;
  1337. const doUnmount = () => {
  1338. try {
  1339. if (this._flowSteps && this._flowSteps.length) this._unmountFlowMounted();
  1340. else this._unmountDomContent();
  1341. } catch {}
  1342. };
  1343. if (!shouldDelayUnmount) {
  1344. // Restore mounted DOM (moved into popup) before removing overlay
  1345. doUnmount();
  1346. }
  1347. let customClose = false;
  1348. // Soft close for non-popupAnimation cases (avoid abrupt cut)
  1349. if (!this.params.popupAnimation) {
  1350. try {
  1351. const popup = this.dom.popup;
  1352. if (popup) {
  1353. popup.style.transition = 'opacity 0.22s ease';
  1354. popup.style.opacity = '0';
  1355. popup.style.transform = '';
  1356. }
  1357. if (this.dom.overlay) {
  1358. const overlay = this.dom.overlay;
  1359. // Use inline opacity to avoid class-based jumps
  1360. overlay.style.transition = 'opacity 0.22s ease';
  1361. overlay.style.opacity = '1';
  1362. requestAnimationFrame(() => {
  1363. try {
  1364. if (overlay._layerInstance !== this) return;
  1365. overlay.style.opacity = '0';
  1366. } catch {}
  1367. });
  1368. }
  1369. customClose = true;
  1370. } catch {}
  1371. }
  1372. if (!customClose) {
  1373. this.dom.overlay.classList.remove('show');
  1374. }
  1375. try {
  1376. if (this.dom.overlay) {
  1377. const overlay = this.dom.overlay;
  1378. const delay = customClose ? 240 : 300;
  1379. overlay._layerCloseTimer = setTimeout(() => {
  1380. if (shouldDelayUnmount) {
  1381. doUnmount();
  1382. }
  1383. if (overlay._layerInstance !== this) return;
  1384. if (overlay.parentNode) {
  1385. overlay.parentNode.removeChild(overlay);
  1386. }
  1387. }, delay);
  1388. }
  1389. } catch {}
  1390. if (this._onKeydown) {
  1391. try { document.removeEventListener('keydown', this._onKeydown); } catch {}
  1392. this._onKeydown = null;
  1393. }
  1394. try {
  1395. if (typeof this.params.willClose === 'function') this.params.willClose(this.dom.popup);
  1396. } catch {}
  1397. try {
  1398. if (typeof this.params.didClose === 'function') this.params.didClose();
  1399. } catch {}
  1400. const value = (this._flowSteps && this._flowSteps.length) ? (this._flowValues || []) : undefined;
  1401. let data;
  1402. if (this._flowSteps && this._flowSteps.length && this._flowAutoForm && this._flowAutoForm.enabled) {
  1403. const root = (this.dom && (this.dom.stepStack || this.dom.content || this.dom.popup)) || null;
  1404. data = this._collectFormData(root);
  1405. }
  1406. if (isConfirmed === true) {
  1407. const payload = { isConfirmed: true, isDenied: false, isDismissed: false, value };
  1408. if (data !== undefined) payload.data = data;
  1409. this.resolve(payload);
  1410. } else if (isConfirmed === false) {
  1411. const payload = { isConfirmed: false, isDenied: false, isDismissed: true, dismiss: reason || 'cancel', value };
  1412. if (data !== undefined) payload.data = data;
  1413. this.resolve(payload);
  1414. } else {
  1415. const payload = { isConfirmed: false, isDenied: false, isDismissed: true, dismiss: reason || 'backdrop', value };
  1416. if (data !== undefined) payload.data = data;
  1417. this.resolve(payload);
  1418. }
  1419. }
  1420. _assignFormValue(data, name, value, forceArray) {
  1421. if (!data || !name) return;
  1422. let key = name;
  1423. let asArray = !!forceArray;
  1424. if (key.endsWith('[]')) {
  1425. key = key.slice(0, -2);
  1426. asArray = true;
  1427. }
  1428. if (!(key in data)) {
  1429. data[key] = asArray ? [value] : value;
  1430. return;
  1431. }
  1432. if (Array.isArray(data[key])) {
  1433. data[key].push(value);
  1434. return;
  1435. }
  1436. data[key] = [data[key], value];
  1437. }
  1438. _collectFormData(root) {
  1439. const data = {};
  1440. if (!root || !root.querySelectorAll) return data;
  1441. const fields = root.querySelectorAll('input, select, textarea');
  1442. fields.forEach((el) => {
  1443. try {
  1444. if (!el || el.disabled) return;
  1445. const name = (el.getAttribute('name') || '').trim();
  1446. if (!name) return;
  1447. const tag = (el.tagName || '').toLowerCase();
  1448. if (tag === 'select') {
  1449. if (el.multiple) {
  1450. const values = Array.from(el.options || []).filter((o) => o.selected).map((o) => o.value);
  1451. values.forEach((v) => this._assignFormValue(data, name, v, true));
  1452. } else {
  1453. this._assignFormValue(data, name, el.value, false);
  1454. }
  1455. return;
  1456. }
  1457. if (tag === 'textarea') {
  1458. this._assignFormValue(data, name, el.value, false);
  1459. return;
  1460. }
  1461. const type = (el.getAttribute('type') || 'text').toLowerCase();
  1462. if (type === 'radio') {
  1463. if (el.checked) this._assignFormValue(data, name, el.value, false);
  1464. return;
  1465. }
  1466. if (type === 'checkbox') {
  1467. if (el.checked) this._assignFormValue(data, name, el.value, true);
  1468. return;
  1469. }
  1470. if (type === 'file') {
  1471. const files = el.files ? Array.from(el.files) : [];
  1472. this._assignFormValue(data, name, files, true);
  1473. return;
  1474. }
  1475. this._assignFormValue(data, name, el.value, false);
  1476. } catch {}
  1477. });
  1478. return data;
  1479. }
  1480. _normalizeDomSpec(params) {
  1481. // Preferred: params.dom (selector/Element/template)
  1482. // Backward: params.content (selector/Element) OR advanced object { dom, mode, clone }
  1483. const p = params || {};
  1484. let dom = p.dom;
  1485. let mode = p.domMode || 'move';
  1486. if (dom == null && p.content != null) {
  1487. if (typeof p.content === 'object' && !(p.content instanceof Element)) {
  1488. if (p.content && (p.content.dom != null || p.content.selector != null)) {
  1489. dom = (p.content.dom != null) ? p.content.dom : p.content.selector;
  1490. if (p.content.mode) mode = p.content.mode;
  1491. if (p.content.clone === true) mode = 'clone';
  1492. }
  1493. } else {
  1494. dom = p.content;
  1495. }
  1496. }
  1497. if (dom == null) return null;
  1498. return { dom, mode };
  1499. }
  1500. _mountDomContentInto(target, domSpec, opts = null) {
  1501. // Like _mountDomContent, but mounts into the provided container.
  1502. const collectFlow = !!(opts && opts.collectFlow);
  1503. const originalContent = this.dom.content;
  1504. // Temporarily redirect this.dom.content for reuse of internal logic.
  1505. try { this.dom.content = target; } catch {}
  1506. try {
  1507. const before = this._mounted;
  1508. this._mountDomContent(domSpec);
  1509. const rec = this._mounted;
  1510. // If we mounted in move-mode, _mounted holds record; detach it from single-mode tracking.
  1511. if (collectFlow && rec && rec.kind === 'move') {
  1512. this._flowMountedList.push(rec);
  1513. this._mounted = before; // restore previous single record (usually null)
  1514. }
  1515. } finally {
  1516. try { this.dom.content = originalContent; } catch {}
  1517. }
  1518. }
  1519. _unmountFlowMounted() {
  1520. // Restore all moved DOM nodes for flow steps
  1521. const list = Array.isArray(this._flowMountedList) ? this._flowMountedList : [];
  1522. this._flowMountedList = [];
  1523. list.forEach((m) => {
  1524. try {
  1525. if (!m || m.kind !== 'move') return;
  1526. // Reuse single unmount logic by swapping _mounted
  1527. const prev = this._mounted;
  1528. this._mounted = m;
  1529. this._unmountDomContent();
  1530. this._mounted = prev;
  1531. } catch {}
  1532. });
  1533. }
  1534. _mountDomContent(domSpec) {
  1535. try {
  1536. if (!this.dom.content) return;
  1537. this._unmountDomContent(); // ensure only one mount at a time
  1538. const forceVisible = (el) => {
  1539. if (!el) return { prevHidden: false, prevInlineDisplay: '' };
  1540. const prevHidden = !!el.hidden;
  1541. const prevInlineDisplay = (el.style && typeof el.style.display === 'string') ? el.style.display : '';
  1542. try { el.hidden = false; } catch {}
  1543. try {
  1544. const cs = (typeof getComputedStyle === 'function') ? getComputedStyle(el) : null;
  1545. const display = cs ? String(cs.display || '') : '';
  1546. // If element is hidden via CSS (e.g. .hidden-dom{display:none}),
  1547. // add an inline override so it becomes visible inside the popup.
  1548. if (display === 'none') el.style.display = 'block';
  1549. else if (el.style && el.style.display === 'none') el.style.display = 'block';
  1550. } catch {}
  1551. return { prevHidden, prevInlineDisplay };
  1552. };
  1553. let node = domSpec.dom;
  1554. if (typeof node === 'string') node = document.querySelector(node);
  1555. if (!node) return;
  1556. // <template> support: always clone template content
  1557. if (typeof HTMLTemplateElement !== 'undefined' && node instanceof HTMLTemplateElement) {
  1558. const frag = node.content.cloneNode(true);
  1559. this.dom.content.appendChild(frag);
  1560. this._mounted = { kind: 'template' };
  1561. return;
  1562. }
  1563. if (!(node instanceof Element)) return;
  1564. if (domSpec.mode === 'clone') {
  1565. const clone = node.cloneNode(true);
  1566. // If original is hidden (via attr or CSS), the clone may inherit; force show it in popup.
  1567. try { clone.hidden = false; } catch {}
  1568. try {
  1569. const cs = (typeof getComputedStyle === 'function') ? getComputedStyle(node) : null;
  1570. const display = cs ? String(cs.display || '') : '';
  1571. if (display === 'none') clone.style.display = 'block';
  1572. } catch {}
  1573. this.dom.content.appendChild(clone);
  1574. this._mounted = { kind: 'clone' };
  1575. return;
  1576. }
  1577. // Default: move into popup but restore on close
  1578. const placeholder = document.createComment('layer-dom-placeholder');
  1579. const parent = node.parentNode;
  1580. const nextSibling = node.nextSibling;
  1581. if (!parent) {
  1582. // Detached node: moving would lose it when overlay is removed; clone instead.
  1583. const clone = node.cloneNode(true);
  1584. try { clone.hidden = false; } catch {}
  1585. try { if (clone.style && clone.style.display === 'none') clone.style.display = ''; } catch {}
  1586. this.dom.content.appendChild(clone);
  1587. this._mounted = { kind: 'clone' };
  1588. return;
  1589. }
  1590. try { parent.insertBefore(placeholder, nextSibling); } catch {}
  1591. const { prevHidden, prevInlineDisplay } = forceVisible(node);
  1592. this.dom.content.appendChild(node);
  1593. this._mounted = { kind: 'move', originalEl: node, placeholder, parent, nextSibling, prevHidden, prevInlineDisplay };
  1594. } catch {
  1595. // ignore
  1596. }
  1597. }
  1598. _unmountDomContent() {
  1599. const m = this._mounted;
  1600. if (!m) return;
  1601. this._mounted = null;
  1602. if (m.kind !== 'move') return;
  1603. const node = m.originalEl;
  1604. if (!node) return;
  1605. // Restore hidden/display
  1606. try { node.hidden = !!m.prevHidden; } catch {}
  1607. try {
  1608. if (node.style && typeof m.prevInlineDisplay === 'string') node.style.display = m.prevInlineDisplay;
  1609. } catch {}
  1610. // Move back to original position
  1611. try {
  1612. const ph = m.placeholder;
  1613. if (ph && ph.parentNode) {
  1614. ph.parentNode.insertBefore(node, ph);
  1615. ph.parentNode.removeChild(ph);
  1616. return;
  1617. }
  1618. } catch {}
  1619. // Fallback: append to original parent
  1620. try {
  1621. if (m.parent) m.parent.appendChild(node);
  1622. } catch {}
  1623. }
  1624. _setButtonsDisabled(disabled) {
  1625. try {
  1626. if (this.dom && this.dom.confirmBtn) this.dom.confirmBtn.disabled = !!disabled;
  1627. if (this.dom && this.dom.cancelBtn) this.dom.cancelBtn.disabled = !!disabled;
  1628. } catch {}
  1629. }
  1630. _normalizeButtonIcon(icon) {
  1631. if (!icon) return null;
  1632. try {
  1633. if (icon && icon.nodeType) return icon.cloneNode(true);
  1634. } catch {}
  1635. if (typeof icon === 'string') {
  1636. const s = icon.trim();
  1637. if (!s) return null;
  1638. if (s.indexOf('<') !== -1 && s.indexOf('>') !== -1) {
  1639. const wrap = document.createElement('span');
  1640. wrap.innerHTML = s;
  1641. return wrap;
  1642. }
  1643. return document.createTextNode(s);
  1644. }
  1645. return null;
  1646. }
  1647. _setButtonContent(btn, text, icon, iconPosition) {
  1648. if (!btn) return;
  1649. const labelText = (text === undefined || text === null) ? '' : String(text);
  1650. if (!icon) {
  1651. try { btn.textContent = labelText; } catch {}
  1652. return;
  1653. }
  1654. while (btn.firstChild) btn.removeChild(btn.firstChild);
  1655. const iconNode = this._normalizeButtonIcon(icon);
  1656. const iconWrap = el('span', `${PREFIX}btn-icon`);
  1657. if (iconNode) iconWrap.appendChild(iconNode);
  1658. const label = el('span', `${PREFIX}btn-label`, labelText);
  1659. const atEnd = iconPosition === 'end';
  1660. if (atEnd) {
  1661. btn.appendChild(label);
  1662. btn.appendChild(iconWrap);
  1663. } else {
  1664. btn.appendChild(iconWrap);
  1665. btn.appendChild(label);
  1666. }
  1667. }
  1668. async _handleConfirm() {
  1669. // Flow next / finalize
  1670. if (this._flowSteps && this._flowSteps.length) {
  1671. return this._flowNext();
  1672. }
  1673. // Single popup: support async preConfirm
  1674. const pre = this.params && this.params.preConfirm;
  1675. if (typeof pre === 'function') {
  1676. try {
  1677. this._setButtonsDisabled(true);
  1678. const r = pre(this.dom && this.dom.popup);
  1679. const v = (r && typeof r.then === 'function') ? await r : r;
  1680. if (v === false) {
  1681. this._setButtonsDisabled(false);
  1682. return;
  1683. }
  1684. // store value in non-flow mode as single value
  1685. this._flowValues = [v];
  1686. } catch (e) {
  1687. console.error(e);
  1688. this._setButtonsDisabled(false);
  1689. return;
  1690. }
  1691. }
  1692. this._close(true, 'confirm');
  1693. }
  1694. _handleCancel() {
  1695. if (this._flowSteps && this._flowSteps.length) {
  1696. // default: if not first step, cancel acts as "back"
  1697. if (this._flowIndex > 0) {
  1698. this._flowPrev();
  1699. return;
  1700. }
  1701. }
  1702. this._close(false, 'cancel');
  1703. }
  1704. _getFlowStepOptions(index) {
  1705. const step = (this._flowSteps && this._flowSteps[index]) ? this._flowSteps[index] : {};
  1706. const base = this._flowBase || {};
  1707. const merged = { ...base, ...step };
  1708. // Default button texts for flow
  1709. const isLast = index >= (this._flowSteps.length - 1);
  1710. if (!('confirmButtonText' in step)) merged.confirmButtonText = isLast ? (base.confirmButtonText || 'OK') : 'Next';
  1711. // Show cancel as Back after first step (unless step explicitly overrides)
  1712. if (index > 0) {
  1713. if (!('showCancelButton' in step)) merged.showCancelButton = true;
  1714. if (!('cancelButtonText' in step)) merged.cancelButtonText = 'Back';
  1715. } else {
  1716. // First step default keeps base settings
  1717. if (!('cancelButtonText' in step) && merged.showCancelButton) merged.cancelButtonText = merged.cancelButtonText || 'Cancel';
  1718. }
  1719. // Icon/animation policy for flow:
  1720. // - During steps: no icon/animations by default (avoids distraction + layout jitter)
  1721. // - Allow icon only if step explicitly uses `icon:'question'`, or step is marked as summary.
  1722. const isSummary = !!(step && (step.summary === true || step.isSummary === true));
  1723. const explicitIcon = ('icon' in step) ? step.icon : undefined;
  1724. const baseIcon = ('icon' in base) ? base.icon : undefined;
  1725. const chosenIcon = (explicitIcon !== undefined) ? explicitIcon : baseIcon;
  1726. const isContainerStep = !!(step && step.__fromContainer);
  1727. const allowContainerIcon = isContainerStep && explicitIcon !== undefined;
  1728. if (!isSummary && !isLast) {
  1729. if (allowContainerIcon) {
  1730. merged.icon = chosenIcon;
  1731. } else {
  1732. merged.icon = (chosenIcon === 'question') ? 'question' : null;
  1733. merged.iconAnimation = false;
  1734. }
  1735. } else if (!isSummary && isLast) {
  1736. // last step: still suppress unless summary/question/container icon
  1737. if (allowContainerIcon) {
  1738. merged.icon = chosenIcon;
  1739. } else {
  1740. merged.icon = (chosenIcon === 'question') ? 'question' : null;
  1741. merged.iconAnimation = false;
  1742. }
  1743. } else {
  1744. // summary step: allow icon; animation follows explicit config (default true only if provided elsewhere)
  1745. if (!('icon' in step) && chosenIcon === undefined) merged.icon = null;
  1746. }
  1747. if (allowContainerIcon) {
  1748. if (!('iconAnimation' in step) && !('iconAnimation' in base)) {
  1749. merged.iconAnimation = true;
  1750. }
  1751. }
  1752. return merged;
  1753. }
  1754. async _flowNext() {
  1755. const idx = this._flowIndex;
  1756. const total = this._flowSteps.length;
  1757. const isLast = idx >= (total - 1);
  1758. // preConfirm hook for current step
  1759. const pre = this.params && this.params.preConfirm;
  1760. if (typeof pre === 'function') {
  1761. try {
  1762. this._setButtonsDisabled(true);
  1763. const r = pre(this.dom && this.dom.popup, idx);
  1764. const v = (r && typeof r.then === 'function') ? await r : r;
  1765. if (v === false) {
  1766. this._setButtonsDisabled(false);
  1767. return;
  1768. }
  1769. this._flowValues[idx] = v;
  1770. } catch (e) {
  1771. console.error(e);
  1772. this._setButtonsDisabled(false);
  1773. return;
  1774. }
  1775. }
  1776. if (isLast) {
  1777. this._close(true, 'confirm');
  1778. return;
  1779. }
  1780. this._setButtonsDisabled(false);
  1781. await this._flowGo(idx + 1, 'next');
  1782. }
  1783. async _flowPrev() {
  1784. const idx = this._flowIndex;
  1785. if (idx <= 0) return;
  1786. await this._flowGo(idx - 1, 'prev');
  1787. }
  1788. async _flowGo(index, direction) {
  1789. const next = (this._flowResolved && this._flowResolved[index]) ? this._flowResolved[index] : this._getFlowStepOptions(index);
  1790. await this._transitionToFlow(index, next, direction);
  1791. }
  1792. async _transitionToFlow(nextIndex, nextOptions, direction) {
  1793. const popup = this.dom && this.dom.popup;
  1794. const content = this.dom && this.dom.content;
  1795. const panes = this.dom && this.dom.stepPanes;
  1796. if (!popup || !content || !panes || !panes.length) {
  1797. this._flowIndex = nextIndex;
  1798. this.params = nextOptions;
  1799. this._render({ flow: true });
  1800. return;
  1801. }
  1802. const fromIndex = this._flowIndex;
  1803. const fromPane = panes[fromIndex];
  1804. const toPane = panes[nextIndex];
  1805. if (!fromPane || !toPane) {
  1806. this._flowIndex = nextIndex;
  1807. this.params = nextOptions;
  1808. this._render({ flow: true });
  1809. return;
  1810. }
  1811. // Measure current content height
  1812. const oldH = content.getBoundingClientRect().height;
  1813. // Prepare target pane for measurement without affecting layout
  1814. const prevDisplay = toPane.style.display;
  1815. const prevPos = toPane.style.position;
  1816. const prevVis = toPane.style.visibility;
  1817. const prevPointer = toPane.style.pointerEvents;
  1818. toPane.style.display = '';
  1819. toPane.style.position = 'absolute';
  1820. toPane.style.visibility = 'hidden';
  1821. toPane.style.pointerEvents = 'none';
  1822. toPane.style.left = '0';
  1823. toPane.style.right = '0';
  1824. const newH = toPane.getBoundingClientRect().height;
  1825. // Restore pane styles (keep hidden until animation starts)
  1826. toPane.style.position = prevPos;
  1827. toPane.style.visibility = prevVis;
  1828. toPane.style.pointerEvents = prevPointer;
  1829. toPane.style.display = prevDisplay; // usually 'none'
  1830. // Apply new options (title/buttons/icon policy) before showing the pane
  1831. this._flowIndex = nextIndex;
  1832. this.params = nextOptions;
  1833. this._applyPopupTheme(this.params);
  1834. const isNext = direction !== 'prev';
  1835. const enterFrom = isNext ? 100 : -100;
  1836. const exitTo = isNext ? -100 : 100;
  1837. const slideDuration = 320;
  1838. // Update title with directional slide (keep in sync with panes)
  1839. let titleAnim = null;
  1840. let titleCleanup = null;
  1841. try {
  1842. const titleEl = this.dom && this.dom.title;
  1843. if (titleEl) {
  1844. const nextTitle = this.params.title || '';
  1845. const prevTitle = titleEl.textContent || '';
  1846. if (prevTitle !== nextTitle) {
  1847. const clone = titleEl.cloneNode(true);
  1848. try { clone.textContent = prevTitle; } catch {}
  1849. try {
  1850. const popupRect = popup.getBoundingClientRect();
  1851. const titleRect = titleEl.getBoundingClientRect();
  1852. clone.style.position = 'absolute';
  1853. clone.style.left = '0';
  1854. clone.style.right = '0';
  1855. clone.style.top = Math.max(0, titleRect.top - popupRect.top) + 'px';
  1856. clone.style.width = '100%';
  1857. clone.style.pointerEvents = 'none';
  1858. clone.style.willChange = 'transform, opacity';
  1859. popup.appendChild(clone);
  1860. } catch {}
  1861. titleEl.textContent = nextTitle;
  1862. try {
  1863. titleEl.style.willChange = 'transform, opacity';
  1864. titleEl.style.transform = `translateX(${enterFrom}%)`;
  1865. titleEl.style.opacity = '0';
  1866. } catch {}
  1867. if (titleEl.animate && clone.animate) {
  1868. const inAnim = titleEl.animate(
  1869. [
  1870. { transform: `translateX(${enterFrom}%)`, opacity: 0.2 },
  1871. { transform: 'translateX(0%)', opacity: 1 }
  1872. ],
  1873. { duration: slideDuration, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' }
  1874. );
  1875. const outAnim = clone.animate(
  1876. [
  1877. { transform: 'translateX(0%)', opacity: 1 },
  1878. { transform: `translateX(${exitTo}%)`, opacity: 0.1 }
  1879. ],
  1880. { duration: slideDuration, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' }
  1881. );
  1882. titleAnim = Promise.all([
  1883. inAnim.finished ? inAnim.finished.catch(() => {}) : Promise.resolve(),
  1884. outAnim.finished ? outAnim.finished.catch(() => {}) : Promise.resolve()
  1885. ]);
  1886. } else {
  1887. const ease = 'cubic-bezier(0.2, 0.9, 0.2, 1)';
  1888. const transition = `transform ${slideDuration}ms ${ease}, opacity ${slideDuration}ms ${ease}`;
  1889. try { titleEl.style.transition = transition; } catch {}
  1890. try { clone.style.transition = transition; } catch {}
  1891. requestAnimationFrame(() => {
  1892. try {
  1893. titleEl.style.transform = 'translateX(0%)';
  1894. titleEl.style.opacity = '1';
  1895. clone.style.transform = `translateX(${exitTo}%)`;
  1896. clone.style.opacity = '0.1';
  1897. } catch {}
  1898. });
  1899. titleAnim = new Promise((resolve) => setTimeout(resolve, slideDuration + 40));
  1900. }
  1901. titleCleanup = () => {
  1902. try { if (clone && clone.parentNode) clone.parentNode.removeChild(clone); } catch {}
  1903. try { titleEl.style.willChange = ''; } catch {}
  1904. try { titleEl.style.transition = ''; } catch {}
  1905. try { titleEl.style.transform = ''; } catch {}
  1906. try { titleEl.style.opacity = ''; } catch {}
  1907. };
  1908. } else {
  1909. titleEl.textContent = nextTitle;
  1910. }
  1911. }
  1912. } catch {}
  1913. const nextBgSpec = this._normalizeBackgroundSpec(this.params && this.params.background);
  1914. const bgTransition = this._transitionBackground(nextBgSpec, direction);
  1915. this._applyPopupSize(this.params);
  1916. // Icon updates (only if needed)
  1917. try {
  1918. const wantsIcon = !!this.params.icon;
  1919. if (!wantsIcon && this.dom.icon) {
  1920. this._destroySvgAniIcon();
  1921. this.dom.icon.remove();
  1922. this.dom.icon = null;
  1923. } else if (wantsIcon) {
  1924. const same = this._isSameIconType(this.dom.icon, this.params.icon);
  1925. if (!this.dom.icon || !same) {
  1926. if (this.dom.icon) {
  1927. this._destroySvgAniIcon();
  1928. this.dom.icon.remove();
  1929. }
  1930. this.dom.icon = this._createIcon(this.params.icon);
  1931. // icon should be on top (before title)
  1932. popup.insertBefore(this.dom.icon, this.dom.title || popup.firstChild);
  1933. }
  1934. }
  1935. } catch {}
  1936. this._updateFlowActions();
  1937. // Prepare panes for animation
  1938. toPane.style.display = '';
  1939. toPane.style.position = 'absolute';
  1940. toPane.style.left = '0';
  1941. toPane.style.right = '0';
  1942. toPane.style.top = '0';
  1943. toPane.style.transform = `translateX(${enterFrom}%)`;
  1944. toPane.style.opacity = '0';
  1945. toPane.style.pointerEvents = 'none';
  1946. fromPane.style.position = 'absolute';
  1947. fromPane.style.left = '0';
  1948. fromPane.style.right = '0';
  1949. fromPane.style.top = '0';
  1950. fromPane.style.transform = 'translateX(0%)';
  1951. fromPane.style.opacity = '1';
  1952. fromPane.style.pointerEvents = 'none';
  1953. // Lock content height during transition
  1954. content.style.height = oldH + 'px';
  1955. content.style.overflow = 'hidden';
  1956. let heightAnim = null;
  1957. let fromAnim = null;
  1958. let toAnim = null;
  1959. let slideCleanup = null;
  1960. try {
  1961. heightAnim = content.animate(
  1962. [{ height: oldH + 'px' }, { height: newH + 'px' }],
  1963. { duration: 220, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' }
  1964. );
  1965. } catch {}
  1966. // Ensure the new pane is in layout before starting slide (fixes missing transitions on some browsers).
  1967. try { void toPane.offsetWidth; } catch {}
  1968. await new Promise((resolve) => requestAnimationFrame(resolve));
  1969. try {
  1970. if (fromPane.animate && toPane.animate) {
  1971. fromAnim = fromPane.animate(
  1972. [
  1973. { transform: 'translateX(0%)', opacity: 1 },
  1974. { transform: `translateX(${exitTo}%)`, opacity: 0.1 }
  1975. ],
  1976. { duration: slideDuration, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' }
  1977. );
  1978. toAnim = toPane.animate(
  1979. [
  1980. { transform: `translateX(${enterFrom}%)`, opacity: 0.2 },
  1981. { transform: 'translateX(0%)', opacity: 1 }
  1982. ],
  1983. { duration: slideDuration, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' }
  1984. );
  1985. } else {
  1986. const ease = 'cubic-bezier(0.2, 0.9, 0.2, 1)';
  1987. const transition = `transform ${slideDuration}ms ${ease}, opacity ${slideDuration}ms ${ease}`;
  1988. fromPane.style.transition = transition;
  1989. toPane.style.transition = transition;
  1990. slideCleanup = () => {
  1991. try { fromPane.style.transition = ''; } catch {}
  1992. try { toPane.style.transition = ''; } catch {}
  1993. };
  1994. // Force a layout so transitions apply reliably.
  1995. void fromPane.offsetWidth;
  1996. requestAnimationFrame(() => {
  1997. try {
  1998. fromPane.style.transform = `translateX(${exitTo}%)`;
  1999. fromPane.style.opacity = '0.1';
  2000. toPane.style.transform = 'translateX(0%)';
  2001. toPane.style.opacity = '1';
  2002. } catch {}
  2003. });
  2004. const fallback = new Promise((resolve) => setTimeout(resolve, slideDuration + 40));
  2005. fromAnim = fallback;
  2006. toAnim = fallback;
  2007. }
  2008. } catch {}
  2009. try {
  2010. await Promise.all([
  2011. heightAnim && heightAnim.finished ? heightAnim.finished.catch(() => {}) : Promise.resolve(),
  2012. fromAnim && fromAnim.finished ? fromAnim.finished.catch(() => {}) : Promise.resolve(),
  2013. toAnim && toAnim.finished ? toAnim.finished.catch(() => {}) : Promise.resolve(),
  2014. bgTransition && typeof bgTransition.then === 'function' ? bgTransition.catch(() => {}) : Promise.resolve(),
  2015. titleAnim && typeof titleAnim.then === 'function' ? titleAnim.catch(() => {}) : Promise.resolve()
  2016. ]);
  2017. } catch {}
  2018. try { if (titleCleanup) titleCleanup(); } catch {}
  2019. try { if (slideCleanup) slideCleanup(); } catch {}
  2020. // Cleanup styles and hide old pane
  2021. fromPane.style.display = 'none';
  2022. fromPane.style.position = '';
  2023. fromPane.style.left = '';
  2024. fromPane.style.right = '';
  2025. fromPane.style.top = '';
  2026. fromPane.style.transform = '';
  2027. fromPane.style.opacity = '';
  2028. fromPane.style.pointerEvents = '';
  2029. toPane.style.position = 'relative';
  2030. toPane.style.left = '';
  2031. toPane.style.right = '';
  2032. toPane.style.top = '';
  2033. toPane.style.transform = '';
  2034. toPane.style.opacity = '';
  2035. toPane.style.pointerEvents = '';
  2036. content.style.height = '';
  2037. content.style.overflow = '';
  2038. // Re-adjust ring background if icon exists (rare in flow)
  2039. try { this._adjustRingBackgroundColor(); } catch {}
  2040. }
  2041. _isSameIconType(iconEl, type) {
  2042. if (!iconEl) return false;
  2043. const raw = String(type || '').trim();
  2044. if (isSvgAniIcon(raw)) {
  2045. const name = getSvgAniIconName(raw);
  2046. return iconEl.dataset && iconEl.dataset.svgani === name;
  2047. }
  2048. try {
  2049. return iconEl.classList && iconEl.classList.contains(raw);
  2050. } catch {
  2051. return false;
  2052. }
  2053. }
  2054. _destroySvgAniIcon() {
  2055. const icon = this.dom && this.dom.icon;
  2056. if (!icon) return;
  2057. const inst = icon._svgAniInstance;
  2058. if (inst && typeof inst.destroy === 'function') {
  2059. try { inst.destroy(); } catch {}
  2060. }
  2061. try { icon._svgAniInstance = null; } catch {}
  2062. }
  2063. _initSvgAniIcon(iconEl, name) {
  2064. if (!iconEl) return;
  2065. const container = iconEl.querySelector(`.${PREFIX}svgAni`);
  2066. if (!container) return;
  2067. const cleanName = String(name || '').trim();
  2068. if (!cleanName) return;
  2069. const url = resolveSvgAniJsonUrl(cleanName);
  2070. if (!url) return;
  2071. const wantsLoop = (this.params && typeof this.params.iconLoop === 'boolean')
  2072. ? this.params.iconLoop
  2073. : true;
  2074. const wantsAutoplay = !(this.params && this.params.iconAnimation === false);
  2075. const showError = (msg) => {
  2076. try {
  2077. container.textContent = String(msg || '');
  2078. container.classList.add(`${PREFIX}svgAni-error`);
  2079. } catch {}
  2080. };
  2081. const loadData = () => new Promise((resolve, reject) => {
  2082. try {
  2083. if (typeof fetch === 'function') {
  2084. fetch(url).then((res) => {
  2085. if (!res || !res.ok) throw new Error('fetch failed');
  2086. return res.json();
  2087. }).then(resolve).catch(reject);
  2088. return;
  2089. }
  2090. const xhr = new XMLHttpRequest();
  2091. xhr.open('GET', url, true);
  2092. xhr.responseType = 'json';
  2093. xhr.onload = () => {
  2094. if (xhr.status >= 200 && xhr.status < 300) {
  2095. const data = xhr.response || (xhr.responseText ? JSON.parse(xhr.responseText) : null);
  2096. resolve(data);
  2097. } else {
  2098. reject(new Error('xhr failed'));
  2099. }
  2100. };
  2101. xhr.onerror = () => reject(new Error('xhr error'));
  2102. xhr.send();
  2103. } catch (e) {
  2104. reject(e);
  2105. }
  2106. });
  2107. (async () => {
  2108. const svgAniLib = await ensureSvgAniLib();
  2109. if (!svgAniLib) {
  2110. showError('SvgAni lib not loaded.');
  2111. return;
  2112. }
  2113. const connected = await waitForConnected(iconEl);
  2114. if (!connected) return;
  2115. let data = null;
  2116. try { data = await loadData(); } catch {}
  2117. if (!data) {
  2118. showError('Failed to load animation.');
  2119. return;
  2120. }
  2121. if (!iconEl.isConnected) return;
  2122. try {
  2123. const anim = svgAniLib.loadAnimation({
  2124. container,
  2125. renderer: 'svg',
  2126. loop: wantsLoop,
  2127. autoplay: wantsAutoplay,
  2128. animationData: data
  2129. });
  2130. iconEl._svgAniInstance = anim;
  2131. if (!wantsAutoplay && anim && typeof anim.goToAndStop === 'function') {
  2132. anim.goToAndStop(0, true);
  2133. }
  2134. } catch {
  2135. showError('Failed to init animation.');
  2136. }
  2137. })();
  2138. }
  2139. _rerenderInside() {
  2140. this._destroySvgAniIcon();
  2141. // Update popup content without recreating overlay (used in flow transitions)
  2142. const popup = this._clearPopup();
  2143. if (!popup) return;
  2144. this._applyPopupTheme(this.params);
  2145. // Icon
  2146. this.dom.icon = null;
  2147. if (this.params.icon) {
  2148. this.dom.icon = this._createIcon(this.params.icon);
  2149. popup.appendChild(this.dom.icon);
  2150. }
  2151. // Title
  2152. this.dom.title = null;
  2153. if (this.params.title) {
  2154. this.dom.title = el('h2', `${PREFIX}title`, this.params.title);
  2155. popup.appendChild(this.dom.title);
  2156. }
  2157. // Content
  2158. this.dom.content = null;
  2159. if (this.params.text || this.params.html || this.params.content || this.params.dom) {
  2160. this.dom.content = el('div', `${PREFIX}content`);
  2161. const domSpec = this._normalizeDomSpec(this.params);
  2162. if (domSpec) this._mountDomContent(domSpec);
  2163. else if (this.params.html) this.dom.content.innerHTML = this.params.html;
  2164. else this.dom.content.textContent = this.params.text;
  2165. popup.appendChild(this.dom.content);
  2166. }
  2167. // Actions / buttons
  2168. this.dom.actions = el('div', `${PREFIX}actions`);
  2169. this.dom.cancelBtn = null;
  2170. if (this.params.showCancelButton) {
  2171. this.dom.cancelBtn = el('button', `${PREFIX}button ${PREFIX}cancel`, '');
  2172. this._setButtonContent(this.dom.cancelBtn, this.params.cancelButtonText);
  2173. this.dom.cancelBtn.onclick = () => this._handleCancel();
  2174. this.dom.actions.appendChild(this.dom.cancelBtn);
  2175. }
  2176. this.dom.confirmBtn = el('button', `${PREFIX}button ${PREFIX}confirm`, '');
  2177. this._setButtonContent(this.dom.confirmBtn, this.params.confirmButtonText);
  2178. this.dom.confirmBtn.onclick = () => this._handleConfirm();
  2179. this.dom.actions.appendChild(this.dom.confirmBtn);
  2180. popup.appendChild(this.dom.actions);
  2181. // Re-run open hooks for each step
  2182. try {
  2183. if (typeof this.params.didOpen === 'function') this.params.didOpen(this.dom.popup);
  2184. } catch {}
  2185. }
  2186. }
  2187. return Layer;
  2188. })));