layer.js 77 KB

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