layer.js 58 KB

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