layer.js 77 KB

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