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
+1211 -408

No files matched your search

+1
View File
@@ -27,3 +27,4 @@ desktop.ini
# User definition
docs
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) {
const element = document.createElement(tagName);
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 * as utility from './utility';
/** @typedef {import('./global')} */
/**
* @param {FrameRequestCallback | TimerHandler} callback
* @returns {number}
*/
function requestAnimationFrame(callback) {
if (typeof utility.global.requestAnimationFrame === 'function') {
utility.global.requestAnimationFrame(callback);
} else {
setTimeout(callback, 0);
return utility.global.requestAnimationFrame(/** @type {FrameRequestCallback} */(callback));
}
return setTimeout(callback, 0);
}
/**
* @private
* @returns {number}
*/
function scrollLeft() {
const n = document.documentElement;
return (utility.global.scrollX || n.scrollLeft) - (n.clientLeft || 0);
}
/**
* @private
* @returns {number}
*/
function scrollTop() {
const n = document.documentElement;
return (utility.global.scrollY || n.scrollTop) - (n.clientTop || 0);
}
/**
* @private
* @param {HTMLElement} e
* @returns {DOMRectReadOnly}
*/
function offset(e) {
const rect = e.getBoundingClientRect();
return {
top: rect.top + scrollTop(),
left: rect.left + scrollLeft(),
height: rect.height,
width: rect.width
};
return new DOMRectReadOnly(
rect.left + scrollLeft(),
rect.top + scrollTop(),
rect.width,
rect.height
);
}
class OptionBase {
_option;
/** @type {import('./types').GetTextCallback} */
r;
/**
* @param {import('./types').OptionParamBase} opt
*/
constructor(opt) {
this._option = opt;
const getText = opt.getText;
if (typeof getText === 'function') {
this.r = getText;
} else if (typeof GetTextByKey === 'function') {
this.r = GetTextByKey;
} else if (typeof utility.global.GetTextByKey === 'function') {
this.r = utility.global.GetTextByKey;
} else {
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
* @param {HTMLDivElement} wrapper
* @param {(auto: boolean) => void} [onDismissed]
* @param {(auto?: boolean) => void} [onDismissed]
* @param {boolean} [auto]
*/
function closeNotify(wrapper, onDismissed, auto) {
@@ -93,22 +98,26 @@ function closeNotify(wrapper, onDismissed, auto) {
}
/**
*
* @param {NotifyOption} opts
* @param {import('./types').NotifyOption} [opts]
* @returns {HTMLDivElement | undefined}
*/
function notify(opts) {
opts ||= {};
const message = opts?.message;
if (message == null) {
return;
}
/** @type {number} */
let timer;
const close = createIcon('fa-light', 'times');
close.classList.add('ui-notify-close');
close.addEventListener('click', () => {
timer && clearTimeout(timer);
closeNotify(wrapper, opts.onDismissed);
closeNotify(wrapper, opts?.onDismissed);
});
let type;
let typeClass;
opts.type ||= 'success';
switch (opts.type) {
switch (opts?.type) {
case 'warning':
type = 'exclamation-circle';
typeClass = 'warning';
@@ -117,39 +126,36 @@ function notify(opts) {
type = 'times-circle';
typeClass = 'error';
break;
case 'success':
type = 'check-circle';
typeClass = 'success';
break;
default:
type = opts.type;
type = opts?.type ?? 'check-circle';
typeClass = 'success';
break;
}
const icon = createIcon('fa-solid', type);
icon.classList.add('ui-notify-type', typeClass);
const title = opts?.title;
const wrapper = createElement('div', 'ui-notify',
utility.nullOrEmpty(opts.title) ?
utility.nullOrEmpty(title) ?
createElement('div', 'ui-notify-single',
icon,
createElement('span', 'ui-notify-message', opts.message),
createElement('span', 'ui-notify-message', message),
close
) :
createElement('div', 'ui-notify-content',
createElement('div', 'ui-notify-header',
icon,
createElement('h2', 'ui-notify-title', opts.title),
createElement('h2', 'ui-notify-title', title),
close
),
createElement('span', 'ui-notify-message', opts.message)
createElement('span', 'ui-notify-message', message)
)
);
if (!opts.persistent) {
if (opts?.persistent !== true) {
timer = setTimeout(() => {
closeNotify(wrapper, opts.onDismissed, true);
}, opts.timeout || 3000);
closeNotify(wrapper, opts?.onDismissed, true);
}, opts?.timeout || 3000);
}
(opts.parent ?? document.body).appendChild(wrapper);
(opts?.parent ?? document.body).appendChild(wrapper);
setTimeout(() => wrapper.classList.add('active'), 10);
return wrapper;
}
+46 -14
View File
@@ -1,8 +1,20 @@
import './css/checkbox.scss';
import { createElement } from "../functions";
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);
checkIcon.classList.add('ui-check-icon');
const indeterminateIcon = createIcon(type, 'minus');
@@ -24,7 +36,7 @@ function fillCheckbox(container, type = 'fa-regular', label, tabindex = -1, char
}
}, checkIcon, indeterminateIcon)
);
if (label instanceof Element) {
if (label instanceof HTMLElement) {
container.appendChild(label);
} else if (label != null && String(label).length > 0) {
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 = {}) {
const container = createElement('label', 'ui-check-wrapper ui-radio-wrapper',
createElement('input', input => {
input.setAttribute('type', 'radio');
if (!nullOrEmpty(opts.name)) {
input.name = opts.name;
}
if (opts.checked === true) {
input.checked = true;
}
@@ -61,10 +80,15 @@ export function createRadiobox(opts = {}) {
if (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;
}
/**
* 创建一个复选框
* @param {CheckboxOptions} opts
* @returns {HTMLLabelElement}
*/
export function createCheckbox(opts = {}) {
const container = createElement('label', opts.switch ? 'ui-switch' : 'ui-check-wrapper',
createElement('input', input => {
@@ -112,7 +136,7 @@ export function createCheckbox(opts = {}) {
} else if (opts.checkedNode != null && opts.uncheckedNode != null) {
container.classList.add('ui-check-image-wrapper');
let height = opts.imageHeight;
if (isNaN(height) || height <= 0) {
if (!isPositive(height)) {
height = 14;
}
opts.checkedNode.classList.add('checked');
@@ -120,16 +144,22 @@ export function createCheckbox(opts = {}) {
opts.uncheckedNode.classList.add('unchecked');
container.appendChild(opts.uncheckedNode);
} else {
fillCheckbox(container, opts.type, opts.label, opts.tabIndex, undefined, opts.title);
fillCheckbox(container, opts.type, opts.label, opts.tabIndex, opts.title);
}
return container;
}
/**
* 解析容器元素内符合条件的子元素为复选框元素
* @param {HTMLElement} container
* @param {boolean} [legacy]
* @returns {HTMLElement}
*/
export function resolveCheckbox(container = document.body, legacy) {
if (legacy) {
const checks = container.querySelectorAll('input[type="checkbox"]');
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
continue;
}
@@ -140,7 +170,7 @@ export function resolveCheckbox(container = document.body, legacy) {
}
if (label == null) {
const e = chk.nextElementSibling;
if (e != null) {
if (e instanceof HTMLElement) {
if (e.tagName === 'LABEL') {
label = e;
} else if (e.tagName === 'SPAN' && e.dataset.lgid != null) {
@@ -151,7 +181,7 @@ export function resolveCheckbox(container = document.body, legacy) {
}
if (label == null) {
const e = chk.previousElementSibling;
if (e != null) {
if (e instanceof HTMLElement) {
if (e.tagName === 'LABEL') {
label = e;
} 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');
chk.parentElement.insertBefore(label, chk);
chk.parentElement?.insertBefore(label, chk);
} else {
text = label.innerText;
}
@@ -172,12 +202,15 @@ export function resolveCheckbox(container = document.body, legacy) {
label.className = 'ui-check-wrapper';
}
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);
}
}
const boxes = container.querySelectorAll('label[data-checkbox]');
for (let box of boxes) {
if (!(box instanceof HTMLLabelElement)) {
continue;
}
if (!box.classList.contains('ui-check-wrapper')) {
box.classList.add('ui-check-wrapper');
}
@@ -189,8 +222,7 @@ export function resolveCheckbox(container = document.body, legacy) {
fillCheckbox(box,
box.dataset.type,
box.dataset.label,
box.dataset.tabIndex,
undefined,
Number(box.dataset.tabIndex),
box.title);
box.removeAttribute('title');
box.removeAttribute('data-type');
@@ -198,7 +230,7 @@ export function resolveCheckbox(container = document.body, legacy) {
}
const input = createElement('input');
const id = box.dataset.id;
if (id?.length > 0) {
if (!nullOrEmpty(id)) {
input.id = id;
}
if (box.dataset.checked != null) {
+73 -80
View File
@@ -1,20 +1,18 @@
import { createElement } from "../functions";
import { isPositive, nullOrEmpty } from "../utility";
import { isPositive, isTag, nullOrEmpty } from "../utility";
/**
* 创建或转换日期选择框
* @param {string} [min] - 最小可选日期
* @param {string} [max] - 最大可选日期
* @param {HTMLInputElement | string} [element] - 转换该元素为日期选择框
* @param {string | null} [min] 最小可选日期
* @param {string | null} [max] 最大可选日期
* @param {HTMLInputElement | string} [element] 转换该元素为日期选择框
* @returns {HTMLInputElement} 返回创建或转换的日期选择框
*/
export function createDateInput(min, max, element) {
let date;
if (typeof element === 'string') {
element = document.querySelector(element);
}
if (element instanceof HTMLInputElement) {
date = element;
const e = typeof element === 'string' ? document.querySelector(element) : element;
if (e instanceof HTMLInputElement) {
date = e;
date.classList.add('ui-date-cell');
} else {
date = createElement('input', 'ui-date-cell');
@@ -41,7 +39,7 @@ export function createDateInput(min, max, element) {
* @returns 返回 `yyyy-MM-dd` 格式的字符串
*/
export function toDateValue(dt, local) {
if (isNaN(dt)) {
if (!(dt instanceof Date) || isNaN(dt.getTime())) {
return '';
}
const year = local ? dt.getFullYear() : dt.getUTCFullYear();
@@ -52,8 +50,8 @@ export function toDateValue(dt, local) {
/**
* 获取日期格式器
* @param {Date} date - 待格式的日期
* @param {boolean} [utc=true] - 是否按 UTC 时间格式化
* @param {Date} date 待格式的日期
* @param {boolean} [utc=true] 是否按 UTC 时间格式化
* @returns {any} 返回格式化工具对象
*/
export function getFormatter(date, utc) {
@@ -96,11 +94,11 @@ export function getFormatter(date, utc) {
t: () => new Date(r.Y(), r.n(), 0).getDate(),
/**
* @private
* @returns {('1' | '0')} 返回是否为闰年
* @returns {(1 | 0)} 返回是否为闰年
*/
L() {
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
@@ -151,7 +149,7 @@ export function getFormatter(date, utc) {
* @private
* @returns {string} 返回时区描述字符串
*/
e: () => /\((.*)\)/.exec(String(date))[1] || 'Coordinated Universal Time',
e: () => /\((.*)\)/.exec(String(date))?.[1] || 'Coordinated Universal Time',
/**
* @private
* @returns {string} 返回时区偏移字符串
@@ -175,7 +173,7 @@ export function getFormatter(date, utc) {
/**
* 格式化日期为 M/d/yyyy 格式的字符串
* @param {Date | number | string} date - 需要格式化的日期值,支持的格式如下:
* @param {Date | number | string} date 需要格式化的日期值,支持的格式如下:
*
* * `"2024-01-26"`
* * `"2024/1/26"`
@@ -183,7 +181,7 @@ export function getFormatter(date, utc) {
* * `"1/26/2024"`
* * `"638418240000000000"`
* * `new Date('2024-01-26')`
* @param {string} [formatter] - 格式化格式,默认为 `"m/d/Y"`
* @param {string} [formatter] 格式化格式,默认为 `"m/d/Y"`
*
* * Y - 年,例如 `2024`
* * y - 年的后两位,例如 `"24"`
@@ -212,17 +210,17 @@ export function formatDate(date, formatter) {
if (date === '') {
return '';
}
if (isNaN(date)) {
if (typeof date === 'string') {
let e = /^(\d{4})-(\d{2})-(\d{2})/.exec(date);
if (e == null) {
e = /^(\d{4})\/(\d{1,2})\/(\d{1,2})/.exec(date);
}
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 {
e = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(date);
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 {
return date;
}
@@ -238,20 +236,23 @@ export function formatDate(date, formatter) {
const f = getFormatter(date);
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 {string} [formatter] - 日期格式化字符串(仅设置显示元素时调用)
*/
export function setDateValue(element, val, formatter) {
if (element.tagName === 'INPUT') {
if (element == null) {
return;
}
if (isTag(element, 'input')) {
if (val === '') {
element.value = '';
} else if (isNaN(val)) {
} else if (typeof val === 'string') {
if (/^\d{4}-\d{2}-\d{2}/.test(val)) {
element.value = String(val).substring(0, 10);
} 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) {
const date = element?.valueAsDate;
if (date instanceof Date && !isNaN(date)) {
if (date instanceof Date && !isNaN(date.getTime())) {
const year = date.getUTCFullYear();
if (year < 1900 || year > 9999) {
return '';
@@ -319,6 +320,16 @@ export function getDateValue(element, formatter) {
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
@@ -326,48 +337,22 @@ export function getDateValue(element, formatter) {
export class DateSelector {
_var = {
/**
* @type {HTMLInputElement}
* @type {HTMLInputElement | undefined}
* @private
*/
el: null,
options: {
el: undefined,
/**
* @type {boolean?}
* @type {DateOptions}
* @private
*/
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
}
options: {}
};
/**
* 日期发生变化时触发的事件
* @type {((date?: Date) => void) | undefined}
* @event
* @param {Date} date - 修改后的日期值
* @param {Date} [date] - 修改后的日期值
* @this DateSelector
*/
onDateChanged;
@@ -375,11 +360,7 @@ export class DateSelector {
/**
* 日期选择框构造函数
* @constructor
* @param {object} [opts] - 日期选择框初始化参数
* @param {boolean} [opts.enabled] - 是否可用
* @param {string} [opts.minDate] - 最小可选择日期
* @param {string} [opts.maxDate] - 最大可选择日期
* @param {DateFormatterCallback} [opts.valueFormatter] - 自定义格式化函数
* @param {DateOptions} [opts] 日期选择框初始化参数
* @example <caption>创建一个 DateSelector 并插入到元素中</caption>
* <div id="dateFrom"></div>
* @example
@@ -400,7 +381,9 @@ export class DateSelector {
* dateSelectorTo.create('#dateTo');
*/
constructor(opts) {
this._var.options = opts ?? {};
if (opts != null) {
this._var.options = opts;
}
}
/**
@@ -411,7 +394,7 @@ export class DateSelector {
create(element) {
const opts = this._var.options;
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)) {
el.classList.add(opts.className);
}
@@ -419,6 +402,9 @@ export class DateSelector {
el.disabled = opts.enabled === false;
}
el.addEventListener('blur', e => {
if (!(e.target instanceof HTMLInputElement)) {
return;
}
const date = this._getDate(e.target.valueAsDate);
if (date == null) {
e.target.value = '';
@@ -434,7 +420,7 @@ export class DateSelector {
/**
* 获取日期选择框元素
* @readonly
* @type {HTMLInputElement}
* @type {HTMLInputElement | undefined}
*/
get element() { return this._var.el }
@@ -442,57 +428,63 @@ export class DateSelector {
* 获取或设置日期选择框是否启用
* @type {boolean}
*/
get enabled() { return !this._var.el.disabled }
get enabled() { return this._var.el?.disabled === false }
set enabled(flag) {
if (this._var.el != null) {
this._var.el.disabled = flag === false;
}
}
/**
* 获取格式化的日期值,或设置日期值,支持的格式参见 {@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) {
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) {
if (this._var.el != null && !nullOrEmpty(date)) {
this._var.el.min = 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) {
if (this._var.el != null && !nullOrEmpty(date)) {
this._var.el.max = date;
}
this._var.options.maxDate = date;
}
/**
* @private
* @param {Date} date
* @returns {Date | any}
* @param {Date | null | undefined} date
* @returns {Date | undefined}
*/
_getDate(date) {
if (date instanceof Date && !isNaN(date)) {
if (date instanceof Date && !isNaN(date.getTime())) {
const year = date.getUTCFullYear();
if (year < 1900 || year > 9999) {
return null;
return;
}
if (typeof this._var.options.valueFormatter === 'function') {
return this._var.options.valueFormatter(date);
}
return date;
}
return null;
}
/**
@@ -500,9 +492,7 @@ export class DateSelector {
* 解析的属性为 `id`, `class`, `data-min`, `data-max`, `disabled`
* @static
* @param {HTMLElement} [dom=document.body] 父元素
* @param {Function} [trigger] 日期设置事件触发函数
* @param {Date} trigger.{this} - 上下文为触发设置日期的 `DateSelector` 实例
* @param {Date} trigger.date - 修改后的日期值
* @param {(this: DateSelector, date?: Date) => void} [trigger] 日期设置事件触发函数, 上下文为触发设置日期的 `DateSelector` 实例
* @example <caption>HTML</caption>
* <input id="dateFrom" data-type="date" data-min="1980-01-01"/>
* @example <caption>解析父容器</caption>
@@ -519,6 +509,9 @@ export class DateSelector {
static resolve(dom = document.body, trigger) {
const dates = dom.querySelectorAll('input[data-type="date"]');
for (let dat of dates) {
if (!(dat instanceof HTMLInputElement)) {
continue;
}
const val = dat.value;
const dateSelector = new DateSelector({
minDate: dat.getAttribute('data-min'),
+195 -52
View File
@@ -26,10 +26,11 @@ if (dropdownGlobal == null) {
continue;
}
panel.classList.remove('active');
const dropId = panel.parentElement.dataset.dropId;
const dropId = panel.parentElement?.dataset.dropId;
if (dropId == null) {
continue;
}
/** @type {Dropdown | undefined} */
const dropdown = this[dropId];
if (dropdown?.multiSelect && typeof dropdown.onCollapsed === 'function') {
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;
if (typeof template === 'function') {
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)) {
label.replaceChildren(...htmls.filter(it => it != null).map(it => it.cloneNode(true)));
} else {
let text = itemlist.map(it => it[textkey]).join(', ');
let text = itemlist.map(it => String(it[textkey])).join(', ');
if (nullOrEmpty(text)) {
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) {
if (!Array.isArray(searchkeys) || searchkeys.length === 0) {
searchkeys = [textkey];
@@ -87,6 +104,12 @@ function filterSource(searchkeys, textkey, key, source) {
return source;
}
/**
* @private
* @param {DropdownItem} it
* @param {string} valuekey
* @param {string} textkey
*/
function getValue(it, valuekey, textkey) {
if (it == null) {
return null;
@@ -105,7 +128,7 @@ function getValue(it, valuekey, textkey) {
* @property {string} [valueKey=value] - 值关键字
* @property {string} [htmlKey=html] - 源码显示的关键字
* @property {string} [childKey=children] - 子集合的关键字
* @property {Function} [htmlTemplate] - 模板创建函数
* @property {(this: Dropdown, it: DropdownItem) => string} [htmlTemplate] - 模板创建函数
* @property {number} [maxLength=500] - 最大输入长度
* @property {boolean} [multiSelect] - 是否允许多选
* @property {string} [selected] - 选中值
@@ -119,28 +142,62 @@ function getValue(it, valuekey, textkey) {
* @property {string} [placeholder] - 输入框的提示文本
* @property {boolean} [slideFixed] - 是否固定为向下展开
* @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 {
_var = {};
// _var.options;
// _var.wrapper;
// _var.container;
// _var.label;
// _var.allChecked;
// _var.source;
// _var.lastSelected;
// _var.selected;
// _var.selectedList;
_var = {
/** @type {DropdownOptions} */
options: undefined,
/** @type {HTMLDivElement} */
wrapper: undefined,
/** @type {HTMLDivElement} */
container: undefined,
/** @type {HTMLInputElement | HTMLLabelElement} */
label: undefined,
allChecked: false,
/** @type {DropdownItem[]} */
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;
/** @type {((list: DropdownItem[]) => void) | undefined} */
onSelectedList;
/** @type {((it: DropdownItem) => void) | undefined} */
onSelected;
/** @type {((this: Dropdown) => void) | undefined} */
onExpanded;
/** @type {((this: Dropdown) => void) | undefined} */
onCollapsed;
/**
* @param {DropdownOptions} options
*/
constructor(options = {}) {
options.textKey ??= 'text';
options.valueKey ??= 'value';
@@ -284,6 +341,11 @@ export class Dropdown {
} else {
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() {
@@ -306,6 +368,13 @@ export class Dropdown {
}
const valuekey = this._var.options.valueKey;
const childkey = this._var.options.childKey;
/**
* @private
* @param {DropdownItem[]} list
* @param {string} [id]
* @param {number} [level]
* @returns {DropdownItem[]}
*/
function reduceItems(list, id, level = 0) {
if (!Array.isArray(list)) {
return [];
@@ -326,6 +395,13 @@ export class Dropdown {
get selectedList() { return this._var.selectedList || [] }
/**
*
* @param {string} selected
* @param {boolean} [silence]
* @param {boolean} [ignoreCase]
* @returns {boolean | undefined}
*/
select(selected, silence, ignoreCase) {
if (typeof selected !== 'string') {
selected = String(selected);
@@ -395,12 +471,16 @@ export class Dropdown {
return true;
}
/**
*
* @param {string[]} selectedlist
* @param {boolean} silence
* @returns {boolean | undefined}
*/
selectlist(selectedlist, silence) {
const source = this.source;
const valuekey = this._var.options.valueKey;
const textkey = this._var.options.textKey;
const template = this._var.options.htmlTemplate;
const htmlkey = this._var.options.htmlKey;
const itemlist = selectedlist.map(a => {
const v = typeof a === 'string' ? a : String(a);
let item = source.find(it => String(getValue(it, valuekey, textkey)) === v);
@@ -415,15 +495,11 @@ export class Dropdown {
this._var.allChecked = false;
source.forEach(it => delete it.__checked);
if (itemlist.length === 0) {
this._var.selectedList = null;
delete this._var.selectedList;
this._var.label.innerText = r('none', '( None )');
return false;
}
selectItems(this._var.label, itemlist, template, htmlkey, textkey);
this._var.selectedList = itemlist;
if (!silence && typeof this.onSelectedList === 'function') {
this.onSelectedList(itemlist);
}
this._selectList(list, silence);
}
get _expanded() { return this._var.container?.classList?.contains('active') }
@@ -445,7 +521,14 @@ export class Dropdown {
const key = e.target.value.toLowerCase();
const source = filterSource(options.searchKeys, options.textKey, key, this.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'));
panel.appendChild(search);
}
@@ -530,6 +613,11 @@ export class Dropdown {
}
}
/**
*
* @param {HTMLDivElement} list
* @param {number} top
*/
_onlistscroll(list, top) {
const offset = (this.multiSelect && !this.ignoreAll) ? DropdownItemHeight : 0;
top -= (top % (DropdownItemHeight * 2)) + offset;
@@ -553,6 +641,7 @@ export class Dropdown {
} else {
array = array.slice(-20);
}
/** @type {HTMLDivElement} */
const content = list.querySelector('.drop-content');
content.replaceChildren();
this._dofilllist(content, array);
@@ -560,6 +649,10 @@ export class Dropdown {
}
}
/**
*
* @param {DropdownItem[]} source
*/
_filllist(source) {
const list = this._var.container.querySelector('.ui-drop-list');
list.replaceChildren();
@@ -571,7 +664,7 @@ export class Dropdown {
const content = createElement('div', 'drop-content');
if (this.multiSelect && !this.ignoreAll) {
list.appendChild(
createElement('li', null,
createElement('li', undefined,
createCheckbox({
label: r('allItem', '( All )'),
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) {
if (childkey == null) {
return false;
}
if (Array.isArray(item[childkey])) {
for (let t of item[childkey]) {
if (it === String(getValue(t, valuekey, textkey))) {
@@ -629,13 +734,19 @@ export class Dropdown {
return false;
}
/**
*
* @param {HTMLDivElement} content
* @param {DropdownItem[]} array
* @returns {number | undefined}
*/
_dofilllist(content, array) {
const multiselect = this.multiSelect;
const valuekey = this._var.options.valueKey;
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 selected = this.selected;
let scrolled;
array.forEach((item, i) => {
@@ -698,7 +809,7 @@ export class Dropdown {
} else {
if (label == null) {
label = createElement('span');
label.innerHTML = item[textkey];
label.innerText = item[textkey];
}
wrapper.appendChild(label);
if (selected != null && String(selected[valuekey]) === val) {
@@ -711,25 +822,15 @@ export class Dropdown {
return scrolled;
}
_triggerselect(checkbox, item) {
let list;
/**
* @param {DropdownItem[]} [source]
* @returns {DropdownItem[]}
*/
_getSelectedList(source) {
const valuekey = this._var.options.valueKey;
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 source = this.source;
if (checkbox.getAttribute('isall') === '1') {
const allchecked = this._var.allChecked = checkbox.checked;
const boxes = this._var.container.querySelectorAll('input.dataitem');
boxes.forEach(box => box.checked = allchecked);
source.forEach(it => it.__checked = allchecked ? 1 : 0);
list = [];
} else {
const all = this._var.container.querySelector('input[isall="1"]');
const val = checkbox.dataset.value;
const getSelectedList = () => {
const list = [];
source ??= this.source;
source.filter(it => it.__p == null).forEach(it => {
const key = String(getValue(it, valuekey, textkey));
if (it.__checked === 1) {
@@ -742,7 +843,30 @@ export class Dropdown {
}
});
return list;
};
}
/**
*
* @param {HTMLInputElement} checkbox
* @param {DropdownItem} item
*/
_triggerselect(checkbox, item) {
let list;
const valuekey = this._var.options.valueKey;
const textkey = this._var.options.textKey;
const childkey = this._var.options.childKey;
const source = this.source;
if (checkbox.getAttribute('isall') === '1') {
const allchecked = this._var.allChecked = checkbox.checked;
/** @type {NodeListOf<HTMLInputElement>} */
const boxes = this._var.container.querySelectorAll('input.dataitem');
boxes.forEach(box => box.checked = allchecked);
source.forEach(it => it.__checked = allchecked ? 1 : 0);
list = [];
} else {
/** @type {HTMLInputElement | null} */
const all = this._var.container.querySelector('input[isall="1"]');
const val = checkbox.dataset.value;
if (checkbox.checked) {
item.__checked = 1;
if (item.__p != null) {
@@ -766,7 +890,7 @@ export class Dropdown {
}
list = [];
} else {
list = getSelectedList();
list = this._getSelectedList();
}
} else {
if (item[childkey]?.length > 0) {
@@ -793,10 +917,11 @@ export class Dropdown {
all.checked = false;
}
}
list = getSelectedList();
list = this._getSelectedList();
}
}
// refresh selection
/** @type {NodeListOf<HTMLInputElement>} */
const checkboxes = this._var.container.querySelectorAll('input.dataitem');
checkboxes.forEach(c => {
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) {
this._var.label.innerText = r('allItem', '( All )');
} else {
selectItems(this._var.label, list, template, htmlkey, textkey);
selectItems.call(this, list);
}
this._var.selectedList = list;
if (typeof this.onSelectedList === 'function') {
if (!silence && typeof this.onSelectedList === 'function') {
this.onSelectedList(list);
}
}
/**
*
* @param {HTMLElement} dom
* @param {(this: Dropdown, item: DropdownItem) => void} [trigger]
* @returns
*/
static resolve(dom = document.body, trigger) {
const selects = dom.querySelectorAll('select');
for (let sel of selects) {
const source = [...sel.children].map(it => {
return { value: it.value, text: it.innerText }
});
const source = [...sel.children].map(
/**
* @param {HTMLOptionElement} it
* @returns {DropdownItem}
*/
it => ({ value: it.value, text: it.innerText }));
const drop = new Dropdown({
selected: sel.value,
disabled: sel.disabled,
+16 -4
View File
@@ -1,16 +1,28 @@
/**
* @param {HTMLElement} element
* @param {RegExp} regex
* @returns {HTMLElement}
*/
export function validation(element, regex) {
if (element instanceof HTMLElement && regex instanceof RegExp) {
element.addEventListener('change', e => {
if (regex.test(e.target.value)) {
e.target.classList.remove('validation-error');
const target = e.target;
if (target instanceof HTMLElement) {
if (regex.test(/** @type {HTMLInputElement} */(target).value)) {
target.classList.remove('validation-error');
} else {
e.target.classList.add('validation-error');
target.classList.add('validation-error');
}
}
})
}
return element;
}
/**
* @param {{[key: string]: string}} style
* @returns {string}
*/
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('; ');
}
+41 -3
View File
@@ -1,13 +1,22 @@
import { global } from "../utility";
const svgns = 'http://www.w3.org/2000/svg';
/** @type {Object.<string, string>} */
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
};
/**
* @private
* @param {string} type
* @param {string} id
* @returns {SVGUseElement}
*/
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 ||
(typeof _network !== 'undefined' ? _network.root :
(typeof _net !== 'undefined' ? _net.root : ''));
(typeof global._network !== 'undefined' ? global._network.root :
(typeof global._net !== 'undefined' ? global._net.root : ''));
const ver = c.resver == null ? '' : `?${c.resver}`;
const use = document.createElementNS(svgns, 'use');
if (id?.length === 1 && id.charCodeAt(0) > 0xf000) {
@@ -17,6 +26,13 @@ function createUse(type, id) {
return use;
}
/**
* @template {typeof SVGElement} K
* @param {K} svg
* @param {string} type
* @param {string} id
* @returns {K}
*/
export function changeIcon(svg, type, id) {
if (svg instanceof SVGElement) {
svg.replaceChildren(createUse(type, id));
@@ -24,10 +40,23 @@ export function changeIcon(svg, type, id) {
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) {
const svg = document.createElementNS(svgns, 'svg');
svg.classList.add('ui-icon');
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') {
style(svg);
} else if (style != null) {
@@ -41,15 +70,24 @@ export function createIcon(type, id, style, action) {
return svg;
}
/**
* @param {HTMLElement} container
* @returns {HTMLElement}
*/
export function resolveIcon(container) {
const svgs = container.querySelectorAll('svg[data-id]');
for (let icon of svgs) {
if (!(icon instanceof SVGElement)) {
continue;
}
icon.classList.add('ui-icon');
const type = icon.dataset.type;
const id = icon.dataset.id;
if (type != null && id != null) {
icon.replaceChildren(createUse(type, id));
icon.removeAttribute('data-type');
icon.removeAttribute('data-id');
}
}
return container;
}
+68 -14
View File
@@ -3,6 +3,10 @@ import { createElement } from "../functions";
import { createIcon } from "./icon";
import { get } from "../utility/request";
/**
* @param {string} url
* @returns {HTMLAnchorElement}
*/
export function createPicture(url) {
return createElement('a', a => {
a.className = 'ui-media-picture';
@@ -15,18 +19,30 @@ export function createPicture(url) {
);
}
/**
* @private
* @param {Blob} blob
* @returns {Promise<Uint8Array<ArrayBuffer>>}
*/
function readBlob(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = e => {
if (e.target?.result instanceof ArrayBuffer) {
const data = new Uint8Array(e.target.result);
resolve(data);
}
};
reader.onerror = reject;
reader.readAsArrayBuffer(blob);
});
}
/**
*
* @param {Uint8Array<ArrayBuffer>} array
* @returns
*/
function playAmrArray(array) {
return new Promise((resolve, reject) => {
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) {
return new Promise(resolve => {
const ctx = new AudioContext();
@@ -61,6 +83,11 @@ function playPcm(samples, ended) {
});
}
/**
* @private
* @param {number} time
* @returns {string}
*/
function getTimeLabel(time) {
// time = Math.round(time);
// 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');
}
/**
* @param {string} mime
* @param {string} url
* @returns {HTMLAudioElement | HTMLDivElement}
*/
export function createAudio(mime, url) {
if ((mime === 'audio/amr' || mime === '.amr') && typeof AMR !== 'undefined') {
const timestamp = createElement('span', 'ui-media-timestamp');
timestamp.textContent = '0:00 / 0:00';
/** @type {AudioContext | null} */
let context;
/** @type {number} */
let timer;
return createElement('div', 'ui-media-audio',
createElement('button', button => {
@@ -132,6 +166,10 @@ export function createAudio(mime, url) {
});
}
/**
* @param {string} url
* @returns {HTMLVideoElement}
*/
export function createVideo(url) {
return createElement('video', 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') {
return createElement('div', `ui-media-file ${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 {any} [options] - 播放参数
* @param {boolean} options.[autoPlay] - 是否自动播放
* @param {boolean} options.[autoFullScreen] - 是否自动全屏
* @param {boolean} options.[autoLoop] - 是否循环播放
* @param {Function} options.[onLoaded] - 视频加载完成回调
* @param {Function} [callback] - 视频元素处理回调函数
* @param {string[]} urls 视频 url 数组
* @param {VideoPlayOptions} [options] 播放参数
* @param {(wrapper: HTMLDivElement) => void} [callback] 视频元素处理回调函数
* @returns {HTMLDivElement} 返回联动视频元素
*/
export function createVideoList(urls, options, callback) {
@@ -169,10 +216,13 @@ export function createVideoList(urls, options, callback) {
const length = urls.length;
const container = createElement('div', 'ui-media-video-container');
let seekBufferBar;
/** @type {HTMLDivElement} */
let seekProgressBar;
let playIcon;
let timeLabel;
/** @type {HTMLDivElement} */
let volumeProgressBar;
/** @type {HTMLDivElement} */
let volumeIcon;
const videos = Array(length);
@@ -180,10 +230,14 @@ export function createVideoList(urls, options, callback) {
let prepared = 0;
let ended = 0;
/** @type {boolean} */
let playing;
let duration = -1;
/** @type {string} */
let durationLabel;
/** @type {number} */
let seekBarWidth;
/** @type {boolean} */
let mousing;
const controller = createElement('div', 'ui-video-control active',
createElement('div', seek => {
@@ -369,7 +423,7 @@ export function createVideoList(urls, options, callback) {
video.addEventListener('progress', () => {
const buffered = video.buffered;
for (let i = 0; i < buffered.length; ++i) {
let buffer = seekBufferBar.children[i];
let buffer = /** @type {HTMLElement} */ (seekBufferBar.children[i]);
if (buffer == null) {
seekBufferBar.append(buffer = createElement('div', 'ui-video-buffer'));
}
@@ -383,9 +437,9 @@ export function createVideoList(urls, options, callback) {
}
});
video.addEventListener('canplaythrough', () => {
const w = video.parentElement.querySelector('.ui-video-waiting');
if (w != null) {
w.style.opacity = 0;
const w = video.parentElement?.querySelector('.ui-video-waiting');
if (w instanceof HTMLElement) {
w.style.opacity = '0';
}
if (waiting[i]) {
waiting[i] = false;
@@ -406,9 +460,9 @@ export function createVideoList(urls, options, callback) {
});
video.addEventListener('waiting', () => {
waiting[i] = true;
const w = video.parentElement.querySelector('.ui-video-waiting');
if (w != null) {
w.style.opacity = 1;
const w = video.parentElement?.querySelector('.ui-video-waiting');
if (w instanceof HTMLElement) {
w.style.opacity = '1';
}
videos.forEach(v => v.pause());
});
+105 -59
View File
@@ -6,6 +6,9 @@ import { createElement } from "../functions";
import { createIcon, changeIcon } from "./icon";
import { requestAnimationFrame } from "../ui";
/** @typedef {import('../types').PopupOptions} PopupOptions */
/** @typedef {import('../types').PopupRectParam} PopupRectParam */
const ResizeMods = {
right: 1,
bottom: 2,
@@ -30,58 +33,87 @@ const IconStyle = 'fa-light';
// [ResizeMods.topLeft]: 'nwse-resize'
// }
/**
* @private
* @param {string} px
* @returns {number | undefined}
*/
function trimPx(px) {
if (typeof px !== 'string') {
return px;
}
if (px.endsWith('px')) {
const size = Number(px.substring(0, px.length - 2));
return isNaN(size) ? px : size;
if (!isNaN(size)) {
return size;
}
}
return px;
}
/** @type {import('../types').Popup} */
export class Popup {
_var = {};
// _var.mask;
// _var.option;
// _var.bounds;
// _var.cursor;
_var = {
/** @type {HTMLElement | undefined} */
mask: undefined,
/** @type {PopupOptions | undefined} */
option: undefined,
/** @type {PopupRectParam | undefined} */
bounds: undefined,
cursor: undefined
};
constructor(opts = {}) {
/**
* @param {PopupOptions} [opts]
*/
constructor(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) {
const element = this._var.mask?.querySelector('.ui-popup-container .ui-popup-header .ui-popup-header-title');
if (element != null) {
if (element instanceof HTMLElement) {
if (typeof title === 'string') {
element.innerText = title;
} else {
element.replaceChildren(title);
}
}
if (this._var.option != null) {
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) {
let loading = this._var.mask?.querySelector('.ui-popup-body>.ui-popup-loading');
let loading = this._getLoadingPanel();
if (loading == null) {
return;
}
if (flag === false) {
loading.style.visibility = 'hidden';
loading.style.opacity = 0;
loading.style.opacity = '0';
} else {
loading.style.visibility = 'visible';
loading.style.opacity = 1;
loading.style.opacity = '1';
}
}
/** @returns {PopupRectParam | undefined} */
get rect() {
const container = this.container;
if (container == null) {
return null;
return;
}
const style = global.getComputedStyle(container);
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)
};
}
/**
* @param {PopupRectParam} r
*/
set rect(r) {
const container = this.container;
if (container == null) {
return;
}
const css = [];
if (!isNaN(r.left)) {
if (r.left != null && !isNaN(r.left)) {
css.push(`left: ${r.left}px`);
}
if (!isNaN(r.top)) {
if (r.top != null && !isNaN(r.top)) {
css.push(`top: ${r.top}px`);
}
const collapse = container.querySelector('.ui-popup-header-icons>.icon-expand');
@@ -115,14 +150,14 @@ export class Popup {
changeIcon(collapse, IconStyle, 'expand-alt');
}
} else {
if (!isNaN(r.width) && r.width > 0) {
if (r.width != null && !isNaN(r.width) && r.width > 0) {
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`);
}
container.classList.remove('ui-popup-collapse');
this._var.bounds = null;
delete this._var.bounds;
if (collapse != null) {
changeIcon(collapse, IconStyle, 'compress-alt');
}
@@ -136,24 +171,28 @@ export class Popup {
const option = this._var.option;
const mask = this._var.mask;
const doClose = () => {
if (option.persistent) {
if (option?.persistent) {
if (mask != null) {
mask.style.display = 'none';
}
} else {
mask.remove();
this._var.mask = null;
mask?.remove();
delete this._var.mask;
}
}
if (animation) {
if (mask != null) {
mask.classList.add('ui-popup-active');
mask.style.opacity = 0;
mask.style.opacity = '0';
}
setTimeout(() => { doClose(); }, 120);
} else {
doClose();
}
if (typeof option.onMasking === 'function') {
if (typeof option?.onMasking === 'function') {
option.onMasking.call(this, false);
}
if (typeof option.resolve === 'function') {
if (typeof option?.resolve === 'function') {
option.resolve.call(this, {
result,
popup: this
@@ -168,18 +207,18 @@ export class Popup {
create() {
const mask = createElement('div', 'ui-popup-mask ui-popup-active');
const option = this._var.option;
if (option.mask === false) {
if (option?.mask === false) {
mask.classList.add('ui-popup-transparent');
} else if (typeof option.onMasking === 'function') {
} else if (typeof option?.onMasking === 'function') {
option.onMasking.call(this, true);
}
if (!isNaN(option.zIndex)) {
if (option?.zIndex != null && !isNaN(option.zIndex)) {
mask.style.zIndex = String(option.zIndex);
}
const container = createElement('div', 'ui-popup-container');
if (option.changeZIndex === true) {
if (option?.changeZIndex === true) {
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;
masks.forEach(m => {
let index;
@@ -195,7 +234,7 @@ export class Popup {
}
});
mask.dataset.zindex = mask.style.zIndex;
mask.style.zIndex = max + 1;
mask.style.zIndex = `${max + 1}`;
});
} else {
@@ -205,17 +244,17 @@ export class Popup {
tabIndex = 0;
}
container.tabIndex = tabIndex + 1;
let content = option.content;
let content = option?.content;
if (!(content instanceof HTMLElement)) {
content = createElement('div', d => d.innerText = content);
}
container.append(
createElement('div', header => {
header.className = 'ui-popup-header';
let title = option.title;
let title = option?.title;
if (!(title instanceof HTMLElement)) {
title = createElement('div', t => {
if (option.movable === false) {
if (option?.movable === false) {
t.className = 'ui-popup-header-title no-move';
} else {
t.className = 'ui-popup-header-title';
@@ -224,7 +263,7 @@ export class Popup {
});
}
header.appendChild(title);
if (option.movable !== false) {
if (option?.movable !== false) {
const move = header; // title.querySelector('.ui-popup-move') ?? title;
move.addEventListener('mousedown', e => {
if (['svg', 'use'].includes(e.target?.tagName)) {
@@ -233,9 +272,10 @@ export class Popup {
if (e.buttons !== 1) {
return;
}
const parent = option.mask === false ? mask.parentElement : mask;
const parent = option?.mask === false ? mask.parentElement : mask;
const x = e.clientX - container.offsetLeft;
const y = e.clientY - container.offsetTop;
/** @type {boolean} */
let moved;
const move = e => {
if (e.buttons === 1) {
@@ -250,7 +290,7 @@ export class Popup {
const up = () => {
parent.removeEventListener('mousemove', move, { passive: false });
parent.removeEventListener('mouseup', up);
if (moved === true && typeof option.onMoveEnded === 'function') {
if (moved === true && typeof option?.onMoveEnded === 'function') {
option.onMoveEnded.call(this);
}
moved = false;
@@ -260,7 +300,7 @@ export class Popup {
}
const icons = createElement('div', icons => {
icons.className = 'ui-popup-header-icons';
if (option.collapsable === true) {
if (option?.collapsable === true) {
const collapse = createIcon(IconStyle, 'compress-alt');
collapse.tabIndex = tabIndex + 2;
collapse.classList.add('icon-expand');
@@ -274,7 +314,7 @@ export class Popup {
const bounds = this._var.bounds;
if (bounds != null) {
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');
changeIcon(collapse, IconStyle, 'compress-alt');
@@ -285,13 +325,13 @@ export class Popup {
container.classList.add('ui-popup-collapse');
changeIcon(collapse, IconStyle, 'expand-alt');
}
if (typeof option.onResizeEnded === 'function') {
if (typeof option?.onResizeEnded === 'function') {
option.onResizeEnded.call(this);
}
});
icons.appendChild(collapse);
}
if (option.closable !== false) {
if (option?.closable !== false) {
const cancel = createIcon(IconStyle, 'times');
cancel.tabIndex = tabIndex + 3;
cancel.addEventListener('keypress', e => {
@@ -309,7 +349,7 @@ export class Popup {
createElement('div', null, createIcon(IconStyle, 'spinner-third'))
))
);
if (Array.isArray(option.buttons) && option.buttons.length > 0) {
if (Array.isArray(option?.buttons) && option.buttons.length > 0) {
tabIndex = Math.max.apply(null, [...container.querySelectorAll('[tabindex]')].map(e => e.tabIndex ?? 0));
container.appendChild(
createElement('div', 'ui-popup-footer', ...option.buttons.map((b, i) => {
@@ -320,7 +360,7 @@ export class Popup {
if (b.isPrimary) {
button.classList.add('primary');
}
if (b.tabIndex > 0) {
if (b.tabIndex != null && b.tabIndex > 0) {
button.tabIndex = b.tabIndex;
} else {
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');
}
// resizable
if (option.resizable === true) {
if (option?.resizable === true) {
container.append(
createElement('layer', layer => {
layer.className = 'ui-popup-border ui-popup-border-right';
@@ -430,18 +470,20 @@ export class Popup {
return Promise.resolve(mask);
}
}
if (this._var.option.mask === false) {
if (this._var.option?.mask === false) {
// calculator position
const container = this.container;
if (container != null) {
container.style.left = String((parent.offsetWidth - container.offsetWidth) / 2) + 'px';
container.style.top = String((parent.offsetHeight - container.offsetHeight) / 2) + 'px';
container.style.top = String((parent.offsetHeight - container.offsetHeight) / 2) + 'px'
};
}
return new Promise(resolve => {
mask.style.display = '';
requestAnimationFrame(() => {
mask.classList.remove('ui-popup-active');
mask.style.opacity = 1;
this.container.focus();
mask.style.opacity = '1';
this.container?.focus();
setTimeout(() => resolve(mask), 120);
});
});
@@ -452,8 +494,11 @@ export class Popup {
return;
}
const container = this.container;
if (container == null) {
return;
}
const option = this._var.option;
if (typeof option.onResizeStarted === 'function') {
if (typeof option?.onResizeStarted === 'function') {
option.onResizeStarted.call(this);
}
const mask = this._var.mask;
@@ -467,13 +512,14 @@ export class Popup {
left: container.offsetLeft,
top: container.offsetTop
};
const minWidth = option.minWidth ?? 200;
const minHeight = option.minHeight ?? 200;
const minWidth = option?.minWidth ?? 200;
const minHeight = option?.minHeight ?? 200;
/** @type {boolean} */
let resized;
const parent = option.mask === false ? mask.parentElement : mask;
const parent = option?.mask === false ? mask.parentElement : mask;
const move = e => {
if (e.buttons !== 1) {
parent.dispatchEvent(new MouseEvent('mouseup'));
parent?.dispatchEvent(new MouseEvent('mouseup'));
return;
}
const offsetX = e.clientX - originalX;
@@ -512,24 +558,24 @@ export class Popup {
y += offsetY;
}
}
if (typeof option.onResizing === 'function') {
if (typeof option?.onResizing === 'function') {
option.onResizing.call(this, x, y, width, height);
} else {
container.style.cssText += `left: ${x}px; top: ${y}px; width: ${width}px; height: ${height}px`;
}
resized = true;
}
parent.addEventListener('mousemove', move, { passive: false });
parent?.addEventListener('mousemove', move, { passive: false });
const up = () => {
parent.removeEventListener('mousemove', move, { passive: false });
parent.removeEventListener('mouseup', up);
// mask.style.cursor = this._var.cursor;
if (resized === true && typeof option.onResizeEnded === 'function') {
if (resized === true && typeof option?.onResizeEnded === 'function') {
option.onResizeEnded.call(this);
}
resized = false;
};
parent.addEventListener('mouseup', up);
parent?.addEventListener('mouseup', up);
}
}
+10 -5
View File
@@ -3,14 +3,14 @@ import "./css/tab.scss";
/**
* Tab 页创建参数类
* @typedef TabOption
* @property {HTMLElement} container - 父容器
* @property {HTMLElement} container 父容器
*/
import { createElement } from "../functions";
/**
* 创建 Tab 页
* @param {TabOption | HTMLElement} options - 创建选项
* @param {TabOption | HTMLElement} options 创建选项
*/
export function createTab(options) {
if (options instanceof HTMLElement) {
@@ -29,13 +29,18 @@ export function createTab(options) {
createElement('div', header => {
header.className = 'ui-tab-header';
header.addEventListener('click', e => {
const title = e.target;
if (title.classList.contains('ui-tab-title')) {
const title = /** @type {HTMLElement} */ (e.target);
if (title != null && title.classList.contains('ui-tab-title')) {
// title
header.querySelectorAll('.ui-tab-title').forEach(t => t === title ? t.classList.add('selected') : t.classList.remove('selected'));
// pages
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;
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;
if (isParent) {
const tipid = container.dataset.tipId;
@@ -43,11 +52,13 @@ export function setTooltip(container, content, flag = false, parent = null, maxL
container.appendChild(wrapper);
}
/** @type {number} */
let tid;
container.addEventListener('mouseenter', () => {
tid && clearTimeout(tid);
/** @type {HTMLElement | null} */
let c = container;
while (c?.offsetWidth == null) {
while (c != null && c.offsetWidth == null) {
c = c.parentElement;
}
if (c == null) {
@@ -56,17 +67,16 @@ export function setTooltip(container, content, flag = false, parent = null, maxL
if (!flag || c.scrollWidth > c.offsetWidth) {
wrapper.style.cssText += 'left: -9999px; top: -9999px; display: block';
tid = setTimeout(() => {
/** @type {HTMLElement | null} */
let p;
let left;
let top;
left = c.offsetLeft;
top = c.offsetTop;
let left = c.offsetLeft;
let top = c.offsetTop;
if (isParent) {
p = c.offsetParent;
p = /** @type {HTMLElement} */ (c.offsetParent);
while (p != null && p !== parent) {
left += p.offsetLeft;
top += p.offsetTop;
p = p.offsetParent;
p = /** @type {HTMLElement} */ (p.offsetParent);
}
}
p = c.parentElement;
@@ -92,7 +102,7 @@ export function setTooltip(container, content, flag = false, parent = null, maxL
// check overflow
let t = c.offsetTop;
let l = c.offsetLeft;
p = c.offsetParent;
p = /** @type {HTMLElement} */ (c.offsetParent);
if (p == null) {
return;
}
@@ -105,7 +115,7 @@ export function setTooltip(container, content, flag = false, parent = null, maxL
}
t += p.offsetTop;
l += p.offsetLeft;
const parent = p.offsetParent;
const parent = /** @type {HTMLElement} */ (p.offsetParent);
while (p != null) {
const w = p.clientWidth;
if (w < lastWidth) {
@@ -171,16 +181,27 @@ export function setTooltip(container, content, flag = false, parent = null, maxL
tid && clearTimeout(tid);
tid = setTimeout(() => {
wrapper.style.visibility = 'hidden';
wrapper.style.opacity = 0;
wrapper.style.opacity = '0';
tid = setTimeout(() => wrapper.style.display = 'none', 120);
}, 300);
});
return container;
}
/**
* @param {HTMLElement} [container]
* @returns {HTMLElement}
* @example
* ```
* <span title="tooltip text"></span>
* ```
*/
export function resolveTooltip(container = document.body) {
const tips = container.querySelectorAll('[title]');
for (let tip of tips) {
if (!(tip instanceof HTMLElement)) {
continue;
}
const title = tip.getAttribute('title');
if (title != null) {
tip.removeAttribute('title');
+68 -12
View File
@@ -1,58 +1,108 @@
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 { 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) {
return !isNaN(n) && n > 0;
const l = typeof n !== 'number' ? Number(n) : n;
return !isNaN(l) && l > 0;
}
/**
* @returns {boolean}
*/
function isMobile() {
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) {
return;
}
const ctx = typeof context === 'undefined' ?
/** @type {TContext} */ (/** @type {unknown} */ (g)) :
context;
method.tiid && clearTimeout(method.tiid);
const current = new Date();
const current = Date.now();
if (method.tdate == null || current - method.tdate > delay) {
method.apply(context, args);
method.apply(ctx, args);
method.tdate = current;
} 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) {
return;
}
const ctx = typeof context === 'undefined' ?
/** @type {TContext} */ (/** @type {unknown} */ (g)) :
context;
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) {
return (v > 0 ? Math.floor : Math.ceil)(v);
}
/**
* @param {string} text
* @returns {boolean}
*/
function isEmail(text) {
return /^\w[-\w.+]*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(text);
}
/**
* @param {string} text
* @returns {boolean}
*/
function isPhone(text) {
if (/^[1-9]\d{9,}$/.test(text)) {
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 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) {
if (password == null || typeof password !== 'string') {
return 0;
@@ -68,6 +118,11 @@ function getPasswordStrength(password) {
return secure;
}
/**
* @param {string} [password]
* @param {number} [min=3]
* @returns {boolean}
*/
function verifyPassword(password, min) {
min ??= 3;
const secure = getPasswordStrength(password);
@@ -80,7 +135,9 @@ export {
setCookie,
deleteCookie,
// lgres
domLoad,
init,
isTag,
r,
lang,
// request
@@ -106,6 +163,5 @@ export {
isEmail,
isPhone,
getPasswordStrength,
verifyPassword,
domLoad
verifyPassword
}
+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) {
if (name == null) {
return;
@@ -6,7 +13,7 @@ export function setCookie(name, value, expireDays, host, encode) {
if (expireDays != null) {
const d = new Date();
d.setTime(d.getTime() + (expireDays * 24 * 60 * 60 * 1000));
extra += `; expires=${d.toGMTString()}`;
extra += `; expires=${d.toUTCString()}`;
}
if (/^(https|wss):$/.test(location.protocol)) {
extra += '; secure';
@@ -17,6 +24,10 @@ export function setCookie(name, value, expireDays, host, encode) {
document.cookie = `${name}=${value}${extra}`;
}
/**
* @param {string} [name]
* @returns {string | null}
*/
export function getCookie(name) {
if (name == null) {
return null;
@@ -32,6 +43,9 @@ export function getCookie(name) {
return null;
}
/**
* @param {string} name
*/
export function deleteCookie(name) {
setCookie(name, '', -1);
}
+94 -15
View File
@@ -2,14 +2,19 @@ import { getCookie } from "./cookie";
import { get } from "./request";
import { nullOrEmpty } from "./strings";
/** @typedef {import('../types').LanguageResource} LanguageResource */
const g = typeof window !== 'undefined' ? window : self;
/** @type {LanguageResource} */
let cache;
function getCurrentLgId() {
let lgid;
if (typeof consts !== 'undefined') {
lgid = getCookie(consts.cookie?.lang);
if (typeof g.consts !== 'undefined') {
lgid = getCookie(g.consts.cookie?.lang);
if (nullOrEmpty(lgid)) {
lgid = consts.user?.language;
lgid = g.consts.user?.language;
}
}
if (nullOrEmpty(lgid)) {
@@ -42,13 +47,23 @@ function getCurrentLgId() {
return 'en';
}
/**
* @private
* @param {"en" | "en_au" | "en_ca" | "fr_ca" | "zh_cn" | "es" | "fr" | "pt"} lgid
* @returns {string}
*/
function getStorageKey(lgid) {
if (typeof consts !== 'undefined') {
return (consts.prefix || '') + `res_${lgid}`;
if (typeof g.consts !== 'undefined') {
return (g.consts.prefix || '') + `res_${lgid}`;
}
return `res_${lgid}`;
}
/**
* @private
* @param {string} [template]
* @returns {Promise<LanguageResource>}
*/
async function doRefreshLgres(template = '') {
const lgid = getCurrentLgId();
const url = template.length > 0 ? template.replace('{lgid}', lgid) : `language/${lgid}`;
@@ -58,21 +73,27 @@ async function doRefreshLgres(template = '') {
return dict;
}
/**
*
* @param {string} [template]
* @param {LanguageResource | null} [lgres]
* @returns {Promise<LanguageResource>}
*/
async function refreshLgres(template, lgres) {
if (lgres == null || typeof consts === 'undefined') {
if (lgres == null || typeof g.consts === 'undefined') {
lgres = await doRefreshLgres(template);
}
const ver = Number(consts.resver);
const ver = Number(g.consts?.resver);
const currentVer = Number(lgres.ver);
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);
}
Object.defineProperty(lgres, 'r', {
writable: false,
configurable: false,
enumerable: false,
value: function (key, defaultValue) {
value: function (/** @type {string} */ key, /** @type {string | undefined} */ defaultValue) {
return getLanguage(this, key, defaultValue);
}
});
@@ -80,15 +101,47 @@ async function refreshLgres(template, lgres) {
return lgres;
}
/**
* @private
* @param {LanguageResource} lgres
* @param {string} [key]
* @param {string | null} [defaultValue]
* @returns {string}
*/
function getLanguage(lgres, key, defaultValue) {
if (key == null) {
return '';
}
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) {
for (let text of dom.querySelectorAll('[data-lgid]')) {
if (!(text instanceof HTMLElement)) {
continue;
}
const key = text.dataset.lgid;
if (text.tagName === 'INPUT') {
if (isTag(text, 'input')) {
text.value = getLanguage(result, key, text.value);
} else {
text.innerText = getLanguage(result, key, text.innerText);
@@ -97,12 +150,18 @@ function applyLanguage(dom, result) {
text.dataset.lgid = '';
}
for (let title of dom.querySelectorAll('[data-title-lgid]')) {
if (!(title instanceof HTMLElement)) {
continue;
}
const key = title.dataset.titleLgid;
title.setAttribute('title', getLanguage(result, key, title.getAttribute('title')));
// delete title.dataset.titleLgid;
title.dataset.titleLgid = '';
}
for (let holder of dom.querySelectorAll('[data-placeholder-lgid]')) {
if (!(holder instanceof HTMLElement)) {
continue;
}
const key = holder.dataset.placeholderLgid;
holder.setAttribute('placeholder', getLanguage(result, key, holder.getAttribute('placeholder')));
// delete holder.dataset.placeholderLgid;
@@ -110,9 +169,13 @@ function applyLanguage(dom, result) {
}
}
/**
* @returns {Promise<void>}
*/
export function domLoad() {
if (document.readyState === 'loading') {
return new Promise((resolve, reject) => {
/** @type {number | undefined} */
let tid = setTimeout(() => reject('timeout'), 30000);
document.addEventListener('DOMContentLoaded', () => {
clearTimeout(tid);
@@ -124,13 +187,24 @@ export function domLoad() {
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 = {}) {
const lgid = getCurrentLgId();
let lgres = localStorage.getItem(getStorageKey(lgid));
const json = localStorage.getItem(getStorageKey(lgid));
let result;
if (lgres != null) {
if (json != null) {
try {
lgres = JSON.parse(lgres);
const lgres = JSON.parse(json);
result = await refreshLgres(options.template, lgres);
} catch (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) {
if (cache != null) {
return getLanguage(cache, key, defaultValue);
}
return defaultValue;
return defaultValue ?? '';
}
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) {
if (/^(https?|wss?|ftp):/.test(url)) {
return url;
}
if (typeof consts === 'undefined') {
if (typeof g.consts === 'undefined') {
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), {
method: options.method || 'GET',
method: options?.method || 'GET',
headers: {
...options.customHeaders,
'Accept': options.accept ?? 'application/json'
...options?.customHeaders,
'Accept': options?.accept ?? 'application/json'
},
mode: options.mode,
signal: options.signal,
mode: options?.mode,
signal: options?.signal,
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) {
// contentType = 'multipart/form-data';
} else {
@@ -30,21 +65,19 @@ export function post(url, data, options = {}) {
data = JSON.stringify(data);
}
// contentType = 'application/json';
if (options.customHeaders == null) {
options.customHeaders = {};
}
if (options.customHeaders['Content-Type'] == null) {
options.customHeaders['Content-Type'] = 'application/json';
if (headers['Content-Type'] == null) {
headers['Content-Type'] = 'application/json';
}
}
/** @type {RequestInit} */
const opts = {
method: options.method || 'POST',
headers: options.customHeaders,
method: options?.method || 'POST',
headers,
body: data,
signal: options.signal,
signal: options?.signal,
cache: 'no-cache'
};
if (options.diagnostic) {
if (options?.diagnostic) {
const started = new Date().getTime();
return new Promise((resolve, reject) => {
fetch(combineUrl(url), opts).then(response => {
@@ -58,7 +91,13 @@ export function post(url, data, options = {}) {
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) => {
const request = new XMLHttpRequest();
request.onreadystatechange = function () {
@@ -73,7 +112,7 @@ export function upload(url, data, options = {}) {
if (typeof options.progress === 'function') {
request.upload.addEventListener('progress', function (ev) {
if (ev.lengthComputable) {
options.progress.call(this, ev);
options.progress?.call(this, ev);
}
}, false);
}
+41 -7
View File
@@ -1,7 +1,17 @@
/**
* @param {string | null} [s]
* @returns {s is null | undefined | ""}
*/
export function nullOrEmpty(s) {
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) {
if (nullOrEmpty(s) || key == null) {
return false;
@@ -15,6 +25,11 @@ export function contains(s, key, ignoreCase) {
return s.includes(key);
}
/**
* @param {string} s
* @param {string} suffix
* @returns {boolean}
*/
export function endsWith(s, suffix) {
if (nullOrEmpty(s) || nullOrEmpty(suffix)) {
return false;
@@ -22,6 +37,12 @@ export function endsWith(s, suffix) {
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) {
if (nullOrEmpty(s) || isNaN(num) || num <= s.length) {
return s;
@@ -29,6 +50,10 @@ export function padStart(s, num, char) {
return (char ?? ' ').repeat(num - s.length);
}
/**
* @param {string} msg
* @returns {string}
*/
export function formatUrl(msg) {
//const urlReg = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ig;
//const urlArrray = str.match(urlReg);
@@ -36,7 +61,7 @@ export function formatUrl(msg) {
const r = msg.match(p);
msg = escapeHtml(msg);
if (r?.length > 0) {
if (r != null && r.length > 0) {
const rs = [];
for (let t of r) {
t = t.replace(/["'\r\n ]/g, '');
@@ -45,13 +70,14 @@ export function formatUrl(msg) {
}
}
const win = typeof window !== 'undefined' ? window : self;
let path;
if (typeof consts !== 'undefined') {
path = consts.path;
} else if (typeof _network !== 'undefined') {
path = _network.root;
} else if (typeof _net !== 'undefined') {
path = _net.root;
if (typeof win.consts !== 'undefined') {
path = win.consts.path;
} else if (typeof win._network !== 'undefined') {
path = win._network.root;
} else if (typeof win._net !== 'undefined') {
path = win._net.root;
}
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>`);
@@ -61,6 +87,10 @@ export function formatUrl(msg) {
return msg;
}
/**
* @param {string} text
* @returns {string}
*/
export function escapeHtml(text) {
if (text == null) {
return '';
@@ -74,6 +104,10 @@ export function escapeHtml(text) {
.replaceAll(' ', '&nbsp;');
}
/**
* @param {string} text
* @returns {string}
*/
export function escapeEmoji(text) {
if (text == null) {
return '';
+19 -19
View File
@@ -1,20 +1,22 @@
{
"name": "ui-lib",
"private": true,
"version": "1.0.7",
"name": "@soft-qr/ui-lib",
"version": "1.0.9",
"publishConfig": {
"registry": "https://git.soft.qr/api/packages/soft-qr/npm/"
},
"author": "cl",
"type": "module",
"files": [
"dist"
],
"module": "./dist/ui.js",
"types": "./dist/ui.d.ts",
"exports": {
"ui": {
"import": "./dist/ui.es.js",
"require": "./dist/ui.min.js"
".": {
"types": "./dist/ui.d.ts",
"import": "./dist/ui.js"
},
"utility": {
"import": "./dist/utility.es.js",
"require": "./dist/utility.min.js"
}
"./style.css": "./dist/ui.min.css"
},
"browserslist": [
"last 1 versions",
@@ -23,19 +25,17 @@
"scripts": {
"dev": "vite",
"build": "node ./vite.build.js",
"doc": "typedoc",
"jsdoc": "jsdoc -c jsdoc.json",
"jsdoc-date": "jsdoc -c jsdoc-date.json"
},
"devDependencies": {
"@mxssfd/typedoc-theme": "^1.1.6",
"clean-jsdoc-theme": "^4.3.0",
"clean-jsdoc-theme": "^5.3.0",
"docdash": "^2.0.2",
"jsdoc": "^4.0.3",
"postcss-preset-env": "^9.6.0",
"sass": "^1.77.8",
"typedoc": "^0.26.5",
"vite": "^5.3.4",
"vite-plugin-externals": "^0.6.2"
"jsdoc": "^4.0.5",
"postcss-preset-env": "^11.6.2",
"sass": "^1.108.2",
"typescript": "^6.0.3",
"unplugin-dts": "^1.1.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": [
"./lib/functions*",
"./lib/ui/**/*"
],
"exclude": [
"./dist",
"node_modules"
"lib/functions.js",
"lib/ui.js",
"lib/ui",
"lib/utility.js",
"lib/utility"
]
}
-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
}
+72 -26
View File
@@ -1,9 +1,68 @@
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 { viteExternalsPlugin } from "vite-plugin-externals";
// empty out dir
rmSync(resolve('dist'), { recursive: true, force: true });
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,
css: {
postcss: {
@@ -12,33 +71,20 @@ const libraries = [
},
build: {
lib: {
entry: './lib/ui.js',
name: 'lib-ui',
formats: ['cjs', 'umd'],
fileName: (format, name) => format === 'cjs' ? `${name}-cjs.min.js` : `${name}.min.js`
entry: {
[name]: path
},
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',
name: `lib-${name}`,
cssFileName: `${name}.min`,
formats: ['umd'],
fileName: (_format, name) => `${name}.min.js`
fileName: (_format, name) => `${name}.js`
},
rolldownOptions,
sourcemap: true,
emptyOutDir: false
}
}
]
libraries.forEach(async b => await build(b))
},
plugins: [
dts()
]
});
}