layer.js 78 KB

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