layer.js 46 KB

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