layer.js 76 KB

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