| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963 |
- (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>.
- const ensureXjsCss = () => {
- try {
- if (typeof document === 'undefined') return;
- if (!document.head) return;
- const existingHref = Array.from(document.querySelectorAll('link[rel="stylesheet"]'))
- .map((l) => (l.getAttribute('href') || '').trim())
- .find((h) => /(^|\/)xjs\.css(\?|#|$)/.test(h));
- if (existingHref) return;
- const id = 'xjs-css';
- if (document.getElementById(id)) return;
- 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;
- document.head.appendChild(link);
- } catch {
- // ignore
- }
- };
- class Layer {
- constructor() {
- 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;
- // Step/flow support
- this._flowSteps = null; // Array<options>
- this._flowIndex = 0;
- this._flowValues = [];
- this._flowBase = null; // base options merged into each step
- }
- // Constructor helper when called as function: const popup = Layer({...})
- static get isProxy() { return true; }
-
- // Static entry point
- static fire(options) {
- const instance = new Layer();
- return instance._fire(options);
- }
-
- // Chainable entry point (builder-style)
- // Example:
- // Layer.$({ title: 'Hi' }).fire().then(...)
- // Layer.$().config({ title: 'Hi' }).fire()
- static $(options) {
- const instance = new Layer();
- if (options !== undefined) instance.config(options);
- return instance;
- }
-
- // Chainable config helper (does not render until `.fire()` 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' }).fire()
- 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).fire();
- }
-
- // Instance entry point (chainable)
- fire(options) {
- // Flow mode: if configured via .step()/.steps(), ignore per-call options and use steps
- if (this._flowSteps && this._flowSteps.length) {
- if (options !== undefined && options !== null) {
- // allow providing base options at fire-time
- this.params = { ...(this.params || {}), ...normalizeOptions(options, arguments[1], arguments[2]) };
- }
- return this._fireFlow();
- }
- const merged = (options === undefined) ? (this.params || {}) : options;
- return this._fire(merged);
- }
- _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 = [];
- this._flowBase = { ...(this.params || {}) };
- this.promise = new Promise((resolve, reject) => {
- this.resolve = resolve;
- this.reject = reject;
- });
- const first = this._getFlowStepOptions(0);
- this.params = first;
- this._render({ flow: true });
- return this.promise;
- }
- static _getXjs() {
- // Prefer xjs, fallback to animal (compat)
- const g = (typeof window !== 'undefined') ? window : (typeof globalThis !== 'undefined' ? globalThis : null);
- if (!g) return null;
- const x = g.xjs || g.animal;
- return (typeof x === 'function') ? x : null;
- }
- _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`);
- 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);
- // 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) {
- this.dom.overlay.addEventListener('click', (e) => {
- if (e.target === this.dom.overlay) {
- this._close(null); // Dismiss
- }
- });
- }
- document.body.appendChild(this.dom.overlay);
- // Animation
- requestAnimationFrame(() => {
- this.dom.overlay.classList.add('show');
- this._didOpen();
- });
- }
- _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) {
- const X = Layer._getXjs();
- if (X && this.dom.popup) {
- // Override the CSS scale transition with a spring-ish entrance.
- try {
- this.dom.popup.style.transition = 'none';
- this.dom.popup.style.transform = 'scale(0.92)';
- X(this.dom.popup).animate({
- scale: [0.92, 1],
- y: [-6, 0],
- duration: 520,
- easing: { stiffness: 260, damping: 16 }
- });
- } 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 { 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;
- // Restore mounted DOM (moved into popup) before removing overlay
- try { this._unmountDomContent(); } catch {}
- this.dom.overlay.classList.remove('show');
- setTimeout(() => {
- if (this.dom.overlay && this.dom.overlay.parentNode) {
- this.dom.overlay.parentNode.removeChild(this.dom.overlay);
- }
- }, 300);
- 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;
- if (isConfirmed === true) {
- this.resolve({ isConfirmed: true, isDenied: false, isDismissed: false, value });
- } else if (isConfirmed === false) {
- this.resolve({ isConfirmed: false, isDenied: false, isDismissed: true, dismiss: reason || 'cancel', value });
- } else {
- this.resolve({ isConfirmed: false, isDenied: false, isDismissed: true, dismiss: reason || 'backdrop', value });
- }
- }
- _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 };
- }
- _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';
- }
- 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._getFlowStepOptions(index);
- this._flowIndex = index;
- await this._transitionTo(next, direction);
- }
- async _transitionTo(nextOptions, direction) {
- // Animate popup swap (keep overlay)
- const popup = this.dom && this.dom.popup;
- if (!popup) {
- this.params = nextOptions;
- this._rerenderInside();
- return;
- }
- // First, unmount moved DOM from current step so it can be remounted later
- try { this._unmountDomContent(); } catch {}
- const outKeyframes = [
- { opacity: 1, transform: 'translateY(0px)' },
- { opacity: 0.55, transform: `translateY(${direction === 'prev' ? '8px' : '-8px'})` }
- ];
- const inKeyframes = [
- { opacity: 0.55, transform: `translateY(${direction === 'prev' ? '-8px' : '8px'})` },
- { opacity: 1, transform: 'translateY(0px)' }
- ];
- try {
- const a = popup.animate(outKeyframes, { duration: 140, easing: 'ease-out', fill: 'forwards' });
- await (a && a.finished ? a.finished.catch(() => {}) : Promise.resolve());
- } catch {}
- // Apply new options
- this.params = nextOptions;
- this._rerenderInside();
- try {
- const b = popup.animate(inKeyframes, { duration: 200, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)', fill: 'forwards' });
- await (b && b.finished ? b.finished.catch(() => {}) : Promise.resolve());
- } catch {}
- // Re-adjust icon ring bg in case popup background differs
- 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;
- })));
|