add jsdoc comments

This commit is contained in:
lchen committed 2026-11-18 10:14:21 +08:00
1 parent 6de354ad47
commit 8c1205bc13
24 files changed
+1228 -425

No files matched your search

+1
View File
@@ -27,3 +27,4 @@ desktop.ini
# User definition # User definition
docs docs
jsdoc jsdoc
package-lock.json
+1
View File
@@ -0,0 +1 @@
@soft-qr:registry=https://git.soft.qr/api/packages/soft-qr/npm/
+7
View File
@@ -1,3 +1,10 @@
/**
* @template {keyof HTMLElementTagNameMap} K
* @param {K} tagName
* @param {string | ((e: HTMLElementTagNameMap[K]) => void) | null} [init]
* @param {...(string | Node)} children
* @returns {HTMLElementTagNameMap[K]}
*/
export function createElement(tagName, init, ...children) { export function createElement(tagName, init, ...children) {
const element = document.createElement(tagName); const element = document.createElement(tagName);
if (typeof init === 'function') { if (typeof init === 'function') {
+16
View File
@@ -0,0 +1,16 @@
export { };
declare global {
interface Window {
GetTextByKey?: (key: string, defaultValue?: string | null) => string;
consts?: {
resver: number,
path: string,
prefix: string,
cookie?: { lang: string },
user?: { language: string }
};
_network?: { root: string };
_net?: { root: string };
}
}
+161
View File
@@ -0,0 +1,161 @@
export type GetTextCallback = (key: string, defaultValue?: string | null) => string;
export interface LanguageResource {
[key: string]: string | undefined | GetTextCallback;
r: GetTextCallback;
}
export interface OptionParamBase {
getText?: GetTextCallback;
}
export interface NotifyOption {
message: string | HTMLElement;
parent?: HTMLElement;
title?: string;
type?: "success" | "warning" | "error";
persistent?: boolean;
timeout?: number;
onDismissed?: (auto?: boolean) => void;
}
export interface PopupRectParam {
collapsed?: boolean;
left?: number;
top?: number;
width?: number;
height?: number;
}
export interface Popup {
constructor(opts?: PopupOptions): void;
get container(): HTMLElement;
get title(): string;
set title(title: string);
get loading(): boolean;
set loading(flag: boolean);
get rect(): PopupRectParam | null;
set rect(r: PopupRectParam);
close(result?: any, animation?: boolean): void;
create(): HTMLDivElement;
show(parent?: HTMLElement, hidden?: boolean): Promise<HTMLElement> | undefined;
};
export interface PopupButton {
className?: string;
tabIndex?: number;
key: string;
text: string;
isPrimary?: boolean;
trigger: (this: Popup) => boolean | Promise<boolean>;
}
export interface PopupOptions {
/** 弹出框内容,可以是文本或者 html 元素 */
content: string | HTMLElement;
/** 弹出框标题,可以是文本或者 html 元素 */
title: string | HTMLElement;
/** 是否持久化显示 */
persistent?: boolean;
/** 是否包含遮罩层,默认为 `true` */
mask?: boolean;
/** 遮罩层 z-index */
zIndex?: number;
/** 是否在获取焦点时修改 z-index */
changeZIndex?: boolean;
/** 是否允许关闭 */
closable?: boolean;
/** 是否允许移动 */
movable?: boolean;
/** 是否允许修改大小 */
resizable?: boolean;
/** 最小宽度,默认 200 */
minWidth?: number;
/** 最小高度,默认 200 */
minHeight?: number;
/** 是否允许弹出框收折 */
collapsable?: boolean;
/** 弹出框的按钮定义集合 */
buttons?: PopupButton[];
/**
* 遮罩层显示或者隐藏时的回调函数
* @param this 当前 popup 对象
* @param masking 显示或隐藏遮罩层
*/
onMasking?: (this: Popup, masking: boolean) => void;
/**
* 移动结束时的回调函数
* @param this 当前 popup 对象
*/
onMoveEnded?: (this: Popup) => void;
/**
* 修改大小开始时的回调函数
* @param this 当前 popup 对象
*/
onResizeStarted?: (this: Popup) => void;
/**
* 修改大小中的回调函数
* @param this 当前 popup 对象
* @param x 坐标 x
* @param y 坐标 y
* @param width 当前宽度
* @param height 当前高度
*/
onResizing?: (this: Popup, x: number, y: number, width: number, height: number) => void;
/**
* 修改大小结束时的回调函数
* @param this 当前 popup 对象
*/
onResizeEnded?: (this: Popup) => void;
/**
* 弹出框关闭时的回调函数
*/
resolve?: (this: Popup, result: { result: any, popup: Popup }) => void;
}
/**
* 复选框选项
*/
export interface CheckboxOptions {
/** 样式类名 */
className?: string;
/** 是否可用 */
enabled?: boolean;
/** html 名称 */
name?: string;
/** 焦点索引 */
tabIndex?: number;
/** 是否为 switch 样式 */
switch?: boolean;
/** 样式分类 */
type?: "fa-light" | "fa-regular" | "fa-solid";
/** 标签 */
label?: string | HTMLElement;
/** 标签提示文本 */
title?: string;
/** 是否已选中 */
checked?: boolean;
/** 是否处于中间状态 */
indeterminate?: boolean;
/** 图片高度 */
imageHeight?: number;
/** 选中时显示的元素 */
checkedNode?: HTMLElement;
/** 未选中时显示的元素 */
uncheckedNode?: HTMLElement;
/** 自定义 html 属性 */
customAttributes?: { [key: string]: string };
/**
* 复选框选择状态改变时触发
* @param this 当前复选框对应的 HtmlInput 元素
* @param ev 选择事件对象
*/
onchange?: (this: HTMLInputElement, ev: Event) => any;
}
+50 -44
View File
@@ -14,72 +14,77 @@ import { validation, convertCssStyle } from './ui/extension';
import { createDateInput, toDateValue, getFormatter, formatDate, setDateValue, getDateValue, DateSelector } from './ui/date'; import { createDateInput, toDateValue, getFormatter, formatDate, setDateValue, getDateValue, DateSelector } from './ui/date';
import * as utility from './utility'; import * as utility from './utility';
/** @typedef {import('./global')} */
/**
* @param {FrameRequestCallback | TimerHandler} callback
* @returns {number}
*/
function requestAnimationFrame(callback) { function requestAnimationFrame(callback) {
if (typeof utility.global.requestAnimationFrame === 'function') { if (typeof utility.global.requestAnimationFrame === 'function') {
utility.global.requestAnimationFrame(callback); return utility.global.requestAnimationFrame(/** @type {FrameRequestCallback} */(callback));
} else {
setTimeout(callback, 0);
} }
return setTimeout(callback, 0);
} }
/**
* @private
* @returns {number}
*/
function scrollLeft() { function scrollLeft() {
const n = document.documentElement; const n = document.documentElement;
return (utility.global.scrollX || n.scrollLeft) - (n.clientLeft || 0); return (utility.global.scrollX || n.scrollLeft) - (n.clientLeft || 0);
} }
/**
* @private
* @returns {number}
*/
function scrollTop() { function scrollTop() {
const n = document.documentElement; const n = document.documentElement;
return (utility.global.scrollY || n.scrollTop) - (n.clientTop || 0); return (utility.global.scrollY || n.scrollTop) - (n.clientTop || 0);
} }
/** /**
* @private
* @param {HTMLElement} e * @param {HTMLElement} e
* @returns {DOMRectReadOnly}
*/ */
function offset(e) { function offset(e) {
const rect = e.getBoundingClientRect(); const rect = e.getBoundingClientRect();
return { return new DOMRectReadOnly(
top: rect.top + scrollTop(), rect.left + scrollLeft(),
left: rect.left + scrollLeft(), rect.top + scrollTop(),
height: rect.height, rect.width,
width: rect.width rect.height
}; );
} }
class OptionBase { class OptionBase {
_option; _option;
/** @type {import('./types').GetTextCallback} */
r; r;
/**
* @param {import('./types').OptionParamBase} opt
*/
constructor(opt) { constructor(opt) {
this._option = opt; this._option = opt;
const getText = opt.getText; const getText = opt.getText;
if (typeof getText === 'function') { if (typeof getText === 'function') {
this.r = getText; this.r = getText;
} else if (typeof GetTextByKey === 'function') { } else if (typeof utility.global.GetTextByKey === 'function') {
this.r = GetTextByKey; this.r = utility.global.GetTextByKey;
} else { } else {
this.r = utility.r; this.r = utility.r;
} }
} }
} }
/**
* 通知选项
* @typedef NotifyOption
* @property {string | HTMLElement} message - 内容,支持自定义元素
* @property {HTMLElement} [parent] - 目标父元素
* @property {string} [title] - 标题
* @property {"success" | "warning" | "error"} [type] - 提示类型
* @property {boolean} [persistent] - 是否持续显示,默认为 `false`,3 秒后自动关闭
* @property {number} [timeout] - 超时时间,默认 3 秒
* @property {(auto: boolean) => void} [onDismissed] - 关闭时触发的函数
*/
/** /**
* @private * @private
* @param {HTMLDivElement} wrapper * @param {HTMLDivElement} wrapper
* @param {(auto: boolean) => void} [onDismissed] * @param {(auto?: boolean) => void} [onDismissed]
* @param {boolean} [auto] * @param {boolean} [auto]
*/ */
function closeNotify(wrapper, onDismissed, auto) { function closeNotify(wrapper, onDismissed, auto) {
@@ -93,22 +98,26 @@ function closeNotify(wrapper, onDismissed, auto) {
} }
/** /**
* * @param {import('./types').NotifyOption} [opts]
* @param {NotifyOption} opts * @returns {HTMLDivElement | undefined}
*/ */
function notify(opts) { function notify(opts) {
opts ||= {}; const message = opts?.message;
if (message == null) {
return;
}
/** @type {number} */
let timer; let timer;
const close = createIcon('fa-light', 'times'); const close = createIcon('fa-light', 'times');
close.classList.add('ui-notify-close'); close.classList.add('ui-notify-close');
close.addEventListener('click', () => { close.addEventListener('click', () => {
timer && clearTimeout(timer); timer && clearTimeout(timer);
closeNotify(wrapper, opts.onDismissed); closeNotify(wrapper, opts?.onDismissed);
}); });
let type; let type;
let typeClass; let typeClass;
opts.type ||= 'success'; switch (opts?.type) {
switch (opts.type) {
case 'warning': case 'warning':
type = 'exclamation-circle'; type = 'exclamation-circle';
typeClass = 'warning'; typeClass = 'warning';
@@ -117,39 +126,36 @@ function notify(opts) {
type = 'times-circle'; type = 'times-circle';
typeClass = 'error'; typeClass = 'error';
break; break;
case 'success':
type = 'check-circle';
typeClass = 'success';
break;
default: default:
type = opts.type; type = opts?.type ?? 'check-circle';
typeClass = 'success'; typeClass = 'success';
break; break;
} }
const icon = createIcon('fa-solid', type); const icon = createIcon('fa-solid', type);
icon.classList.add('ui-notify-type', typeClass); icon.classList.add('ui-notify-type', typeClass);
const title = opts?.title;
const wrapper = createElement('div', 'ui-notify', const wrapper = createElement('div', 'ui-notify',
utility.nullOrEmpty(opts.title) ? utility.nullOrEmpty(title) ?
createElement('div', 'ui-notify-single', createElement('div', 'ui-notify-single',
icon, icon,
createElement('span', 'ui-notify-message', opts.message), createElement('span', 'ui-notify-message', message),
close close
) : ) :
createElement('div', 'ui-notify-content', createElement('div', 'ui-notify-content',
createElement('div', 'ui-notify-header', createElement('div', 'ui-notify-header',
icon, icon,
createElement('h2', 'ui-notify-title', opts.title), createElement('h2', 'ui-notify-title', title),
close close
), ),
createElement('span', 'ui-notify-message', opts.message) createElement('span', 'ui-notify-message', message)
) )
); );
if (!opts.persistent) { if (opts?.persistent !== true) {
timer = setTimeout(() => { timer = setTimeout(() => {
closeNotify(wrapper, opts.onDismissed, true); closeNotify(wrapper, opts?.onDismissed, true);
}, opts.timeout || 3000); }, opts?.timeout || 3000);
} }
(opts.parent ?? document.body).appendChild(wrapper); (opts?.parent ?? document.body).appendChild(wrapper);
setTimeout(() => wrapper.classList.add('active'), 10); setTimeout(() => wrapper.classList.add('active'), 10);
return wrapper; return wrapper;
} }
+47 -15
View File
@@ -1,8 +1,20 @@
import './css/checkbox.scss'; import './css/checkbox.scss';
import { createElement } from "../functions"; import { createElement } from "../functions";
import { createIcon } from "./icon"; import { createIcon } from "./icon";
import { isPositive, nullOrEmpty } from '../utility';
function fillCheckbox(container, type = 'fa-regular', label, tabindex = -1, charactor = 'check', title) { /** @typedef {import('../types').CheckboxOptions} CheckboxOptions */
/**
* @private
* @param {HTMLElement} container
* @param {string} [type="fa-regular"]
* @param {string | HTMLElement} [label]
* @param {number} [tabindex]
* @param {string} [title]
* @param {string} [charactor]
*/
function fillCheckbox(container, type = 'fa-regular', label, tabindex = -1, title, charactor = 'check') {
const checkIcon = createIcon(type, charactor); const checkIcon = createIcon(type, charactor);
checkIcon.classList.add('ui-check-icon'); checkIcon.classList.add('ui-check-icon');
const indeterminateIcon = createIcon(type, 'minus'); const indeterminateIcon = createIcon(type, 'minus');
@@ -24,7 +36,7 @@ function fillCheckbox(container, type = 'fa-regular', label, tabindex = -1, char
} }
}, checkIcon, indeterminateIcon) }, checkIcon, indeterminateIcon)
); );
if (label instanceof Element) { if (label instanceof HTMLElement) {
container.appendChild(label); container.appendChild(label);
} else if (label != null && String(label).length > 0) { } else if (label != null && String(label).length > 0) {
container.appendChild( container.appendChild(
@@ -38,11 +50,18 @@ function fillCheckbox(container, type = 'fa-regular', label, tabindex = -1, char
} }
} }
/**
* 创建一个单选框
* @param {CheckboxOptions} opts
* @returns {HTMLLabelElement}
*/
export function createRadiobox(opts = {}) { export function createRadiobox(opts = {}) {
const container = createElement('label', 'ui-check-wrapper ui-radio-wrapper', const container = createElement('label', 'ui-check-wrapper ui-radio-wrapper',
createElement('input', input => { createElement('input', input => {
input.setAttribute('type', 'radio'); input.setAttribute('type', 'radio');
input.name = opts.name; if (!nullOrEmpty(opts.name)) {
input.name = opts.name;
}
if (opts.checked === true) { if (opts.checked === true) {
input.checked = true; input.checked = true;
} }
@@ -61,10 +80,15 @@ export function createRadiobox(opts = {}) {
if (opts.className) { if (opts.className) {
container.classList.add(opts.className); container.classList.add(opts.className);
} }
fillCheckbox(container, opts.type, opts.label, opts.tabIndex, 'circle', opts.title); fillCheckbox(container, opts.type, opts.label, opts.tabIndex, opts.title, 'circle');
return container; return container;
} }
/**
* 创建一个复选框
* @param {CheckboxOptions} opts
* @returns {HTMLLabelElement}
*/
export function createCheckbox(opts = {}) { export function createCheckbox(opts = {}) {
const container = createElement('label', opts.switch ? 'ui-switch' : 'ui-check-wrapper', const container = createElement('label', opts.switch ? 'ui-switch' : 'ui-check-wrapper',
createElement('input', input => { createElement('input', input => {
@@ -112,7 +136,7 @@ export function createCheckbox(opts = {}) {
} else if (opts.checkedNode != null && opts.uncheckedNode != null) { } else if (opts.checkedNode != null && opts.uncheckedNode != null) {
container.classList.add('ui-check-image-wrapper'); container.classList.add('ui-check-image-wrapper');
let height = opts.imageHeight; let height = opts.imageHeight;
if (isNaN(height) || height <= 0) { if (!isPositive(height)) {
height = 14; height = 14;
} }
opts.checkedNode.classList.add('checked'); opts.checkedNode.classList.add('checked');
@@ -120,16 +144,22 @@ export function createCheckbox(opts = {}) {
opts.uncheckedNode.classList.add('unchecked'); opts.uncheckedNode.classList.add('unchecked');
container.appendChild(opts.uncheckedNode); container.appendChild(opts.uncheckedNode);
} else { } else {
fillCheckbox(container, opts.type, opts.label, opts.tabIndex, undefined, opts.title); fillCheckbox(container, opts.type, opts.label, opts.tabIndex, opts.title);
} }
return container; return container;
} }
/**
* 解析容器元素内符合条件的子元素为复选框元素
* @param {HTMLElement} container
* @param {boolean} [legacy]
* @returns {HTMLElement}
*/
export function resolveCheckbox(container = document.body, legacy) { export function resolveCheckbox(container = document.body, legacy) {
if (legacy) { if (legacy) {
const checks = container.querySelectorAll('input[type="checkbox"]'); const checks = container.querySelectorAll('input[type="checkbox"]');
for (let chk of checks) { for (let chk of checks) {
if (chk.parentElement.classList.contains('ui-check-wrapper')) { if (!(chk instanceof HTMLInputElement) || chk.parentElement?.classList.contains('ui-check-wrapper')) {
// skip // skip
continue; continue;
} }
@@ -140,7 +170,7 @@ export function resolveCheckbox(container = document.body, legacy) {
} }
if (label == null) { if (label == null) {
const e = chk.nextElementSibling; const e = chk.nextElementSibling;
if (e != null) { if (e instanceof HTMLElement) {
if (e.tagName === 'LABEL') { if (e.tagName === 'LABEL') {
label = e; label = e;
} else if (e.tagName === 'SPAN' && e.dataset.lgid != null) { } else if (e.tagName === 'SPAN' && e.dataset.lgid != null) {
@@ -151,7 +181,7 @@ export function resolveCheckbox(container = document.body, legacy) {
} }
if (label == null) { if (label == null) {
const e = chk.previousElementSibling; const e = chk.previousElementSibling;
if (e != null) { if (e instanceof HTMLElement) {
if (e.tagName === 'LABEL') { if (e.tagName === 'LABEL') {
label = e; label = e;
} else if (text == null && e.tagName === 'SPAN' && e.dataset.lgid != null) { } else if (text == null && e.tagName === 'SPAN' && e.dataset.lgid != null) {
@@ -160,9 +190,9 @@ export function resolveCheckbox(container = document.body, legacy) {
} }
} }
} }
if (label == null) { if (!(label instanceof HTMLElement)) {
label = createElement('label'); label = createElement('label');
chk.parentElement.insertBefore(label, chk); chk.parentElement?.insertBefore(label, chk);
} else { } else {
text = label.innerText; text = label.innerText;
} }
@@ -172,12 +202,15 @@ export function resolveCheckbox(container = document.body, legacy) {
label.className = 'ui-check-wrapper'; label.className = 'ui-check-wrapper';
} }
label.replaceChildren(); label.replaceChildren();
fillCheckbox(label, 'fa-regular', text, chk.tabIndex, undefined, label.title); fillCheckbox(label, 'fa-regular', text, chk.tabIndex, label.title);
label.insertBefore(chk, label.firstChild); label.insertBefore(chk, label.firstChild);
} }
} }
const boxes = container.querySelectorAll('label[data-checkbox]'); const boxes = container.querySelectorAll('label[data-checkbox]');
for (let box of boxes) { for (let box of boxes) {
if (!(box instanceof HTMLLabelElement)) {
continue;
}
if (!box.classList.contains('ui-check-wrapper')) { if (!box.classList.contains('ui-check-wrapper')) {
box.classList.add('ui-check-wrapper'); box.classList.add('ui-check-wrapper');
} }
@@ -189,8 +222,7 @@ export function resolveCheckbox(container = document.body, legacy) {
fillCheckbox(box, fillCheckbox(box,
box.dataset.type, box.dataset.type,
box.dataset.label, box.dataset.label,
box.dataset.tabIndex, Number(box.dataset.tabIndex),
undefined,
box.title); box.title);
box.removeAttribute('title'); box.removeAttribute('title');
box.removeAttribute('data-type'); box.removeAttribute('data-type');
@@ -198,7 +230,7 @@ export function resolveCheckbox(container = document.body, legacy) {
} }
const input = createElement('input'); const input = createElement('input');
const id = box.dataset.id; const id = box.dataset.id;
if (id?.length > 0) { if (!nullOrEmpty(id)) {
input.id = id; input.id = id;
} }
if (box.dataset.checked != null) { if (box.dataset.checked != null) {
+79 -86
View File
@@ -1,20 +1,18 @@
import { createElement } from "../functions"; import { createElement } from "../functions";
import { isPositive, nullOrEmpty } from "../utility"; import { isPositive, isTag, nullOrEmpty } from "../utility";
/** /**
* 创建或转换日期选择框 * 创建或转换日期选择框
* @param {string} [min] - 最小可选日期 * @param {string | null} [min] 最小可选日期
* @param {string} [max] - 最大可选日期 * @param {string | null} [max] 最大可选日期
* @param {HTMLInputElement | string} [element] - 转换该元素为日期选择框 * @param {HTMLInputElement | string} [element] 转换该元素为日期选择框
* @returns {HTMLInputElement} 返回创建或转换的日期选择框 * @returns {HTMLInputElement} 返回创建或转换的日期选择框
*/ */
export function createDateInput(min, max, element) { export function createDateInput(min, max, element) {
let date; let date;
if (typeof element === 'string') { const e = typeof element === 'string' ? document.querySelector(element) : element;
element = document.querySelector(element); if (e instanceof HTMLInputElement) {
} date = e;
if (element instanceof HTMLInputElement) {
date = element;
date.classList.add('ui-date-cell'); date.classList.add('ui-date-cell');
} else { } else {
date = createElement('input', 'ui-date-cell'); date = createElement('input', 'ui-date-cell');
@@ -41,7 +39,7 @@ export function createDateInput(min, max, element) {
* @returns 返回 `yyyy-MM-dd` 格式的字符串 * @returns 返回 `yyyy-MM-dd` 格式的字符串
*/ */
export function toDateValue(dt, local) { export function toDateValue(dt, local) {
if (isNaN(dt)) { if (!(dt instanceof Date) || isNaN(dt.getTime())) {
return ''; return '';
} }
const year = local ? dt.getFullYear() : dt.getUTCFullYear(); const year = local ? dt.getFullYear() : dt.getUTCFullYear();
@@ -52,8 +50,8 @@ export function toDateValue(dt, local) {
/** /**
* 获取日期格式器 * 获取日期格式器
* @param {Date} date - 待格式的日期 * @param {Date} date 待格式的日期
* @param {boolean} [utc=true] - 是否按 UTC 时间格式化 * @param {boolean} [utc=true] 是否按 UTC 时间格式化
* @returns {any} 返回格式化工具对象 * @returns {any} 返回格式化工具对象
*/ */
export function getFormatter(date, utc) { export function getFormatter(date, utc) {
@@ -96,11 +94,11 @@ export function getFormatter(date, utc) {
t: () => new Date(r.Y(), r.n(), 0).getDate(), t: () => new Date(r.Y(), r.n(), 0).getDate(),
/** /**
* @private * @private
* @returns {('1' | '0')} 返回是否为闰年 * @returns {(1 | 0)} 返回是否为闰年
*/ */
L() { L() {
const y = r.Y(); const y = r.Y();
return t % 4 === 0 && t % 100 !== 0 || t % 400 === 0 ? 1 : 0; return y % 4 === 0 && y % 100 !== 0 || y % 400 === 0 ? 1 : 0;
}, },
/** /**
* @private * @private
@@ -151,7 +149,7 @@ export function getFormatter(date, utc) {
* @private * @private
* @returns {string} 返回时区描述字符串 * @returns {string} 返回时区描述字符串
*/ */
e: () => /\((.*)\)/.exec(String(date))[1] || 'Coordinated Universal Time', e: () => /\((.*)\)/.exec(String(date))?.[1] || 'Coordinated Universal Time',
/** /**
* @private * @private
* @returns {string} 返回时区偏移字符串 * @returns {string} 返回时区偏移字符串
@@ -175,7 +173,7 @@ export function getFormatter(date, utc) {
/** /**
* 格式化日期为 M/d/yyyy 格式的字符串 * 格式化日期为 M/d/yyyy 格式的字符串
* @param {Date | number | string} date - 需要格式化的日期值,支持的格式如下: * @param {Date | number | string} date 需要格式化的日期值,支持的格式如下:
* *
* * `"2024-01-26"` * * `"2024-01-26"`
* * `"2024/1/26"` * * `"2024/1/26"`
@@ -183,7 +181,7 @@ export function getFormatter(date, utc) {
* * `"1/26/2024"` * * `"1/26/2024"`
* * `"638418240000000000"` * * `"638418240000000000"`
* * `new Date('2024-01-26')` * * `new Date('2024-01-26')`
* @param {string} [formatter] - 格式化格式,默认为 `"m/d/Y"` * @param {string} [formatter] 格式化格式,默认为 `"m/d/Y"`
* *
* * Y - 年,例如 `2024` * * Y - 年,例如 `2024`
* * y - 年的后两位,例如 `"24"` * * y - 年的后两位,例如 `"24"`
@@ -212,17 +210,17 @@ export function formatDate(date, formatter) {
if (date === '') { if (date === '') {
return ''; return '';
} }
if (isNaN(date)) { if (typeof date === 'string') {
let e = /^(\d{4})-(\d{2})-(\d{2})/.exec(date); let e = /^(\d{4})-(\d{2})-(\d{2})/.exec(date);
if (e == null) { if (e == null) {
e = /^(\d{4})\/(\d{1,2})\/(\d{1,2})/.exec(date); e = /^(\d{4})\/(\d{1,2})\/(\d{1,2})/.exec(date);
} }
if (e != null) { if (e != null) {
date = new Date(e[1], parseInt(e[2]) - 1, e[3]); date = new Date(parseInt(e[1]), parseInt(e[2]) - 1, parseInt(e[3]));
} else { } else {
e = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(date); e = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(date);
if (e != null) { if (e != null) {
date = new Date(e[3], parseInt(e[1]) - 1, e[2]); date = new Date(parseInt(e[3]), parseInt(e[1]) - 1, parseInt(e[2]));
} else { } else {
return date; return date;
} }
@@ -238,20 +236,23 @@ export function formatDate(date, formatter) {
const f = getFormatter(date); const f = getFormatter(date);
return formatter.replace(/\\?(.?)/gi, (k, v) => f[k] ? f[k]() : v); return formatter.replace(/\\?(.?)/gi, (k, v) => f[k] ? f[k]() : v);
} }
return date; return String(date);
} }
/** /**
* 设置显示日期 * 设置显示日期
* @param {HTMLElement} element - 要设置显示日期的元素 * @param {HTMLElement | undefined} element - 要设置显示日期的元素
* @param {Date | number | string} val - 日期值,支持格式参见 {@linkcode formatDate} * @param {Date | number | string} val - 日期值,支持格式参见 {@linkcode formatDate}
* @param {string} [formatter] - 日期格式化字符串(仅设置显示元素时调用) * @param {string} [formatter] - 日期格式化字符串(仅设置显示元素时调用)
*/ */
export function setDateValue(element, val, formatter) { export function setDateValue(element, val, formatter) {
if (element.tagName === 'INPUT') { if (element == null) {
return;
}
if (isTag(element, 'input')) {
if (val === '') { if (val === '') {
element.value = ''; element.value = '';
} else if (isNaN(val)) { } else if (typeof val === 'string') {
if (/^\d{4}-\d{2}-\d{2}/.test(val)) { if (/^\d{4}-\d{2}-\d{2}/.test(val)) {
element.value = String(val).substring(0, 10); element.value = String(val).substring(0, 10);
} else if (/^\d{4}\/\d{2}\/\d{2}/.test(val)) { } else if (/^\d{4}\/\d{2}\/\d{2}/.test(val)) {
@@ -299,7 +300,7 @@ export function setDateValue(element, val, formatter) {
*/ */
export function getDateValue(element, formatter) { export function getDateValue(element, formatter) {
const date = element?.valueAsDate; const date = element?.valueAsDate;
if (date instanceof Date && !isNaN(date)) { if (date instanceof Date && !isNaN(date.getTime())) {
const year = date.getUTCFullYear(); const year = date.getUTCFullYear();
if (year < 1900 || year > 9999) { if (year < 1900 || year > 9999) {
return ''; return '';
@@ -319,6 +320,16 @@ export function getDateValue(element, formatter) {
return ''; return '';
} }
/**
* @typedef DateOptions
* @property {boolean} [enabled=true] 是否可用
* @property {string | null} [minDate] 最小可选择日期
* @property {string | null} [maxDate] 最大可选择日期
* @property {number} [tabIndex] 索引
* @property {string} [className] 类型名
* @property {DateFormatterCallback} [valueFormatter] 自定义格式化函数
*/
/** /**
* 日期选择框类 * 日期选择框类
* @class * @class
@@ -326,48 +337,22 @@ export function getDateValue(element, formatter) {
export class DateSelector { export class DateSelector {
_var = { _var = {
/** /**
* @type {HTMLInputElement} * @type {HTMLInputElement | undefined}
* @private * @private
*/ */
el: null, el: undefined,
options: { /**
/** * @type {DateOptions}
* @type {boolean?} * @private
* @private */
*/ options: {}
enabled: true,
/**
* @type {string?}
* @private
*/
minDate: null,
/**
* @type {string?}
* @private
*/
maxDate: null,
/**
* @type {number?}
* @private
*/
tabIndex: null,
/**
* @type {string?}
* @private
*/
className: null,
/**
* @type {DateFormatterCallback?}
* @private
*/
valueFormatter: null
}
}; };
/** /**
* 日期发生变化时触发的事件 * 日期发生变化时触发的事件
* @type {((date?: Date) => void) | undefined}
* @event * @event
* @param {Date} date - 修改后的日期值 * @param {Date} [date] - 修改后的日期值
* @this DateSelector * @this DateSelector
*/ */
onDateChanged; onDateChanged;
@@ -375,11 +360,7 @@ export class DateSelector {
/** /**
* 日期选择框构造函数 * 日期选择框构造函数
* @constructor * @constructor
* @param {object} [opts] - 日期选择框初始化参数 * @param {DateOptions} [opts] 日期选择框初始化参数
* @param {boolean} [opts.enabled] - 是否可用
* @param {string} [opts.minDate] - 最小可选择日期
* @param {string} [opts.maxDate] - 最大可选择日期
* @param {DateFormatterCallback} [opts.valueFormatter] - 自定义格式化函数
* @example <caption>创建一个 DateSelector 并插入到元素中</caption> * @example <caption>创建一个 DateSelector 并插入到元素中</caption>
* <div id="dateFrom"></div> * <div id="dateFrom"></div>
* @example * @example
@@ -400,7 +381,9 @@ export class DateSelector {
* dateSelectorTo.create('#dateTo'); * dateSelectorTo.create('#dateTo');
*/ */
constructor(opts) { constructor(opts) {
this._var.options = opts ?? {}; if (opts != null) {
this._var.options = opts;
}
} }
/** /**
@@ -411,7 +394,7 @@ export class DateSelector {
create(element) { create(element) {
const opts = this._var.options; const opts = this._var.options;
const el = createDateInput(opts.minDate, opts.maxDate, element); const el = createDateInput(opts.minDate, opts.maxDate, element);
isPositive(opts.tabIndex) && el.setAttribute('tabindex', opts.tabIndex); isPositive(opts.tabIndex) && el.setAttribute('tabindex', String(opts.tabIndex));
if (!nullOrEmpty(opts.className)) { if (!nullOrEmpty(opts.className)) {
el.classList.add(opts.className); el.classList.add(opts.className);
} }
@@ -419,6 +402,9 @@ export class DateSelector {
el.disabled = opts.enabled === false; el.disabled = opts.enabled === false;
} }
el.addEventListener('blur', e => { el.addEventListener('blur', e => {
if (!(e.target instanceof HTMLInputElement)) {
return;
}
const date = this._getDate(e.target.valueAsDate); const date = this._getDate(e.target.valueAsDate);
if (date == null) { if (date == null) {
e.target.value = ''; e.target.value = '';
@@ -434,7 +420,7 @@ export class DateSelector {
/** /**
* 获取日期选择框元素 * 获取日期选择框元素
* @readonly * @readonly
* @type {HTMLInputElement} * @type {HTMLInputElement | undefined}
*/ */
get element() { return this._var.el } get element() { return this._var.el }
@@ -442,57 +428,63 @@ export class DateSelector {
* 获取或设置日期选择框是否启用 * 获取或设置日期选择框是否启用
* @type {boolean} * @type {boolean}
*/ */
get enabled() { return !this._var.el.disabled } get enabled() { return this._var.el?.disabled === false }
set enabled(flag) { set enabled(flag) {
this._var.el.disabled = flag === false; if (this._var.el != null) {
this._var.el.disabled = flag === false;
}
} }
/** /**
* 获取格式化的日期值,或设置日期值,支持的格式参见 {@linkcode formatDate} * 获取格式化的日期值,或设置日期值,支持的格式参见 {@linkcode formatDate}
* @type {string | any} * @type {Date | undefined}
*/ */
get value() { return this._getDate(this._var.el.valueAsDate) } get value() { return this._getDate(this._var.el?.valueAsDate) }
/** @param {string | number | Date} val */
set value(val) { set value(val) {
setDateValue(this._var.el, val); setDateValue(this._var.el, val);
} }
/** /**
* 获取或设置最小可选择日期 * 获取或设置最小可选择日期
* @type {string} * @type {string | undefined}
*/ */
get minDate() { return this._var.el.min } get minDate() { return this._var.el?.min }
set minDate(date) { set minDate(date) {
this._var.el.min = date; if (this._var.el != null && !nullOrEmpty(date)) {
this._var.el.min = date;
}
this._var.options.minDate = date; this._var.options.minDate = date;
} }
/** /**
* 获取或设置最大可选择日期 * 获取或设置最大可选择日期
* @type {string} * @type {string | undefined}
*/ */
get maxDate() { return this._var.el.max } get maxDate() { return this._var.el?.max }
set maxDate(date) { set maxDate(date) {
this._var.el.max = date; if (this._var.el != null && !nullOrEmpty(date)) {
this._var.el.max = date;
}
this._var.options.maxDate = date; this._var.options.maxDate = date;
} }
/** /**
* @private * @private
* @param {Date} date * @param {Date | null | undefined} date
* @returns {Date | any} * @returns {Date | undefined}
*/ */
_getDate(date) { _getDate(date) {
if (date instanceof Date && !isNaN(date)) { if (date instanceof Date && !isNaN(date.getTime())) {
const year = date.getUTCFullYear(); const year = date.getUTCFullYear();
if (year < 1900 || year > 9999) { if (year < 1900 || year > 9999) {
return null; return;
} }
if (typeof this._var.options.valueFormatter === 'function') { if (typeof this._var.options.valueFormatter === 'function') {
return this._var.options.valueFormatter(date); return this._var.options.valueFormatter(date);
} }
return date; return date;
} }
return null;
} }
/** /**
@@ -500,9 +492,7 @@ export class DateSelector {
* 解析的属性为 `id`, `class`, `data-min`, `data-max`, `disabled` * 解析的属性为 `id`, `class`, `data-min`, `data-max`, `disabled`
* @static * @static
* @param {HTMLElement} [dom=document.body] 父元素 * @param {HTMLElement} [dom=document.body] 父元素
* @param {Function} [trigger] 日期设置事件触发函数 * @param {(this: DateSelector, date?: Date) => void} [trigger] 日期设置事件触发函数, 上下文为触发设置日期的 `DateSelector` 实例
* @param {Date} trigger.{this} - 上下文为触发设置日期的 `DateSelector` 实例
* @param {Date} trigger.date - 修改后的日期值
* @example <caption>HTML</caption> * @example <caption>HTML</caption>
* <input id="dateFrom" data-type="date" data-min="1980-01-01"/> * <input id="dateFrom" data-type="date" data-min="1980-01-01"/>
* @example <caption>解析父容器</caption> * @example <caption>解析父容器</caption>
@@ -519,6 +509,9 @@ export class DateSelector {
static resolve(dom = document.body, trigger) { static resolve(dom = document.body, trigger) {
const dates = dom.querySelectorAll('input[data-type="date"]'); const dates = dom.querySelectorAll('input[data-type="date"]');
for (let dat of dates) { for (let dat of dates) {
if (!(dat instanceof HTMLInputElement)) {
continue;
}
const val = dat.value; const val = dat.value;
const dateSelector = new DateSelector({ const dateSelector = new DateSelector({
minDate: dat.getAttribute('data-min'), minDate: dat.getAttribute('data-min'),
+195 -52
View File
@@ -26,10 +26,11 @@ if (dropdownGlobal == null) {
continue; continue;
} }
panel.classList.remove('active'); panel.classList.remove('active');
const dropId = panel.parentElement.dataset.dropId; const dropId = panel.parentElement?.dataset.dropId;
if (dropId == null) { if (dropId == null) {
continue; continue;
} }
/** @type {Dropdown | undefined} */
const dropdown = this[dropId]; const dropdown = this[dropId];
if (dropdown?.multiSelect && typeof dropdown.onCollapsed === 'function') { if (dropdown?.multiSelect && typeof dropdown.onCollapsed === 'function') {
dropdown.onCollapsed(); dropdown.onCollapsed();
@@ -52,7 +53,16 @@ if (dropdownGlobal == null) {
}); });
} }
function selectItems(label, itemlist, template, htmlkey, textkey) { /**
* @private
* @this Dropdown
* @param {DropdownItem[]} itemlist
*/
function selectItems(itemlist) {
const label = this._var.label;
const template = this._var.options.htmlTemplate;
const htmlkey = this._var.options.htmlKey;
const textkey = this._var.options.textKey;
let htmls; let htmls;
if (typeof template === 'function') { if (typeof template === 'function') {
htmls = itemlist.map(it => template.call(this, it)); htmls = itemlist.map(it => template.call(this, it));
@@ -62,7 +72,7 @@ function selectItems(label, itemlist, template, htmlkey, textkey) {
if (htmls.some(it => it instanceof HTMLElement)) { if (htmls.some(it => it instanceof HTMLElement)) {
label.replaceChildren(...htmls.filter(it => it != null).map(it => it.cloneNode(true))); label.replaceChildren(...htmls.filter(it => it != null).map(it => it.cloneNode(true)));
} else { } else {
let text = itemlist.map(it => it[textkey]).join(', '); let text = itemlist.map(it => String(it[textkey])).join(', ');
if (nullOrEmpty(text)) { if (nullOrEmpty(text)) {
text = r('noneItem', '( None )'); text = r('noneItem', '( None )');
} }
@@ -70,6 +80,13 @@ function selectItems(label, itemlist, template, htmlkey, textkey) {
} }
} }
/**
* @private
* @param {string[]} searchkeys
* @param {string} textkey
* @param {string} key
* @param {DropdownItem[]} source
*/
function filterSource(searchkeys, textkey, key, source) { function filterSource(searchkeys, textkey, key, source) {
if (!Array.isArray(searchkeys) || searchkeys.length === 0) { if (!Array.isArray(searchkeys) || searchkeys.length === 0) {
searchkeys = [textkey]; searchkeys = [textkey];
@@ -87,6 +104,12 @@ function filterSource(searchkeys, textkey, key, source) {
return source; return source;
} }
/**
* @private
* @param {DropdownItem} it
* @param {string} valuekey
* @param {string} textkey
*/
function getValue(it, valuekey, textkey) { function getValue(it, valuekey, textkey) {
if (it == null) { if (it == null) {
return null; return null;
@@ -105,7 +128,7 @@ function getValue(it, valuekey, textkey) {
* @property {string} [valueKey=value] - 值关键字 * @property {string} [valueKey=value] - 值关键字
* @property {string} [htmlKey=html] - 源码显示的关键字 * @property {string} [htmlKey=html] - 源码显示的关键字
* @property {string} [childKey=children] - 子集合的关键字 * @property {string} [childKey=children] - 子集合的关键字
* @property {Function} [htmlTemplate] - 模板创建函数 * @property {(this: Dropdown, it: DropdownItem) => string} [htmlTemplate] - 模板创建函数
* @property {number} [maxLength=500] - 最大输入长度 * @property {number} [maxLength=500] - 最大输入长度
* @property {boolean} [multiSelect] - 是否允许多选 * @property {boolean} [multiSelect] - 是否允许多选
* @property {string} [selected] - 选中值 * @property {string} [selected] - 选中值
@@ -119,28 +142,62 @@ function getValue(it, valuekey, textkey) {
* @property {string} [placeholder] - 输入框的提示文本 * @property {string} [placeholder] - 输入框的提示文本
* @property {boolean} [slideFixed] - 是否固定为向下展开 * @property {boolean} [slideFixed] - 是否固定为向下展开
* @property {HTMLElement} [wrapper] - 父元素,默认添加到头元素之后 * @property {HTMLElement} [wrapper] - 父元素,默认添加到头元素之后
* @property {boolean} [ignoreAll] - 是否忽略 All 选项
*/
/**
* 数据项基础类型
* @typedef DropdownItemBase
* @property {0 | 1 | 2 | undefined} [__checked] 是否选中
* @property {string} [__p] 父节点 Id
* @property {number} [__level] 层级
* @interface
*/
/**
* 数据项类型
* @typedef {DropdownItemBase & Object.<string, any>} DropdownItem
*/ */
export class Dropdown { export class Dropdown {
_var = {}; _var = {
// _var.options; /** @type {DropdownOptions} */
options: undefined,
// _var.wrapper; /** @type {HTMLDivElement} */
// _var.container; wrapper: undefined,
// _var.label; /** @type {HTMLDivElement} */
container: undefined,
// _var.allChecked; /** @type {HTMLInputElement | HTMLLabelElement} */
// _var.source; label: undefined,
// _var.lastSelected; allChecked: false,
// _var.selected; /** @type {DropdownItem[]} */
// _var.selectedList; source: undefined,
/** @type {DropdownItem[]} */
currentSource: undefined,
/** @type {string | undefined} */
lastSelected: undefined,
/** @type {DropdownItem | undefined} */
selected: undefined,
/** @type {DropdownItem[] | undefined} */
selectedList: undefined,
dropTop: 0,
dropHeight: 0
};
/** @type {(() => DropdownItem[]) | undefined} */
sourceFilter; sourceFilter;
/** @type {((list: DropdownItem[]) => void) | undefined} */
onSelectedList; onSelectedList;
/** @type {((it: DropdownItem) => void) | undefined} */
onSelected; onSelected;
/** @type {((this: Dropdown) => void) | undefined} */
onExpanded; onExpanded;
/** @type {((this: Dropdown) => void) | undefined} */
onCollapsed; onCollapsed;
/**
* @param {DropdownOptions} options
*/
constructor(options = {}) { constructor(options = {}) {
options.textKey ??= 'text'; options.textKey ??= 'text';
options.valueKey ??= 'value'; options.valueKey ??= 'value';
@@ -284,6 +341,11 @@ export class Dropdown {
} else { } else {
this._var.wrapper.querySelector('.ui-drop-header').classList.remove('disabled'); this._var.wrapper.querySelector('.ui-drop-header').classList.remove('disabled');
} }
/** @type {HTMLInputElement} */
const input = this._var.wrapper.querySelector('.ui-drop-text');
if (input != null) {
input.disabled = flag;
}
} }
get source() { get source() {
@@ -306,6 +368,13 @@ export class Dropdown {
} }
const valuekey = this._var.options.valueKey; const valuekey = this._var.options.valueKey;
const childkey = this._var.options.childKey; const childkey = this._var.options.childKey;
/**
* @private
* @param {DropdownItem[]} list
* @param {string} [id]
* @param {number} [level]
* @returns {DropdownItem[]}
*/
function reduceItems(list, id, level = 0) { function reduceItems(list, id, level = 0) {
if (!Array.isArray(list)) { if (!Array.isArray(list)) {
return []; return [];
@@ -326,6 +395,13 @@ export class Dropdown {
get selectedList() { return this._var.selectedList || [] } get selectedList() { return this._var.selectedList || [] }
/**
*
* @param {string} selected
* @param {boolean} [silence]
* @param {boolean} [ignoreCase]
* @returns {boolean | undefined}
*/
select(selected, silence, ignoreCase) { select(selected, silence, ignoreCase) {
if (typeof selected !== 'string') { if (typeof selected !== 'string') {
selected = String(selected); selected = String(selected);
@@ -395,12 +471,16 @@ export class Dropdown {
return true; return true;
} }
/**
*
* @param {string[]} selectedlist
* @param {boolean} silence
* @returns {boolean | undefined}
*/
selectlist(selectedlist, silence) { selectlist(selectedlist, silence) {
const source = this.source; const source = this.source;
const valuekey = this._var.options.valueKey; const valuekey = this._var.options.valueKey;
const textkey = this._var.options.textKey; const textkey = this._var.options.textKey;
const template = this._var.options.htmlTemplate;
const htmlkey = this._var.options.htmlKey;
const itemlist = selectedlist.map(a => { const itemlist = selectedlist.map(a => {
const v = typeof a === 'string' ? a : String(a); const v = typeof a === 'string' ? a : String(a);
let item = source.find(it => String(getValue(it, valuekey, textkey)) === v); let item = source.find(it => String(getValue(it, valuekey, textkey)) === v);
@@ -415,15 +495,11 @@ export class Dropdown {
this._var.allChecked = false; this._var.allChecked = false;
source.forEach(it => delete it.__checked); source.forEach(it => delete it.__checked);
if (itemlist.length === 0) { if (itemlist.length === 0) {
this._var.selectedList = null; delete this._var.selectedList;
this._var.label.innerText = r('none', '( None )'); this._var.label.innerText = r('none', '( None )');
return false; return false;
} }
selectItems(this._var.label, itemlist, template, htmlkey, textkey); this._selectList(list, silence);
this._var.selectedList = itemlist;
if (!silence && typeof this.onSelectedList === 'function') {
this.onSelectedList(itemlist);
}
} }
get _expanded() { return this._var.container?.classList?.contains('active') } get _expanded() { return this._var.container?.classList?.contains('active') }
@@ -445,7 +521,14 @@ export class Dropdown {
const key = e.target.value.toLowerCase(); const key = e.target.value.toLowerCase();
const source = filterSource(options.searchKeys, options.textKey, key, this.source); const source = filterSource(options.searchKeys, options.textKey, key, this.source);
this._filllist(source); this._filllist(source);
}) });
input.addEventListener('blur', e => {
const key = e.target.value.toLowerCase();
if (!nullOrEmpty(key)) {
const list = this._getSelectedList(this._var.currentSource);
this._selectList(list);
}
});
search.append(input, createIcon('fa-light', 'search')); search.append(input, createIcon('fa-light', 'search'));
panel.appendChild(search); panel.appendChild(search);
} }
@@ -530,6 +613,11 @@ export class Dropdown {
} }
} }
/**
*
* @param {HTMLDivElement} list
* @param {number} top
*/
_onlistscroll(list, top) { _onlistscroll(list, top) {
const offset = (this.multiSelect && !this.ignoreAll) ? DropdownItemHeight : 0; const offset = (this.multiSelect && !this.ignoreAll) ? DropdownItemHeight : 0;
top -= (top % (DropdownItemHeight * 2)) + offset; top -= (top % (DropdownItemHeight * 2)) + offset;
@@ -553,6 +641,7 @@ export class Dropdown {
} else { } else {
array = array.slice(-20); array = array.slice(-20);
} }
/** @type {HTMLDivElement} */
const content = list.querySelector('.drop-content'); const content = list.querySelector('.drop-content');
content.replaceChildren(); content.replaceChildren();
this._dofilllist(content, array); this._dofilllist(content, array);
@@ -560,6 +649,10 @@ export class Dropdown {
} }
} }
/**
*
* @param {DropdownItem[]} source
*/
_filllist(source) { _filllist(source) {
const list = this._var.container.querySelector('.ui-drop-list'); const list = this._var.container.querySelector('.ui-drop-list');
list.replaceChildren(); list.replaceChildren();
@@ -571,7 +664,7 @@ export class Dropdown {
const content = createElement('div', 'drop-content'); const content = createElement('div', 'drop-content');
if (this.multiSelect && !this.ignoreAll) { if (this.multiSelect && !this.ignoreAll) {
list.appendChild( list.appendChild(
createElement('li', null, createElement('li', undefined,
createCheckbox({ createCheckbox({
label: r('allItem', '( All )'), label: r('allItem', '( All )'),
checked: this._var.allChecked, checked: this._var.allChecked,
@@ -615,7 +708,19 @@ export class Dropdown {
} }
} }
/**
*
* @param {string} it
* @param {DropdownItem} item
* @param {string} valuekey
* @param {string} textkey
* @param {string} [childkey]
* @returns {boolean}
*/
_contains(it, item, valuekey, textkey, childkey) { _contains(it, item, valuekey, textkey, childkey) {
if (childkey == null) {
return false;
}
if (Array.isArray(item[childkey])) { if (Array.isArray(item[childkey])) {
for (let t of item[childkey]) { for (let t of item[childkey]) {
if (it === String(getValue(t, valuekey, textkey))) { if (it === String(getValue(t, valuekey, textkey))) {
@@ -629,13 +734,19 @@ export class Dropdown {
return false; return false;
} }
/**
*
* @param {HTMLDivElement} content
* @param {DropdownItem[]} array
* @returns {number | undefined}
*/
_dofilllist(content, array) { _dofilllist(content, array) {
const multiselect = this.multiSelect; const multiselect = this.multiSelect;
const valuekey = this._var.options.valueKey; const valuekey = this._var.options.valueKey;
const textkey = this._var.options.textKey; const textkey = this._var.options.textKey;
const template = this._var.options.htmlTemplate; const template = this._var.options.htmlTemplate;
const htmlkey = this._var.options.htmlKey; const htmlkey = this._var.options.htmlKey;
const childkey = this._var.options.childKey; // const childkey = this._var.options.childKey;
const selected = this.selected; const selected = this.selected;
let scrolled; let scrolled;
array.forEach((item, i) => { array.forEach((item, i) => {
@@ -698,7 +809,7 @@ export class Dropdown {
} else { } else {
if (label == null) { if (label == null) {
label = createElement('span'); label = createElement('span');
label.innerHTML = item[textkey]; label.innerText = item[textkey];
} }
wrapper.appendChild(label); wrapper.appendChild(label);
if (selected != null && String(selected[valuekey]) === val) { if (selected != null && String(selected[valuekey]) === val) {
@@ -711,38 +822,51 @@ export class Dropdown {
return scrolled; return scrolled;
} }
/**
* @param {DropdownItem[]} [source]
* @returns {DropdownItem[]}
*/
_getSelectedList(source) {
const valuekey = this._var.options.valueKey;
const textkey = this._var.options.textKey;
const list = [];
source ??= this.source;
source.filter(it => it.__p == null).forEach(it => {
const key = String(getValue(it, valuekey, textkey));
if (it.__checked === 1) {
list.push(it);
} else if (it.__checked === 2) {
const children = source.filter(c => c.__checked === 1 && c.__p === key);
if (children.length > 0) {
Array.prototype.push.apply(list, children);
}
}
});
return list;
}
/**
*
* @param {HTMLInputElement} checkbox
* @param {DropdownItem} item
*/
_triggerselect(checkbox, item) { _triggerselect(checkbox, item) {
let list; let list;
const valuekey = this._var.options.valueKey; const valuekey = this._var.options.valueKey;
const textkey = this._var.options.textKey; const textkey = this._var.options.textKey;
const template = this._var.options.htmlTemplate;
const htmlkey = this._var.options.htmlKey;
const childkey = this._var.options.childKey; const childkey = this._var.options.childKey;
const source = this.source; const source = this.source;
if (checkbox.getAttribute('isall') === '1') { if (checkbox.getAttribute('isall') === '1') {
const allchecked = this._var.allChecked = checkbox.checked; const allchecked = this._var.allChecked = checkbox.checked;
/** @type {NodeListOf<HTMLInputElement>} */
const boxes = this._var.container.querySelectorAll('input.dataitem'); const boxes = this._var.container.querySelectorAll('input.dataitem');
boxes.forEach(box => box.checked = allchecked); boxes.forEach(box => box.checked = allchecked);
source.forEach(it => it.__checked = allchecked ? 1 : 0); source.forEach(it => it.__checked = allchecked ? 1 : 0);
list = []; list = [];
} else { } else {
/** @type {HTMLInputElement | null} */
const all = this._var.container.querySelector('input[isall="1"]'); const all = this._var.container.querySelector('input[isall="1"]');
const val = checkbox.dataset.value; const val = checkbox.dataset.value;
const getSelectedList = () => {
const list = [];
source.filter(it => it.__p == null).forEach(it => {
const key = String(getValue(it, valuekey, textkey));
if (it.__checked === 1) {
list.push(it);
} else if (it.__checked === 2) {
const children = source.filter(c => c.__checked === 1 && c.__p === key);
if (children.length > 0) {
Array.prototype.push.apply(list, children);
}
}
});
return list;
};
if (checkbox.checked) { if (checkbox.checked) {
item.__checked = 1; item.__checked = 1;
if (item.__p != null) { if (item.__p != null) {
@@ -766,7 +890,7 @@ export class Dropdown {
} }
list = []; list = [];
} else { } else {
list = getSelectedList(); list = this._getSelectedList();
} }
} else { } else {
if (item[childkey]?.length > 0) { if (item[childkey]?.length > 0) {
@@ -793,10 +917,11 @@ export class Dropdown {
all.checked = false; all.checked = false;
} }
} }
list = getSelectedList(); list = this._getSelectedList();
} }
} }
// refresh selection // refresh selection
/** @type {NodeListOf<HTMLInputElement>} */
const checkboxes = this._var.container.querySelectorAll('input.dataitem'); const checkboxes = this._var.container.querySelectorAll('input.dataitem');
checkboxes.forEach(c => { checkboxes.forEach(c => {
const val = c.dataset.value; const val = c.dataset.value;
@@ -807,23 +932,41 @@ export class Dropdown {
} }
}); });
this._selectList(list);
}
/**
* @private
* @param {DropdownItem[]} list
* @param {boolean} [silence]
*/
_selectList(list, silence) {
if (this._var.allChecked) { if (this._var.allChecked) {
this._var.label.innerText = r('allItem', '( All )'); this._var.label.innerText = r('allItem', '( All )');
} else { } else {
selectItems(this._var.label, list, template, htmlkey, textkey); selectItems.call(this, list);
} }
this._var.selectedList = list; this._var.selectedList = list;
if (typeof this.onSelectedList === 'function') { if (!silence && typeof this.onSelectedList === 'function') {
this.onSelectedList(list); this.onSelectedList(list);
} }
} }
/**
*
* @param {HTMLElement} dom
* @param {(this: Dropdown, item: DropdownItem) => void} [trigger]
* @returns
*/
static resolve(dom = document.body, trigger) { static resolve(dom = document.body, trigger) {
const selects = dom.querySelectorAll('select'); const selects = dom.querySelectorAll('select');
for (let sel of selects) { for (let sel of selects) {
const source = [...sel.children].map(it => { const source = [...sel.children].map(
return { value: it.value, text: it.innerText } /**
}); * @param {HTMLOptionElement} it
* @returns {DropdownItem}
*/
it => ({ value: it.value, text: it.innerText }));
const drop = new Dropdown({ const drop = new Dropdown({
selected: sel.value, selected: sel.value,
disabled: sel.disabled, disabled: sel.disabled,
+17 -5
View File
@@ -1,16 +1,28 @@
/**
* @param {HTMLElement} element
* @param {RegExp} regex
* @returns {HTMLElement}
*/
export function validation(element, regex) { export function validation(element, regex) {
if (element instanceof HTMLElement && regex instanceof RegExp) { if (element instanceof HTMLElement && regex instanceof RegExp) {
element.addEventListener('change', e => { element.addEventListener('change', e => {
if (regex.test(e.target.value)) { const target = e.target;
e.target.classList.remove('validation-error'); if (target instanceof HTMLElement) {
} else { if (regex.test(/** @type {HTMLInputElement} */(target).value)) {
e.target.classList.add('validation-error'); target.classList.remove('validation-error');
} else {
target.classList.add('validation-error');
}
} }
}) })
} }
return element; return element;
} }
/**
* @param {{[key: string]: string}} style
* @returns {string}
*/
export function convertCssStyle(style) { export function convertCssStyle(style) {
return Object.entries(style).map(s => `${s[0]}: ${s[1]}`).join('; '); return Object.entries(style).map(([key, value]) => `${key}: ${value}`).join('; ');
} }
+44 -6
View File
@@ -1,13 +1,22 @@
import { global } from "../utility";
const svgns = 'http://www.w3.org/2000/svg'; const svgns = 'http://www.w3.org/2000/svg';
/** @type {Object.<string, string>} */
const dict = { const dict = {
"\uf000": "glass-martini", "\uf001": "music", "\uf002": "search", "\uf004": "heart", "\uf005": "star", "\uf007": "user", "\uf008": "film", "\uf009": "th-large", "\uf00a": "th", "\uf00b": "th-list", "\uf00c": "check", "\uf00d": "times", "\uf00e": "search-plus", "\uf010": "search-minus", "\uf011": "power-off", "\uf012": "signal", "\uf013": "cog", "\uf015": "home", "\uf017": "clock", "\uf018": "road", "\uf019": "download", "\uf01c": "inbox", "\uf01e": "redo", "\uf021": "sync", "\uf022": "list-alt", "\uf023": "lock", "\uf024": "flag", "\uf025": "headphones", "\uf026": "volume-off", "\uf027": "volume-down", "\uf028": "volume-up", "\uf029": "qrcode", "\uf02a": "barcode", "\uf02b": "tag", "\uf02c": "tags", "\uf02d": "book", "\uf02e": "bookmark", "\uf02f": "print", "\uf030": "camera", "\uf031": "font", "\uf032": "bold", "\uf033": "italic", "\uf034": "text-height", "\uf035": "text-width", "\uf036": "align-left", "\uf037": "align-center", "\uf038": "align-right", "\uf039": "align-justify", "\uf03a": "list", "\uf03b": "outdent", "\uf03c": "indent", "\uf03d": "video", "\uf03e": "image", "\uf040": "pencil", "\uf041": "map-marker", "\uf042": "adjust", "\uf043": "tint", "\uf044": "edit", "\uf047": "arrows", "\uf048": "step-backward", "\uf049": "fast-backward", "\uf04a": "backward", "\uf04b": "play", "\uf04c": "pause", "\uf04d": "stop", "\uf04e": "forward", "\uf050": "fast-forward", "\uf051": "step-forward", "\uf052": "eject", "\uf053": "chevron-left", "\uf054": "chevron-right", "\uf055": "plus-circle", "\uf056": "minus-circle", "\uf057": "times-circle", "\uf058": "check-circle", "\uf059": "question-circle", "\uf05a": "info-circle", "\uf05b": "crosshairs", "\uf05e": "ban", "\uf060": "arrow-left", "\uf061": "arrow-right", "\uf062": "arrow-up", "\uf063": "arrow-down", "\uf064": "share", "\uf065": "expand", "\uf066": "compress", "\uf067": "plus", "\uf068": "minus", "\uf069": "asterisk", "\uf06a": "exclamation-circle", "\uf06b": "gift", "\uf06c": "leaf", "\uf06d": "fire", "\uf06e": "eye", "\uf070": "eye-slash", "\uf071": "exclamation-triangle", "\uf072": "plane", "\uf073": "calendar-alt", "\uf074": "random", "\uf075": "comment", "\uf076": "magnet", "\uf077": "chevron-up", "\uf078": "chevron-down", "\uf079": "retweet", "\uf07a": "shopping-cart", "\uf07b": "folder", "\uf07c": "folder-open", "\uf07d": "arrows-v", "\uf07e": "arrows-h", "\uf080": "chart-bar", "\uf083": "camera-retro", "\uf084": "key", "\uf085": "cogs", "\uf086": "comments", "\uf089": "star-half", "\uf08b": "sign-out", "\uf08d": "thumbtack", "\uf08e": "external-link", "\uf090": "sign-in", "\uf091": "trophy", "\uf093": "upload", "\uf094": "lemon", "\uf095": "phone", "\uf098": "phone-square", "\uf09c": "unlock", "\uf09d": "credit-card", "\uf09e": "rss", "\uf0a0": "hdd", "\uf0a1": "bullhorn", "\uf0a3": "certificate", "\uf0a4": "hand-point-right", "\uf0a5": "hand-point-left", "\uf0a6": "hand-point-up", "\uf0a7": "hand-point-down", "\uf0a8": "arrow-circle-left", "\uf0a9": "arrow-circle-right", "\uf0aa": "arrow-circle-up", "\uf0ab": "arrow-circle-down", "\uf0ac": "globe", "\uf0ad": "wrench", "\uf0ae": "tasks", "\uf0b0": "filter", "\uf0b1": "briefcase", "\uf0b2": "arrows-alt", "\uf0c0": "users", "\uf0c1": "link", "\uf0c2": "cloud", "\uf0c3": "flask", "\uf0c4": "cut", "\uf0c5": "copy", "\uf0c6": "paperclip", "\uf0c7": "save", "\uf0c8": "square", "\uf0c9": "bars", "\uf0ca": "list-ul", "\uf0cb": "list-ol", "\uf0cc": "strikethrough", "\uf0cd": "underline", "\uf0ce": "table", "\uf0d0": "magic", "\uf0d1": "truck", "\uf0d6": "money-bill", "\uf0d7": "caret-down", "\uf0d8": "caret-up", "\uf0d9": "caret-left", "\uf0da": "caret-right", "\uf0db": "columns", "\uf0dc": "sort", "\uf0dd": "sort-down", "\uf0de": "sort-up", "\uf0e0": "envelope", "\uf0e2": "undo", "\uf0e3": "gavel", "\uf0e4": "tachometer", "\uf0e7": "bolt", "\uf0e8": "sitemap", "\uf0e9": "umbrella", "\uf0ea": "paste", "\uf0eb": "lightbulb", "\uf0ec": "exchange", "\uf0ed": "cloud-download", "\uf0ee": "cloud-upload", "\uf0f0": "user-md", "\uf0f1": "stethoscope", "\uf0f2": "suitcase", "\uf0f3": "bell", "\uf0f4": "coffee", "\uf0f8": "hospital", "\uf0f9": "ambulance", "\uf0fa": "medkit", "\uf0fb": "fighter-jet", "\uf0fc": "beer", "\uf0fd": "h-square", "\uf0fe": "plus-square", "\uf100": "angle-double-left", "\uf101": "angle-double-right", "\uf102": "angle-double-up", "\uf103": "angle-double-down", "\uf104": "angle-left", "\uf105": "angle-right", "\uf106": "angle-up", "\uf107": "angle-down", "\uf108": "desktop", "\uf109": "laptop", "\uf10a": "tablet", "\uf10b": "mobile", "\uf10d": "quote-left", "\uf10e": "quote-right", "\uf110": "spinner", "\uf111": "circle", "\uf118": "smile", "\uf119": "frown", "\uf11a": "meh", "\uf11b": "gamepad", "\uf11c": "keyboard", "\uf11e": "flag-checkered", "\uf120": "terminal", "\uf121": "code", "\uf122": "reply-all", "\uf124": "location-arrow", "\uf125": "crop", "\uf126": "code-branch", "\uf127": "unlink", "\uf128": "question", "\uf129": "info", "\uf12a": "exclamation", "\uf12b": "superscript", "\ufLine truncated "\uf000": "glass-martini", "\uf001": "music", "\uf002": "search", "\uf004": "heart", "\uf005": "star", "\uf007": "user", "\uf008": "film", "\uf009": "th-large", "\uf00a": "th", "\uf00b": "th-list", "\uf00c": "check", "\uf00d": "times", "\uf00e": "search-plus", "\uf010": "search-minus", "\uf011": "power-off", "\uf012": "signal", "\uf013": "cog", "\uf015": "home", "\uf017": "clock", "\uf018": "road", "\uf019": "download", "\uf01c": "inbox", "\uf01e": "redo", "\uf021": "sync", "\uf022": "list-alt", "\uf023": "lock", "\uf024": "flag", "\uf025": "headphones", "\uf026": "volume-off", "\uf027": "volume-down", "\uf028": "volume-up", "\uf029": "qrcode", "\uf02a": "barcode", "\uf02b": "tag", "\uf02c": "tags", "\uf02d": "book", "\uf02e": "bookmark", "\uf02f": "print", "\uf030": "camera", "\uf031": "font", "\uf032": "bold", "\uf033": "italic", "\uf034": "text-height", "\uf035": "text-width", "\uf036": "align-left", "\uf037": "align-center", "\uf038": "align-right", "\uf039": "align-justify", "\uf03a": "list", "\uf03b": "outdent", "\uf03c": "indent", "\uf03d": "video", "\uf03e": "image", "\uf040": "pencil", "\uf041": "map-marker", "\uf042": "adjust", "\uf043": "tint", "\uf044": "edit", "\uf047": "arrows", "\uf048": "step-backward", "\uf049": "fast-backward", "\uf04a": "backward", "\uf04b": "play", "\uf04c": "pause", "\uf04d": "stop", "\uf04e": "forward", "\uf050": "fast-forward", "\uf051": "step-forward", "\uf052": "eject", "\uf053": "chevron-left", "\uf054": "chevron-right", "\uf055": "plus-circle", "\uf056": "minus-circle", "\uf057": "times-circle", "\uf058": "check-circle", "\uf059": "question-circle", "\uf05a": "info-circle", "\uf05b": "crosshairs", "\uf05e": "ban", "\uf060": "arrow-left", "\uf061": "arrow-right", "\uf062": "arrow-up", "\uf063": "arrow-down", "\uf064": "share", "\uf065": "expand", "\uf066": "compress", "\uf067": "plus", "\uf068": "minus", "\uf069": "asterisk", "\uf06a": "exclamation-circle", "\uf06b": "gift", "\uf06c": "leaf", "\uf06d": "fire", "\uf06e": "eye", "\uf070": "eye-slash", "\uf071": "exclamation-triangle", "\uf072": "plane", "\uf073": "calendar-alt", "\uf074": "random", "\uf075": "comment", "\uf076": "magnet", "\uf077": "chevron-up", "\uf078": "chevron-down", "\uf079": "retweet", "\uf07a": "shopping-cart", "\uf07b": "folder", "\uf07c": "folder-open", "\uf07d": "arrows-v", "\uf07e": "arrows-h", "\uf080": "chart-bar", "\uf083": "camera-retro", "\uf084": "key", "\uf085": "cogs", "\uf086": "comments", "\uf089": "star-half", "\uf08b": "sign-out", "\uf08d": "thumbtack", "\uf08e": "external-link", "\uf090": "sign-in", "\uf091": "trophy", "\uf093": "upload", "\uf094": "lemon", "\uf095": "phone", "\uf098": "phone-square", "\uf09c": "unlock", "\uf09d": "credit-card", "\uf09e": "rss", "\uf0a0": "hdd", "\uf0a1": "bullhorn", "\uf0a3": "certificate", "\uf0a4": "hand-point-right", "\uf0a5": "hand-point-left", "\uf0a6": "hand-point-up", "\uf0a7": "hand-point-down", "\uf0a8": "arrow-circle-left", "\uf0a9": "arrow-circle-right", "\uf0aa": "arrow-circle-up", "\uf0ab": "arrow-circle-down", "\uf0ac": "globe", "\uf0ad": "wrench", "\uf0ae": "tasks", "\uf0b0": "filter", "\uf0b1": "briefcase", "\uf0b2": "arrows-alt", "\uf0c0": "users", "\uf0c1": "link", "\uf0c2": "cloud", "\uf0c3": "flask", "\uf0c4": "cut", "\uf0c5": "copy", "\uf0c6": "paperclip", "\uf0c7": "save", "\uf0c8": "square", "\uf0c9": "bars", "\uf0ca": "list-ul", "\uf0cb": "list-ol", "\uf0cc": "strikethrough", "\uf0cd": "underline", "\uf0ce": "table", "\uf0d0": "magic", "\uf0d1": "truck", "\uf0d6": "money-bill", "\uf0d7": "caret-down", "\uf0d8": "caret-up", "\uf0d9": "caret-left", "\uf0da": "caret-right", "\uf0db": "columns", "\uf0dc": "sort", "\uf0dd": "sort-down", "\uf0de": "sort-up", "\uf0e0": "envelope", "\uf0e2": "undo", "\uf0e3": "gavel", "\uf0e4": "tachometer", "\uf0e7": "bolt", "\uf0e8": "sitemap", "\uf0e9": "umbrella", "\uf0ea": "paste", "\uf0eb": "lightbulb", "\uf0ec": "exchange", "\uf0ed": "cloud-download", "\uf0ee": "cloud-upload", "\uf0f0": "user-md", "\uf0f1": "stethoscope", "\uf0f2": "suitcase", "\uf0f3": "bell", "\uf0f4": "coffee", "\uf0f8": "hospital", "\uf0f9": "ambulance", "\uf0fa": "medkit", "\uf0fb": "fighter-jet", "\uf0fc": "beer", "\uf0fd": "h-square", "\uf0fe": "plus-square", "\uf100": "angle-double-left", "\uf101": "angle-double-right", "\uf102": "angle-double-up", "\uf103": "angle-double-down", "\uf104": "angle-left", "\uf105": "angle-right", "\uf106": "angle-up", "\uf107": "angle-down", "\uf108": "desktop", "\uf109": "laptop", "\uf10a": "tablet", "\uf10b": "mobile", "\uf10d": "quote-left", "\uf10e": "quote-right", "\uf110": "spinner", "\uf111": "circle", "\uf118": "smile", "\uf119": "frown", "\uf11a": "meh", "\uf11b": "gamepad", "\uf11c": "keyboard", "\uf11e": "flag-checkered", "\uf120": "terminal", "\uf121": "code", "\uf122": "reply-all", "\uf124": "location-arrow", "\uf125": "crop", "\uf126": "code-branch", "\uf127": "unlink", "\uf128": "question", "\uf129": "info", "\uf12a": "exclamation", "\uf12b": "superscript", "\ufLine truncated
}; };
/**
* @private
* @param {string} type
* @param {string} id
* @returns {SVGUseElement}
*/
function createUse(type, id) { function createUse(type, id) {
const c = typeof consts !== 'undefined' ? consts : {}; const c = typeof global.consts !== 'undefined' ? global.consts : { resver: null, path: null };
const path = c.path || const path = c.path ||
(typeof _network !== 'undefined' ? _network.root : (typeof global._network !== 'undefined' ? global._network.root :
(typeof _net !== 'undefined' ? _net.root : '')); (typeof global._net !== 'undefined' ? global._net.root : ''));
const ver = c.resver == null ? '' : `?${c.resver}`; const ver = c.resver == null ? '' : `?${c.resver}`;
const use = document.createElementNS(svgns, 'use'); const use = document.createElementNS(svgns, 'use');
if (id?.length === 1 && id.charCodeAt(0) > 0xf000) { if (id?.length === 1 && id.charCodeAt(0) > 0xf000) {
@@ -17,6 +26,13 @@ function createUse(type, id) {
return use; return use;
} }
/**
* @template {typeof SVGElement} K
* @param {K} svg
* @param {string} type
* @param {string} id
* @returns {K}
*/
export function changeIcon(svg, type, id) { export function changeIcon(svg, type, id) {
if (svg instanceof SVGElement) { if (svg instanceof SVGElement) {
svg.replaceChildren(createUse(type, id)); svg.replaceChildren(createUse(type, id));
@@ -24,10 +40,23 @@ export function changeIcon(svg, type, id) {
return svg; return svg;
} }
/**
* @param {string} type
* @param {string} id
* @param {{[key: string]: string} | ((icon: SVGSVGElement) => {[key: string]: string})} [style]
* @param {(this: SVGSVGElement, ev: PointerEvent) => any} [action]
* @returns {SVGSVGElement}
*/
export function createIcon(type, id, style, action) { export function createIcon(type, id, style, action) {
const svg = document.createElementNS(svgns, 'svg'); const svg = document.createElementNS(svgns, 'svg');
svg.classList.add('ui-icon'); svg.classList.add('ui-icon');
svg.appendChild(createUse(type, id)); svg.appendChild(createUse(type, id));
const css = typeof style === 'function' ? style(svg) : style;
if (css != null) {
for (let [key, value] of Object.entries(css)) {
svg.style.setProperty(key, value);
}
}
if (typeof style === 'function') { if (typeof style === 'function') {
style(svg); style(svg);
} else if (style != null) { } else if (style != null) {
@@ -41,15 +70,24 @@ export function createIcon(type, id, style, action) {
return svg; return svg;
} }
/**
* @param {HTMLElement} container
* @returns {HTMLElement}
*/
export function resolveIcon(container) { export function resolveIcon(container) {
const svgs = container.querySelectorAll('svg[data-id]'); const svgs = container.querySelectorAll('svg[data-id]');
for (let icon of svgs) { for (let icon of svgs) {
if (!(icon instanceof SVGElement)) {
continue;
}
icon.classList.add('ui-icon'); icon.classList.add('ui-icon');
const type = icon.dataset.type; const type = icon.dataset.type;
const id = icon.dataset.id; const id = icon.dataset.id;
icon.replaceChildren(createUse(type, id)); if (type != null && id != null) {
icon.removeAttribute('data-type'); icon.replaceChildren(createUse(type, id));
icon.removeAttribute('data-id'); icon.removeAttribute('data-type');
icon.removeAttribute('data-id');
}
} }
return container; return container;
} }
+68 -14
View File
@@ -3,6 +3,10 @@ import { createElement } from "../functions";
import { createIcon } from "./icon"; import { createIcon } from "./icon";
import { get } from "../utility/request"; import { get } from "../utility/request";
/**
* @param {string} url
* @returns {HTMLAnchorElement}
*/
export function createPicture(url) { export function createPicture(url) {
return createElement('a', a => { return createElement('a', a => {
a.className = 'ui-media-picture'; a.className = 'ui-media-picture';
@@ -15,18 +19,30 @@ export function createPicture(url) {
); );
} }
/**
* @private
* @param {Blob} blob
* @returns {Promise<Uint8Array<ArrayBuffer>>}
*/
function readBlob(blob) { function readBlob(blob) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = e => { reader.onload = e => {
if (e.target?.result instanceof ArrayBuffer) {
const data = new Uint8Array(e.target.result); const data = new Uint8Array(e.target.result);
resolve(data); resolve(data);
}
}; };
reader.onerror = reject; reader.onerror = reject;
reader.readAsArrayBuffer(blob); reader.readAsArrayBuffer(blob);
}); });
} }
/**
*
* @param {Uint8Array<ArrayBuffer>} array
* @returns
*/
function playAmrArray(array) { function playAmrArray(array) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const samples = AMR.decode(array); const samples = AMR.decode(array);
@@ -38,6 +54,12 @@ function playAmrArray(array) {
}); });
} }
/**
* @private
* @param {Float32Array<ArrayBuffer>} samples
* @param {(ctx: AudioContext) => void} ended
* @returns {Promise<AudioContext>}
*/
function playPcm(samples, ended) { function playPcm(samples, ended) {
return new Promise(resolve => { return new Promise(resolve => {
const ctx = new AudioContext(); const ctx = new AudioContext();
@@ -61,6 +83,11 @@ function playPcm(samples, ended) {
}); });
} }
/**
* @private
* @param {number} time
* @returns {string}
*/
function getTimeLabel(time) { function getTimeLabel(time) {
// time = Math.round(time); // time = Math.round(time);
// return String(Math.floor(time / 60)).padStart(2, '0') + ':' + String(time % 60).padStart(2, '0'); // return String(Math.floor(time / 60)).padStart(2, '0') + ':' + String(time % 60).padStart(2, '0');
@@ -76,11 +103,18 @@ function getTimeLabel(time) {
return m + ':' + String(time % 60).padStart(2, '0'); return m + ':' + String(time % 60).padStart(2, '0');
} }
/**
* @param {string} mime
* @param {string} url
* @returns {HTMLAudioElement | HTMLDivElement}
*/
export function createAudio(mime, url) { export function createAudio(mime, url) {
if ((mime === 'audio/amr' || mime === '.amr') && typeof AMR !== 'undefined') { if ((mime === 'audio/amr' || mime === '.amr') && typeof AMR !== 'undefined') {
const timestamp = createElement('span', 'ui-media-timestamp'); const timestamp = createElement('span', 'ui-media-timestamp');
timestamp.textContent = '0:00 / 0:00'; timestamp.textContent = '0:00 / 0:00';
/** @type {AudioContext | null} */
let context; let context;
/** @type {number} */
let timer; let timer;
return createElement('div', 'ui-media-audio', return createElement('div', 'ui-media-audio',
createElement('button', button => { createElement('button', button => {
@@ -132,6 +166,10 @@ export function createAudio(mime, url) {
}); });
} }
/**
* @param {string} url
* @returns {HTMLVideoElement}
*/
export function createVideo(url) { export function createVideo(url) {
return createElement('video', video => { return createElement('video', video => {
video.className = 'ui-media-video'; video.className = 'ui-media-video';
@@ -140,6 +178,11 @@ export function createVideo(url) {
}); });
} }
/**
* @param {string} url
* @param {string} icon
* @returns {HTMLDivElement}
*/
export function createFile(url, icon = 'file-alt') { export function createFile(url, icon = 'file-alt') {
return createElement('div', `ui-media-file ${icon}`, return createElement('div', `ui-media-file ${icon}`,
createIcon('fa-solid', icon), createIcon('fa-solid', icon),
@@ -151,15 +194,19 @@ export function createFile(url, icon = 'file-alt') {
); );
} }
/**
* @typedef VideoPlayOptions
* @property {boolean} [autoPlay] 是否自动播放
* @property {boolean} [autoFullScreen] 是否自动全屏
* @property {boolean} [autoLoop] 是否循环播放
* @property {Function} [onLoaded] 视频加载完成回调
*/
/** /**
* 创建联动视频元素 * 创建联动视频元素
* @param {string[]} urls - 视频 url 数组 * @param {string[]} urls 视频 url 数组
* @param {any} [options] - 播放参数 * @param {VideoPlayOptions} [options] 播放参数
* @param {boolean} options.[autoPlay] - 是否自动播放 * @param {(wrapper: HTMLDivElement) => void} [callback] 视频元素处理回调函数
* @param {boolean} options.[autoFullScreen] - 是否自动全屏
* @param {boolean} options.[autoLoop] - 是否循环播放
* @param {Function} options.[onLoaded] - 视频加载完成回调
* @param {Function} [callback] - 视频元素处理回调函数
* @returns {HTMLDivElement} 返回联动视频元素 * @returns {HTMLDivElement} 返回联动视频元素
*/ */
export function createVideoList(urls, options, callback) { export function createVideoList(urls, options, callback) {
@@ -169,10 +216,13 @@ export function createVideoList(urls, options, callback) {
const length = urls.length; const length = urls.length;
const container = createElement('div', 'ui-media-video-container'); const container = createElement('div', 'ui-media-video-container');
let seekBufferBar; let seekBufferBar;
/** @type {HTMLDivElement} */
let seekProgressBar; let seekProgressBar;
let playIcon; let playIcon;
let timeLabel; let timeLabel;
/** @type {HTMLDivElement} */
let volumeProgressBar; let volumeProgressBar;
/** @type {HTMLDivElement} */
let volumeIcon; let volumeIcon;
const videos = Array(length); const videos = Array(length);
@@ -180,10 +230,14 @@ export function createVideoList(urls, options, callback) {
let prepared = 0; let prepared = 0;
let ended = 0; let ended = 0;
/** @type {boolean} */
let playing; let playing;
let duration = -1; let duration = -1;
/** @type {string} */
let durationLabel; let durationLabel;
/** @type {number} */
let seekBarWidth; let seekBarWidth;
/** @type {boolean} */
let mousing; let mousing;
const controller = createElement('div', 'ui-video-control active', const controller = createElement('div', 'ui-video-control active',
createElement('div', seek => { createElement('div', seek => {
@@ -369,7 +423,7 @@ export function createVideoList(urls, options, callback) {
video.addEventListener('progress', () => { video.addEventListener('progress', () => {
const buffered = video.buffered; const buffered = video.buffered;
for (let i = 0; i < buffered.length; ++i) { for (let i = 0; i < buffered.length; ++i) {
let buffer = seekBufferBar.children[i]; let buffer = /** @type {HTMLElement} */ (seekBufferBar.children[i]);
if (buffer == null) { if (buffer == null) {
seekBufferBar.append(buffer = createElement('div', 'ui-video-buffer')); seekBufferBar.append(buffer = createElement('div', 'ui-video-buffer'));
} }
@@ -383,9 +437,9 @@ export function createVideoList(urls, options, callback) {
} }
}); });
video.addEventListener('canplaythrough', () => { video.addEventListener('canplaythrough', () => {
const w = video.parentElement.querySelector('.ui-video-waiting'); const w = video.parentElement?.querySelector('.ui-video-waiting');
if (w != null) { if (w instanceof HTMLElement) {
w.style.opacity = 0; w.style.opacity = '0';
} }
if (waiting[i]) { if (waiting[i]) {
waiting[i] = false; waiting[i] = false;
@@ -406,9 +460,9 @@ export function createVideoList(urls, options, callback) {
}); });
video.addEventListener('waiting', () => { video.addEventListener('waiting', () => {
waiting[i] = true; waiting[i] = true;
const w = video.parentElement.querySelector('.ui-video-waiting'); const w = video.parentElement?.querySelector('.ui-video-waiting');
if (w != null) { if (w instanceof HTMLElement) {
w.style.opacity = 1; w.style.opacity = '1';
} }
videos.forEach(v => v.pause()); videos.forEach(v => v.pause());
}); });
+110 -64
View File
@@ -6,6 +6,9 @@ import { createElement } from "../functions";
import { createIcon, changeIcon } from "./icon"; import { createIcon, changeIcon } from "./icon";
import { requestAnimationFrame } from "../ui"; import { requestAnimationFrame } from "../ui";
/** @typedef {import('../types').PopupOptions} PopupOptions */
/** @typedef {import('../types').PopupRectParam} PopupRectParam */
const ResizeMods = { const ResizeMods = {
right: 1, right: 1,
bottom: 2, bottom: 2,
@@ -30,58 +33,87 @@ const IconStyle = 'fa-light';
// [ResizeMods.topLeft]: 'nwse-resize' // [ResizeMods.topLeft]: 'nwse-resize'
// } // }
/**
* @private
* @param {string} px
* @returns {number | undefined}
*/
function trimPx(px) { function trimPx(px) {
if (typeof px !== 'string') { if (typeof px !== 'string') {
return px; return px;
} }
if (px.endsWith('px')) { if (px.endsWith('px')) {
const size = Number(px.substring(0, px.length - 2)); const size = Number(px.substring(0, px.length - 2));
return isNaN(size) ? px : size; if (!isNaN(size)) {
return size;
}
} }
return px;
} }
/** @type {import('../types').Popup} */
export class Popup { export class Popup {
_var = {}; _var = {
// _var.mask; /** @type {HTMLElement | undefined} */
// _var.option; mask: undefined,
// _var.bounds; /** @type {PopupOptions | undefined} */
// _var.cursor; option: undefined,
/** @type {PopupRectParam | undefined} */
bounds: undefined,
cursor: undefined
};
constructor(opts = {}) { /**
* @param {PopupOptions} [opts]
*/
constructor(opts) {
this._var.option = opts; this._var.option = opts;
} }
get container() { return this._var.mask.querySelector('.ui-popup-container') } 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) { set title(title) {
const element = this._var.mask?.querySelector('.ui-popup-container .ui-popup-header .ui-popup-header-title'); const element = this._var.mask?.querySelector('.ui-popup-container .ui-popup-header .ui-popup-header-title');
if (element != null) { if (element instanceof HTMLElement) {
element.innerText = title; if (typeof title === 'string') {
element.innerText = title;
} else {
element.replaceChildren(title);
}
}
if (this._var.option != null) {
this._var.option.title = title;
} }
this._var.option.title = title;
} }
get loading() { return this._var.mask?.querySelector('.ui-popup-body>.ui-popup-loading')?.style?.visibility === 'visible' } _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) { set loading(flag) {
let loading = this._var.mask?.querySelector('.ui-popup-body>.ui-popup-loading'); let loading = this._getLoadingPanel();
if (loading == null) { if (loading == null) {
return; return;
} }
if (flag === false) { if (flag === false) {
loading.style.visibility = 'hidden'; loading.style.visibility = 'hidden';
loading.style.opacity = 0; loading.style.opacity = '0';
} else { } else {
loading.style.visibility = 'visible'; loading.style.visibility = 'visible';
loading.style.opacity = 1; loading.style.opacity = '1';
} }
} }
/** @returns {PopupRectParam | undefined} */
get rect() { get rect() {
const container = this.container; const container = this.container;
if (container == null) { if (container == null) {
return null; return;
} }
const style = global.getComputedStyle(container); const style = global.getComputedStyle(container);
const collapsed = container.classList.contains('ui-popup-collapse'); const collapsed = container.classList.contains('ui-popup-collapse');
@@ -94,16 +126,19 @@ export class Popup {
height: collapsed === true && bounds != null ? bounds.height : trimPx(style.height) height: collapsed === true && bounds != null ? bounds.height : trimPx(style.height)
}; };
} }
/**
* @param {PopupRectParam} r
*/
set rect(r) { set rect(r) {
const container = this.container; const container = this.container;
if (container == null) { if (container == null) {
return; return;
} }
const css = []; const css = [];
if (!isNaN(r.left)) { if (r.left != null && !isNaN(r.left)) {
css.push(`left: ${r.left}px`); css.push(`left: ${r.left}px`);
} }
if (!isNaN(r.top)) { if (r.top != null && !isNaN(r.top)) {
css.push(`top: ${r.top}px`); css.push(`top: ${r.top}px`);
} }
const collapse = container.querySelector('.ui-popup-header-icons>.icon-expand'); const collapse = container.querySelector('.ui-popup-header-icons>.icon-expand');
@@ -115,14 +150,14 @@ export class Popup {
changeIcon(collapse, IconStyle, 'expand-alt'); changeIcon(collapse, IconStyle, 'expand-alt');
} }
} else { } else {
if (!isNaN(r.width) && r.width > 0) { if (r.width != null && !isNaN(r.width) && r.width > 0) {
css.push(`width: ${r.width}px`); css.push(`width: ${r.width}px`);
} }
if (!isNaN(r.height) && r.height > 0) { if (r.height != null && !isNaN(r.height) && r.height > 0) {
css.push(`height: ${r.height}px`); css.push(`height: ${r.height}px`);
} }
container.classList.remove('ui-popup-collapse'); container.classList.remove('ui-popup-collapse');
this._var.bounds = null; delete this._var.bounds;
if (collapse != null) { if (collapse != null) {
changeIcon(collapse, IconStyle, 'compress-alt'); changeIcon(collapse, IconStyle, 'compress-alt');
} }
@@ -136,24 +171,28 @@ export class Popup {
const option = this._var.option; const option = this._var.option;
const mask = this._var.mask; const mask = this._var.mask;
const doClose = () => { const doClose = () => {
if (option.persistent) { if (option?.persistent) {
mask.style.display = 'none'; if (mask != null) {
mask.style.display = 'none';
}
} else { } else {
mask.remove(); mask?.remove();
this._var.mask = null; delete this._var.mask;
} }
} }
if (animation) { if (animation) {
mask.classList.add('ui-popup-active'); if (mask != null) {
mask.style.opacity = 0; mask.classList.add('ui-popup-active');
mask.style.opacity = '0';
}
setTimeout(() => { doClose(); }, 120); setTimeout(() => { doClose(); }, 120);
} else { } else {
doClose(); doClose();
} }
if (typeof option.onMasking === 'function') { if (typeof option?.onMasking === 'function') {
option.onMasking.call(this, false); option.onMasking.call(this, false);
} }
if (typeof option.resolve === 'function') { if (typeof option?.resolve === 'function') {
option.resolve.call(this, { option.resolve.call(this, {
result, result,
popup: this popup: this
@@ -168,18 +207,18 @@ export class Popup {
create() { create() {
const mask = createElement('div', 'ui-popup-mask ui-popup-active'); const mask = createElement('div', 'ui-popup-mask ui-popup-active');
const option = this._var.option; const option = this._var.option;
if (option.mask === false) { if (option?.mask === false) {
mask.classList.add('ui-popup-transparent'); mask.classList.add('ui-popup-transparent');
} else if (typeof option.onMasking === 'function') { } else if (typeof option?.onMasking === 'function') {
option.onMasking.call(this, true); option.onMasking.call(this, true);
} }
if (!isNaN(option.zIndex)) { if (option?.zIndex != null && !isNaN(option.zIndex)) {
mask.style.zIndex = String(option.zIndex); mask.style.zIndex = String(option.zIndex);
} }
const container = createElement('div', 'ui-popup-container'); const container = createElement('div', 'ui-popup-container');
if (option.changeZIndex === true) { if (option?.changeZIndex === true) {
container.addEventListener('mousedown', () => { container.addEventListener('mousedown', () => {
const masks = [...this._var.mask.parentElement.children].filter(e => e.classList.contains('ui-popup-mask')); const masks = [...this._var.mask?.parentElement?.children].filter(e => e.classList.contains('ui-popup-mask'));
let max = 200; let max = 200;
masks.forEach(m => { masks.forEach(m => {
let index; let index;
@@ -195,7 +234,7 @@ export class Popup {
} }
}); });
mask.dataset.zindex = mask.style.zIndex; mask.dataset.zindex = mask.style.zIndex;
mask.style.zIndex = max + 1; mask.style.zIndex = `${max + 1}`;
}); });
} else { } else {
@@ -205,17 +244,17 @@ export class Popup {
tabIndex = 0; tabIndex = 0;
} }
container.tabIndex = tabIndex + 1; container.tabIndex = tabIndex + 1;
let content = option.content; let content = option?.content;
if (!(content instanceof HTMLElement)) { if (!(content instanceof HTMLElement)) {
content = createElement('div', d => d.innerText = content); content = createElement('div', d => d.innerText = content);
} }
container.append( container.append(
createElement('div', header => { createElement('div', header => {
header.className = 'ui-popup-header'; header.className = 'ui-popup-header';
let title = option.title; let title = option?.title;
if (!(title instanceof HTMLElement)) { if (!(title instanceof HTMLElement)) {
title = createElement('div', t => { title = createElement('div', t => {
if (option.movable === false) { if (option?.movable === false) {
t.className = 'ui-popup-header-title no-move'; t.className = 'ui-popup-header-title no-move';
} else { } else {
t.className = 'ui-popup-header-title'; t.className = 'ui-popup-header-title';
@@ -224,7 +263,7 @@ export class Popup {
}); });
} }
header.appendChild(title); header.appendChild(title);
if (option.movable !== false) { if (option?.movable !== false) {
const move = header; // title.querySelector('.ui-popup-move') ?? title; const move = header; // title.querySelector('.ui-popup-move') ?? title;
move.addEventListener('mousedown', e => { move.addEventListener('mousedown', e => {
if (['svg', 'use'].includes(e.target?.tagName)) { if (['svg', 'use'].includes(e.target?.tagName)) {
@@ -233,9 +272,10 @@ export class Popup {
if (e.buttons !== 1) { if (e.buttons !== 1) {
return; return;
} }
const parent = option.mask === false ? mask.parentElement : mask; const parent = option?.mask === false ? mask.parentElement : mask;
const x = e.clientX - container.offsetLeft; const x = e.clientX - container.offsetLeft;
const y = e.clientY - container.offsetTop; const y = e.clientY - container.offsetTop;
/** @type {boolean} */
let moved; let moved;
const move = e => { const move = e => {
if (e.buttons === 1) { if (e.buttons === 1) {
@@ -250,7 +290,7 @@ export class Popup {
const up = () => { const up = () => {
parent.removeEventListener('mousemove', move, { passive: false }); parent.removeEventListener('mousemove', move, { passive: false });
parent.removeEventListener('mouseup', up); parent.removeEventListener('mouseup', up);
if (moved === true && typeof option.onMoveEnded === 'function') { if (moved === true && typeof option?.onMoveEnded === 'function') {
option.onMoveEnded.call(this); option.onMoveEnded.call(this);
} }
moved = false; moved = false;
@@ -260,7 +300,7 @@ export class Popup {
} }
const icons = createElement('div', icons => { const icons = createElement('div', icons => {
icons.className = 'ui-popup-header-icons'; icons.className = 'ui-popup-header-icons';
if (option.collapsable === true) { if (option?.collapsable === true) {
const collapse = createIcon(IconStyle, 'compress-alt'); const collapse = createIcon(IconStyle, 'compress-alt');
collapse.tabIndex = tabIndex + 2; collapse.tabIndex = tabIndex + 2;
collapse.classList.add('icon-expand'); collapse.classList.add('icon-expand');
@@ -274,7 +314,7 @@ export class Popup {
const bounds = this._var.bounds; const bounds = this._var.bounds;
if (bounds != null) { if (bounds != null) {
container.style.cssText += `width: ${bounds.width}px; height: ${bounds.height}px`; container.style.cssText += `width: ${bounds.width}px; height: ${bounds.height}px`;
this._var.bounds = null; delete this._var.bounds;
} }
container.classList.remove('ui-popup-collapse'); container.classList.remove('ui-popup-collapse');
changeIcon(collapse, IconStyle, 'compress-alt'); changeIcon(collapse, IconStyle, 'compress-alt');
@@ -285,13 +325,13 @@ export class Popup {
container.classList.add('ui-popup-collapse'); container.classList.add('ui-popup-collapse');
changeIcon(collapse, IconStyle, 'expand-alt'); changeIcon(collapse, IconStyle, 'expand-alt');
} }
if (typeof option.onResizeEnded === 'function') { if (typeof option?.onResizeEnded === 'function') {
option.onResizeEnded.call(this); option.onResizeEnded.call(this);
} }
}); });
icons.appendChild(collapse); icons.appendChild(collapse);
} }
if (option.closable !== false) { if (option?.closable !== false) {
const cancel = createIcon(IconStyle, 'times'); const cancel = createIcon(IconStyle, 'times');
cancel.tabIndex = tabIndex + 3; cancel.tabIndex = tabIndex + 3;
cancel.addEventListener('keypress', e => { cancel.addEventListener('keypress', e => {
@@ -309,7 +349,7 @@ export class Popup {
createElement('div', null, createIcon(IconStyle, 'spinner-third')) 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)); tabIndex = Math.max.apply(null, [...container.querySelectorAll('[tabindex]')].map(e => e.tabIndex ?? 0));
container.appendChild( container.appendChild(
createElement('div', 'ui-popup-footer', ...option.buttons.map((b, i) => { createElement('div', 'ui-popup-footer', ...option.buttons.map((b, i) => {
@@ -320,7 +360,7 @@ export class Popup {
if (b.isPrimary) { if (b.isPrimary) {
button.classList.add('primary'); button.classList.add('primary');
} }
if (b.tabIndex > 0) { if (b.tabIndex != null && b.tabIndex > 0) {
button.tabIndex = b.tabIndex; button.tabIndex = b.tabIndex;
} else { } else {
button.tabIndex = tabIndex + i + 1; button.tabIndex = tabIndex + i + 1;
@@ -362,7 +402,7 @@ export class Popup {
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 // resizable
if (option.resizable === true) { if (option?.resizable === true) {
container.append( container.append(
createElement('layer', layer => { createElement('layer', layer => {
layer.className = 'ui-popup-border ui-popup-border-right'; layer.className = 'ui-popup-border ui-popup-border-right';
@@ -430,18 +470,20 @@ export class Popup {
return Promise.resolve(mask); return Promise.resolve(mask);
} }
} }
if (this._var.option.mask === false) { if (this._var.option?.mask === false) {
// calculator position // calculator position
const container = this.container; const container = this.container;
container.style.left = String((parent.offsetWidth - container.offsetWidth) / 2) + 'px'; if (container != null) {
container.style.top = String((parent.offsetHeight - container.offsetHeight) / 2) + 'px'; container.style.left = String((parent.offsetWidth - container.offsetWidth) / 2) + 'px';
container.style.top = String((parent.offsetHeight - container.offsetHeight) / 2) + 'px'
};
} }
return new Promise(resolve => { return new Promise(resolve => {
mask.style.display = ''; mask.style.display = '';
requestAnimationFrame(() => { requestAnimationFrame(() => {
mask.classList.remove('ui-popup-active'); mask.classList.remove('ui-popup-active');
mask.style.opacity = 1; mask.style.opacity = '1';
this.container.focus(); this.container?.focus();
setTimeout(() => resolve(mask), 120); setTimeout(() => resolve(mask), 120);
}); });
}); });
@@ -452,8 +494,11 @@ export class Popup {
return; return;
} }
const container = this.container; const container = this.container;
if (container == null) {
return;
}
const option = this._var.option; const option = this._var.option;
if (typeof option.onResizeStarted === 'function') { if (typeof option?.onResizeStarted === 'function') {
option.onResizeStarted.call(this); option.onResizeStarted.call(this);
} }
const mask = this._var.mask; const mask = this._var.mask;
@@ -467,13 +512,14 @@ export class Popup {
left: container.offsetLeft, left: container.offsetLeft,
top: container.offsetTop top: container.offsetTop
}; };
const minWidth = option.minWidth ?? 200; const minWidth = option?.minWidth ?? 200;
const minHeight = option.minHeight ?? 200; const minHeight = option?.minHeight ?? 200;
/** @type {boolean} */
let resized; let resized;
const parent = option.mask === false ? mask.parentElement : mask; const parent = option?.mask === false ? mask.parentElement : mask;
const move = e => { const move = e => {
if (e.buttons !== 1) { if (e.buttons !== 1) {
parent.dispatchEvent(new MouseEvent('mouseup')); parent?.dispatchEvent(new MouseEvent('mouseup'));
return; return;
} }
const offsetX = e.clientX - originalX; const offsetX = e.clientX - originalX;
@@ -512,24 +558,24 @@ export class Popup {
y += offsetY; y += offsetY;
} }
} }
if (typeof option.onResizing === 'function') { if (typeof option?.onResizing === 'function') {
option.onResizing.call(this, x, y, width, height); option.onResizing.call(this, x, y, width, height);
} else { } else {
container.style.cssText += `left: ${x}px; top: ${y}px; width: ${width}px; height: ${height}px`; container.style.cssText += `left: ${x}px; top: ${y}px; width: ${width}px; height: ${height}px`;
} }
resized = true; resized = true;
} }
parent.addEventListener('mousemove', move, { passive: false }); parent?.addEventListener('mousemove', move, { passive: false });
const up = () => { const up = () => {
parent.removeEventListener('mousemove', move, { passive: false }); parent.removeEventListener('mousemove', move, { passive: false });
parent.removeEventListener('mouseup', up); parent.removeEventListener('mouseup', up);
// mask.style.cursor = this._var.cursor; // mask.style.cursor = this._var.cursor;
if (resized === true && typeof option.onResizeEnded === 'function') { if (resized === true && typeof option?.onResizeEnded === 'function') {
option.onResizeEnded.call(this); option.onResizeEnded.call(this);
} }
resized = false; resized = false;
}; };
parent.addEventListener('mouseup', up); parent?.addEventListener('mouseup', up);
} }
} }
+10 -5
View File
@@ -3,14 +3,14 @@ import "./css/tab.scss";
/** /**
* Tab 页创建参数类 * Tab 页创建参数类
* @typedef TabOption * @typedef TabOption
* @property {HTMLElement} container - 父容器 * @property {HTMLElement} container 父容器
*/ */
import { createElement } from "../functions"; import { createElement } from "../functions";
/** /**
* 创建 Tab 页 * 创建 Tab 页
* @param {TabOption | HTMLElement} options - 创建选项 * @param {TabOption | HTMLElement} options 创建选项
*/ */
export function createTab(options) { export function createTab(options) {
if (options instanceof HTMLElement) { if (options instanceof HTMLElement) {
@@ -29,13 +29,18 @@ export function createTab(options) {
createElement('div', header => { createElement('div', header => {
header.className = 'ui-tab-header'; header.className = 'ui-tab-header';
header.addEventListener('click', e => { header.addEventListener('click', e => {
const title = e.target; const title = /** @type {HTMLElement} */ (e.target);
if (title.classList.contains('ui-tab-title')) { if (title != null && title.classList.contains('ui-tab-title')) {
// title // title
header.querySelectorAll('.ui-tab-title').forEach(t => t === title ? t.classList.add('selected') : t.classList.remove('selected')); header.querySelectorAll('.ui-tab-title').forEach(t => t === title ? t.classList.add('selected') : t.classList.remove('selected'));
// pages // pages
const page = title.dataset.for; const page = title.dataset.for;
container.querySelectorAll('[data-page]').forEach(p => p.style.display = p.dataset.page === page ? 'block' : ''); container.querySelectorAll('[data-page]').forEach(p => {
if (!(p instanceof HTMLElement)) {
return;
}
p.style.display = p.dataset.page === page ? 'block' : '';
});
} }
}); });
}) })
+32 -11
View File
@@ -4,7 +4,16 @@ import { global } from '../utility';
const pointerHeight = 12; const pointerHeight = 12;
export function setTooltip(container, content, flag = false, parent = null, maxLeft = null) { /**
*
* @param {HTMLElement} container
* @param {string | HTMLElement} content
* @param {boolean} [flag]
* @param {HTMLElement} [parent]
* @param {(left: number) => number} [maxLeft]
* @returns
*/
export function setTooltip(container, content, flag = false, parent, maxLeft) {
const isParent = parent instanceof HTMLElement; const isParent = parent instanceof HTMLElement;
if (isParent) { if (isParent) {
const tipid = container.dataset.tipId; const tipid = container.dataset.tipId;
@@ -43,11 +52,13 @@ export function setTooltip(container, content, flag = false, parent = null, maxL
container.appendChild(wrapper); container.appendChild(wrapper);
} }
/** @type {number} */
let tid; let tid;
container.addEventListener('mouseenter', () => { container.addEventListener('mouseenter', () => {
tid && clearTimeout(tid); tid && clearTimeout(tid);
/** @type {HTMLElement | null} */
let c = container; let c = container;
while (c?.offsetWidth == null) { while (c != null && c.offsetWidth == null) {
c = c.parentElement; c = c.parentElement;
} }
if (c == null) { if (c == null) {
@@ -56,17 +67,16 @@ export function setTooltip(container, content, flag = false, parent = null, maxL
if (!flag || c.scrollWidth > c.offsetWidth) { if (!flag || c.scrollWidth > c.offsetWidth) {
wrapper.style.cssText += 'left: -9999px; top: -9999px; display: block'; wrapper.style.cssText += 'left: -9999px; top: -9999px; display: block';
tid = setTimeout(() => { tid = setTimeout(() => {
/** @type {HTMLElement | null} */
let p; let p;
let left; let left = c.offsetLeft;
let top; let top = c.offsetTop;
left = c.offsetLeft;
top = c.offsetTop;
if (isParent) { if (isParent) {
p = c.offsetParent; p = /** @type {HTMLElement} */ (c.offsetParent);
while (p != null && p !== parent) { while (p != null && p !== parent) {
left += p.offsetLeft; left += p.offsetLeft;
top += p.offsetTop; top += p.offsetTop;
p = p.offsetParent; p = /** @type {HTMLElement} */ (p.offsetParent);
} }
} }
p = c.parentElement; p = c.parentElement;
@@ -92,7 +102,7 @@ export function setTooltip(container, content, flag = false, parent = null, maxL
// check overflow // check overflow
let t = c.offsetTop; let t = c.offsetTop;
let l = c.offsetLeft; let l = c.offsetLeft;
p = c.offsetParent; p = /** @type {HTMLElement} */ (c.offsetParent);
if (p == null) { if (p == null) {
return; return;
} }
@@ -105,7 +115,7 @@ export function setTooltip(container, content, flag = false, parent = null, maxL
} }
t += p.offsetTop; t += p.offsetTop;
l += p.offsetLeft; l += p.offsetLeft;
const parent = p.offsetParent; const parent = /** @type {HTMLElement} */ (p.offsetParent);
while (p != null) { while (p != null) {
const w = p.clientWidth; const w = p.clientWidth;
if (w < lastWidth) { if (w < lastWidth) {
@@ -171,16 +181,27 @@ export function setTooltip(container, content, flag = false, parent = null, maxL
tid && clearTimeout(tid); tid && clearTimeout(tid);
tid = setTimeout(() => { tid = setTimeout(() => {
wrapper.style.visibility = 'hidden'; wrapper.style.visibility = 'hidden';
wrapper.style.opacity = 0; wrapper.style.opacity = '0';
tid = setTimeout(() => wrapper.style.display = 'none', 120); tid = setTimeout(() => wrapper.style.display = 'none', 120);
}, 300); }, 300);
}); });
return container; return container;
} }
/**
* @param {HTMLElement} [container]
* @returns {HTMLElement}
* @example
* ```
* <span title="tooltip text"></span>
* ```
*/
export function resolveTooltip(container = document.body) { export function resolveTooltip(container = document.body) {
const tips = container.querySelectorAll('[title]'); const tips = container.querySelectorAll('[title]');
for (let tip of tips) { for (let tip of tips) {
if (!(tip instanceof HTMLElement)) {
continue;
}
const title = tip.getAttribute('title'); const title = tip.getAttribute('title');
if (title != null) { if (title != null) {
tip.removeAttribute('title'); tip.removeAttribute('title');
+68 -12
View File
@@ -1,58 +1,108 @@
import { getCookie, setCookie, deleteCookie } from "./utility/cookie"; import { getCookie, setCookie, deleteCookie } from "./utility/cookie";
import { domLoad, init, r, lang } from "./utility/lgres"; import { domLoad, init, isTag, r, lang } from "./utility/lgres";
import { get, post, upload } from "./utility/request"; import { get, post, upload } from "./utility/request";
import { nullOrEmpty, contains, endsWith, padStart, formatUrl, escapeHtml, escapeEmoji } from "./utility/strings"; import { nullOrEmpty, contains, endsWith, padStart, formatUrl, escapeHtml, escapeEmoji } from "./utility/strings";
let g = typeof globalThis !== 'undefined' ? globalThis : self; const g = typeof window !== 'undefined' ? window : self;
/**
* @param {any} n
* @returns {n is number}
*/
function isPositive(n) { function isPositive(n) {
return !isNaN(n) && n > 0; const l = typeof n !== 'number' ? Number(n) : n;
return !isNaN(l) && l > 0;
} }
/**
* @returns {boolean}
*/
function isMobile() { function isMobile() {
return /mobile/i.test(navigator.userAgent); return /mobile/i.test(navigator.userAgent);
} }
function throttle(method, delay = 100, context = g, ...args) { /**
* @template {any[]} TArgs
* @template [TContext=typeof globalThis]
* @param {((this: TContext, ...args: TArgs) => void) & { tiid?: number; tdate?: number }} method
* @param {number} [delay=100]
* @param {TContext} [context]
* @param {TArgs} args
* @returns {void}
*/
function throttle(method, delay = 100, context, ...args) {
if (method == null) { if (method == null) {
return; return;
} }
const ctx = typeof context === 'undefined' ?
/** @type {TContext} */ (/** @type {unknown} */ (g)) :
context;
method.tiid && clearTimeout(method.tiid); method.tiid && clearTimeout(method.tiid);
const current = new Date(); const current = Date.now();
if (method.tdate == null || current - method.tdate > delay) { if (method.tdate == null || current - method.tdate > delay) {
method.apply(context, args); method.apply(ctx, args);
method.tdate = current; method.tdate = current;
} else { } else {
method.tiid = setTimeout(() => method.apply(context, args), delay); method.tiid = setTimeout(() => method.apply(ctx, args), delay);
} }
} }
function debounce(method, delay = 100, context = g, ...args) { /**
* @template {any[]} TArgs
* @template [TContext=typeof globalThis]
* @param {((this: TContext, ...args: TArgs) => void) & { tiid?: number }} method
* @param {number} [delay=100]
* @param {TContext} [context]
* @param {TArgs} args
* @returns {void}
*/
function debounce(method, delay = 100, context, ...args) {
if (method == null) { if (method == null) {
return; return;
} }
const ctx = typeof context === 'undefined' ?
/** @type {TContext} */ (/** @type {unknown} */ (g)) :
context;
method.tiid && clearTimeout(method.tiid); method.tiid && clearTimeout(method.tiid);
method.tiid = setTimeout(() => method.apply(context, args), delay); method.tiid = setTimeout(() => method.apply(ctx, args), delay);
} }
/**
* @param {number} v
* @returns {number}
*/
function truncate(v) { function truncate(v) {
return (v > 0 ? Math.floor : Math.ceil)(v); return (v > 0 ? Math.floor : Math.ceil)(v);
} }
/**
* @param {string} text
* @returns {boolean}
*/
function isEmail(text) { function isEmail(text) {
return /^\w[-\w.+]*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(text); return /^\w[-\w.+]*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(text);
} }
/**
* @param {string} text
* @returns {boolean}
*/
function isPhone(text) { function isPhone(text) {
if (/^[1-9]\d{9,}$/.test(text)) { if (/^[1-9]\d{9,}$/.test(text)) {
return true; return true;
} }
if (/^\+?[1-9][\d-]{9,}\d$/.test(text) && /^[1-9]\d{9,}$/.test(text.replace('+', '').replace(new RegExp('-', 'g'), ''))) { if (/^\+?[1-9][\d-]{9,}\d$/.test(text) && /^[1-9]\d{9,}$/.test(text.replace(/\+/g, '').replace(/-/g, ''))) {
return true; return true;
} }
return false; return false;
} }
/**
* `[0-9]`, `[a-z]`, `[A-Z]`, `[^0-9a-zA-Z]`
* each additional type adds one layer of strength.
* @param {string} [password]
* @returns {number}
*/
function getPasswordStrength(password) { function getPasswordStrength(password) {
if (password == null || typeof password !== 'string') { if (password == null || typeof password !== 'string') {
return 0; return 0;
@@ -68,6 +118,11 @@ function getPasswordStrength(password) {
return secure; return secure;
} }
/**
* @param {string} [password]
* @param {number} [min=3]
* @returns {boolean}
*/
function verifyPassword(password, min) { function verifyPassword(password, min) {
min ??= 3; min ??= 3;
const secure = getPasswordStrength(password); const secure = getPasswordStrength(password);
@@ -80,7 +135,9 @@ export {
setCookie, setCookie,
deleteCookie, deleteCookie,
// lgres // lgres
domLoad,
init, init,
isTag,
r, r,
lang, lang,
// request // request
@@ -106,6 +163,5 @@ export {
isEmail, isEmail,
isPhone, isPhone,
getPasswordStrength, getPasswordStrength,
verifyPassword, verifyPassword
domLoad
} }
+15 -1
View File
@@ -1,3 +1,10 @@
/**
* @param {string} name
* @param {string} value
* @param {number} [expireDays]
* @param {string} [host]
* @param {boolean} [encode]
*/
export function setCookie(name, value, expireDays, host, encode) { export function setCookie(name, value, expireDays, host, encode) {
if (name == null) { if (name == null) {
return; return;
@@ -6,7 +13,7 @@ export function setCookie(name, value, expireDays, host, encode) {
if (expireDays != null) { if (expireDays != null) {
const d = new Date(); const d = new Date();
d.setTime(d.getTime() + (expireDays * 24 * 60 * 60 * 1000)); d.setTime(d.getTime() + (expireDays * 24 * 60 * 60 * 1000));
extra += `; expires=${d.toGMTString()}`; extra += `; expires=${d.toUTCString()}`;
} }
if (/^(https|wss):$/.test(location.protocol)) { if (/^(https|wss):$/.test(location.protocol)) {
extra += '; secure'; extra += '; secure';
@@ -17,6 +24,10 @@ export function setCookie(name, value, expireDays, host, encode) {
document.cookie = `${name}=${value}${extra}`; document.cookie = `${name}=${value}${extra}`;
} }
/**
* @param {string} [name]
* @returns {string | null}
*/
export function getCookie(name) { export function getCookie(name) {
if (name == null) { if (name == null) {
return null; return null;
@@ -32,6 +43,9 @@ export function getCookie(name) {
return null; return null;
} }
/**
* @param {string} name
*/
export function deleteCookie(name) { export function deleteCookie(name) {
setCookie(name, '', -1); setCookie(name, '', -1);
} }
+94 -15
View File
@@ -2,14 +2,19 @@ import { getCookie } from "./cookie";
import { get } from "./request"; import { get } from "./request";
import { nullOrEmpty } from "./strings"; import { nullOrEmpty } from "./strings";
/** @typedef {import('../types').LanguageResource} LanguageResource */
const g = typeof window !== 'undefined' ? window : self;
/** @type {LanguageResource} */
let cache; let cache;
function getCurrentLgId() { function getCurrentLgId() {
let lgid; let lgid;
if (typeof consts !== 'undefined') { if (typeof g.consts !== 'undefined') {
lgid = getCookie(consts.cookie?.lang); lgid = getCookie(g.consts.cookie?.lang);
if (nullOrEmpty(lgid)) { if (nullOrEmpty(lgid)) {
lgid = consts.user?.language; lgid = g.consts.user?.language;
} }
} }
if (nullOrEmpty(lgid)) { if (nullOrEmpty(lgid)) {
@@ -42,13 +47,23 @@ function getCurrentLgId() {
return 'en'; return 'en';
} }
/**
* @private
* @param {"en" | "en_au" | "en_ca" | "fr_ca" | "zh_cn" | "es" | "fr" | "pt"} lgid
* @returns {string}
*/
function getStorageKey(lgid) { function getStorageKey(lgid) {
if (typeof consts !== 'undefined') { if (typeof g.consts !== 'undefined') {
return (consts.prefix || '') + `res_${lgid}`; return (g.consts.prefix || '') + `res_${lgid}`;
} }
return `res_${lgid}`; return `res_${lgid}`;
} }
/**
* @private
* @param {string} [template]
* @returns {Promise<LanguageResource>}
*/
async function doRefreshLgres(template = '') { async function doRefreshLgres(template = '') {
const lgid = getCurrentLgId(); const lgid = getCurrentLgId();
const url = template.length > 0 ? template.replace('{lgid}', lgid) : `language/${lgid}`; const url = template.length > 0 ? template.replace('{lgid}', lgid) : `language/${lgid}`;
@@ -58,21 +73,27 @@ async function doRefreshLgres(template = '') {
return dict; return dict;
} }
/**
*
* @param {string} [template]
* @param {LanguageResource | null} [lgres]
* @returns {Promise<LanguageResource>}
*/
async function refreshLgres(template, lgres) { async function refreshLgres(template, lgres) {
if (lgres == null || typeof consts === 'undefined') { if (lgres == null || typeof g.consts === 'undefined') {
lgres = await doRefreshLgres(template); lgres = await doRefreshLgres(template);
} }
const ver = Number(consts.resver); const ver = Number(g.consts?.resver);
const currentVer = Number(lgres.ver); const currentVer = Number(lgres.ver);
if (isNaN(currentVer) || isNaN(ver) || ver > currentVer) { if (isNaN(currentVer) || isNaN(ver) || ver > currentVer) {
console.log(`found new language res version: ${lgres.ver} => ${consts.resver}`); console.log(`found new language res version: ${lgres.ver} => ${g.consts?.resver}`);
lgres = await doRefreshLgres(template); lgres = await doRefreshLgres(template);
} }
Object.defineProperty(lgres, 'r', { Object.defineProperty(lgres, 'r', {
writable: false, writable: false,
configurable: false, configurable: false,
enumerable: false, enumerable: false,
value: function (key, defaultValue) { value: function (/** @type {string} */ key, /** @type {string | undefined} */ defaultValue) {
return getLanguage(this, key, defaultValue); return getLanguage(this, key, defaultValue);
} }
}); });
@@ -80,15 +101,47 @@ async function refreshLgres(template, lgres) {
return lgres; return lgres;
} }
/**
* @private
* @param {LanguageResource} lgres
* @param {string} [key]
* @param {string | null} [defaultValue]
* @returns {string}
*/
function getLanguage(lgres, key, defaultValue) { function getLanguage(lgres, key, defaultValue) {
if (key == null) {
return '';
}
let value = lgres[key]; let value = lgres[key];
return value ?? defaultValue; if (value != null && typeof value !== 'string') {
value = String(value);
}
return value ?? defaultValue ?? '';
} }
/**
* @private
* @template {keyof HTMLElementTagNameMap} K
* @param {Element} element
* @param {K} tagName
* @returns {element is HTMLElementTagNameMap[K]}
*/
export function isTag(element, tagName) {
return element.tagName.toLowerCase() === tagName;
}
/**
* @private
* @param {HTMLElement} dom
* @param {LanguageResource} result
*/
function applyLanguage(dom, result) { function applyLanguage(dom, result) {
for (let text of dom.querySelectorAll('[data-lgid]')) { for (let text of dom.querySelectorAll('[data-lgid]')) {
if (!(text instanceof HTMLElement)) {
continue;
}
const key = text.dataset.lgid; const key = text.dataset.lgid;
if (text.tagName === 'INPUT') { if (isTag(text, 'input')) {
text.value = getLanguage(result, key, text.value); text.value = getLanguage(result, key, text.value);
} else { } else {
text.innerText = getLanguage(result, key, text.innerText); text.innerText = getLanguage(result, key, text.innerText);
@@ -97,12 +150,18 @@ function applyLanguage(dom, result) {
text.dataset.lgid = ''; text.dataset.lgid = '';
} }
for (let title of dom.querySelectorAll('[data-title-lgid]')) { for (let title of dom.querySelectorAll('[data-title-lgid]')) {
if (!(title instanceof HTMLElement)) {
continue;
}
const key = title.dataset.titleLgid; const key = title.dataset.titleLgid;
title.setAttribute('title', getLanguage(result, key, title.getAttribute('title'))); title.setAttribute('title', getLanguage(result, key, title.getAttribute('title')));
// delete title.dataset.titleLgid; // delete title.dataset.titleLgid;
title.dataset.titleLgid = ''; title.dataset.titleLgid = '';
} }
for (let holder of dom.querySelectorAll('[data-placeholder-lgid]')) { for (let holder of dom.querySelectorAll('[data-placeholder-lgid]')) {
if (!(holder instanceof HTMLElement)) {
continue;
}
const key = holder.dataset.placeholderLgid; const key = holder.dataset.placeholderLgid;
holder.setAttribute('placeholder', getLanguage(result, key, holder.getAttribute('placeholder'))); holder.setAttribute('placeholder', getLanguage(result, key, holder.getAttribute('placeholder')));
// delete holder.dataset.placeholderLgid; // delete holder.dataset.placeholderLgid;
@@ -110,9 +169,13 @@ function applyLanguage(dom, result) {
} }
} }
/**
* @returns {Promise<void>}
*/
export function domLoad() { export function domLoad() {
if (document.readyState === 'loading') { if (document.readyState === 'loading') {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
/** @type {number | undefined} */
let tid = setTimeout(() => reject('timeout'), 30000); let tid = setTimeout(() => reject('timeout'), 30000);
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
clearTimeout(tid); clearTimeout(tid);
@@ -124,13 +187,24 @@ export function domLoad() {
return Promise.resolve(); return Promise.resolve();
} }
/**
* @typedef LgresOptions
* @property {string} [template]
* @property {(result: LanguageResource) => void} [callback]
*/
/**
* @param {HTMLElement} dom
* @param {LgresOptions} options
* @returns
*/
export async function init(dom = document.body, options = {}) { export async function init(dom = document.body, options = {}) {
const lgid = getCurrentLgId(); const lgid = getCurrentLgId();
let lgres = localStorage.getItem(getStorageKey(lgid)); const json = localStorage.getItem(getStorageKey(lgid));
let result; let result;
if (lgres != null) { if (json != null) {
try { try {
lgres = JSON.parse(lgres); const lgres = JSON.parse(json);
result = await refreshLgres(options.template, lgres); result = await refreshLgres(options.template, lgres);
} catch (e) { } catch (e) {
console.error('error while parsing lgres, try refresh ...', e); console.error('error while parsing lgres, try refresh ...', e);
@@ -152,11 +226,16 @@ export async function init(dom = document.body, options = {}) {
} }
} }
/**
* @param {string} key
* @param {string | null} [defaultValue]
* @returns {string}
*/
export function r(key, defaultValue) { export function r(key, defaultValue) {
if (cache != null) { if (cache != null) {
return getLanguage(cache, key, defaultValue); return getLanguage(cache, key, defaultValue);
} }
return defaultValue; return defaultValue ?? '';
} }
export const lang = { export const lang = {
+60 -21
View File
@@ -1,28 +1,63 @@
const g = typeof window !== 'undefined' ? window : self;
/**
* @private
* @param {string} url
* @returns {string}
*/
function combineUrl(url) { function combineUrl(url) {
if (/^(https?|wss?|ftp):/.test(url)) { if (/^(https?|wss?|ftp):/.test(url)) {
return url; return url;
} }
if (typeof consts === 'undefined') { if (typeof g.consts === 'undefined') {
return url; return url;
} }
return (consts.path || '') + url; return (g.consts.path || '') + url;
} }
export function get(url, options = {}) { /**
* @typedef RequestOptions
* @property {string} [method]
* @property {string} [accept]
* @property {Object.<string, string>} [customHeaders]
* @property {RequestMode} [mode]
* @property {AbortSignal | null} [signal]
* @property {boolean} [diagnostic]
* @property {(this: XMLHttpRequestUpload, e: ProgressEvent<XMLHttpRequestEventTarget>) => any} [progress]
*/
/**
* @param {string} url
* @param {RequestOptions} [options]
* @returns {Promise<Response>}
*/
export function get(url, options) {
return fetch(combineUrl(url), { return fetch(combineUrl(url), {
method: options.method || 'GET', method: options?.method || 'GET',
headers: { headers: {
...options.customHeaders, ...options?.customHeaders,
'Accept': options.accept ?? 'application/json' 'Accept': options?.accept ?? 'application/json'
}, },
mode: options.mode, mode: options?.mode,
signal: options.signal, signal: options?.signal,
cache: 'default' cache: 'default'
}); });
} }
export function post(url, data, options = {}) { /**
// let contentType; * @typedef DiagnosedResponse
* @property {number} time
* @property {Response} response
*/
/**
* @param {string} url
* @param {BodyInit | null} [data]
* @param {RequestOptions} [options]
* @returns {Promise<Response | DiagnosedResponse>}
*/
export function post(url, data, options) {
const headers = options?.customHeaders ?? {};
if (data instanceof FormData) { if (data instanceof FormData) {
// contentType = 'multipart/form-data'; // contentType = 'multipart/form-data';
} else { } else {
@@ -30,21 +65,19 @@ export function post(url, data, options = {}) {
data = JSON.stringify(data); data = JSON.stringify(data);
} }
// contentType = 'application/json'; // contentType = 'application/json';
if (options.customHeaders == null) { if (headers['Content-Type'] == null) {
options.customHeaders = {}; headers['Content-Type'] = 'application/json';
}
if (options.customHeaders['Content-Type'] == null) {
options.customHeaders['Content-Type'] = 'application/json';
} }
} }
/** @type {RequestInit} */
const opts = { const opts = {
method: options.method || 'POST', method: options?.method || 'POST',
headers: options.customHeaders, headers,
body: data, body: data,
signal: options.signal, signal: options?.signal,
cache: 'no-cache' cache: 'no-cache'
}; };
if (options.diagnostic) { if (options?.diagnostic) {
const started = new Date().getTime(); const started = new Date().getTime();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
fetch(combineUrl(url), opts).then(response => { fetch(combineUrl(url), opts).then(response => {
@@ -58,7 +91,13 @@ export function post(url, data, options = {}) {
return fetch(combineUrl(url), opts); return fetch(combineUrl(url), opts);
} }
export function upload(url, data, options = {}) { /**
* @param {string} url
* @param {FormData} data
* @param {RequestOptions} options
* @returns {Promise<XMLHttpRequest>}
*/
export function upload(url, data, options) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const request = new XMLHttpRequest(); const request = new XMLHttpRequest();
request.onreadystatechange = function () { request.onreadystatechange = function () {
@@ -73,7 +112,7 @@ export function upload(url, data, options = {}) {
if (typeof options.progress === 'function') { if (typeof options.progress === 'function') {
request.upload.addEventListener('progress', function (ev) { request.upload.addEventListener('progress', function (ev) {
if (ev.lengthComputable) { if (ev.lengthComputable) {
options.progress.call(this, ev); options.progress?.call(this, ev);
} }
}, false); }, false);
} }
+41 -7
View File
@@ -1,7 +1,17 @@
/**
* @param {string | null} [s]
* @returns {s is null | undefined | ""}
*/
export function nullOrEmpty(s) { export function nullOrEmpty(s) {
return s == null || typeof s !== 'string' || s.length === 0; return s == null || typeof s !== 'string' || s.length === 0;
} }
/**
* @param {string} s
* @param {string} key
* @param {boolean} [ignoreCase]
* @returns {boolean}
*/
export function contains(s, key, ignoreCase) { export function contains(s, key, ignoreCase) {
if (nullOrEmpty(s) || key == null) { if (nullOrEmpty(s) || key == null) {
return false; return false;
@@ -15,6 +25,11 @@ export function contains(s, key, ignoreCase) {
return s.includes(key); return s.includes(key);
} }
/**
* @param {string} s
* @param {string} suffix
* @returns {boolean}
*/
export function endsWith(s, suffix) { export function endsWith(s, suffix) {
if (nullOrEmpty(s) || nullOrEmpty(suffix)) { if (nullOrEmpty(s) || nullOrEmpty(suffix)) {
return false; return false;
@@ -22,6 +37,12 @@ export function endsWith(s, suffix) {
return s.endsWith(suffix); // === s.length - suffix.length; return s.endsWith(suffix); // === s.length - suffix.length;
} }
/**
* @param {string} s
* @param {number} num
* @param {string} char
* @returns {string}
*/
export function padStart(s, num, char) { export function padStart(s, num, char) {
if (nullOrEmpty(s) || isNaN(num) || num <= s.length) { if (nullOrEmpty(s) || isNaN(num) || num <= s.length) {
return s; return s;
@@ -29,6 +50,10 @@ export function padStart(s, num, char) {
return (char ?? ' ').repeat(num - s.length); return (char ?? ' ').repeat(num - s.length);
} }
/**
* @param {string} msg
* @returns {string}
*/
export function formatUrl(msg) { export function formatUrl(msg) {
//const urlReg = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ig; //const urlReg = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ig;
//const urlArrray = str.match(urlReg); //const urlArrray = str.match(urlReg);
@@ -36,7 +61,7 @@ export function formatUrl(msg) {
const r = msg.match(p); const r = msg.match(p);
msg = escapeHtml(msg); msg = escapeHtml(msg);
if (r?.length > 0) { if (r != null && r.length > 0) {
const rs = []; const rs = [];
for (let t of r) { for (let t of r) {
t = t.replace(/["'\r\n ]/g, ''); t = t.replace(/["'\r\n ]/g, '');
@@ -45,13 +70,14 @@ export function formatUrl(msg) {
} }
} }
const win = typeof window !== 'undefined' ? window : self;
let path; let path;
if (typeof consts !== 'undefined') { if (typeof win.consts !== 'undefined') {
path = consts.path; path = win.consts.path;
} else if (typeof _network !== 'undefined') { } else if (typeof win._network !== 'undefined') {
path = _network.root; path = win._network.root;
} else if (typeof _net !== 'undefined') { } else if (typeof win._net !== 'undefined') {
path = _net.root; path = win._net.root;
} }
for (let r of rs) { for (let r of rs) {
msg = msg.replaceAll(r, `<a target="_blank" href="${r}"><svg><use xlink:href="${path || ''}fonts/fa-regular.svg#link"></use></svg></a>`); msg = msg.replaceAll(r, `<a target="_blank" href="${r}"><svg><use xlink:href="${path || ''}fonts/fa-regular.svg#link"></use></svg></a>`);
@@ -61,6 +87,10 @@ export function formatUrl(msg) {
return msg; return msg;
} }
/**
* @param {string} text
* @returns {string}
*/
export function escapeHtml(text) { export function escapeHtml(text) {
if (text == null) { if (text == null) {
return ''; return '';
@@ -74,6 +104,10 @@ export function escapeHtml(text) {
.replaceAll(' ', '&nbsp;'); .replaceAll(' ', '&nbsp;');
} }
/**
* @param {string} text
* @returns {string}
*/
export function escapeEmoji(text) { export function escapeEmoji(text) {
if (text == null) { if (text == null) {
return ''; return '';
+19 -19
View File
@@ -1,20 +1,22 @@
{ {
"name": "ui-lib", "name": "@soft-qr/ui-lib",
"private": true, "version": "1.0.9",
"version": "1.0.7", "publishConfig": {
"registry": "https://git.soft.qr/api/packages/soft-qr/npm/"
},
"author": "cl",
"type": "module", "type": "module",
"files": [ "files": [
"dist" "dist"
], ],
"module": "./dist/ui.js",
"types": "./dist/ui.d.ts",
"exports": { "exports": {
"ui": { ".": {
"import": "./dist/ui.es.js", "types": "./dist/ui.d.ts",
"require": "./dist/ui.min.js" "import": "./dist/ui.js"
}, },
"utility": { "./style.css": "./dist/ui.min.css"
"import": "./dist/utility.es.js",
"require": "./dist/utility.min.js"
}
}, },
"browserslist": [ "browserslist": [
"last 1 versions", "last 1 versions",
@@ -23,19 +25,17 @@
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "node ./vite.build.js", "build": "node ./vite.build.js",
"doc": "typedoc",
"jsdoc": "jsdoc -c jsdoc.json", "jsdoc": "jsdoc -c jsdoc.json",
"jsdoc-date": "jsdoc -c jsdoc-date.json" "jsdoc-date": "jsdoc -c jsdoc-date.json"
}, },
"devDependencies": { "devDependencies": {
"@mxssfd/typedoc-theme": "^1.1.6", "clean-jsdoc-theme": "^5.3.0",
"clean-jsdoc-theme": "^4.3.0",
"docdash": "^2.0.2", "docdash": "^2.0.2",
"jsdoc": "^4.0.3", "jsdoc": "^4.0.5",
"postcss-preset-env": "^9.6.0", "postcss-preset-env": "^11.6.2",
"sass": "^1.77.8", "sass": "^1.108.2",
"typedoc": "^0.26.5", "typescript": "^6.0.3",
"vite": "^5.3.4", "unplugin-dts": "^1.1.2",
"vite-plugin-externals": "^0.6.2" "vite": "^8.3.8"
} }
} }
+20 -6
View File
@@ -1,10 +1,24 @@
{ {
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"types": ["vite/client"],
"allowJs": true,
"checkJs": true,
"declaration": true,
"noEmit": true,
"isolatedModules": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": true
},
"include": [ "include": [
"./lib/functions*", "lib/functions.js",
"./lib/ui/**/*" "lib/ui.js",
], "lib/ui",
"exclude": [ "lib/utility.js",
"./dist", "lib/utility"
"node_modules"
] ]
} }
-15
View File
@@ -1,15 +0,0 @@
{
"entryPoints": [
"lib/ui/date.d.ts",
"lib/ui/dropdown.d.ts",
"lib/ui/grid/column.d.ts",
"lib/ui/grid/grid.d.ts"
],
"out": "./docs",
"readme": "README.md",
"name": "UI Library",
"plugin": ["@mxssfd/typedoc-theme"],
"theme": "my-theme",
"disableSources": true,
"cleanOutputDir": true
}
+73 -27
View File
@@ -1,9 +1,68 @@
import { build } from "vite"; import { build } from "vite";
import { rmSync } from 'node:fs';
import { resolve } from 'node:path';
import dts from 'unplugin-dts/vite';
import postcssPresetEnv from "postcss-preset-env"; import postcssPresetEnv from "postcss-preset-env";
import { viteExternalsPlugin } from "vite-plugin-externals";
// empty out dir
rmSync(resolve('dist'), { recursive: true, force: true });
const libraries = [ const libraries = [
{ {
name: 'utility',
path: resolve('./lib/utility.js')
},
{
name: 'ui',
path: resolve('./lib/ui.js')
},
/*/
{
name: 'app',
path: resolve('./lib/app.js'),
rolldownOptions: {
external: ['../../ui'],
output: {
format: 'umd',
globals(id) {
let index = id.lastIndexOf('/');
if (index < 0) {
index = id.lastIndexOf('\\');
}
id = id.substring(index + 1);
switch (id) {
case 'ui': return 'lib-ui';
default: return id;
}
}
}
}
},
{
name: 'element',
path: resolve('./lib/element.js'),
rolldownOptions: {
external: ['../ui'],
output: {
format: 'umd',
globals(id) {
let index = id.lastIndexOf('/');
if (index < 0) {
index = id.lastIndexOf('\\');
}
id = id.substring(index + 1);
switch (id) {
case 'ui': return 'lib-ui';
default: return id;
}
}
}
}
},//*/
]
for (const { name, path, rolldownOptions } of libraries) {
await build({
clearScreen: false, clearScreen: false,
css: { css: {
postcss: { postcss: {
@@ -12,33 +71,20 @@ const libraries = [
}, },
build: { build: {
lib: { lib: {
entry: './lib/ui.js', entry: {
name: 'lib-ui', [name]: path
formats: ['cjs', 'umd'], },
fileName: (format, name) => format === 'cjs' ? `${name}-cjs.min.js` : `${name}.min.js` name: `lib-${name}`,
}, cssFileName: `${name}.min`,
rollupOptions: {
output: {
assetFileNames: info => info.name === 'style.css' ? 'ui.min.css' : info.name
}
},
sourcemap: true,
emptyOutDir: false
}
},
{
clearScreen: false,
build: {
lib: {
entry: './lib/utility.js',
name: 'lib-utility',
formats: ['umd'], formats: ['umd'],
fileName: (_format, name) => `${name}.min.js` fileName: (_format, name) => `${name}.js`
}, },
rolldownOptions,
sourcemap: true, sourcemap: true,
emptyOutDir: false emptyOutDir: false
} },
} plugins: [
] dts()
]
libraries.forEach(async b => await build(b)) });
}