This commit is contained in:
lchen committed 2026-11-23 17:22:07 +08:00
1 parent 5cb14ffd44
commit 05ce7035dd
15 files changed
+946 -460

No files matched your search

+142 -246
View File
@@ -2,36 +2,14 @@ import "./css/popup.scss";
import { r as lang } from "../utility/lgres";
import { nullOrEmpty } from "../utility/strings";
import { global } from "../utility";
import { createElement } from "../functions";
import { appendResizer, createElement, makeMovable, mergeOptions } from "../functions";
import { createIcon, changeIcon } from "./icon";
import { requestAnimationFrame } from "../ui";
/** @import { PopupOptions, PopupRectParam } from '../types' */
const ResizeMods = {
right: 1,
bottom: 2,
left: 4,
top: 8,
bottomRight: 2 | 1,
bottomLeft: 2 | 4,
topRight: 8 | 1,
topLeft: 8 | 4
}
/** @import { PopupOptions, PopupRectParam, PopupButton, Popup as IPopup, MarkRequired, InputOptions } from '../types' */
const IconStyle = 'fa-light';
// const Cursors = {
// [ResizeMods.right]: 'ew-resize',
// [ResizeMods.bottom]: 'ns-resize',
// [ResizeMods.bottomRight]: 'nwse-resize',
// [ResizeMods.left]: 'ew-resize',
// [ResizeMods.bottomLeft]: 'nesw-resize',
// [ResizeMods.top]: 'ns-resize',
// [ResizeMods.topRight]: 'nesw-resize',
// [ResizeMods.topLeft]: 'nwse-resize'
// }
/**
* @private
* @param {string} px
@@ -49,28 +27,47 @@ function trimPx(px) {
}
}
/** @type {import('../types').Popup} */
/** @satisfies {Partial<PopupOptions>} */
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<PopupOptions, keyof typeof DEFAULT_OPTIONS>} ResolvedPopupOptions */
/**
* @implements {IPopup}
*/
export class Popup {
_var = {
/** @type {HTMLElement | undefined} */
mask: undefined,
/** @type {PopupOptions | undefined} */
option: undefined,
/** @type {ResolvedPopupOptions} */
option: DEFAULT_OPTIONS,
/** @type {PopupRectParam | undefined} */
bounds: undefined,
cursor: undefined
};
/**
* @param {PopupOptions} [opts]
* @param {PopupOptions} opts
*/
constructor(opts) {
this._var.option = 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 ?? ''; }
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) {
@@ -80,9 +77,7 @@ export class Popup {
element.replaceChildren(title);
}
}
if (this._var.option != null) {
this._var.option.title = title;
}
this._var.option.title = title;
}
_getLoadingPanel() {
@@ -166,11 +161,15 @@ export class Popup {
}
}
/**
* @param {any} [result]
* @param {boolean} [animation]
*/
close(result = null, animation = true) {
const option = this._var.option;
const mask = this._var.mask;
const doClose = () => {
if (option?.persistent) {
if (option.persistent) {
if (mask != null) {
mask.style.display = 'none';
}
@@ -188,10 +187,10 @@ export class Popup {
} else {
doClose();
}
if (typeof option?.onMasking === 'function') {
if (typeof option.onMasking === 'function') {
option.onMasking.call(this, false);
}
if (typeof option?.resolve === 'function') {
if (typeof option.resolve === 'function') {
option.resolve.call(this, {
result,
popup: this
@@ -206,20 +205,24 @@ export class Popup {
create() {
const mask = createElement('div', 'ui-popup-mask ui-popup-active');
const option = this._var.option;
if (option?.mask === false) {
if (!option.mask) {
mask.classList.add('ui-popup-transparent');
} else if (typeof option?.onMasking === 'function') {
} else if (typeof option.onMasking === 'function') {
option.onMasking.call(this, true);
}
if (option?.zIndex != null && !isNaN(option.zIndex)) {
if (option.zIndex != null && !isNaN(option.zIndex)) {
mask.style.zIndex = String(option.zIndex);
}
const container = createElement('div', 'ui-popup-container');
if (option?.changeZIndex === true) {
const container = createElement('div', 'ui-popup-container drag-box');
if (option.changeZIndex) {
container.addEventListener('mousedown', () => {
const masks = [...this._var.mask?.parentElement?.children].filter(e => e.classList.contains('ui-popup-mask'));
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;
masks.forEach(m => {
(/** @type {HTMLElement[]} */ (masks)).forEach(m => {
let index;
if (m.dataset.zindex != null) {
index = parseInt(m.dataset.zindex);
@@ -243,63 +246,27 @@ export class Popup {
tabIndex = 0;
}
container.tabIndex = tabIndex + 1;
let content = option?.content;
let content = option.content;
if (!(content instanceof HTMLElement)) {
content = createElement('div', d => d.innerText = content);
content = createElement('div', d => d.innerText = (/** @type {string} */ (content)));
}
container.append(
createElement('div', header => {
header.className = 'ui-popup-header';
let title = option?.title;
let title = option.title;
if (!(title instanceof HTMLElement)) {
title = createElement('div', t => {
if (option?.movable === false) {
t.className = 'ui-popup-header-title no-move';
} else {
t.className = 'ui-popup-header-title';
}
t.innerText = title;
t.className = 'ui-popup-header-title';
t.innerText = (/** @type {string} */ (title));
});
}
header.appendChild(title);
if (option?.movable !== false) {
const move = header; // title.querySelector('.ui-popup-move') ?? title;
move.addEventListener('mousedown', e => {
if (['svg', 'use'].includes(e.target?.tagName)) {
return;
}
if (e.buttons !== 1) {
return;
}
const parent = option?.mask === false ? mask.parentElement : mask;
const x = e.clientX - container.offsetLeft;
const y = e.clientY - container.offsetTop;
/** @type {boolean} */
let moved;
const move = e => {
if (e.buttons === 1) {
container.style.left = `${e.clientX - x}px`;
container.style.top = `${e.clientY - y}px`;
moved = true;
} else {
parent.dispatchEvent(new MouseEvent('mouseup'));
}
};
parent.addEventListener('mousemove', move, { passive: false });
const up = () => {
parent.removeEventListener('mousemove', move, { passive: false });
parent.removeEventListener('mouseup', up);
if (moved === true && typeof option?.onMoveEnded === 'function') {
option.onMoveEnded.call(this);
}
moved = false;
};
parent.addEventListener('mouseup', up);
});
if (option.movable) {
header.classList.add('drag-hover');
}
const icons = createElement('div', icons => {
icons.className = 'ui-popup-header-icons';
if (option?.collapsable === true) {
if (option.collapsable) {
const collapse = createIcon(IconStyle, 'compress-alt');
collapse.tabIndex = tabIndex + 2;
collapse.classList.add('icon-expand');
@@ -324,13 +291,13 @@ export class Popup {
container.classList.add('ui-popup-collapse');
changeIcon(collapse, IconStyle, 'expand-alt');
}
if (typeof option?.onResizeEnded === 'function') {
if (typeof option.onResizeEnded === 'function') {
option.onResizeEnded.call(this);
}
});
icons.appendChild(collapse);
}
if (option?.closable !== false) {
if (option.closable) {
const cancel = createIcon(IconStyle, 'times');
cancel.tabIndex = tabIndex + 3;
cancel.addEventListener('keypress', e => {
@@ -348,7 +315,7 @@ export class Popup {
createElement('div', null, createIcon(IconStyle, 'spinner-third'))
))
);
if (Array.isArray(option?.buttons) && option.buttons.length > 0) {
if (Array.isArray(option.buttons) && option.buttons.length > 0) {
tabIndex = Math.max.apply(null, [...container.querySelectorAll('[tabindex]')].map(e => e.tabIndex ?? 0));
container.appendChild(
createElement('div', 'ui-popup-footer', ...option.buttons.map((b, i) => {
@@ -368,14 +335,14 @@ export class Popup {
button.addEventListener('click', () => {
if (typeof b.trigger === 'function') {
const result = b.trigger(this);
if (typeof result?.then === 'function') {
if (typeof result === 'boolean' || typeof result === 'string' || typeof result === 'number') {
this.close(result);
} else if (typeof result?.then === 'function') {
result.then(r => {
if (r !== false) {
this.close(r);
}
}).catch(reason => console.warn(reason));
} else if (result !== false) {
this.close(result);
}
} else {
this.close(b.key ?? i);
@@ -387,10 +354,12 @@ export class Popup {
const tabs = [...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();
@@ -398,50 +367,34 @@ export class Popup {
});
}
} else {
container.querySelector('.ui-popup-body>.ui-popup-loading').classList.add('ui-popup-loading-content');
container.querySelector('.ui-popup-body>.ui-popup-loading')?.classList.add('ui-popup-loading-content');
}
// resizable
if (option?.resizable === true) {
container.append(
createElement('layer', layer => {
layer.className = 'ui-popup-border ui-popup-border-right';
layer.addEventListener('mousedown', e => this._resize(ResizeMods.right, e));
}),
createElement('layer', layer => {
layer.className = 'ui-popup-border ui-popup-border-bottom';
layer.addEventListener('mousedown', e => this._resize(ResizeMods.bottom, e));
}),
createElement('layer', layer => {
layer.className = 'ui-popup-border ui-popup-border-left';
layer.addEventListener('mousedown', e => this._resize(ResizeMods.left, e));
}),
createElement('layer', layer => {
layer.className = 'ui-popup-border ui-popup-border-top';
layer.addEventListener('mousedown', e => this._resize(ResizeMods.top, e));
}),
createElement('layer', layer => {
layer.className = 'ui-popup-border ui-popup-border-bottom-right';
layer.addEventListener('mousedown', e => this._resize(ResizeMods.bottomRight, e));
}),
createElement('layer', layer => {
layer.className = 'ui-popup-border ui-popup-border-bottom-left';
layer.addEventListener('mousedown', e => this._resize(ResizeMods.bottomLeft, e));
}),
createElement('layer', layer => {
layer.className = 'ui-popup-border ui-popup-border-top-left';
layer.addEventListener('mousedown', e => this._resize(ResizeMods.topLeft, e));
}),
createElement('layer', layer => {
layer.className = 'ui-popup-border ui-popup-border-top-right';
layer.addEventListener('mousedown', e => this._resize(ResizeMods.topRight, e));
})
)
if (option.resizable) {
appendResizer(container);
}
if (option.movable || option.resizable) {
const parent = !option.mask ? document.body : mask;
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<HTMLElement> | undefined}
*/
show(parent = document.body, hidden = false) {
if (parent == null) {
return;
@@ -469,7 +422,7 @@ export class Popup {
return Promise.resolve(mask);
}
}
if (this._var.option?.mask === false) {
if (!this._var.option.mask) {
// calculator position
const container = this.container;
if (container != null) {
@@ -487,97 +440,14 @@ export class Popup {
});
});
}
_resize(mod, e) {
if (e.buttons !== 1) {
return;
}
const container = this.container;
if (container == null) {
return;
}
const option = this._var.option;
if (typeof option?.onResizeStarted === 'function') {
option.onResizeStarted.call(this);
}
const mask = this._var.mask;
// this._var.cursor = mask.style.cursor;
// mask.style.cursor = Cursors[mod];
const originalX = e.clientX;
const originalY = e.clientY;
const original = {
width: container.offsetWidth,
height: container.offsetHeight,
left: container.offsetLeft,
top: container.offsetTop
};
const minWidth = option?.minWidth ?? 200;
const minHeight = option?.minHeight ?? 200;
/** @type {boolean} */
let resized;
const parent = option?.mask === false ? mask.parentElement : mask;
const move = e => {
if (e.buttons !== 1) {
parent?.dispatchEvent(new MouseEvent('mouseup'));
return;
}
const offsetX = e.clientX - originalX;
const offsetY = e.clientY - originalY;
let width = original.width;
let height = original.height;
let x = original.left;
let y = original.top;
if ((mod & ResizeMods.right) === ResizeMods.right) {
width += offsetX;
if (width < minWidth) {
width = minWidth;
}
}
if ((mod & ResizeMods.bottom) === ResizeMods.bottom) {
height += offsetY;
if (height < minHeight) {
height = minHeight;
}
}
if ((mod & ResizeMods.left) === ResizeMods.left) {
width -= offsetX;
if (width < minWidth) {
width = minWidth;
x = originalX + original.width - minWidth;
} else {
x += offsetX;
}
}
if ((mod & ResizeMods.top) === ResizeMods.top) {
height -= offsetY;
if (height < minHeight) {
height = minHeight;
y = originalY + original.height - minHeight;
} else {
y += offsetY;
}
}
if (typeof option?.onResizing === 'function') {
option.onResizing.call(this, x, y, width, height);
} else {
container.style.cssText += `left: ${x}px; top: ${y}px; width: ${width}px; height: ${height}px`;
}
resized = true;
}
parent?.addEventListener('mousemove', move, { passive: false });
const up = () => {
parent.removeEventListener('mousemove', move, { passive: false });
parent.removeEventListener('mouseup', up);
// mask.style.cursor = this._var.cursor;
if (resized === true && typeof option?.onResizeEnded === 'function') {
option.onResizeEnded.call(this);
}
resized = false;
};
parent?.addEventListener('mouseup', up);
}
}
/**
* @param {string | HTMLElement} title
* @param {string | HTMLElement} content
* @param {...PopupButton} buttons
* @returns {Popup}
*/
export function createPopup(title, content, ...buttons) {
const popup = new Popup({
title,
@@ -589,11 +459,11 @@ export function createPopup(title, content, ...buttons) {
/**
* 解析对话框元素
* @param {HTMLElement | string} wrapper - 解析该 `.dialog` 元素
* @param {HTMLElement | string | null} wrapper - 解析该 `.dialog` 元素
* @param {Function} [callback] - 关闭对话框时的回调
* @param {boolean} [removable] - 是否可移除
* @param {number} [zIndex] - 对话框默认 `z-index`
* @returns {Popup} 返回弹出框字典
* @returns {Popup | null} 返回弹出框字典
*/
export function resolvePopup(wrapper, callback, removable, zIndex) {
if (typeof wrapper === 'string') {
@@ -606,18 +476,20 @@ export function resolvePopup(wrapper, callback, removable, zIndex) {
return null;
}
const title = wrapper.querySelector('.dialog-title>.title')?.innerText;
/** @type {HTMLElement | null} */
const content = wrapper.querySelector('.dialog-title+div');
const buttons = [...wrapper.querySelectorAll('.dialog-func>input[type="button"]')].reverse().map(b => ({
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,
trigger: b.onclick == null ? null : (popup => (b.onclick.call(popup), false))
// @ts-ignore
trigger: b.onclick == null ? undefined : ((/** @type {IPopup} */ popup) => (b.onclick?.call(popup, null), false))
}));
const popup = new Popup({
title,
content,
content: content ?? '',
persistent: !removable,
resolve: typeof callback === 'function' ? (result => callback(result)) : null,
resolve: typeof callback === 'function' ? (result => callback(result)) : undefined,
zIndex: wrapper.zIndex ?? zIndex,
buttons
});
@@ -634,8 +506,15 @@ const iconTypes = {
'error': 'times-circle'
}
/**
* @param {string | HTMLElement} title
* @param {string} message
* @param {keyof iconTypes} iconType
* @param {HTMLElement} parent
* @returns {Promise<any>}
*/
export function showAlert(title, message, iconType = 'info', parent = document.body) {
const r = typeof GetTextByKey === 'function' ? GetTextByKey : lang;
const r = typeof global.GetTextByKey === 'function' ? global.GetTextByKey : lang;
return new Promise(resolve => {
const popup = new Popup({
title,
@@ -648,16 +527,26 @@ export function showAlert(title, message, iconType = 'info', parent = document.b
{ text: r('ok', 'OK'), isPrimary: true }
]
});
popup.show(parent).then(mask => {
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<any>}
*/
export function showInput(title, multiline, message, options, buttons, parent = document.body) {
const r = typeof GetTextByKey === 'function' ? GetTextByKey : lang;
options ??= {};
const r = typeof global.GetTextByKey === 'function' ? global.GetTextByKey : lang;
const opts = mergeOptions({}, options);
return new Promise(resolve => {
const input = multiline ?
createElement('textarea', text => {
@@ -667,29 +556,29 @@ export function showInput(title, multiline, message, options, buttons, parent =
input.type = 'text';
input.className = 'ui-input';
});
for (let key of Object.keys(options)) {
for (let key of Object.keys(opts)) {
switch (key) {
case 'tabIndex':
if (!isNaN(options.tabIndex)) {
input.tabIndex = options.tabIndex;
if (!isNaN(opts.tabIndex)) {
input.tabIndex = opts.tabIndex;
}
break;
case 'default':
if (!nullOrEmpty(options.default)) {
input.value = options.default;
if (!nullOrEmpty(opts.default)) {
input.value = opts.default;
}
break;
case 'placeholder':
if (!nullOrEmpty(options.placeholder)) {
input.placeholder = options.placeholder;
if (!nullOrEmpty(opts.placeholder)) {
input.placeholder = opts.placeholder;
}
break;
default:
input[key] = options[key];
input[key] = opts[key];
break;
}
}
if (isNaN(options.tabIndex)) {
if (isNaN(opts.tabIndex)) {
let tabIndex = Math.max.apply(null, [...document.querySelectorAll('[tabindex]')].map(e => e.tabIndex ?? 0));
if (tabIndex < 0) {
tabIndex = 0;
@@ -708,12 +597,21 @@ export function showInput(title, multiline, message, options, buttons, parent =
{ key: 'no', text: r('no', 'No') }
]
});
popup.show(parent).then(() => input.focus());
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 GetTextByKey === 'function' ? GetTextByKey : lang;
const r = typeof global.GetTextByKey === 'function' ? global.GetTextByKey : lang;
return new Promise(resolve => {
const wrapper = createElement('div', 'message-wrapper');
if (!nullOrEmpty(iconType)) {
@@ -731,13 +629,10 @@ export function showConfirm(title, content, buttons, iconType = 'question', pare
text: b.text,
isPrimary: b.isPrimary,
trigger: p => {
let result;
if (typeof b.trigger === 'function') {
result = b.trigger(p, b);
} else {
result = b.key ?? i;
return b.trigger(p, b);
}
return result;
return b.key ?? i;
}
};
}) ??
@@ -746,7 +641,8 @@ export function showConfirm(title, content, buttons, iconType = 'question', pare
{ key: 'no', text: r('no', 'No') }
]
});
popup.show(parent).then(mask => {
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();
});