| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597 |
- (function (global, factory) {
- const LayerClass = factory();
- // Allow usage as `Layer({...})` or `new Layer()`
- // But Layer is a class. We can wrap it in a proxy or factory function.
-
- function LayerFactory(options) {
- if (options && typeof options === 'object') {
- return LayerClass.$(options);
- }
- return new LayerClass();
- }
-
- // Copy static methods (including non-enumerable class statics like `fire` / `$`)
- // Class static methods are non-enumerable by default, so Object.assign() would miss them.
- const copyStatic = (to, from) => {
- try {
- Object.getOwnPropertyNames(from).forEach((k) => {
- if (k === 'prototype' || k === 'name' || k === 'length') return;
- const desc = Object.getOwnPropertyDescriptor(from, k);
- if (!desc) return;
- Object.defineProperty(to, k, desc);
- });
- } catch (e) {
- // Best-effort fallback
- try { Object.assign(to, from); } catch {}
- }
- };
- copyStatic(LayerFactory, LayerClass);
- // Also copy prototype for instanceof checks if needed (though tricky with factory)
- LayerFactory.prototype = LayerClass.prototype;
-
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = LayerFactory :
- typeof define === 'function' && define.amd ? define(() => LayerFactory) :
- (global.Layer = LayerFactory);
- }(this, (function () {
- 'use strict';
- const PREFIX = 'layer-';
- const RING_TYPES = new Set(['success', 'error', 'warning', 'info', 'question']);
- const RING_BG_PARTS_SELECTOR = `.${PREFIX}success-circular-line-left, .${PREFIX}success-circular-line-right, .${PREFIX}success-fix`;
- const normalizeOptions = (options, text, icon) => {
- if (typeof options !== 'string') return options || {};
- const o = { title: options };
- if (text) o.text = text;
- if (icon) o.icon = icon;
- return o;
- };
-
- const el = (tag, className, text) => {
- const node = document.createElement(tag);
- if (className) node.className = className;
- if (text !== undefined) node.textContent = text;
- return node;
- };
-
- const svgEl = (tag) => document.createElementNS('http://www.w3.org/2000/svg', tag);
-
- // Ensure library CSS is loaded (xjs.css)
- // - CSS is centralized in xjs.css (no runtime <style> injection).
- // - We still auto-load it for convenience/compat, since consumers may forget the <link>.
- let _xjsCssReady = null; // Promise<void>
- const waitForStylesheet = (link) => new Promise((resolve) => {
- if (!link) return resolve();
- if (link.sheet) return resolve();
- let done = false;
- const finish = () => {
- if (done) return;
- done = true;
- resolve();
- };
- try { link.addEventListener('load', finish, { once: true }); } catch {}
- try { link.addEventListener('error', finish, { once: true }); } catch {}
- // Fallback timeout: avoid blocking forever if the load event is missed.
- setTimeout(finish, 200);
- });
- const ensureXjsCss = () => {
- try {
- if (_xjsCssReady) return _xjsCssReady;
- if (typeof document === 'undefined') return Promise.resolve();
- if (!document.head) return Promise.resolve();
- const existingLink = Array.from(document.querySelectorAll('link[rel="stylesheet"]'))
- .find((l) => /(^|\/)xjs\.css(\?|#|$)/.test((l.getAttribute('href') || '').trim()));
- if (existingLink) return (_xjsCssReady = waitForStylesheet(existingLink));
- const id = 'xjs-css';
- const existing = document.getElementById(id);
- if (existing) return (_xjsCssReady = waitForStylesheet(existing));
- const scripts = Array.from(document.getElementsByTagName('script'));
- const scriptSrc = scripts
- .map((s) => s && s.src)
- .find((src) => /(^|\/)(xjs|layer)\.js(\?|#|$)/.test(String(src || '')));
- let href = 'xjs.css';
- if (scriptSrc) {
- href = String(scriptSrc)
- .replace(/(^|\/)xjs\.js(\?|#|$)/, '$1xjs.css$2')
- .replace(/(^|\/)layer\.js(\?|#|$)/, '$1xjs.css$2');
- }
- const link = document.createElement('link');
- link.id = id;
- link.rel = 'stylesheet';
- link.href = href;
- _xjsCssReady = waitForStylesheet(link);
- document.head.appendChild(link);
- return _xjsCssReady;
- } catch {
- // ignore
- return Promise.resolve();
- }
- };
- class Layer {
- constructor() {
- this._cssReady = ensureXjsCss();
- this.params = {};
- this.dom = {};
- this.promise = null;
- this.resolve = null;
- this.reject = null;
- this._onKeydown = null;
- this._mounted = null; // { kind, originalEl, placeholder, parent, nextSibling, prevHidden, prevInlineDisplay }
- this._isClosing = false;
- this._isReplace = false;
- // Step/flow support
- this._flowSteps = null; // Array<options>
- this._flowIndex = 0;
- this._flowValues = [];
- this._flowBase = null; // base options merged into each step
- this._flowResolved = null; // resolved merged steps
- this._flowMountedList = []; // mounted DOM records for move-mode steps
- this._flowAutoForm = null; // { enabled: true } when using step container shorthand
- }
- // Constructor helper when called as function: const popup = Layer({...})
- static get isProxy() { return true; }
-
- // Static entry point
- static run(options) {
- const instance = new Layer();
- return instance._fire(options);
- }
- // Backward-compatible alias
- static fire(options) { return Layer.run(options); }
-
- // Chainable entry point (builder-style)
- // Example:
- // Layer.$({ title: 'Hi' }).run().then(...)
- // Layer.$().config({ title: 'Hi' }).run()
- static $(options) {
- const instance = new Layer();
- if (options !== undefined) instance.config(options);
- return instance;
- }
-
- // Chainable config helper (does not render until `.run()` is called)
- config(options = {}) {
- // Support the same shorthand as Layer.fire(title, text, icon)
- options = normalizeOptions(options, arguments[1], arguments[2]);
- this.params = { ...(this.params || {}), ...options };
- return this;
- }
- // Add a single step (chainable)
- // Usage:
- // Layer.$().step({ title:'A', dom:'#step1' }).step({ title:'B', dom:'#step2' }).run()
- step(options = {}) {
- if (!this._flowSteps) this._flowSteps = [];
- this._flowSteps.push(normalizeOptions(options, arguments[1], arguments[2]));
- return this;
- }
- // Add multiple steps at once (chainable)
- steps(steps = []) {
- if (!Array.isArray(steps)) return this;
- if (!this._flowSteps) this._flowSteps = [];
- steps.forEach((s) => this.step(s));
- return this;
- }
- // Convenience static helper: Layer.flow([steps], baseOptions?)
- static flow(steps = [], baseOptions = {}) {
- return Layer.$(baseOptions).steps(steps).run();
- }
-
- // Instance entry point (chainable)
- run(options) {
- const hasArgs = (options !== undefined && options !== null);
- const normalized = hasArgs ? normalizeOptions(options, arguments[1], arguments[2]) : null;
- const merged = hasArgs ? normalized : (this.params || {});
- // If no explicit steps yet, allow shorthand: { step: '#container', stepItem: '.item' }
- if (!this._flowSteps || !this._flowSteps.length) {
- const didInit = this._initFlowFromStepContainer(merged);
- if (didInit) {
- this.params = { ...(this.params || {}), ...this._stripStepOptions(merged) };
- }
- }
- // Flow mode: if configured via .step()/.steps() or step container shorthand, ignore per-call options and use steps
- if (this._flowSteps && this._flowSteps.length) {
- if (hasArgs) {
- // allow providing base options at fire-time
- this.params = { ...(this.params || {}), ...this._stripStepOptions(merged) };
- }
- return this._fireFlow();
- }
- return this._fire(merged);
- }
- // Backward-compatible alias
- fire(options) { return this.run(options); }
- _fire(options = {}) {
- options = normalizeOptions(options, arguments[1], arguments[2]);
- this.params = {
- title: '',
- text: '',
- icon: null,
- iconSize: null, // e.g. '6em' / '72px'
- confirmButtonText: 'OK',
- cancelButtonText: 'Cancel',
- showCancelButton: false,
- confirmButtonColor: '#3085d6',
- cancelButtonColor: '#aaa',
- closeOnClickOutside: true,
- closeOnEsc: true,
- iconAnimation: true,
- popupAnimation: true,
- // Content:
- // - text: plain text
- // - html: innerHTML
- // - dom: selector / Element / <template> (preferred)
- // - content: backward compat for selector/Element OR advanced { dom, mode, clone }
- dom: null,
- domMode: 'move', // 'move' (default) | 'clone'
- // Hook for confirming (also used in flow steps)
- // Return false to prevent close / next.
- // Return a value to be attached as `value`.
- // May return Promise.
- preConfirm: null,
- ...options
- };
- this.promise = new Promise((resolve, reject) => {
- this.resolve = resolve;
- this.reject = reject;
- });
- this._render();
- return this.promise;
- }
- _fireFlow() {
- this._flowIndex = 0;
- this._flowValues = [];
- // In flow mode:
- // - keep iconAnimation off by default (avoids jitter)
- // - BUT allow popupAnimation by default so the first step has the same entrance feel
- const base = { ...(this.params || {}) };
- if (!('popupAnimation' in base)) base.popupAnimation = true;
- if (!('iconAnimation' in base)) base.iconAnimation = false;
- this._flowBase = base;
- this.promise = new Promise((resolve, reject) => {
- this.resolve = resolve;
- this.reject = reject;
- });
- this._flowResolved = (this._flowSteps || []).map((_, i) => this._getFlowStepOptions(i));
- const first = this._flowResolved[0] || this._getFlowStepOptions(0);
- this.params = first;
- this._render({ flow: true });
- return this.promise;
- }
- static _getXjs() {
- // Prefer $ (main), fallback to xjs/animal (compat)
- const g = (typeof window !== 'undefined') ? window : (typeof globalThis !== 'undefined' ? globalThis : null);
- if (!g) return null;
- const x = g.$ || g.xjs || g.animal;
- return (typeof x === 'function') ? x : null;
- }
- _stripStepOptions(options) {
- const out = { ...(options || {}) };
- try { delete out.step; } catch {}
- try { delete out.stepItem; } catch {}
- return out;
- }
- _normalizeStepContainer(options) {
- const opts = options || {};
- const raw = opts.step;
- if (!raw || typeof document === 'undefined') return null;
- const container = (typeof raw === 'string') ? document.querySelector(raw) : raw;
- if (!container || (typeof Element !== 'undefined' && !(container instanceof Element))) return null;
- const itemSelector = opts.stepItem;
- let items = [];
- if (typeof itemSelector === 'string' && itemSelector.trim()) {
- try { items = Array.from(container.querySelectorAll(itemSelector)); } catch {}
- } else {
- try { items = Array.from(container.children || []); } catch {}
- }
- return { container, items };
- }
- _initFlowFromStepContainer(options) {
- const spec = this._normalizeStepContainer(options);
- if (!spec) return false;
- const { items } = spec;
- if (!items || !items.length) {
- try { console.warn('Layer step container has no items.'); } catch {}
- return false;
- }
- this._flowSteps = items.map((item) => {
- const step = { dom: item };
- try {
- const title =
- (item.getAttribute('data-step-title') || item.getAttribute('data-layer-title') || item.getAttribute('title') || '').trim();
- if (title) step.title = title;
- } catch {}
- return step;
- });
- this._flowAutoForm = { enabled: true };
- return true;
- }
- _render(meta = null) {
- // Remove existing if any (but first, try to restore any mounted DOM from the previous instance)
- const existing = document.querySelector(`.${PREFIX}overlay`);
- const wantReplace = !!(this.params && this.params.replace);
- this._isReplace = false;
- if (existing && wantReplace) {
- try {
- const prev = existing._layerInstance;
- if (prev && typeof prev._forceDestroy === 'function') prev._forceDestroy('replace');
- } catch {}
- try {
- if (existing._layerCloseTimer) {
- clearTimeout(existing._layerCloseTimer);
- existing._layerCloseTimer = null;
- }
- } catch {}
- try {
- if (existing._layerOnClick) {
- existing.removeEventListener('click', existing._layerOnClick);
- existing._layerOnClick = null;
- }
- } catch {}
- try {
- while (existing.firstChild) existing.removeChild(existing.firstChild);
- } catch {}
- try {
- existing.style.visibility = '';
- existing.classList.add('show');
- // Reset any inline fade state from the previous close
- existing.style.transition = 'none';
- existing.style.opacity = '1';
- requestAnimationFrame(() => {
- try { existing.style.transition = ''; } catch {}
- });
- } catch {}
- this.dom.overlay = existing;
- this.dom.overlay._layerInstance = this;
- this._isReplace = true;
- } else {
- if (existing) {
- try {
- const prev = existing._layerInstance;
- if (prev && typeof prev._forceDestroy === 'function') prev._forceDestroy('replace');
- } catch {}
- try { existing.remove(); } catch {}
- }
- // Create Overlay
- this.dom.overlay = el('div', `${PREFIX}overlay`);
- this.dom.overlay._layerInstance = this;
- }
- // Create Popup
- this.dom.popup = el('div', `${PREFIX}popup`);
- this.dom.overlay.appendChild(this.dom.popup);
- // Flow mode: pre-mount all steps and switch by hide/show (DOM continuity, less jitter)
- if (meta && meta.flow) {
- this._renderFlowUI();
- return;
- }
- // Icon
- if (this.params.icon) {
- this.dom.icon = this._createIcon(this.params.icon);
- this.dom.popup.appendChild(this.dom.icon);
- }
- // Title
- if (this.params.title) {
- this.dom.title = el('h2', `${PREFIX}title`, this.params.title);
- this.dom.popup.appendChild(this.dom.title);
- }
- // Content (Text / HTML / Element)
- if (this.params.text || this.params.html || this.params.content || this.params.dom) {
- this.dom.content = el('div', `${PREFIX}content`);
- // DOM content (preferred: dom, backward: content)
- const domSpec = this._normalizeDomSpec(this.params);
- if (domSpec) {
- this._mountDomContent(domSpec);
- } else if (this.params.html) {
- this.dom.content.innerHTML = this.params.html;
- } else {
- this.dom.content.textContent = this.params.text;
- }
-
- this.dom.popup.appendChild(this.dom.content);
- }
- // Actions
- this.dom.actions = el('div', `${PREFIX}actions`);
-
- // Cancel Button
- if (this.params.showCancelButton) {
- this.dom.cancelBtn = el('button', `${PREFIX}button ${PREFIX}cancel`, this.params.cancelButtonText);
- this.dom.cancelBtn.style.backgroundColor = this.params.cancelButtonColor;
- this.dom.cancelBtn.onclick = () => this._handleCancel();
- this.dom.actions.appendChild(this.dom.cancelBtn);
- }
- // Confirm Button
- this.dom.confirmBtn = el('button', `${PREFIX}button ${PREFIX}confirm`, this.params.confirmButtonText);
- this.dom.confirmBtn.style.backgroundColor = this.params.confirmButtonColor;
- this.dom.confirmBtn.onclick = () => this._handleConfirm();
- this.dom.actions.appendChild(this.dom.confirmBtn);
- this.dom.popup.appendChild(this.dom.actions);
- // Event Listeners
- if (this.params.closeOnClickOutside) {
- const onClick = (e) => {
- if (e.target === this.dom.overlay) {
- this._close(null); // Dismiss
- }
- };
- try {
- if (this.dom.overlay._layerOnClick) {
- this.dom.overlay.removeEventListener('click', this.dom.overlay._layerOnClick);
- }
- } catch {}
- this.dom.overlay._layerOnClick = onClick;
- this.dom.overlay.addEventListener('click', onClick);
- } else {
- try {
- if (this.dom.overlay._layerOnClick) {
- this.dom.overlay.removeEventListener('click', this.dom.overlay._layerOnClick);
- this.dom.overlay._layerOnClick = null;
- }
- } catch {}
- }
- // Avoid first-open overlay "flash": wait for CSS before inserting into DOM,
- // then show on a clean frame so opacity transitions are smooth.
- const ready = this._cssReady && typeof this._cssReady.then === 'function' ? this._cssReady : Promise.resolve();
- ready.then(() => {
- try { this.dom.overlay.style.visibility = ''; } catch {}
- if (!this.dom.overlay.parentNode) {
- document.body.appendChild(this.dom.overlay);
- }
- // Double-rAF gives the browser a chance to apply styles before animating.
- requestAnimationFrame(() => {
- requestAnimationFrame(() => {
- this.dom.overlay.classList.add('show');
- this._didOpen();
- });
- });
- });
- }
- _renderFlowUI() {
- // Icon/title/content/actions are stable; steps are pre-mounted and toggled.
- const popup = this.dom.popup;
- if (!popup) return;
- // Clear popup
- while (popup.firstChild) popup.removeChild(popup.firstChild);
- // Icon (in flow: suppressed by default unless question or summary)
- this.dom.icon = null;
- if (this.params.icon) {
- this.dom.icon = this._createIcon(this.params.icon);
- popup.appendChild(this.dom.icon);
- }
- // Title (always present for flow)
- this.dom.title = el('h2', `${PREFIX}title`, this.params.title || '');
- popup.appendChild(this.dom.title);
- // Content container
- this.dom.content = el('div', `${PREFIX}content`);
- // Stack container: keep panes absolute so we can cross-fade without layout thrash
- this.dom.stepStack = el('div', `${PREFIX}step-stack`);
- this.dom.stepStack.style.position = 'relative';
- this.dom.stepStack.style.width = '100%';
- this.dom.stepPanes = [];
- this._flowMountedList = [];
- const steps = this._flowResolved || (this._flowSteps || []).map((_, i) => this._getFlowStepOptions(i));
- steps.forEach((opt, i) => {
- const pane = el('div', `${PREFIX}step-pane`);
- pane.style.width = '100%';
- pane.style.boxSizing = 'border-box';
- pane.style.display = (i === this._flowIndex) ? '' : 'none';
- // Fill pane: dom/html/text
- const domSpec = this._normalizeDomSpec(opt);
- if (domSpec) {
- this._mountDomContentInto(pane, domSpec, { collectFlow: true });
- } else if (opt.html) {
- pane.innerHTML = opt.html;
- } else if (opt.text) {
- pane.textContent = opt.text;
- }
- this.dom.stepStack.appendChild(pane);
- this.dom.stepPanes.push(pane);
- });
- this.dom.content.appendChild(this.dom.stepStack);
- popup.appendChild(this.dom.content);
- // Actions
- this.dom.actions = el('div', `${PREFIX}actions`);
- popup.appendChild(this.dom.actions);
- this._updateFlowActions();
- // Event Listeners
- if (this.params.closeOnClickOutside) {
- const onClick = (e) => {
- if (e.target === this.dom.overlay) {
- this._close(null, 'backdrop');
- }
- };
- try {
- if (this.dom.overlay._layerOnClick) {
- this.dom.overlay.removeEventListener('click', this.dom.overlay._layerOnClick);
- }
- } catch {}
- this.dom.overlay._layerOnClick = onClick;
- this.dom.overlay.addEventListener('click', onClick);
- } else {
- try {
- if (this.dom.overlay._layerOnClick) {
- this.dom.overlay.removeEventListener('click', this.dom.overlay._layerOnClick);
- this.dom.overlay._layerOnClick = null;
- }
- } catch {}
- }
- // Avoid first-open overlay "flash": wait for CSS before inserting into DOM,
- // then show on a clean frame so opacity transitions are smooth.
- const ready = this._cssReady && typeof this._cssReady.then === 'function' ? this._cssReady : Promise.resolve();
- ready.then(() => {
- try { this.dom.overlay.style.visibility = ''; } catch {}
- if (!this.dom.overlay.parentNode) {
- document.body.appendChild(this.dom.overlay);
- }
- requestAnimationFrame(() => {
- requestAnimationFrame(() => {
- this.dom.overlay.classList.add('show');
- this._didOpen();
- });
- });
- });
- }
- _updateFlowActions() {
- const actions = this.dom && this.dom.actions;
- if (!actions) return;
- while (actions.firstChild) actions.removeChild(actions.firstChild);
- this.dom.cancelBtn = null;
- if (this.params.showCancelButton) {
- this.dom.cancelBtn = el('button', `${PREFIX}button ${PREFIX}cancel`, this.params.cancelButtonText);
- this.dom.cancelBtn.style.backgroundColor = this.params.cancelButtonColor;
- this.dom.cancelBtn.onclick = () => this._handleCancel();
- actions.appendChild(this.dom.cancelBtn);
- }
- this.dom.confirmBtn = el('button', `${PREFIX}button ${PREFIX}confirm`, this.params.confirmButtonText);
- this.dom.confirmBtn.style.backgroundColor = this.params.confirmButtonColor;
- this.dom.confirmBtn.onclick = () => this._handleConfirm();
- actions.appendChild(this.dom.confirmBtn);
- }
- _createIcon(type) {
- const icon = el('div', `${PREFIX}icon ${type}`);
- const applyIconSize = (mode) => {
- if (!(this.params && this.params.iconSize)) return;
- try {
- const s = String(this.params.iconSize).trim();
- if (!s) return;
- // For SweetAlert2-style success icon, scale via font-size so all `em`-based parts remain proportional.
- if (mode === 'font') {
- const m = s.match(/^(-?\d*\.?\d+)\s*(px|em|rem)$/i);
- if (m) {
- const n = parseFloat(m[1]);
- const unit = m[2];
- if (Number.isFinite(n) && n > 0) {
- icon.style.fontSize = (n / 5) + unit; // icon is 5em wide/tall
- return;
- }
- }
- }
- // Fallback: directly size the box (works great for SVG icons)
- icon.style.width = s;
- icon.style.height = s;
- } catch {}
- };
-
- const appendRingParts = () => {
- // Use the same "success-like" ring parts for every built-in icon
- icon.appendChild(el('div', `${PREFIX}success-circular-line-left`));
- icon.appendChild(el('div', `${PREFIX}success-ring`));
- icon.appendChild(el('div', `${PREFIX}success-fix`));
- icon.appendChild(el('div', `${PREFIX}success-circular-line-right`));
- };
-
- const createInnerMarkSvg = () => {
- const svg = svgEl('svg');
- svg.setAttribute('viewBox', '0 0 80 80');
- svg.setAttribute('aria-hidden', 'true');
- svg.setAttribute('focusable', 'false');
- return svg;
- };
-
- const addMarkPath = (svg, d, extraClass) => {
- const p = svgEl('path');
- p.setAttribute('d', d);
- p.setAttribute('class', `${PREFIX}svg-mark ${PREFIX}svg-draw${extraClass ? ' ' + extraClass : ''}`);
- p.setAttribute('stroke', 'currentColor');
- svg.appendChild(p);
- return p;
- };
-
- const addDot = (svg, cx, cy) => {
- const dot = svgEl('circle');
- dot.setAttribute('class', `${PREFIX}svg-dot`);
- dot.setAttribute('cx', String(cx));
- dot.setAttribute('cy', String(cy));
- dot.setAttribute('r', '3.2');
- dot.setAttribute('fill', 'currentColor');
- svg.appendChild(dot);
- return dot;
- };
-
- const appendBuiltInInnerMark = (svg) => {
- if (type === 'error') {
- addMarkPath(svg, 'M28 28 L52 52', `${PREFIX}svg-error-left`);
- addMarkPath(svg, 'M52 28 L28 52', `${PREFIX}svg-error-right`);
- } else if (type === 'warning') {
- addMarkPath(svg, 'M40 20 L40 46', `${PREFIX}svg-warning-line`);
- addDot(svg, 40, 58);
- } else if (type === 'info') {
- addMarkPath(svg, 'M40 34 L40 56', `${PREFIX}svg-info-line`);
- addDot(svg, 40, 25);
- } else if (type === 'question') {
- 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`);
- addDot(svg, 42, 61);
- }
- };
-
- if (type === 'success') {
- // SweetAlert2-compatible DOM structure (circle + tick) for exact style parity
- // <div class="...success-circular-line-left"></div>
- // <div class="...success-mark"><span class="...success-line-tip"></span><span class="...success-line-long"></span></div>
- // <div class="...success-ring"></div>
- // <div class="...success-fix"></div>
- // <div class="...success-circular-line-right"></div>
- icon.appendChild(el('div', `${PREFIX}success-circular-line-left`));
- const mark = el('div', `${PREFIX}success-mark`);
- mark.appendChild(el('span', `${PREFIX}success-line-tip`));
- mark.appendChild(el('span', `${PREFIX}success-line-long`));
- icon.appendChild(mark);
- icon.appendChild(el('div', `${PREFIX}success-ring`));
- icon.appendChild(el('div', `${PREFIX}success-fix`));
- icon.appendChild(el('div', `${PREFIX}success-circular-line-right`));
- applyIconSize('font');
- return icon;
- }
- if (type === 'error' || type === 'warning' || type === 'info' || type === 'question') {
- // Use the same "success-like" ring parts for every icon
- appendRingParts();
- applyIconSize('font');
- // SVG only draws the inner symbol (no SVG ring)
- const svg = createInnerMarkSvg();
- appendBuiltInInnerMark(svg);
- icon.appendChild(svg);
- return icon;
- }
- // Default to SVG icons for other/custom types
- applyIconSize('box');
- const svg = createInnerMarkSvg();
- const ring = svgEl('circle');
- ring.setAttribute('class', `${PREFIX}svg-ring ${PREFIX}svg-draw`);
- ring.setAttribute('cx', '40');
- ring.setAttribute('cy', '40');
- ring.setAttribute('r', '34');
- ring.setAttribute('stroke', 'currentColor');
- svg.appendChild(ring);
- // For custom types, we draw ring only by default (no inner mark).
- icon.appendChild(svg);
-
- return icon;
- }
- _adjustRingBackgroundColor() {
- try {
- const icon = this.dom && this.dom.icon;
- const popup = this.dom && this.dom.popup;
- if (!icon || !popup) return;
- const bg = getComputedStyle(popup).backgroundColor;
- const parts = icon.querySelectorAll(RING_BG_PARTS_SELECTOR);
- parts.forEach((el) => {
- try { el.style.backgroundColor = bg; } catch {}
- });
- } catch {}
- }
- _didOpen() {
- // Keyboard close (ESC)
- if (this.params.closeOnEsc) {
- this._onKeydown = (e) => {
- if (!e) return;
- if (e.key === 'Escape') this._close(null, 'esc');
- };
- document.addEventListener('keydown', this._onKeydown);
- }
- // Keep the "success-like" ring perfectly blended with popup bg
- this._adjustRingBackgroundColor();
- // Popup animation (optional)
- if (this.params.popupAnimation) {
- if (this.dom.popup) {
- // Use WAAPI directly to guarantee the slide+fade effect is visible,
- // independent from xjs.animate implementation details.
- try {
- const popup = this.dom.popup;
- try { popup.classList.add(`${PREFIX}popup-anim-slide`); } catch {}
- const rect = popup.getBoundingClientRect();
- // Default entrance: from above center by "more than half" of popup height.
- // Clamp to viewport so very tall popups don't start far off-screen.
- const vh = (typeof window !== 'undefined' && window && window.innerHeight) ? window.innerHeight : rect.height;
- const baseH = Math.min(rect.height, vh);
- const y0 = -Math.round(Math.max(18, baseH * 0.75));
- // Disable CSS transform transition so it won't fight with WAAPI.
- popup.style.transition = 'none';
- popup.style.willChange = 'transform, opacity';
- // If WAAPI is available, prefer it (most consistent).
- if (popup.animate) {
- const anim = popup.animate(
- [
- { transform: `translateY(${y0}px) scale(0.92)`, opacity: 0 },
- { transform: 'translateY(0px) scale(1)', opacity: 1 }
- ],
- {
- duration: 520,
- easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)',
- fill: 'forwards'
- }
- );
- anim.finished
- .catch(() => {})
- .finally(() => {
- try { popup.style.willChange = ''; } catch {}
- });
- } else {
- // Fallback: try xjs.animate if WAAPI isn't available.
- const X = Layer._getXjs();
- if (X) {
- popup.style.opacity = '0';
- popup.style.transform = `translateY(${y0}px) scale(0.92)`;
- X(popup).animate({
- y: [y0, 0],
- scale: [0.92, 1],
- opacity: [0, 1],
- duration: 520,
- easing: 'ease-out'
- });
- }
- setTimeout(() => {
- try { popup.style.willChange = ''; } catch {}
- }, 560);
- }
- } catch {}
- }
- }
- // Replace mode: if popupAnimation is off, do a soft fade+scale to avoid a hard cut.
- if (!this.params.popupAnimation && this._isReplace && this.dom.popup) {
- try {
- const popup = this.dom.popup;
- popup.style.transition = 'none';
- popup.style.opacity = '0';
- popup.style.transform = 'scale(0.98)';
- requestAnimationFrame(() => {
- popup.style.transition = 'opacity 0.22s ease, transform 0.22s ease';
- popup.style.opacity = '1';
- popup.style.transform = 'scale(1)';
- setTimeout(() => {
- try { popup.style.transition = ''; } catch {}
- try { popup.style.opacity = ''; } catch {}
- try { popup.style.transform = ''; } catch {}
- }, 260);
- });
- } catch {}
- }
- // Icon SVG draw animation
- if (this.params.iconAnimation) {
- this._animateIcon();
- }
- // User hook (SweetAlert-ish naming)
- try {
- if (typeof this.params.didOpen === 'function') this.params.didOpen(this.dom.popup);
- } catch {}
- }
- _animateIcon() {
- const icon = this.dom.icon;
- if (!icon) return;
- const type = (this.params && this.params.icon) || '';
- // Ring animation (same as success) for all built-in icons
- if (RING_TYPES.has(type)) this._adjustRingBackgroundColor();
- try { icon.classList.remove(`${PREFIX}icon-show`); } catch {}
- requestAnimationFrame(() => {
- try { icon.classList.add(`${PREFIX}icon-show`); } catch {}
- });
- // Success tick is CSS-driven; others still draw their SVG mark after the ring starts.
- if (type === 'success') return;
- const X = Layer._getXjs();
- if (!X) return;
- const svg = icon.querySelector('svg');
- if (!svg) return;
- const marks = Array.from(svg.querySelectorAll(`.${PREFIX}svg-mark`));
- const dot = svg.querySelector(`.${PREFIX}svg-dot`);
- // If this is a built-in icon, keep the SweetAlert-like order:
- // ring sweep first (~0.51s), then draw the inner mark.
- const baseDelay = RING_TYPES.has(type) ? 520 : 0;
- if (type === 'error') {
- // Draw order: left-top -> right-bottom, then right-top -> left-bottom
- // NOTE: A tiny delay (like 70ms) looks simultaneous; make it strictly sequential.
- const a = svg.querySelector(`.${PREFIX}svg-error-left`) || marks[0]; // M28 28 L52 52
- const b = svg.querySelector(`.${PREFIX}svg-error-right`) || marks[1]; // M52 28 L28 52
- const dur = 320;
- const gap = 60;
- try { if (a) X(a).draw({ duration: dur, easing: 'ease-out', delay: baseDelay }); } catch {}
- try { if (b) X(b).draw({ duration: dur, easing: 'ease-out', delay: baseDelay + dur + gap }); } catch {}
- } else {
- // warning / info / question (single stroke) or custom SVG symbols
- marks.forEach((m, i) => {
- try { X(m).draw({ duration: 420, easing: 'ease-out', delay: baseDelay + i * 60 }); } catch {}
- });
- }
- if (dot) {
- try {
- dot.style.opacity = '0';
- // Keep dot pop after the ring begins
- const d = baseDelay + 140;
- if (type === 'info') {
- X(dot).animate({ opacity: [0, 1], y: [-8, 0], scale: [0.2, 1], duration: 420, delay: d, easing: { stiffness: 300, damping: 14 } });
- } else {
- X(dot).animate({ opacity: [0, 1], scale: [0.2, 1], duration: 320, delay: d, easing: { stiffness: 320, damping: 18 } });
- }
- } catch {}
- }
- }
- _forceDestroy(reason = 'replace') {
- // Restore mounted DOM (if any) and cleanup listeners; also resolve the promise so it doesn't hang.
- try {
- if (this._flowSteps && this._flowSteps.length) this._unmountFlowMounted();
- else this._unmountDomContent();
- } catch {}
- if (this._onKeydown) {
- try { document.removeEventListener('keydown', this._onKeydown); } catch {}
- this._onKeydown = null;
- }
- try {
- if (this.resolve) {
- this.resolve({ isConfirmed: false, isDenied: false, isDismissed: true, dismiss: reason });
- }
- } catch {}
- }
- _close(isConfirmed, reason) {
- if (this._isClosing) return;
- this._isClosing = true;
- const shouldDelayUnmount = !!(
- (this._mounted && this._mounted.kind === 'move') ||
- (this._flowSteps && this._flowSteps.length && this._flowMountedList && this._flowMountedList.length)
- ) || !this.params.popupAnimation;
- const doUnmount = () => {
- try {
- if (this._flowSteps && this._flowSteps.length) this._unmountFlowMounted();
- else this._unmountDomContent();
- } catch {}
- };
- if (!shouldDelayUnmount) {
- // Restore mounted DOM (moved into popup) before removing overlay
- doUnmount();
- }
- let customClose = false;
- // Soft close for non-popupAnimation cases (avoid abrupt cut)
- if (!this.params.popupAnimation) {
- try {
- const popup = this.dom.popup;
- if (popup) {
- popup.style.transition = 'opacity 0.22s ease';
- popup.style.opacity = '0';
- popup.style.transform = '';
- }
- if (this.dom.overlay) {
- const overlay = this.dom.overlay;
- // Use inline opacity to avoid class-based jumps
- overlay.style.transition = 'opacity 0.22s ease';
- overlay.style.opacity = '1';
- requestAnimationFrame(() => {
- try {
- if (overlay._layerInstance !== this) return;
- overlay.style.opacity = '0';
- } catch {}
- });
- }
- customClose = true;
- } catch {}
- }
- if (!customClose) {
- this.dom.overlay.classList.remove('show');
- }
- try {
- if (this.dom.overlay) {
- const overlay = this.dom.overlay;
- const delay = customClose ? 240 : 300;
- overlay._layerCloseTimer = setTimeout(() => {
- if (shouldDelayUnmount) {
- doUnmount();
- }
- if (overlay._layerInstance !== this) return;
- if (overlay.parentNode) {
- overlay.parentNode.removeChild(overlay);
- }
- }, delay);
- }
- } catch {}
- if (this._onKeydown) {
- try { document.removeEventListener('keydown', this._onKeydown); } catch {}
- this._onKeydown = null;
- }
- try {
- if (typeof this.params.willClose === 'function') this.params.willClose(this.dom.popup);
- } catch {}
- try {
- if (typeof this.params.didClose === 'function') this.params.didClose();
- } catch {}
- const value = (this._flowSteps && this._flowSteps.length) ? (this._flowValues || []) : undefined;
- let data;
- if (this._flowSteps && this._flowSteps.length && this._flowAutoForm && this._flowAutoForm.enabled) {
- const root = (this.dom && (this.dom.stepStack || this.dom.content || this.dom.popup)) || null;
- data = this._collectFormData(root);
- }
- if (isConfirmed === true) {
- const payload = { isConfirmed: true, isDenied: false, isDismissed: false, value };
- if (data !== undefined) payload.data = data;
- this.resolve(payload);
- } else if (isConfirmed === false) {
- const payload = { isConfirmed: false, isDenied: false, isDismissed: true, dismiss: reason || 'cancel', value };
- if (data !== undefined) payload.data = data;
- this.resolve(payload);
- } else {
- const payload = { isConfirmed: false, isDenied: false, isDismissed: true, dismiss: reason || 'backdrop', value };
- if (data !== undefined) payload.data = data;
- this.resolve(payload);
- }
- }
- _assignFormValue(data, name, value, forceArray) {
- if (!data || !name) return;
- let key = name;
- let asArray = !!forceArray;
- if (key.endsWith('[]')) {
- key = key.slice(0, -2);
- asArray = true;
- }
- if (!(key in data)) {
- data[key] = asArray ? [value] : value;
- return;
- }
- if (Array.isArray(data[key])) {
- data[key].push(value);
- return;
- }
- data[key] = [data[key], value];
- }
- _collectFormData(root) {
- const data = {};
- if (!root || !root.querySelectorAll) return data;
- const fields = root.querySelectorAll('input, select, textarea');
- fields.forEach((el) => {
- try {
- if (!el || el.disabled) return;
- const name = (el.getAttribute('name') || '').trim();
- if (!name) return;
- const tag = (el.tagName || '').toLowerCase();
- if (tag === 'select') {
- if (el.multiple) {
- const values = Array.from(el.options || []).filter((o) => o.selected).map((o) => o.value);
- values.forEach((v) => this._assignFormValue(data, name, v, true));
- } else {
- this._assignFormValue(data, name, el.value, false);
- }
- return;
- }
- if (tag === 'textarea') {
- this._assignFormValue(data, name, el.value, false);
- return;
- }
- const type = (el.getAttribute('type') || 'text').toLowerCase();
- if (type === 'radio') {
- if (el.checked) this._assignFormValue(data, name, el.value, false);
- return;
- }
- if (type === 'checkbox') {
- if (el.checked) this._assignFormValue(data, name, el.value, true);
- return;
- }
- if (type === 'file') {
- const files = el.files ? Array.from(el.files) : [];
- this._assignFormValue(data, name, files, true);
- return;
- }
- this._assignFormValue(data, name, el.value, false);
- } catch {}
- });
- return data;
- }
- _normalizeDomSpec(params) {
- // Preferred: params.dom (selector/Element/template)
- // Backward: params.content (selector/Element) OR advanced object { dom, mode, clone }
- const p = params || {};
- let dom = p.dom;
- let mode = p.domMode || 'move';
- if (dom == null && p.content != null) {
- if (typeof p.content === 'object' && !(p.content instanceof Element)) {
- if (p.content && (p.content.dom != null || p.content.selector != null)) {
- dom = (p.content.dom != null) ? p.content.dom : p.content.selector;
- if (p.content.mode) mode = p.content.mode;
- if (p.content.clone === true) mode = 'clone';
- }
- } else {
- dom = p.content;
- }
- }
- if (dom == null) return null;
- return { dom, mode };
- }
- _mountDomContentInto(target, domSpec, opts = null) {
- // Like _mountDomContent, but mounts into the provided container.
- const collectFlow = !!(opts && opts.collectFlow);
- const originalContent = this.dom.content;
- // Temporarily redirect this.dom.content for reuse of internal logic.
- try { this.dom.content = target; } catch {}
- try {
- const before = this._mounted;
- this._mountDomContent(domSpec);
- const rec = this._mounted;
- // If we mounted in move-mode, _mounted holds record; detach it from single-mode tracking.
- if (collectFlow && rec && rec.kind === 'move') {
- this._flowMountedList.push(rec);
- this._mounted = before; // restore previous single record (usually null)
- }
- } finally {
- try { this.dom.content = originalContent; } catch {}
- }
- }
- _unmountFlowMounted() {
- // Restore all moved DOM nodes for flow steps
- const list = Array.isArray(this._flowMountedList) ? this._flowMountedList : [];
- this._flowMountedList = [];
- list.forEach((m) => {
- try {
- if (!m || m.kind !== 'move') return;
- // Reuse single unmount logic by swapping _mounted
- const prev = this._mounted;
- this._mounted = m;
- this._unmountDomContent();
- this._mounted = prev;
- } catch {}
- });
- }
- _mountDomContent(domSpec) {
- try {
- if (!this.dom.content) return;
- this._unmountDomContent(); // ensure only one mount at a time
- const forceVisible = (el) => {
- if (!el) return { prevHidden: false, prevInlineDisplay: '' };
- const prevHidden = !!el.hidden;
- const prevInlineDisplay = (el.style && typeof el.style.display === 'string') ? el.style.display : '';
- try { el.hidden = false; } catch {}
- try {
- const cs = (typeof getComputedStyle === 'function') ? getComputedStyle(el) : null;
- const display = cs ? String(cs.display || '') : '';
- // If element is hidden via CSS (e.g. .hidden-dom{display:none}),
- // add an inline override so it becomes visible inside the popup.
- if (display === 'none') el.style.display = 'block';
- else if (el.style && el.style.display === 'none') el.style.display = 'block';
- } catch {}
- return { prevHidden, prevInlineDisplay };
- };
- let node = domSpec.dom;
- if (typeof node === 'string') node = document.querySelector(node);
- if (!node) return;
- // <template> support: always clone template content
- if (typeof HTMLTemplateElement !== 'undefined' && node instanceof HTMLTemplateElement) {
- const frag = node.content.cloneNode(true);
- this.dom.content.appendChild(frag);
- this._mounted = { kind: 'template' };
- return;
- }
- if (!(node instanceof Element)) return;
- if (domSpec.mode === 'clone') {
- const clone = node.cloneNode(true);
- // If original is hidden (via attr or CSS), the clone may inherit; force show it in popup.
- try { clone.hidden = false; } catch {}
- try {
- const cs = (typeof getComputedStyle === 'function') ? getComputedStyle(node) : null;
- const display = cs ? String(cs.display || '') : '';
- if (display === 'none') clone.style.display = 'block';
- } catch {}
- this.dom.content.appendChild(clone);
- this._mounted = { kind: 'clone' };
- return;
- }
- // Default: move into popup but restore on close
- const placeholder = document.createComment('layer-dom-placeholder');
- const parent = node.parentNode;
- const nextSibling = node.nextSibling;
- if (!parent) {
- // Detached node: moving would lose it when overlay is removed; clone instead.
- const clone = node.cloneNode(true);
- try { clone.hidden = false; } catch {}
- try { if (clone.style && clone.style.display === 'none') clone.style.display = ''; } catch {}
- this.dom.content.appendChild(clone);
- this._mounted = { kind: 'clone' };
- return;
- }
- try { parent.insertBefore(placeholder, nextSibling); } catch {}
- const { prevHidden, prevInlineDisplay } = forceVisible(node);
- this.dom.content.appendChild(node);
- this._mounted = { kind: 'move', originalEl: node, placeholder, parent, nextSibling, prevHidden, prevInlineDisplay };
- } catch {
- // ignore
- }
- }
- _unmountDomContent() {
- const m = this._mounted;
- if (!m) return;
- this._mounted = null;
- if (m.kind !== 'move') return;
- const node = m.originalEl;
- if (!node) return;
- // Restore hidden/display
- try { node.hidden = !!m.prevHidden; } catch {}
- try {
- if (node.style && typeof m.prevInlineDisplay === 'string') node.style.display = m.prevInlineDisplay;
- } catch {}
- // Move back to original position
- try {
- const ph = m.placeholder;
- if (ph && ph.parentNode) {
- ph.parentNode.insertBefore(node, ph);
- ph.parentNode.removeChild(ph);
- return;
- }
- } catch {}
- // Fallback: append to original parent
- try {
- if (m.parent) m.parent.appendChild(node);
- } catch {}
- }
- _setButtonsDisabled(disabled) {
- try {
- if (this.dom && this.dom.confirmBtn) this.dom.confirmBtn.disabled = !!disabled;
- if (this.dom && this.dom.cancelBtn) this.dom.cancelBtn.disabled = !!disabled;
- } catch {}
- }
- async _handleConfirm() {
- // Flow next / finalize
- if (this._flowSteps && this._flowSteps.length) {
- return this._flowNext();
- }
- // Single popup: support async preConfirm
- const pre = this.params && this.params.preConfirm;
- if (typeof pre === 'function') {
- try {
- this._setButtonsDisabled(true);
- const r = pre(this.dom && this.dom.popup);
- const v = (r && typeof r.then === 'function') ? await r : r;
- if (v === false) {
- this._setButtonsDisabled(false);
- return;
- }
- // store value in non-flow mode as single value
- this._flowValues = [v];
- } catch (e) {
- console.error(e);
- this._setButtonsDisabled(false);
- return;
- }
- }
- this._close(true, 'confirm');
- }
- _handleCancel() {
- if (this._flowSteps && this._flowSteps.length) {
- // default: if not first step, cancel acts as "back"
- if (this._flowIndex > 0) {
- this._flowPrev();
- return;
- }
- }
- this._close(false, 'cancel');
- }
- _getFlowStepOptions(index) {
- const step = (this._flowSteps && this._flowSteps[index]) ? this._flowSteps[index] : {};
- const base = this._flowBase || {};
- const merged = { ...base, ...step };
- // Default button texts for flow
- const isLast = index >= (this._flowSteps.length - 1);
- if (!('confirmButtonText' in step)) merged.confirmButtonText = isLast ? (base.confirmButtonText || 'OK') : 'Next';
- // Show cancel as Back after first step (unless step explicitly overrides)
- if (index > 0) {
- if (!('showCancelButton' in step)) merged.showCancelButton = true;
- if (!('cancelButtonText' in step)) merged.cancelButtonText = 'Back';
- } else {
- // First step default keeps base settings
- if (!('cancelButtonText' in step) && merged.showCancelButton) merged.cancelButtonText = merged.cancelButtonText || 'Cancel';
- }
- // Icon/animation policy for flow:
- // - During steps: no icon/animations by default (avoids distraction + layout jitter)
- // - Allow icon only if step explicitly uses `icon:'question'`, or step is marked as summary.
- const isSummary = !!(step && (step.summary === true || step.isSummary === true));
- const explicitIcon = ('icon' in step) ? step.icon : undefined;
- const baseIcon = ('icon' in base) ? base.icon : undefined;
- const chosenIcon = (explicitIcon !== undefined) ? explicitIcon : baseIcon;
- if (!isSummary && !isLast) {
- merged.icon = (chosenIcon === 'question') ? 'question' : null;
- merged.iconAnimation = false;
- } else if (!isSummary && isLast) {
- // last step: still suppress unless summary or question
- merged.icon = (chosenIcon === 'question') ? 'question' : null;
- merged.iconAnimation = false;
- } else {
- // summary step: allow icon; animation follows explicit config (default true only if provided elsewhere)
- if (!('icon' in step) && chosenIcon === undefined) merged.icon = null;
- }
- return merged;
- }
- async _flowNext() {
- const idx = this._flowIndex;
- const total = this._flowSteps.length;
- const isLast = idx >= (total - 1);
- // preConfirm hook for current step
- const pre = this.params && this.params.preConfirm;
- if (typeof pre === 'function') {
- try {
- this._setButtonsDisabled(true);
- const r = pre(this.dom && this.dom.popup, idx);
- const v = (r && typeof r.then === 'function') ? await r : r;
- if (v === false) {
- this._setButtonsDisabled(false);
- return;
- }
- this._flowValues[idx] = v;
- } catch (e) {
- console.error(e);
- this._setButtonsDisabled(false);
- return;
- }
- }
- if (isLast) {
- this._close(true, 'confirm');
- return;
- }
- this._setButtonsDisabled(false);
- await this._flowGo(idx + 1, 'next');
- }
- async _flowPrev() {
- const idx = this._flowIndex;
- if (idx <= 0) return;
- await this._flowGo(idx - 1, 'prev');
- }
- async _flowGo(index, direction) {
- const next = (this._flowResolved && this._flowResolved[index]) ? this._flowResolved[index] : this._getFlowStepOptions(index);
- await this._transitionToFlow(index, next, direction);
- }
- async _transitionToFlow(nextIndex, nextOptions, direction) {
- const popup = this.dom && this.dom.popup;
- const content = this.dom && this.dom.content;
- const panes = this.dom && this.dom.stepPanes;
- if (!popup || !content || !panes || !panes.length) {
- this._flowIndex = nextIndex;
- this.params = nextOptions;
- this._render({ flow: true });
- return;
- }
- const fromIndex = this._flowIndex;
- const fromPane = panes[fromIndex];
- const toPane = panes[nextIndex];
- if (!fromPane || !toPane) {
- this._flowIndex = nextIndex;
- this.params = nextOptions;
- this._render({ flow: true });
- return;
- }
- // Measure current content height
- const oldH = content.getBoundingClientRect().height;
- // Prepare target pane for measurement without affecting layout
- const prevDisplay = toPane.style.display;
- const prevPos = toPane.style.position;
- const prevVis = toPane.style.visibility;
- const prevPointer = toPane.style.pointerEvents;
- toPane.style.display = '';
- toPane.style.position = 'absolute';
- toPane.style.visibility = 'hidden';
- toPane.style.pointerEvents = 'none';
- toPane.style.left = '0';
- toPane.style.right = '0';
- const newH = toPane.getBoundingClientRect().height;
- // Restore pane styles (keep hidden until animation starts)
- toPane.style.position = prevPos;
- toPane.style.visibility = prevVis;
- toPane.style.pointerEvents = prevPointer;
- toPane.style.display = prevDisplay; // usually 'none'
- // Apply new options (title/buttons/icon policy) before showing the pane
- this._flowIndex = nextIndex;
- this.params = nextOptions;
- // Update icon/title/buttons without recreating DOM
- try {
- if (this.dom.title) this.dom.title.textContent = this.params.title || '';
- } catch {}
- // Icon updates (only if needed)
- try {
- const wantsIcon = !!this.params.icon;
- if (!wantsIcon && this.dom.icon) {
- this.dom.icon.remove();
- this.dom.icon = null;
- } else if (wantsIcon) {
- const curType = this.dom.icon ? (Array.from(this.dom.icon.classList).find(c => c !== `${PREFIX}icon`) || '') : '';
- if (!this.dom.icon || !this.dom.icon.classList.contains(String(this.params.icon))) {
- if (this.dom.icon) this.dom.icon.remove();
- this.dom.icon = this._createIcon(this.params.icon);
- // icon should be on top (before title)
- popup.insertBefore(this.dom.icon, this.dom.title || popup.firstChild);
- }
- }
- } catch {}
- this._updateFlowActions();
- // Switch panes with directional slide (next: left, prev: right)
- const isNext = direction !== 'prev';
- const enterFrom = isNext ? 100 : -100;
- const exitTo = isNext ? -100 : 100;
- // Prepare panes for animation
- toPane.style.display = '';
- toPane.style.position = 'absolute';
- toPane.style.left = '0';
- toPane.style.right = '0';
- toPane.style.top = '0';
- toPane.style.transform = `translateX(${enterFrom}%)`;
- toPane.style.opacity = '0';
- toPane.style.pointerEvents = 'none';
- fromPane.style.position = 'absolute';
- fromPane.style.left = '0';
- fromPane.style.right = '0';
- fromPane.style.top = '0';
- fromPane.style.transform = 'translateX(0%)';
- fromPane.style.opacity = '1';
- fromPane.style.pointerEvents = 'none';
- // Lock content height during transition
- content.style.height = oldH + 'px';
- content.style.overflow = 'hidden';
- const slideDuration = 320;
- let heightAnim = null;
- let fromAnim = null;
- let toAnim = null;
- try {
- heightAnim = content.animate(
- [{ height: oldH + 'px' }, { height: newH + 'px' }],
- { duration: 220, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' }
- );
- } catch {}
- try {
- if (fromPane.animate && toPane.animate) {
- fromAnim = fromPane.animate(
- [
- { transform: 'translateX(0%)', opacity: 1 },
- { transform: `translateX(${exitTo}%)`, opacity: 0.1 }
- ],
- { duration: slideDuration, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' }
- );
- toAnim = toPane.animate(
- [
- { transform: `translateX(${enterFrom}%)`, opacity: 0.2 },
- { transform: 'translateX(0%)', opacity: 1 }
- ],
- { duration: slideDuration, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' }
- );
- }
- } catch {}
- try {
- await Promise.all([
- heightAnim && heightAnim.finished ? heightAnim.finished.catch(() => {}) : Promise.resolve(),
- fromAnim && fromAnim.finished ? fromAnim.finished.catch(() => {}) : Promise.resolve(),
- toAnim && toAnim.finished ? toAnim.finished.catch(() => {}) : Promise.resolve()
- ]);
- } catch {}
- // Cleanup styles and hide old pane
- fromPane.style.display = 'none';
- fromPane.style.position = '';
- fromPane.style.left = '';
- fromPane.style.right = '';
- fromPane.style.top = '';
- fromPane.style.transform = '';
- fromPane.style.opacity = '';
- fromPane.style.pointerEvents = '';
- toPane.style.position = 'relative';
- toPane.style.left = '';
- toPane.style.right = '';
- toPane.style.top = '';
- toPane.style.transform = '';
- toPane.style.opacity = '';
- toPane.style.pointerEvents = '';
- content.style.height = '';
- content.style.overflow = '';
- // Re-adjust ring background if icon exists (rare in flow)
- try { this._adjustRingBackgroundColor(); } catch {}
- }
- _rerenderInside() {
- // Update popup content without recreating overlay (used in flow transitions)
- const popup = this.dom && this.dom.popup;
- if (!popup) return;
- // Clear popup (but keep reference)
- while (popup.firstChild) popup.removeChild(popup.firstChild);
- // Icon
- this.dom.icon = null;
- if (this.params.icon) {
- this.dom.icon = this._createIcon(this.params.icon);
- popup.appendChild(this.dom.icon);
- }
- // Title
- this.dom.title = null;
- if (this.params.title) {
- this.dom.title = el('h2', `${PREFIX}title`, this.params.title);
- popup.appendChild(this.dom.title);
- }
- // Content
- this.dom.content = null;
- if (this.params.text || this.params.html || this.params.content || this.params.dom) {
- this.dom.content = el('div', `${PREFIX}content`);
- const domSpec = this._normalizeDomSpec(this.params);
- if (domSpec) this._mountDomContent(domSpec);
- else if (this.params.html) this.dom.content.innerHTML = this.params.html;
- else this.dom.content.textContent = this.params.text;
- popup.appendChild(this.dom.content);
- }
- // Actions / buttons
- this.dom.actions = el('div', `${PREFIX}actions`);
- this.dom.cancelBtn = null;
- if (this.params.showCancelButton) {
- this.dom.cancelBtn = el('button', `${PREFIX}button ${PREFIX}cancel`, this.params.cancelButtonText);
- this.dom.cancelBtn.style.backgroundColor = this.params.cancelButtonColor;
- this.dom.cancelBtn.onclick = () => this._handleCancel();
- this.dom.actions.appendChild(this.dom.cancelBtn);
- }
- this.dom.confirmBtn = el('button', `${PREFIX}button ${PREFIX}confirm`, this.params.confirmButtonText);
- this.dom.confirmBtn.style.backgroundColor = this.params.confirmButtonColor;
- this.dom.confirmBtn.onclick = () => this._handleConfirm();
- this.dom.actions.appendChild(this.dom.confirmBtn);
- popup.appendChild(this.dom.actions);
- // Re-run open hooks for each step
- try {
- if (typeof this.params.didOpen === 'function') this.params.didOpen(this.dom.popup);
- } catch {}
- }
- }
- return Layer;
- })));
|