layer.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  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 normalizeOptions = (options, text, icon) => {
  38. if (typeof options !== 'string') return options || {};
  39. const o = { title: options };
  40. if (text) o.text = text;
  41. if (icon) o.icon = icon;
  42. return o;
  43. };
  44. const el = (tag, className, text) => {
  45. const node = document.createElement(tag);
  46. if (className) node.className = className;
  47. if (text !== undefined) node.textContent = text;
  48. return node;
  49. };
  50. const svgEl = (tag) => document.createElementNS('http://www.w3.org/2000/svg', tag);
  51. // Ensure library CSS is loaded (xjs.css)
  52. // - CSS is centralized in xjs.css (no runtime <style> injection).
  53. // - We still auto-load it for convenience/compat, since consumers may forget the <link>.
  54. let _xjsCssReady = null; // Promise<void>
  55. const waitForStylesheet = (link) => new Promise((resolve) => {
  56. if (!link) return resolve();
  57. if (link.sheet) return resolve();
  58. let done = false;
  59. const finish = () => {
  60. if (done) return;
  61. done = true;
  62. resolve();
  63. };
  64. try { link.addEventListener('load', finish, { once: true }); } catch {}
  65. try { link.addEventListener('error', finish, { once: true }); } catch {}
  66. // Fallback timeout: avoid blocking forever if the load event is missed.
  67. setTimeout(finish, 200);
  68. });
  69. const ensureXjsCss = () => {
  70. try {
  71. if (_xjsCssReady) return _xjsCssReady;
  72. if (typeof document === 'undefined') return Promise.resolve();
  73. if (!document.head) return Promise.resolve();
  74. const existingLink = Array.from(document.querySelectorAll('link[rel="stylesheet"]'))
  75. .find((l) => /(^|\/)xjs\.css(\?|#|$)/.test((l.getAttribute('href') || '').trim()));
  76. if (existingLink) return (_xjsCssReady = waitForStylesheet(existingLink));
  77. const id = 'xjs-css';
  78. const existing = document.getElementById(id);
  79. if (existing) return (_xjsCssReady = waitForStylesheet(existing));
  80. const scripts = Array.from(document.getElementsByTagName('script'));
  81. const scriptSrc = scripts
  82. .map((s) => s && s.src)
  83. .find((src) => /(^|\/)(xjs|layer)\.js(\?|#|$)/.test(String(src || '')));
  84. let href = 'xjs.css';
  85. if (scriptSrc) {
  86. href = String(scriptSrc)
  87. .replace(/(^|\/)xjs\.js(\?|#|$)/, '$1xjs.css$2')
  88. .replace(/(^|\/)layer\.js(\?|#|$)/, '$1xjs.css$2');
  89. }
  90. const link = document.createElement('link');
  91. link.id = id;
  92. link.rel = 'stylesheet';
  93. link.href = href;
  94. _xjsCssReady = waitForStylesheet(link);
  95. document.head.appendChild(link);
  96. return _xjsCssReady;
  97. } catch {
  98. // ignore
  99. return Promise.resolve();
  100. }
  101. };
  102. class Layer {
  103. constructor() {
  104. this._cssReady = ensureXjsCss();
  105. this.params = {};
  106. this.dom = {};
  107. this.promise = null;
  108. this.resolve = null;
  109. this.reject = null;
  110. this._onKeydown = null;
  111. this._mounted = null; // { kind, originalEl, placeholder, parent, nextSibling, prevHidden, prevInlineDisplay }
  112. this._isClosing = false;
  113. this._isReplace = false;
  114. // Step/flow support
  115. this._flowSteps = null; // Array<options>
  116. this._flowIndex = 0;
  117. this._flowValues = [];
  118. this._flowBase = null; // base options merged into each step
  119. this._flowResolved = null; // resolved merged steps
  120. this._flowMountedList = []; // mounted DOM records for move-mode steps
  121. }
  122. // Constructor helper when called as function: const popup = Layer({...})
  123. static get isProxy() { return true; }
  124. // Static entry point
  125. static fire(options) {
  126. const instance = new Layer();
  127. return instance._fire(options);
  128. }
  129. // Chainable entry point (builder-style)
  130. // Example:
  131. // Layer.$({ title: 'Hi' }).fire().then(...)
  132. // Layer.$().config({ title: 'Hi' }).fire()
  133. static $(options) {
  134. const instance = new Layer();
  135. if (options !== undefined) instance.config(options);
  136. return instance;
  137. }
  138. // Chainable config helper (does not render until `.fire()` is called)
  139. config(options = {}) {
  140. // Support the same shorthand as Layer.fire(title, text, icon)
  141. options = normalizeOptions(options, arguments[1], arguments[2]);
  142. this.params = { ...(this.params || {}), ...options };
  143. return this;
  144. }
  145. // Add a single step (chainable)
  146. // Usage:
  147. // Layer.$().step({ title:'A', dom:'#step1' }).step({ title:'B', dom:'#step2' }).fire()
  148. step(options = {}) {
  149. if (!this._flowSteps) this._flowSteps = [];
  150. this._flowSteps.push(normalizeOptions(options, arguments[1], arguments[2]));
  151. return this;
  152. }
  153. // Add multiple steps at once (chainable)
  154. steps(steps = []) {
  155. if (!Array.isArray(steps)) return this;
  156. if (!this._flowSteps) this._flowSteps = [];
  157. steps.forEach((s) => this.step(s));
  158. return this;
  159. }
  160. // Convenience static helper: Layer.flow([steps], baseOptions?)
  161. static flow(steps = [], baseOptions = {}) {
  162. return Layer.$(baseOptions).steps(steps).fire();
  163. }
  164. // Instance entry point (chainable)
  165. fire(options) {
  166. // Flow mode: if configured via .step()/.steps(), ignore per-call options and use steps
  167. if (this._flowSteps && this._flowSteps.length) {
  168. if (options !== undefined && options !== null) {
  169. // allow providing base options at fire-time
  170. this.params = { ...(this.params || {}), ...normalizeOptions(options, arguments[1], arguments[2]) };
  171. }
  172. return this._fireFlow();
  173. }
  174. const merged = (options === undefined) ? (this.params || {}) : options;
  175. return this._fire(merged);
  176. }
  177. _fire(options = {}) {
  178. options = normalizeOptions(options, arguments[1], arguments[2]);
  179. this.params = {
  180. title: '',
  181. text: '',
  182. icon: null,
  183. iconSize: null, // e.g. '6em' / '72px'
  184. confirmButtonText: 'OK',
  185. cancelButtonText: 'Cancel',
  186. showCancelButton: false,
  187. confirmButtonColor: '#3085d6',
  188. cancelButtonColor: '#aaa',
  189. closeOnClickOutside: true,
  190. closeOnEsc: true,
  191. iconAnimation: true,
  192. popupAnimation: true,
  193. // Content:
  194. // - text: plain text
  195. // - html: innerHTML
  196. // - dom: selector / Element / <template> (preferred)
  197. // - content: backward compat for selector/Element OR advanced { dom, mode, clone }
  198. dom: null,
  199. domMode: 'move', // 'move' (default) | 'clone'
  200. // Hook for confirming (also used in flow steps)
  201. // Return false to prevent close / next.
  202. // Return a value to be attached as `value`.
  203. // May return Promise.
  204. preConfirm: null,
  205. ...options
  206. };
  207. this.promise = new Promise((resolve, reject) => {
  208. this.resolve = resolve;
  209. this.reject = reject;
  210. });
  211. this._render();
  212. return this.promise;
  213. }
  214. _fireFlow() {
  215. this._flowIndex = 0;
  216. this._flowValues = [];
  217. // In flow mode:
  218. // - keep iconAnimation off by default (avoids jitter)
  219. // - BUT allow popupAnimation by default so the first step has the same entrance feel
  220. const base = { ...(this.params || {}) };
  221. if (!('popupAnimation' in base)) base.popupAnimation = true;
  222. if (!('iconAnimation' in base)) base.iconAnimation = false;
  223. this._flowBase = base;
  224. this.promise = new Promise((resolve, reject) => {
  225. this.resolve = resolve;
  226. this.reject = reject;
  227. });
  228. this._flowResolved = (this._flowSteps || []).map((_, i) => this._getFlowStepOptions(i));
  229. const first = this._flowResolved[0] || this._getFlowStepOptions(0);
  230. this.params = first;
  231. this._render({ flow: true });
  232. return this.promise;
  233. }
  234. static _getXjs() {
  235. // Prefer xjs, fallback to animal (compat)
  236. const g = (typeof window !== 'undefined') ? window : (typeof globalThis !== 'undefined' ? globalThis : null);
  237. if (!g) return null;
  238. const x = g.xjs || g.animal;
  239. return (typeof x === 'function') ? x : null;
  240. }
  241. _render(meta = null) {
  242. // Remove existing if any (but first, try to restore any mounted DOM from the previous instance)
  243. const existing = document.querySelector(`.${PREFIX}overlay`);
  244. const wantReplace = !!(this.params && this.params.replace);
  245. this._isReplace = false;
  246. if (existing && wantReplace) {
  247. try {
  248. const prev = existing._layerInstance;
  249. if (prev && typeof prev._forceDestroy === 'function') prev._forceDestroy('replace');
  250. } catch {}
  251. try {
  252. if (existing._layerCloseTimer) {
  253. clearTimeout(existing._layerCloseTimer);
  254. existing._layerCloseTimer = null;
  255. }
  256. } catch {}
  257. try {
  258. if (existing._layerOnClick) {
  259. existing.removeEventListener('click', existing._layerOnClick);
  260. existing._layerOnClick = null;
  261. }
  262. } catch {}
  263. try {
  264. while (existing.firstChild) existing.removeChild(existing.firstChild);
  265. } catch {}
  266. try {
  267. existing.style.visibility = '';
  268. existing.classList.add('show');
  269. // Reset any inline fade state from the previous close
  270. existing.style.transition = 'none';
  271. existing.style.opacity = '1';
  272. requestAnimationFrame(() => {
  273. try { existing.style.transition = ''; } catch {}
  274. });
  275. } catch {}
  276. this.dom.overlay = existing;
  277. this.dom.overlay._layerInstance = this;
  278. this._isReplace = true;
  279. } else {
  280. if (existing) {
  281. try {
  282. const prev = existing._layerInstance;
  283. if (prev && typeof prev._forceDestroy === 'function') prev._forceDestroy('replace');
  284. } catch {}
  285. try { existing.remove(); } catch {}
  286. }
  287. // Create Overlay
  288. this.dom.overlay = el('div', `${PREFIX}overlay`);
  289. this.dom.overlay._layerInstance = this;
  290. }
  291. // Create Popup
  292. this.dom.popup = el('div', `${PREFIX}popup`);
  293. this.dom.overlay.appendChild(this.dom.popup);
  294. // Flow mode: pre-mount all steps and switch by hide/show (DOM continuity, less jitter)
  295. if (meta && meta.flow) {
  296. this._renderFlowUI();
  297. return;
  298. }
  299. // Icon
  300. if (this.params.icon) {
  301. this.dom.icon = this._createIcon(this.params.icon);
  302. this.dom.popup.appendChild(this.dom.icon);
  303. }
  304. // Title
  305. if (this.params.title) {
  306. this.dom.title = el('h2', `${PREFIX}title`, this.params.title);
  307. this.dom.popup.appendChild(this.dom.title);
  308. }
  309. // Content (Text / HTML / Element)
  310. if (this.params.text || this.params.html || this.params.content || this.params.dom) {
  311. this.dom.content = el('div', `${PREFIX}content`);
  312. // DOM content (preferred: dom, backward: content)
  313. const domSpec = this._normalizeDomSpec(this.params);
  314. if (domSpec) {
  315. this._mountDomContent(domSpec);
  316. } else if (this.params.html) {
  317. this.dom.content.innerHTML = this.params.html;
  318. } else {
  319. this.dom.content.textContent = this.params.text;
  320. }
  321. this.dom.popup.appendChild(this.dom.content);
  322. }
  323. // Actions
  324. this.dom.actions = el('div', `${PREFIX}actions`);
  325. // Cancel Button
  326. if (this.params.showCancelButton) {
  327. this.dom.cancelBtn = el('button', `${PREFIX}button ${PREFIX}cancel`, this.params.cancelButtonText);
  328. this.dom.cancelBtn.style.backgroundColor = this.params.cancelButtonColor;
  329. this.dom.cancelBtn.onclick = () => this._handleCancel();
  330. this.dom.actions.appendChild(this.dom.cancelBtn);
  331. }
  332. // Confirm Button
  333. this.dom.confirmBtn = el('button', `${PREFIX}button ${PREFIX}confirm`, this.params.confirmButtonText);
  334. this.dom.confirmBtn.style.backgroundColor = this.params.confirmButtonColor;
  335. this.dom.confirmBtn.onclick = () => this._handleConfirm();
  336. this.dom.actions.appendChild(this.dom.confirmBtn);
  337. this.dom.popup.appendChild(this.dom.actions);
  338. // Event Listeners
  339. if (this.params.closeOnClickOutside) {
  340. const onClick = (e) => {
  341. if (e.target === this.dom.overlay) {
  342. this._close(null); // Dismiss
  343. }
  344. };
  345. try {
  346. if (this.dom.overlay._layerOnClick) {
  347. this.dom.overlay.removeEventListener('click', this.dom.overlay._layerOnClick);
  348. }
  349. } catch {}
  350. this.dom.overlay._layerOnClick = onClick;
  351. this.dom.overlay.addEventListener('click', onClick);
  352. } else {
  353. try {
  354. if (this.dom.overlay._layerOnClick) {
  355. this.dom.overlay.removeEventListener('click', this.dom.overlay._layerOnClick);
  356. this.dom.overlay._layerOnClick = null;
  357. }
  358. } catch {}
  359. }
  360. // Avoid first-open overlay "flash": wait for CSS before inserting into DOM,
  361. // then show on a clean frame so opacity transitions are smooth.
  362. const ready = this._cssReady && typeof this._cssReady.then === 'function' ? this._cssReady : Promise.resolve();
  363. ready.then(() => {
  364. try { this.dom.overlay.style.visibility = ''; } catch {}
  365. if (!this.dom.overlay.parentNode) {
  366. document.body.appendChild(this.dom.overlay);
  367. }
  368. // Double-rAF gives the browser a chance to apply styles before animating.
  369. requestAnimationFrame(() => {
  370. requestAnimationFrame(() => {
  371. this.dom.overlay.classList.add('show');
  372. this._didOpen();
  373. });
  374. });
  375. });
  376. }
  377. _renderFlowUI() {
  378. // Icon/title/content/actions are stable; steps are pre-mounted and toggled.
  379. const popup = this.dom.popup;
  380. if (!popup) return;
  381. // Clear popup
  382. while (popup.firstChild) popup.removeChild(popup.firstChild);
  383. // Icon (in flow: suppressed by default unless question or summary)
  384. this.dom.icon = null;
  385. if (this.params.icon) {
  386. this.dom.icon = this._createIcon(this.params.icon);
  387. popup.appendChild(this.dom.icon);
  388. }
  389. // Title (always present for flow)
  390. this.dom.title = el('h2', `${PREFIX}title`, this.params.title || '');
  391. popup.appendChild(this.dom.title);
  392. // Content container
  393. this.dom.content = el('div', `${PREFIX}content`);
  394. // Stack container: keep panes absolute so we can cross-fade without layout thrash
  395. this.dom.stepStack = el('div', `${PREFIX}step-stack`);
  396. this.dom.stepStack.style.position = 'relative';
  397. this.dom.stepStack.style.width = '100%';
  398. this.dom.stepPanes = [];
  399. this._flowMountedList = [];
  400. const steps = this._flowResolved || (this._flowSteps || []).map((_, i) => this._getFlowStepOptions(i));
  401. steps.forEach((opt, i) => {
  402. const pane = el('div', `${PREFIX}step-pane`);
  403. pane.style.width = '100%';
  404. pane.style.boxSizing = 'border-box';
  405. pane.style.display = (i === this._flowIndex) ? '' : 'none';
  406. // Fill pane: dom/html/text
  407. const domSpec = this._normalizeDomSpec(opt);
  408. if (domSpec) {
  409. this._mountDomContentInto(pane, domSpec, { collectFlow: true });
  410. } else if (opt.html) {
  411. pane.innerHTML = opt.html;
  412. } else if (opt.text) {
  413. pane.textContent = opt.text;
  414. }
  415. this.dom.stepStack.appendChild(pane);
  416. this.dom.stepPanes.push(pane);
  417. });
  418. this.dom.content.appendChild(this.dom.stepStack);
  419. popup.appendChild(this.dom.content);
  420. // Actions
  421. this.dom.actions = el('div', `${PREFIX}actions`);
  422. popup.appendChild(this.dom.actions);
  423. this._updateFlowActions();
  424. // Event Listeners
  425. if (this.params.closeOnClickOutside) {
  426. const onClick = (e) => {
  427. if (e.target === this.dom.overlay) {
  428. this._close(null, 'backdrop');
  429. }
  430. };
  431. try {
  432. if (this.dom.overlay._layerOnClick) {
  433. this.dom.overlay.removeEventListener('click', this.dom.overlay._layerOnClick);
  434. }
  435. } catch {}
  436. this.dom.overlay._layerOnClick = onClick;
  437. this.dom.overlay.addEventListener('click', onClick);
  438. } else {
  439. try {
  440. if (this.dom.overlay._layerOnClick) {
  441. this.dom.overlay.removeEventListener('click', this.dom.overlay._layerOnClick);
  442. this.dom.overlay._layerOnClick = null;
  443. }
  444. } catch {}
  445. }
  446. // Avoid first-open overlay "flash": wait for CSS before inserting into DOM,
  447. // then show on a clean frame so opacity transitions are smooth.
  448. const ready = this._cssReady && typeof this._cssReady.then === 'function' ? this._cssReady : Promise.resolve();
  449. ready.then(() => {
  450. try { this.dom.overlay.style.visibility = ''; } catch {}
  451. if (!this.dom.overlay.parentNode) {
  452. document.body.appendChild(this.dom.overlay);
  453. }
  454. requestAnimationFrame(() => {
  455. requestAnimationFrame(() => {
  456. this.dom.overlay.classList.add('show');
  457. this._didOpen();
  458. });
  459. });
  460. });
  461. }
  462. _updateFlowActions() {
  463. const actions = this.dom && this.dom.actions;
  464. if (!actions) return;
  465. while (actions.firstChild) actions.removeChild(actions.firstChild);
  466. this.dom.cancelBtn = null;
  467. if (this.params.showCancelButton) {
  468. this.dom.cancelBtn = el('button', `${PREFIX}button ${PREFIX}cancel`, this.params.cancelButtonText);
  469. this.dom.cancelBtn.style.backgroundColor = this.params.cancelButtonColor;
  470. this.dom.cancelBtn.onclick = () => this._handleCancel();
  471. actions.appendChild(this.dom.cancelBtn);
  472. }
  473. this.dom.confirmBtn = el('button', `${PREFIX}button ${PREFIX}confirm`, this.params.confirmButtonText);
  474. this.dom.confirmBtn.style.backgroundColor = this.params.confirmButtonColor;
  475. this.dom.confirmBtn.onclick = () => this._handleConfirm();
  476. actions.appendChild(this.dom.confirmBtn);
  477. }
  478. _createIcon(type) {
  479. const icon = el('div', `${PREFIX}icon ${type}`);
  480. const applyIconSize = (mode) => {
  481. if (!(this.params && this.params.iconSize)) return;
  482. try {
  483. const s = String(this.params.iconSize).trim();
  484. if (!s) return;
  485. // For SweetAlert2-style success icon, scale via font-size so all `em`-based parts remain proportional.
  486. if (mode === 'font') {
  487. const m = s.match(/^(-?\d*\.?\d+)\s*(px|em|rem)$/i);
  488. if (m) {
  489. const n = parseFloat(m[1]);
  490. const unit = m[2];
  491. if (Number.isFinite(n) && n > 0) {
  492. icon.style.fontSize = (n / 5) + unit; // icon is 5em wide/tall
  493. return;
  494. }
  495. }
  496. }
  497. // Fallback: directly size the box (works great for SVG icons)
  498. icon.style.width = s;
  499. icon.style.height = s;
  500. } catch {}
  501. };
  502. const appendRingParts = () => {
  503. // Use the same "success-like" ring parts for every built-in icon
  504. icon.appendChild(el('div', `${PREFIX}success-circular-line-left`));
  505. icon.appendChild(el('div', `${PREFIX}success-ring`));
  506. icon.appendChild(el('div', `${PREFIX}success-fix`));
  507. icon.appendChild(el('div', `${PREFIX}success-circular-line-right`));
  508. };
  509. const createInnerMarkSvg = () => {
  510. const svg = svgEl('svg');
  511. svg.setAttribute('viewBox', '0 0 80 80');
  512. svg.setAttribute('aria-hidden', 'true');
  513. svg.setAttribute('focusable', 'false');
  514. return svg;
  515. };
  516. const addMarkPath = (svg, d, extraClass) => {
  517. const p = svgEl('path');
  518. p.setAttribute('d', d);
  519. p.setAttribute('class', `${PREFIX}svg-mark ${PREFIX}svg-draw${extraClass ? ' ' + extraClass : ''}`);
  520. p.setAttribute('stroke', 'currentColor');
  521. svg.appendChild(p);
  522. return p;
  523. };
  524. const addDot = (svg, cx, cy) => {
  525. const dot = svgEl('circle');
  526. dot.setAttribute('class', `${PREFIX}svg-dot`);
  527. dot.setAttribute('cx', String(cx));
  528. dot.setAttribute('cy', String(cy));
  529. dot.setAttribute('r', '3.2');
  530. dot.setAttribute('fill', 'currentColor');
  531. svg.appendChild(dot);
  532. return dot;
  533. };
  534. const appendBuiltInInnerMark = (svg) => {
  535. if (type === 'error') {
  536. addMarkPath(svg, 'M28 28 L52 52', `${PREFIX}svg-error-left`);
  537. addMarkPath(svg, 'M52 28 L28 52', `${PREFIX}svg-error-right`);
  538. } else if (type === 'warning') {
  539. addMarkPath(svg, 'M40 20 L40 46', `${PREFIX}svg-warning-line`);
  540. addDot(svg, 40, 58);
  541. } else if (type === 'info') {
  542. addMarkPath(svg, 'M40 34 L40 56', `${PREFIX}svg-info-line`);
  543. addDot(svg, 40, 25);
  544. } else if (type === 'question') {
  545. 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`);
  546. addDot(svg, 42, 61);
  547. }
  548. };
  549. if (type === 'success') {
  550. // SweetAlert2-compatible DOM structure (circle + tick) for exact style parity
  551. // <div class="...success-circular-line-left"></div>
  552. // <div class="...success-mark"><span class="...success-line-tip"></span><span class="...success-line-long"></span></div>
  553. // <div class="...success-ring"></div>
  554. // <div class="...success-fix"></div>
  555. // <div class="...success-circular-line-right"></div>
  556. icon.appendChild(el('div', `${PREFIX}success-circular-line-left`));
  557. const mark = el('div', `${PREFIX}success-mark`);
  558. mark.appendChild(el('span', `${PREFIX}success-line-tip`));
  559. mark.appendChild(el('span', `${PREFIX}success-line-long`));
  560. icon.appendChild(mark);
  561. icon.appendChild(el('div', `${PREFIX}success-ring`));
  562. icon.appendChild(el('div', `${PREFIX}success-fix`));
  563. icon.appendChild(el('div', `${PREFIX}success-circular-line-right`));
  564. applyIconSize('font');
  565. return icon;
  566. }
  567. if (type === 'error' || type === 'warning' || type === 'info' || type === 'question') {
  568. // Use the same "success-like" ring parts for every icon
  569. appendRingParts();
  570. applyIconSize('font');
  571. // SVG only draws the inner symbol (no SVG ring)
  572. const svg = createInnerMarkSvg();
  573. appendBuiltInInnerMark(svg);
  574. icon.appendChild(svg);
  575. return icon;
  576. }
  577. // Default to SVG icons for other/custom types
  578. applyIconSize('box');
  579. const svg = createInnerMarkSvg();
  580. const ring = svgEl('circle');
  581. ring.setAttribute('class', `${PREFIX}svg-ring ${PREFIX}svg-draw`);
  582. ring.setAttribute('cx', '40');
  583. ring.setAttribute('cy', '40');
  584. ring.setAttribute('r', '34');
  585. ring.setAttribute('stroke', 'currentColor');
  586. svg.appendChild(ring);
  587. // For custom types, we draw ring only by default (no inner mark).
  588. icon.appendChild(svg);
  589. return icon;
  590. }
  591. _adjustRingBackgroundColor() {
  592. try {
  593. const icon = this.dom && this.dom.icon;
  594. const popup = this.dom && this.dom.popup;
  595. if (!icon || !popup) return;
  596. const bg = getComputedStyle(popup).backgroundColor;
  597. const parts = icon.querySelectorAll(RING_BG_PARTS_SELECTOR);
  598. parts.forEach((el) => {
  599. try { el.style.backgroundColor = bg; } catch {}
  600. });
  601. } catch {}
  602. }
  603. _didOpen() {
  604. // Keyboard close (ESC)
  605. if (this.params.closeOnEsc) {
  606. this._onKeydown = (e) => {
  607. if (!e) return;
  608. if (e.key === 'Escape') this._close(null, 'esc');
  609. };
  610. document.addEventListener('keydown', this._onKeydown);
  611. }
  612. // Keep the "success-like" ring perfectly blended with popup bg
  613. this._adjustRingBackgroundColor();
  614. // Popup animation (optional)
  615. if (this.params.popupAnimation) {
  616. if (this.dom.popup) {
  617. // Use WAAPI directly to guarantee the slide+fade effect is visible,
  618. // independent from xjs.animate implementation details.
  619. try {
  620. const popup = this.dom.popup;
  621. try { popup.classList.add(`${PREFIX}popup-anim-slide`); } catch {}
  622. const rect = popup.getBoundingClientRect();
  623. // Default entrance: from above center by "more than half" of popup height.
  624. // Clamp to viewport so very tall popups don't start far off-screen.
  625. const vh = (typeof window !== 'undefined' && window && window.innerHeight) ? window.innerHeight : rect.height;
  626. const baseH = Math.min(rect.height, vh);
  627. const y0 = -Math.round(Math.max(18, baseH * 0.75));
  628. // Disable CSS transform transition so it won't fight with WAAPI.
  629. popup.style.transition = 'none';
  630. popup.style.willChange = 'transform, opacity';
  631. // If WAAPI is available, prefer it (most consistent).
  632. if (popup.animate) {
  633. const anim = popup.animate(
  634. [
  635. { transform: `translateY(${y0}px) scale(0.92)`, opacity: 0 },
  636. { transform: 'translateY(0px) scale(1)', opacity: 1 }
  637. ],
  638. {
  639. duration: 520,
  640. easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)',
  641. fill: 'forwards'
  642. }
  643. );
  644. anim.finished
  645. .catch(() => {})
  646. .finally(() => {
  647. try { popup.style.willChange = ''; } catch {}
  648. });
  649. } else {
  650. // Fallback: try xjs.animate if WAAPI isn't available.
  651. const X = Layer._getXjs();
  652. if (X) {
  653. popup.style.opacity = '0';
  654. popup.style.transform = `translateY(${y0}px) scale(0.92)`;
  655. X(popup).animate({
  656. y: [y0, 0],
  657. scale: [0.92, 1],
  658. opacity: [0, 1],
  659. duration: 520,
  660. easing: 'ease-out'
  661. });
  662. }
  663. setTimeout(() => {
  664. try { popup.style.willChange = ''; } catch {}
  665. }, 560);
  666. }
  667. } catch {}
  668. }
  669. }
  670. // Replace mode: if popupAnimation is off, do a soft fade+scale to avoid a hard cut.
  671. if (!this.params.popupAnimation && this._isReplace && this.dom.popup) {
  672. try {
  673. const popup = this.dom.popup;
  674. popup.style.transition = 'none';
  675. popup.style.opacity = '0';
  676. popup.style.transform = 'scale(0.98)';
  677. requestAnimationFrame(() => {
  678. popup.style.transition = 'opacity 0.22s ease, transform 0.22s ease';
  679. popup.style.opacity = '1';
  680. popup.style.transform = 'scale(1)';
  681. setTimeout(() => {
  682. try { popup.style.transition = ''; } catch {}
  683. try { popup.style.opacity = ''; } catch {}
  684. try { popup.style.transform = ''; } catch {}
  685. }, 260);
  686. });
  687. } catch {}
  688. }
  689. // Icon SVG draw animation
  690. if (this.params.iconAnimation) {
  691. this._animateIcon();
  692. }
  693. // User hook (SweetAlert-ish naming)
  694. try {
  695. if (typeof this.params.didOpen === 'function') this.params.didOpen(this.dom.popup);
  696. } catch {}
  697. }
  698. _animateIcon() {
  699. const icon = this.dom.icon;
  700. if (!icon) return;
  701. const type = (this.params && this.params.icon) || '';
  702. // Ring animation (same as success) for all built-in icons
  703. if (RING_TYPES.has(type)) this._adjustRingBackgroundColor();
  704. try { icon.classList.remove(`${PREFIX}icon-show`); } catch {}
  705. requestAnimationFrame(() => {
  706. try { icon.classList.add(`${PREFIX}icon-show`); } catch {}
  707. });
  708. // Success tick is CSS-driven; others still draw their SVG mark after the ring starts.
  709. if (type === 'success') return;
  710. const X = Layer._getXjs();
  711. if (!X) return;
  712. const svg = icon.querySelector('svg');
  713. if (!svg) return;
  714. const marks = Array.from(svg.querySelectorAll(`.${PREFIX}svg-mark`));
  715. const dot = svg.querySelector(`.${PREFIX}svg-dot`);
  716. // If this is a built-in icon, keep the SweetAlert-like order:
  717. // ring sweep first (~0.51s), then draw the inner mark.
  718. const baseDelay = RING_TYPES.has(type) ? 520 : 0;
  719. if (type === 'error') {
  720. // Draw order: left-top -> right-bottom, then right-top -> left-bottom
  721. // NOTE: A tiny delay (like 70ms) looks simultaneous; make it strictly sequential.
  722. const a = svg.querySelector(`.${PREFIX}svg-error-left`) || marks[0]; // M28 28 L52 52
  723. const b = svg.querySelector(`.${PREFIX}svg-error-right`) || marks[1]; // M52 28 L28 52
  724. const dur = 320;
  725. const gap = 60;
  726. try { if (a) X(a).draw({ duration: dur, easing: 'ease-out', delay: baseDelay }); } catch {}
  727. try { if (b) X(b).draw({ duration: dur, easing: 'ease-out', delay: baseDelay + dur + gap }); } catch {}
  728. } else {
  729. // warning / info / question (single stroke) or custom SVG symbols
  730. marks.forEach((m, i) => {
  731. try { X(m).draw({ duration: 420, easing: 'ease-out', delay: baseDelay + i * 60 }); } catch {}
  732. });
  733. }
  734. if (dot) {
  735. try {
  736. dot.style.opacity = '0';
  737. // Keep dot pop after the ring begins
  738. const d = baseDelay + 140;
  739. if (type === 'info') {
  740. X(dot).animate({ opacity: [0, 1], y: [-8, 0], scale: [0.2, 1], duration: 420, delay: d, easing: { stiffness: 300, damping: 14 } });
  741. } else {
  742. X(dot).animate({ opacity: [0, 1], scale: [0.2, 1], duration: 320, delay: d, easing: { stiffness: 320, damping: 18 } });
  743. }
  744. } catch {}
  745. }
  746. }
  747. _forceDestroy(reason = 'replace') {
  748. // Restore mounted DOM (if any) and cleanup listeners; also resolve the promise so it doesn't hang.
  749. try {
  750. if (this._flowSteps && this._flowSteps.length) this._unmountFlowMounted();
  751. else this._unmountDomContent();
  752. } catch {}
  753. if (this._onKeydown) {
  754. try { document.removeEventListener('keydown', this._onKeydown); } catch {}
  755. this._onKeydown = null;
  756. }
  757. try {
  758. if (this.resolve) {
  759. this.resolve({ isConfirmed: false, isDenied: false, isDismissed: true, dismiss: reason });
  760. }
  761. } catch {}
  762. }
  763. _close(isConfirmed, reason) {
  764. if (this._isClosing) return;
  765. this._isClosing = true;
  766. const shouldDelayUnmount = !!(
  767. (this._mounted && this._mounted.kind === 'move') ||
  768. (this._flowSteps && this._flowSteps.length && this._flowMountedList && this._flowMountedList.length)
  769. ) || !this.params.popupAnimation;
  770. const doUnmount = () => {
  771. try {
  772. if (this._flowSteps && this._flowSteps.length) this._unmountFlowMounted();
  773. else this._unmountDomContent();
  774. } catch {}
  775. };
  776. if (!shouldDelayUnmount) {
  777. // Restore mounted DOM (moved into popup) before removing overlay
  778. doUnmount();
  779. }
  780. let customClose = false;
  781. // Soft close for non-popupAnimation cases (avoid abrupt cut)
  782. if (!this.params.popupAnimation) {
  783. try {
  784. const popup = this.dom.popup;
  785. if (popup) {
  786. popup.style.transition = 'opacity 0.22s ease';
  787. popup.style.opacity = '0';
  788. popup.style.transform = '';
  789. }
  790. if (this.dom.overlay) {
  791. const overlay = this.dom.overlay;
  792. // Use inline opacity to avoid class-based jumps
  793. overlay.style.transition = 'opacity 0.22s ease';
  794. overlay.style.opacity = '1';
  795. requestAnimationFrame(() => {
  796. try {
  797. if (overlay._layerInstance !== this) return;
  798. overlay.style.opacity = '0';
  799. } catch {}
  800. });
  801. }
  802. customClose = true;
  803. } catch {}
  804. }
  805. if (!customClose) {
  806. this.dom.overlay.classList.remove('show');
  807. }
  808. try {
  809. if (this.dom.overlay) {
  810. const overlay = this.dom.overlay;
  811. const delay = customClose ? 240 : 300;
  812. overlay._layerCloseTimer = setTimeout(() => {
  813. if (shouldDelayUnmount) {
  814. doUnmount();
  815. }
  816. if (overlay._layerInstance !== this) return;
  817. if (overlay.parentNode) {
  818. overlay.parentNode.removeChild(overlay);
  819. }
  820. }, delay);
  821. }
  822. } catch {}
  823. if (this._onKeydown) {
  824. try { document.removeEventListener('keydown', this._onKeydown); } catch {}
  825. this._onKeydown = null;
  826. }
  827. try {
  828. if (typeof this.params.willClose === 'function') this.params.willClose(this.dom.popup);
  829. } catch {}
  830. try {
  831. if (typeof this.params.didClose === 'function') this.params.didClose();
  832. } catch {}
  833. const value = (this._flowSteps && this._flowSteps.length) ? (this._flowValues || []) : undefined;
  834. if (isConfirmed === true) {
  835. this.resolve({ isConfirmed: true, isDenied: false, isDismissed: false, value });
  836. } else if (isConfirmed === false) {
  837. this.resolve({ isConfirmed: false, isDenied: false, isDismissed: true, dismiss: reason || 'cancel', value });
  838. } else {
  839. this.resolve({ isConfirmed: false, isDenied: false, isDismissed: true, dismiss: reason || 'backdrop', value });
  840. }
  841. }
  842. _normalizeDomSpec(params) {
  843. // Preferred: params.dom (selector/Element/template)
  844. // Backward: params.content (selector/Element) OR advanced object { dom, mode, clone }
  845. const p = params || {};
  846. let dom = p.dom;
  847. let mode = p.domMode || 'move';
  848. if (dom == null && p.content != null) {
  849. if (typeof p.content === 'object' && !(p.content instanceof Element)) {
  850. if (p.content && (p.content.dom != null || p.content.selector != null)) {
  851. dom = (p.content.dom != null) ? p.content.dom : p.content.selector;
  852. if (p.content.mode) mode = p.content.mode;
  853. if (p.content.clone === true) mode = 'clone';
  854. }
  855. } else {
  856. dom = p.content;
  857. }
  858. }
  859. if (dom == null) return null;
  860. return { dom, mode };
  861. }
  862. _mountDomContentInto(target, domSpec, opts = null) {
  863. // Like _mountDomContent, but mounts into the provided container.
  864. const collectFlow = !!(opts && opts.collectFlow);
  865. const originalContent = this.dom.content;
  866. // Temporarily redirect this.dom.content for reuse of internal logic.
  867. try { this.dom.content = target; } catch {}
  868. try {
  869. const before = this._mounted;
  870. this._mountDomContent(domSpec);
  871. const rec = this._mounted;
  872. // If we mounted in move-mode, _mounted holds record; detach it from single-mode tracking.
  873. if (collectFlow && rec && rec.kind === 'move') {
  874. this._flowMountedList.push(rec);
  875. this._mounted = before; // restore previous single record (usually null)
  876. }
  877. } finally {
  878. try { this.dom.content = originalContent; } catch {}
  879. }
  880. }
  881. _unmountFlowMounted() {
  882. // Restore all moved DOM nodes for flow steps
  883. const list = Array.isArray(this._flowMountedList) ? this._flowMountedList : [];
  884. this._flowMountedList = [];
  885. list.forEach((m) => {
  886. try {
  887. if (!m || m.kind !== 'move') return;
  888. // Reuse single unmount logic by swapping _mounted
  889. const prev = this._mounted;
  890. this._mounted = m;
  891. this._unmountDomContent();
  892. this._mounted = prev;
  893. } catch {}
  894. });
  895. }
  896. _mountDomContent(domSpec) {
  897. try {
  898. if (!this.dom.content) return;
  899. this._unmountDomContent(); // ensure only one mount at a time
  900. const forceVisible = (el) => {
  901. if (!el) return { prevHidden: false, prevInlineDisplay: '' };
  902. const prevHidden = !!el.hidden;
  903. const prevInlineDisplay = (el.style && typeof el.style.display === 'string') ? el.style.display : '';
  904. try { el.hidden = false; } catch {}
  905. try {
  906. const cs = (typeof getComputedStyle === 'function') ? getComputedStyle(el) : null;
  907. const display = cs ? String(cs.display || '') : '';
  908. // If element is hidden via CSS (e.g. .hidden-dom{display:none}),
  909. // add an inline override so it becomes visible inside the popup.
  910. if (display === 'none') el.style.display = 'block';
  911. else if (el.style && el.style.display === 'none') el.style.display = 'block';
  912. } catch {}
  913. return { prevHidden, prevInlineDisplay };
  914. };
  915. let node = domSpec.dom;
  916. if (typeof node === 'string') node = document.querySelector(node);
  917. if (!node) return;
  918. // <template> support: always clone template content
  919. if (typeof HTMLTemplateElement !== 'undefined' && node instanceof HTMLTemplateElement) {
  920. const frag = node.content.cloneNode(true);
  921. this.dom.content.appendChild(frag);
  922. this._mounted = { kind: 'template' };
  923. return;
  924. }
  925. if (!(node instanceof Element)) return;
  926. if (domSpec.mode === 'clone') {
  927. const clone = node.cloneNode(true);
  928. // If original is hidden (via attr or CSS), the clone may inherit; force show it in popup.
  929. try { clone.hidden = false; } catch {}
  930. try {
  931. const cs = (typeof getComputedStyle === 'function') ? getComputedStyle(node) : null;
  932. const display = cs ? String(cs.display || '') : '';
  933. if (display === 'none') clone.style.display = 'block';
  934. } catch {}
  935. this.dom.content.appendChild(clone);
  936. this._mounted = { kind: 'clone' };
  937. return;
  938. }
  939. // Default: move into popup but restore on close
  940. const placeholder = document.createComment('layer-dom-placeholder');
  941. const parent = node.parentNode;
  942. const nextSibling = node.nextSibling;
  943. if (!parent) {
  944. // Detached node: moving would lose it when overlay is removed; clone instead.
  945. const clone = node.cloneNode(true);
  946. try { clone.hidden = false; } catch {}
  947. try { if (clone.style && clone.style.display === 'none') clone.style.display = ''; } catch {}
  948. this.dom.content.appendChild(clone);
  949. this._mounted = { kind: 'clone' };
  950. return;
  951. }
  952. try { parent.insertBefore(placeholder, nextSibling); } catch {}
  953. const { prevHidden, prevInlineDisplay } = forceVisible(node);
  954. this.dom.content.appendChild(node);
  955. this._mounted = { kind: 'move', originalEl: node, placeholder, parent, nextSibling, prevHidden, prevInlineDisplay };
  956. } catch {
  957. // ignore
  958. }
  959. }
  960. _unmountDomContent() {
  961. const m = this._mounted;
  962. if (!m) return;
  963. this._mounted = null;
  964. if (m.kind !== 'move') return;
  965. const node = m.originalEl;
  966. if (!node) return;
  967. // Restore hidden/display
  968. try { node.hidden = !!m.prevHidden; } catch {}
  969. try {
  970. if (node.style && typeof m.prevInlineDisplay === 'string') node.style.display = m.prevInlineDisplay;
  971. } catch {}
  972. // Move back to original position
  973. try {
  974. const ph = m.placeholder;
  975. if (ph && ph.parentNode) {
  976. ph.parentNode.insertBefore(node, ph);
  977. ph.parentNode.removeChild(ph);
  978. return;
  979. }
  980. } catch {}
  981. // Fallback: append to original parent
  982. try {
  983. if (m.parent) m.parent.appendChild(node);
  984. } catch {}
  985. }
  986. _setButtonsDisabled(disabled) {
  987. try {
  988. if (this.dom && this.dom.confirmBtn) this.dom.confirmBtn.disabled = !!disabled;
  989. if (this.dom && this.dom.cancelBtn) this.dom.cancelBtn.disabled = !!disabled;
  990. } catch {}
  991. }
  992. async _handleConfirm() {
  993. // Flow next / finalize
  994. if (this._flowSteps && this._flowSteps.length) {
  995. return this._flowNext();
  996. }
  997. // Single popup: support async preConfirm
  998. const pre = this.params && this.params.preConfirm;
  999. if (typeof pre === 'function') {
  1000. try {
  1001. this._setButtonsDisabled(true);
  1002. const r = pre(this.dom && this.dom.popup);
  1003. const v = (r && typeof r.then === 'function') ? await r : r;
  1004. if (v === false) {
  1005. this._setButtonsDisabled(false);
  1006. return;
  1007. }
  1008. // store value in non-flow mode as single value
  1009. this._flowValues = [v];
  1010. } catch (e) {
  1011. console.error(e);
  1012. this._setButtonsDisabled(false);
  1013. return;
  1014. }
  1015. }
  1016. this._close(true, 'confirm');
  1017. }
  1018. _handleCancel() {
  1019. if (this._flowSteps && this._flowSteps.length) {
  1020. // default: if not first step, cancel acts as "back"
  1021. if (this._flowIndex > 0) {
  1022. this._flowPrev();
  1023. return;
  1024. }
  1025. }
  1026. this._close(false, 'cancel');
  1027. }
  1028. _getFlowStepOptions(index) {
  1029. const step = (this._flowSteps && this._flowSteps[index]) ? this._flowSteps[index] : {};
  1030. const base = this._flowBase || {};
  1031. const merged = { ...base, ...step };
  1032. // Default button texts for flow
  1033. const isLast = index >= (this._flowSteps.length - 1);
  1034. if (!('confirmButtonText' in step)) merged.confirmButtonText = isLast ? (base.confirmButtonText || 'OK') : 'Next';
  1035. // Show cancel as Back after first step (unless step explicitly overrides)
  1036. if (index > 0) {
  1037. if (!('showCancelButton' in step)) merged.showCancelButton = true;
  1038. if (!('cancelButtonText' in step)) merged.cancelButtonText = 'Back';
  1039. } else {
  1040. // First step default keeps base settings
  1041. if (!('cancelButtonText' in step) && merged.showCancelButton) merged.cancelButtonText = merged.cancelButtonText || 'Cancel';
  1042. }
  1043. // Icon/animation policy for flow:
  1044. // - During steps: no icon/animations by default (avoids distraction + layout jitter)
  1045. // - Allow icon only if step explicitly uses `icon:'question'`, or step is marked as summary.
  1046. const isSummary = !!(step && (step.summary === true || step.isSummary === true));
  1047. const explicitIcon = ('icon' in step) ? step.icon : undefined;
  1048. const baseIcon = ('icon' in base) ? base.icon : undefined;
  1049. const chosenIcon = (explicitIcon !== undefined) ? explicitIcon : baseIcon;
  1050. if (!isSummary && !isLast) {
  1051. merged.icon = (chosenIcon === 'question') ? 'question' : null;
  1052. merged.iconAnimation = false;
  1053. } else if (!isSummary && isLast) {
  1054. // last step: still suppress unless summary or question
  1055. merged.icon = (chosenIcon === 'question') ? 'question' : null;
  1056. merged.iconAnimation = false;
  1057. } else {
  1058. // summary step: allow icon; animation follows explicit config (default true only if provided elsewhere)
  1059. if (!('icon' in step) && chosenIcon === undefined) merged.icon = null;
  1060. }
  1061. return merged;
  1062. }
  1063. async _flowNext() {
  1064. const idx = this._flowIndex;
  1065. const total = this._flowSteps.length;
  1066. const isLast = idx >= (total - 1);
  1067. // preConfirm hook for current step
  1068. const pre = this.params && this.params.preConfirm;
  1069. if (typeof pre === 'function') {
  1070. try {
  1071. this._setButtonsDisabled(true);
  1072. const r = pre(this.dom && this.dom.popup, idx);
  1073. const v = (r && typeof r.then === 'function') ? await r : r;
  1074. if (v === false) {
  1075. this._setButtonsDisabled(false);
  1076. return;
  1077. }
  1078. this._flowValues[idx] = v;
  1079. } catch (e) {
  1080. console.error(e);
  1081. this._setButtonsDisabled(false);
  1082. return;
  1083. }
  1084. }
  1085. if (isLast) {
  1086. this._close(true, 'confirm');
  1087. return;
  1088. }
  1089. this._setButtonsDisabled(false);
  1090. await this._flowGo(idx + 1, 'next');
  1091. }
  1092. async _flowPrev() {
  1093. const idx = this._flowIndex;
  1094. if (idx <= 0) return;
  1095. await this._flowGo(idx - 1, 'prev');
  1096. }
  1097. async _flowGo(index, direction) {
  1098. const next = (this._flowResolved && this._flowResolved[index]) ? this._flowResolved[index] : this._getFlowStepOptions(index);
  1099. await this._transitionToFlow(index, next, direction);
  1100. }
  1101. async _transitionToFlow(nextIndex, nextOptions, direction) {
  1102. const popup = this.dom && this.dom.popup;
  1103. const content = this.dom && this.dom.content;
  1104. const panes = this.dom && this.dom.stepPanes;
  1105. if (!popup || !content || !panes || !panes.length) {
  1106. this._flowIndex = nextIndex;
  1107. this.params = nextOptions;
  1108. this._render({ flow: true });
  1109. return;
  1110. }
  1111. const fromIndex = this._flowIndex;
  1112. const fromPane = panes[fromIndex];
  1113. const toPane = panes[nextIndex];
  1114. if (!fromPane || !toPane) {
  1115. this._flowIndex = nextIndex;
  1116. this.params = nextOptions;
  1117. this._render({ flow: true });
  1118. return;
  1119. }
  1120. // Measure current content height
  1121. const oldH = content.getBoundingClientRect().height;
  1122. // Prepare target pane for measurement without affecting layout
  1123. const prevDisplay = toPane.style.display;
  1124. const prevPos = toPane.style.position;
  1125. const prevVis = toPane.style.visibility;
  1126. const prevPointer = toPane.style.pointerEvents;
  1127. toPane.style.display = '';
  1128. toPane.style.position = 'absolute';
  1129. toPane.style.visibility = 'hidden';
  1130. toPane.style.pointerEvents = 'none';
  1131. toPane.style.left = '0';
  1132. toPane.style.right = '0';
  1133. const newH = toPane.getBoundingClientRect().height;
  1134. // Restore pane styles (keep hidden until animation starts)
  1135. toPane.style.position = prevPos;
  1136. toPane.style.visibility = prevVis;
  1137. toPane.style.pointerEvents = prevPointer;
  1138. toPane.style.display = prevDisplay; // usually 'none'
  1139. // Apply new options (title/buttons/icon policy) before showing the pane
  1140. this._flowIndex = nextIndex;
  1141. this.params = nextOptions;
  1142. // Update icon/title/buttons without recreating DOM
  1143. try {
  1144. if (this.dom.title) this.dom.title.textContent = this.params.title || '';
  1145. } catch {}
  1146. // Icon updates (only if needed)
  1147. try {
  1148. const wantsIcon = !!this.params.icon;
  1149. if (!wantsIcon && this.dom.icon) {
  1150. this.dom.icon.remove();
  1151. this.dom.icon = null;
  1152. } else if (wantsIcon) {
  1153. const curType = this.dom.icon ? (Array.from(this.dom.icon.classList).find(c => c !== `${PREFIX}icon`) || '') : '';
  1154. if (!this.dom.icon || !this.dom.icon.classList.contains(String(this.params.icon))) {
  1155. if (this.dom.icon) this.dom.icon.remove();
  1156. this.dom.icon = this._createIcon(this.params.icon);
  1157. // icon should be on top (before title)
  1158. popup.insertBefore(this.dom.icon, this.dom.title || popup.firstChild);
  1159. }
  1160. }
  1161. } catch {}
  1162. this._updateFlowActions();
  1163. // Switch panes with only content height transition (no slide/fade between steps)
  1164. toPane.style.display = '';
  1165. toPane.style.position = 'relative';
  1166. // Lock content height during transition
  1167. content.style.height = oldH + 'px';
  1168. content.style.overflow = 'hidden';
  1169. // Animate height
  1170. let heightAnim = null;
  1171. try {
  1172. heightAnim = content.animate(
  1173. [{ height: oldH + 'px' }, { height: newH + 'px' }],
  1174. { duration: 220, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' }
  1175. );
  1176. } catch {}
  1177. try {
  1178. await Promise.all([
  1179. heightAnim && heightAnim.finished ? heightAnim.finished.catch(() => {}) : Promise.resolve()
  1180. ]);
  1181. } catch {}
  1182. // Cleanup styles and hide old pane
  1183. fromPane.style.display = 'none';
  1184. content.style.height = '';
  1185. content.style.overflow = '';
  1186. // Re-adjust ring background if icon exists (rare in flow)
  1187. try { this._adjustRingBackgroundColor(); } catch {}
  1188. }
  1189. _rerenderInside() {
  1190. // Update popup content without recreating overlay (used in flow transitions)
  1191. const popup = this.dom && this.dom.popup;
  1192. if (!popup) return;
  1193. // Clear popup (but keep reference)
  1194. while (popup.firstChild) popup.removeChild(popup.firstChild);
  1195. // Icon
  1196. this.dom.icon = null;
  1197. if (this.params.icon) {
  1198. this.dom.icon = this._createIcon(this.params.icon);
  1199. popup.appendChild(this.dom.icon);
  1200. }
  1201. // Title
  1202. this.dom.title = null;
  1203. if (this.params.title) {
  1204. this.dom.title = el('h2', `${PREFIX}title`, this.params.title);
  1205. popup.appendChild(this.dom.title);
  1206. }
  1207. // Content
  1208. this.dom.content = null;
  1209. if (this.params.text || this.params.html || this.params.content || this.params.dom) {
  1210. this.dom.content = el('div', `${PREFIX}content`);
  1211. const domSpec = this._normalizeDomSpec(this.params);
  1212. if (domSpec) this._mountDomContent(domSpec);
  1213. else if (this.params.html) this.dom.content.innerHTML = this.params.html;
  1214. else this.dom.content.textContent = this.params.text;
  1215. popup.appendChild(this.dom.content);
  1216. }
  1217. // Actions / buttons
  1218. this.dom.actions = el('div', `${PREFIX}actions`);
  1219. this.dom.cancelBtn = null;
  1220. if (this.params.showCancelButton) {
  1221. this.dom.cancelBtn = el('button', `${PREFIX}button ${PREFIX}cancel`, this.params.cancelButtonText);
  1222. this.dom.cancelBtn.style.backgroundColor = this.params.cancelButtonColor;
  1223. this.dom.cancelBtn.onclick = () => this._handleCancel();
  1224. this.dom.actions.appendChild(this.dom.cancelBtn);
  1225. }
  1226. this.dom.confirmBtn = el('button', `${PREFIX}button ${PREFIX}confirm`, this.params.confirmButtonText);
  1227. this.dom.confirmBtn.style.backgroundColor = this.params.confirmButtonColor;
  1228. this.dom.confirmBtn.onclick = () => this._handleConfirm();
  1229. this.dom.actions.appendChild(this.dom.confirmBtn);
  1230. popup.appendChild(this.dom.actions);
  1231. // Re-run open hooks for each step
  1232. try {
  1233. if (typeof this.params.didOpen === 'function') this.params.didOpen(this.dom.popup);
  1234. } catch {}
  1235. }
  1236. }
  1237. return Layer;
  1238. })));