layer.js 82 KB

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