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

+47 -15
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');
input.name = opts.name;
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) {
+79 -86
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: {
/**
* @type {boolean?}
* @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
}
el: undefined,
/**
* @type {DateOptions}
* @private
*/
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) {
this._var.el.disabled = flag === false;
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) {
this._var.el.min = 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) {
this._var.el.max = 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,38 +822,51 @@ export class Dropdown {
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) {
let list;
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;
/** @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;
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) {
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,
+17 -5
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');
} else {
e.target.classList.add('validation-error');
const target = e.target;
if (target instanceof HTMLElement) {
if (regex.test(/** @type {HTMLInputElement} */(target).value)) {
target.classList.remove('validation-error');
} else {
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('; ');
}
+44 -6
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;
icon.replaceChildren(createUse(type, id));
icon.removeAttribute('data-type');
icon.removeAttribute('data-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());
});
+110 -64
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) {
element.innerText = title;
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;
}
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) {
mask.style.display = 'none';
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) {
mask.classList.add('ui-popup-active');
mask.style.opacity = 0;
if (mask != null) {
mask.classList.add('ui-popup-active');
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;
container.style.left = String((parent.offsetWidth - container.offsetWidth) / 2) + 'px';
container.style.top = String((parent.offsetHeight - container.offsetHeight) / 2) + 'px';
if (container != null) {
container.style.left = String((parent.offsetWidth - container.offsetWidth) / 2) + 'px';
container.style.top = String((parent.offsetHeight - container.offsetHeight) / 2) + 'px'
};
}
return new Promise(resolve => {
mask.style.display = '';
requestAnimationFrame(() => {
mask.classList.remove('ui-popup-active');
mask.style.opacity = 1;
this.container.focus();
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');