import "./css/popup.scss"; import { r as lang } from "../utility/lgres"; import { nullOrEmpty } from "../utility/strings"; import { global, isPromiseLike } from "../utility"; import { appendResizer, makeMovable } from "./movable"; import { createElement, mergeOptions } from "../functions"; import { createIcon, changeIcon } from "./icon"; import { requestAnimationFrame } from "../ui"; /** @import { PopupOptions, PopupRectParam, PopupButton, Popup as IPopup, MarkRequired, InputOptions } from '../types' */ const IconStyle = 'fa-light'; /** * @private * @param {string} px * @returns {number | undefined} */ function trimPx(px) { if (typeof px !== 'string') { return px; } if (px.endsWith('px')) { const size = Number(px.substring(0, px.length - 2)); if (!isNaN(size)) { return size; } } } /** @satisfies {Partial} */ const DEFAULT_OPTIONS = { content: '', title: '', persistent: false, mask: true, changeZIndex: false, closable: true, movable: true, resizable: false, minWidth: 200, minHeight: 200, collapsable: false }; /** @typedef {MarkRequired} ResolvedPopupOptions */ /** * @implements {IPopup} */ export class Popup { _var = { /** @type {HTMLElement | undefined} */ mask: undefined, /** @type {ResolvedPopupOptions} */ option: DEFAULT_OPTIONS, /** @type {PopupRectParam | undefined} */ bounds: undefined, cursor: undefined, /** @type {(() => void) | undefined} */ movableDisposer: undefined, __resolved: false }; /** * @param {PopupOptions} opts */ constructor(opts) { this._var.option = mergeOptions(DEFAULT_OPTIONS, opts); } get container() { return /** @type {HTMLElement | undefined} */ (this._var.mask?.querySelector('.ui-popup-container')) } get title() { return this._var.option.title; } set title(title) { const element = this._var.mask?.querySelector('.ui-popup-container .ui-popup-header .ui-popup-header-title'); if (element instanceof HTMLElement) { if (typeof title === 'string') { element.innerText = title; } else { element.replaceChildren(title); } } this._var.option.title = title; } _getLoadingPanel() { const panel = this._var.mask?.querySelector('.ui-popup-body>.ui-popup-loading'); if (panel instanceof HTMLElement) { return panel; } return null; } get loading() { return this._getLoadingPanel()?.style?.visibility === 'visible' } set loading(flag) { let loading = this._getLoadingPanel(); if (loading == null) { return; } if (flag === false) { loading.style.visibility = 'hidden'; loading.style.opacity = '0'; } else { loading.style.visibility = 'visible'; loading.style.opacity = '1'; } } /** @returns {PopupRectParam | undefined} */ get rect() { const container = this.container; if (container == null) { return; } const style = global.getComputedStyle(container); const collapsed = container.classList.contains('ui-popup-collapse'); const bounds = this._var.bounds; return { collapsed, left: trimPx(style.left), top: trimPx(style.top), width: collapsed === true && bounds != null ? bounds.width : trimPx(style.width), height: collapsed === true && bounds != null ? bounds.height : trimPx(style.height) }; } /** * @param {PopupRectParam} r */ set rect(r) { const container = this.container; if (container == null) { return; } const css = []; if (r.left != null && !isNaN(r.left)) { css.push(`left: ${r.left}px`); } if (r.top != null && !isNaN(r.top)) { css.push(`top: ${r.top}px`); } const collapse = container.querySelector('.ui-popup-header-icons>.icon-expand'); if (r.collapsed === true) { css.push('width: 160px', 'height: 40px'); this._var.bounds = r; container.classList.add('ui-popup-collapse'); if (collapse != null) { changeIcon(collapse, IconStyle, 'expand-alt'); } } else { if (r.width != null && !isNaN(r.width) && r.width > 0) { css.push(`width: ${r.width}px`); } if (r.height != null && !isNaN(r.height) && r.height > 0) { css.push(`height: ${r.height}px`); } container.classList.remove('ui-popup-collapse'); delete this._var.bounds; if (collapse != null) { changeIcon(collapse, IconStyle, 'compress-alt'); } } if (css.length > 0) { container.style.cssText += css.join('; '); } } /** * @param {any} [result] * @param {boolean} [animation] */ close(result = null, animation = true) { const option = this._var.option; const mask = this._var.mask; const doClose = () => { if (typeof this._var.movableDisposer === 'function') { this._var.movableDisposer(); } if (option.persistent) { if (mask != null) { mask.style.display = 'none'; } } else { mask?.remove(); delete this._var.mask; } } if (animation) { if (mask != null) { mask.classList.add('ui-popup-active'); mask.style.opacity = '0'; } setTimeout(() => { doClose(); }, 120); } else { doClose(); } if (typeof option.onMasking === 'function') { option.onMasking.call(this, false); } if (typeof option.resolve === 'function') { option.resolve.call(this, { result, popup: this }); } } /** * 创建 Popup 面板 * @returns {HTMLDivElement} 返回遮罩元素(顶层元素) */ create() { const mask = createElement('div', 'ui-popup-mask ui-popup-active'); const option = this._var.option; if (!option.mask) { mask.classList.add('ui-popup-transparent'); } else if (typeof option.onMasking === 'function') { option.onMasking.call(this, true); } if (option.zIndex != null && !isNaN(option.zIndex)) { mask.style.zIndex = String(option.zIndex); } const container = createElement('div', 'ui-popup-container drag-box'); if (option.changeZIndex) { container.addEventListener('mousedown', () => { const children = this._var.mask?.parentElement?.children; if (children == null) { return; } const masks = [...children].filter(e => e.classList.contains('ui-popup-mask')); let max = 200; (/** @type {HTMLElement[]} */ (masks)).forEach(m => { let index; if (m.dataset.zindex != null) { index = parseInt(m.dataset.zindex); m.style.zIndex = isNaN(index) ? '' : String(index); delete m.dataset.zindex; } else { index = parseInt(m.style.zIndex); } if (index > max) { max = index; } }); mask.dataset.zindex = mask.style.zIndex; mask.style.zIndex = `${max + 1}`; }); } else { } let tabIndex = Math.max.apply(null, /** @type {HTMLElement[]} */([...document.querySelectorAll('[tabindex]')]).map(e => e.tabIndex ?? 0)); if (tabIndex < 0) { tabIndex = 0; } container.tabIndex = tabIndex + 1; let content = option.content; if (!(content instanceof HTMLElement)) { content = createElement('div', d => d.innerText = (/** @type {string} */ (content))); } container.append( createElement('div', header => { header.className = 'ui-popup-header'; let title = option.title; if (!(title instanceof HTMLElement)) { title = createElement('div', t => { t.className = 'ui-popup-header-title'; t.innerText = (/** @type {string} */ (title)); }); } header.appendChild(title); if (option.movable) { header.classList.add('drag-hover'); } const icons = createElement('div', icons => { icons.className = 'ui-popup-header-icons'; if (option.collapsable) { const collapse = createIcon(IconStyle, 'compress-alt'); collapse.tabIndex = tabIndex + 2; collapse.classList.add('icon-expand'); collapse.addEventListener('keypress', e => { if (e.key === ' ' || e.key === 'Enter') { collapse.dispatchEvent(new MouseEvent('click')); } }); collapse.addEventListener('click', () => { if (container.classList.contains('ui-popup-collapse')) { const bounds = this._var.bounds; if (bounds != null) { container.style.cssText += `width: ${bounds.width}px; height: ${bounds.height}px`; delete this._var.bounds; } container.classList.remove('ui-popup-collapse'); changeIcon(collapse, IconStyle, 'compress-alt'); } else { const rect = this.rect; this._var.bounds = rect; container.style.cssText += `width: 160px; height: 40px`; container.classList.add('ui-popup-collapse'); changeIcon(collapse, IconStyle, 'expand-alt'); } if (typeof option.onResizeEnded === 'function') { option.onResizeEnded.call(this); } }); icons.appendChild(collapse); } if (option.closable) { const cancel = createIcon(IconStyle, 'times'); cancel.tabIndex = tabIndex + 3; cancel.addEventListener('keypress', e => { if (e.key === ' ' || e.key === 'Enter') { this.close(); } }); cancel.addEventListener('click', () => this.close()); icons.appendChild(cancel); } }); header.appendChild(icons); }), createElement('div', 'ui-popup-body', content, createElement('div', 'ui-popup-loading', createElement('div', null, createIcon(IconStyle, 'spinner-third')) )) ); if (Array.isArray(option.buttons) && option.buttons.length > 0) { tabIndex = Math.max.apply(null, /** @type {HTMLElement[]} */([...container.querySelectorAll('[tabindex]')]).map(e => e.tabIndex ?? 0)); container.appendChild( createElement('div', 'ui-popup-footer', ...option.buttons.map((b, i) => { const button = createElement('button', 'ui-popup-button'); if (b.className != null) { button.classList.add(b.className); } if (b.isPrimary) { button.classList.add('primary'); } if (b.tabIndex != null && b.tabIndex > 0) { button.tabIndex = b.tabIndex; } else { button.tabIndex = tabIndex + i + 1; } button.innerText = b.text; button.addEventListener('click', () => { if (this._var.__resolved) { return; } this._var.__resolved = true; if (typeof b.trigger === 'function') { const result = b.trigger(this); if (typeof result === 'boolean' || typeof result === 'string' || typeof result === 'number') { if (result !== false) { this.close(result); } else { this._var.__resolved = false; } } else if (isPromiseLike(result)) { const tmp = result.then(r => { if (r !== false) { this.close(r); } else { this._var.__resolved = false; } }); if ('catch' in tmp && typeof tmp.catch === 'function') { tmp.catch(/** @param {any} reason */ reason => { this._var.__resolved = false; console.warn(reason); }); } } else { this.close(); } } else { this.close(b.key ?? i); } }); return button; })) ); const tabs = /** @type {HTMLElement[]} */ ([...container.querySelectorAll('[tabindex]')]).map(e => e.tabIndex ?? 0); const tabMin = Math.min.apply(null, tabs); const tabMax = Math.max.apply(null, tabs); /** @type {HTMLElement | null} */ const last = container.querySelector(`[tabindex="${tabMax}"]`); if (last != null) { last.addEventListener('keydown', e => { if (e.key === 'Tab') { /** @type {HTMLElement | null} */ const first = container.querySelector(`[tabindex="${tabMin}"]`); first?.focus(); e.preventDefault(); } }); } } else { container.querySelector('.ui-popup-body>.ui-popup-loading')?.classList.add('ui-popup-loading-content'); } // resizable if (option.resizable) { appendResizer(container); } if (option.movable || option.resizable) { const parent = !option.mask ? document.body : mask; this._var.movableDisposer = makeMovable(parent, { movable: option.movable, resizable: option.resizable, context: this, onMoved: option.onMoveEnded, onResizeStart: option.onResizeStarted, onResized: option.onResizeEnded }); } mask.appendChild(container); this._var.mask = mask; return mask; } /** * @param {HTMLElement} parent * @param {boolean} hidden * @returns {Promise | undefined} */ show(parent = document.body, hidden = false) { if (parent == null) { return; } let mask = this._var.mask; if (mask == null) { mask = this._var.mask = this.create(); } if (mask.parentElement == null) { // const exists = [...parent.children].filter(e => e.classList.contains('ui-popup-mask')); const exists = parent.querySelectorAll('.ui-popup-mask'); let zindex = 0; for (let ex of exists) { let z = parseInt(global.getComputedStyle(ex).zIndex); if (!isNaN(z) && z > zindex) { zindex = z; } } if (zindex > 0) { mask.style.zIndex = String(zindex + 1); } parent.appendChild(mask); if (hidden === true) { mask.style.display = 'none'; return Promise.resolve(mask); } } if (!this._var.option.mask) { // calculator position const container = this.container; if (container != null) { container.style.left = String((parent.offsetWidth - container.offsetWidth) / 2) + 'px'; container.style.top = String((parent.offsetHeight - container.offsetHeight) / 2) + 'px' }; } return new Promise(resolve => { mask.style.display = ''; requestAnimationFrame(() => { mask.classList.remove('ui-popup-active'); mask.style.opacity = '1'; this.container?.focus(); setTimeout(() => resolve(mask), 120); }); }); } } /** * @param {string | HTMLElement} title * @param {string | HTMLElement} content * @param {...PopupButton} buttons * @returns {Popup} */ export function createPopup(title, content, ...buttons) { const popup = new Popup({ title, content, buttons }); return popup; } /** * 解析对话框元素 * @param {HTMLElement | string | null} wrapper - 解析该 `.dialog` 元素 * @param {Function} [callback] - 关闭对话框时的回调 * @param {boolean} [removable] - 是否可移除 * @param {number} [zIndex] - 对话框默认 `z-index` * @returns {Popup | null} 返回弹出框字典 */ export function resolvePopup(wrapper, callback, removable, zIndex) { if (typeof wrapper === 'string') { wrapper = document.querySelector(wrapper); } if (wrapper == null) { return null; } if (!wrapper.classList.contains('dialog')) { return null; } const title = /** @type {HTMLElement | null} */ (wrapper.querySelector('.dialog-title>.title'))?.innerText ?? ''; /** @type {HTMLElement | null} */ const content = wrapper.querySelector('.dialog-title+div'); const buttons = /** @type {HTMLInputElement[]} */ ([...wrapper.querySelectorAll('.dialog-func>input[type="button"]')].reverse()).map(b => ({ tabIndex: b.tabIndex, text: b.value, isPrimary: b.dataset.primary != null, // @ts-ignore trigger: b.onclick == null ? undefined : ((/** @type {IPopup} */ popup) => (b.onclick?.call(popup, null), false)) })); const z = parseInt(global.getComputedStyle(wrapper).zIndex); const popup = new Popup({ title, content: content ?? '', persistent: !removable, resolve: typeof callback === 'function' ? (result => callback(result)) : undefined, zIndex: z == null || isNaN(z) ? zIndex : z, buttons }); popup.show(document.body, true); return popup; } const iconTypes = { 'info': 'info-circle', 'information': 'info-circle', 'warn': 'exclamation-triangle', 'warning': 'exclamation-triangle', 'question': 'question-circle', 'error': 'times-circle' } /** * @param {string | HTMLElement} title * @param {string} message * @param {keyof iconTypes} iconType * @param {HTMLElement} parent * @returns {Promise} */ export function showAlert(title, message, iconType = 'info', parent = document.body) { const r = typeof global.GetTextByKey === 'function' ? global.GetTextByKey : lang; return new Promise(resolve => { const popup = new Popup({ title, content: createElement('div', 'message-wrapper', createIcon('fa-solid', iconTypes[iconType] ?? 'info-circle'), createElement('span', span => span.innerText = message) ), resolve, buttons: [ { text: r('ok', 'OK'), isPrimary: true } ] }); popup.show(parent)?.then(mask => { /** @type {HTMLElement | null} */ const button = mask.querySelector('.ui-popup-container .ui-popup-footer .ui-popup-button'); button?.focus(); }); }); } /** * @param {string | HTMLElement} title * @param {boolean} [multiline] * @param {string} [message] * @param {InputOptions} [options] * @param {PopupButton[]} [buttons] * @param {HTMLElement} parent * @returns {Promise} */ export function showInput(title, multiline, message, options, buttons, parent = document.body) { const r = typeof global.GetTextByKey === 'function' ? global.GetTextByKey : lang; const opts = mergeOptions({ tabIndex: undefined, default: undefined, placeholder: undefined }, options); return new Promise(resolve => { const input = multiline ? createElement('textarea', text => { text.className = 'ui-text'; }) : createElement('input', input => { input.type = 'text'; input.className = 'ui-input'; }); for (let key of Object.keys(opts)) { switch (key) { case 'tabIndex': if (!isNaN(opts.tabIndex)) { input.tabIndex = opts.tabIndex; } break; case 'default': if (!nullOrEmpty(opts.default)) { input.value = opts.default; } break; case 'placeholder': if (!nullOrEmpty(opts.placeholder)) { input.placeholder = opts.placeholder; } break; default: // @ts-ignore input[key] = opts[key]; break; } } if (isNaN(opts.tabIndex)) { let tabIndex = Math.max.apply(null, /** @type {HTMLElement[]} */([...document.querySelectorAll('[tabindex]')]).map(e => e.tabIndex ?? 0)); if (tabIndex < 0) { tabIndex = 0; } input.tabIndex = tabIndex + 4; } const popup = new Popup({ title, content: createElement('div', 'message-wrapper message-wrapper-input', nullOrEmpty(message) ? '' : createElement('span', span => span.innerText = message), input ), resolve: r => resolve(r.result === 'yes' ? input.value : null), buttons: buttons ?? [ { key: 'yes', text: r('yes', 'Yes'), isPrimary: true }, { key: 'no', text: r('no', 'No') } ] }); popup.show(parent)?.then(() => input.focus()); }); } /** * * @param {string | HTMLElement} title * @param {string | HTMLElement} content * @param {PopupButton[]} [buttons] * @param {keyof iconTypes} iconType * @param {HTMLElement} parent * @returns */ export function showConfirm(title, content, buttons, iconType = 'question', parent = document.body) { const r = typeof global.GetTextByKey === 'function' ? global.GetTextByKey : lang; return new Promise(resolve => { const wrapper = createElement('div', 'message-wrapper'); if (!nullOrEmpty(iconType)) { wrapper.appendChild(createIcon('fa-solid', iconTypes[iconType] ?? 'question-circle')); } wrapper.appendChild(content instanceof HTMLElement ? content : createElement('span', span => span.innerText = content)); const popup = new Popup({ title, content: wrapper, resolve, buttons: buttons?.map((b, i) => { return { text: b.text, isPrimary: b.isPrimary, trigger: p => { if (typeof b.trigger === 'function') { return b.trigger(p); } return b.key ?? i; } }; }) ?? [ { key: 'yes', text: r('yes', 'Yes'), isPrimary: true }, { key: 'no', text: r('no', 'No') } ] }); popup.show(parent)?.then(mask => { /** @type {HTMLElement | null} */ const button = mask.querySelector('.ui-popup-container .ui-popup-footer .ui-popup-button:first-child'); button?.focus(); }); }); }