diff --git a/.gitignore b/.gitignore index 089997b..432369e 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,4 @@ desktop.ini # User definition docs jsdoc +package-lock.json diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..ee1c1bd --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +@soft-qr:registry=https://git.soft.qr/api/packages/soft-qr/npm/ \ No newline at end of file diff --git a/lib/functions.js b/lib/functions.js index d52765e..1fc8475 100644 --- a/lib/functions.js +++ b/lib/functions.js @@ -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') { diff --git a/lib/global.d.ts b/lib/global.d.ts new file mode 100644 index 0000000..28985dc --- /dev/null +++ b/lib/global.d.ts @@ -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 }; + } +} \ No newline at end of file diff --git a/lib/types.ts b/lib/types.ts new file mode 100644 index 0000000..ab7c187 --- /dev/null +++ b/lib/types.ts @@ -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 | undefined; +}; + +export interface PopupButton { + className?: string; + tabIndex?: number; + key: string; + text: string; + isPrimary?: boolean; + trigger: (this: Popup) => boolean | Promise; +} + +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; +} diff --git a/lib/ui.js b/lib/ui.js index 8134c5f..662d019 100644 --- a/lib/ui.js +++ b/lib/ui.js @@ -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; } diff --git a/lib/ui/checkbox.js b/lib/ui/checkbox.js index e6123e8..7528d72 100644 --- a/lib/ui/checkbox.js +++ b/lib/ui/checkbox.js @@ -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) { diff --git a/lib/ui/date.js b/lib/ui/date.js index 5967faf..baa60da 100644 --- a/lib/ui/date.js +++ b/lib/ui/date.js @@ -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 创建一个 DateSelector 并插入到元素中 *
* @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 HTML * * @example 解析父容器 @@ -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'), diff --git a/lib/ui/dropdown.js b/lib/ui/dropdown.js index 80117d2..f87270d 100644 --- a/lib/ui/dropdown.js +++ b/lib/ui/dropdown.js @@ -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.} 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} */ 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} */ 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, diff --git a/lib/ui/extension.js b/lib/ui/extension.js index b53a75b..5445083 100644 --- a/lib/ui/extension.js +++ b/lib/ui/extension.js @@ -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('; '); } \ No newline at end of file diff --git a/lib/ui/icon.js b/lib/ui/icon.js index f68ccaa..7de34f2 100644 --- a/lib/ui/icon.js +++ b/lib/ui/icon.js @@ -1,13 +1,22 @@ +import { global } from "../utility"; + const svgns = 'http://www.w3.org/2000/svg'; +/** @type {Object.} */ 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", "\uf12c": "subscript", "\uf12d": "eraser", "\uf12e": "puzzle-piece", "\uf130": "microphone", "\uf131": "microphone-slash", "\uf132": "shield", "\uf133": "calendar", "\uf134": "fire-extinguisher", "\uf135": "rocket", "\uf137": "chevron-circle-left", "\uf138": "chevron-circle-right", "\uf139": "chevron-circle-up", "\uf13a": "chevron-circle-down", "\uf13d": "anchor", "\uf13e": "unlock-alt", "\uf140": "bullseye", "\uf141": "ellipsis-h", "\uf142": "ellipsis-v", "\uf143": "rss-square", "\uf144": "play-circle", "\uf145": "ticket", "\uf146": "minus-square", "\uf148": "level-up", "\uf149": "level-down", "\uf14a": "check-square", "\uf14b": "pen-square", "\uf14c": "external-link-square", "\uf14d": "share-square", "\uf14e": "compass", "\uf150": "caret-square-down", "\uf151": "caret-square-up", "\uf152": "caret-square-right", "\uf153": "euro-sign", "\uf154": "pound-sign", "\uf155": "dollar-sign", "\uf156": "rupee-sign", "\uf157": "yen-sign", "\uf158": "ruble-sign", "\uf159": "won-sign", "\uf15b": "file", "\uf15c": "file-alt", "\uf15d": "sort-alpha-down", "\uf15e": "sort-alpha-up", "\uf160": "sort-amount-down", "\uf161": "sort-amount-up", "\uf162": "sort-numeric-down", "\uf163": "sort-numeric-up", "\uf164": "thumbs-up", "\uf165": "thumbs-down", "\uf175": "long-arrow-down", "\uf176": "long-arrow-up", "\uf177": "long-arrow-left", "\uf178": "long-arrow-right", "\uf182": "female", "\uf183": "male", "\uf185": "sun", "\uf186": "moon", "\uf187": "archive", "\uf188": "bug", "\uf191": "caret-square-left", "\uf192": "dot-circle", "\uf193": "wheelchair", "\uf195": "lira-sign", "\uf197": "space-shuttle", "\uf199": "envelope-square", "\uf19c": "university", "\uf19d": "graduation-cap", "\uf1ab": "language", "\uf1ac": "fax", "\uf1ad": "building", "\uf1ae": "child", "\uf1b0": "paw", "\uf1b2": "cube", "\uf1b3": "cubes", "\uf1b8": "recycle", "\uf1b9": "car", "\uf1ba": "taxi", "\uf1bb": "tree", "\uf1c0": "database", "\uf1c1": "file-pdf", "\uf1c2": "file-word", "\uf1c3": "file-excel", "\uf1c4": "file-powerpoint", "\uf1c5": "file-image", "\uf1c6": "file-archive", "\uf1c7": "file-audio", "\uf1c8": "file-video", "\uf1c9": "file-code", "\uf1cd": "life-ring", "\uf1ce": "circle-notch", "\uf1d8": "paper-plane", "\uf1da": "history", "\uf1dc": "heading", "\uf1dd": "paragraph", "\uf1de": "sliders-h", "\uf1e0": "share-alt", "\uf1e1": "share-alt-square", "\uf1e2": "bomb", "\uf1e3": "futbol", "\uf1e4": "tty", "\uf1e5": "binoculars", "\uf1e6": "plug", "\uf1ea": "newspaper", "\uf1eb": "wifi", "\uf1ec": "calculator", "\uf1f6": "bell-slash", "\uf1f8": "trash", "\uf1f9": "copyright", "\uf1fa": "at", "\uf1fb": "eye-dropper", "\uf1fc": "paint-brush", "\uf1fd": "birthday-cake", "\uf1fe": "chart-area", "\uf200": "chart-pie", "\uf201": "chart-line", "\uf204": "toggle-off", "\uf205": "toggle-on", "\uf206": "bicycle", "\uf207": "bus", "\uf20a": "closed-captioning", "\uf20b": "shekel-sign", "\uf217": "cart-plus", "\uf218": "cart-arrow-down", "\uf219": "diamond", "\uf21a": "ship", "\uf21b": "user-secret", "\uf21c": "motorcycle", "\uf21d": "street-view", "\uf21e": "heartbeat", "\uf221": "venus", "\uf222": "mars", "\uf223": "mercury", "\uf224": "transgender", "\uf225": "transgender-alt", "\uf226": "venus-double", "\uf227": "mars-double", "\uf228": "venus-mars", "\uf229": "mars-stroke", "\uf22a": "mars-stroke-v", "\uf22b": "mars-stroke-h", "\uf22c": "neuter", "\uf22d": "genderless", "\uf233": "server", "\uf234": "user-plus", "\uf235": "user-times", "\uf236": "bed", "\uf238": "train", "\uf239": "subway", "\uf240": "battery-full", "\uf241": "battery-three-quarters", "\uf242": "battery-half", "\uf243": "battery-quarter", "\uf244": "battery-empty", "\uf245": "mouse-pointer", "\uf246": "i-cursor", "\uf247": "object-group", "\uf248": "object-ungroup", "\uf249": "sticky-note", "\uf24d": "clone", "\uf24e": "balance-scale", "\uf251": "hourglass-start", "\uf252": "hourglass-half", "\uf253": "hourglass-end", "\uf254": "hourglass", "\uf255": "hand-rock", "\uf256": "hand-paper", "\uf257": "hand-scissors", "\uf258": "hand-lizard", "\uf259": "hand-spock", "\uf25a": "hand-pointer", "\uf25b": "hand-peace", "\uf25c": "trademark", "\uf25d": "registered", "\uf26c": "tv", "\uf271": "calendar-plus", "\uf272": "calendar-minus", "\uf273": "calendar-times", "\uf274": "calendar-check", "\uf275": "industry", "\uf276": "map-pin", "\uf277": "map-signs", "\uf279": "map", "\uf27a": "comment-alt", "\uf28b": "pause-circle", "\uf28d": "stop-circle", "\uf290": "shopping-bag", "\uf291": "shopping-basket", "\uf292": "hashtag", "\uf295": "percent", "\uf29a": "universal-access", "\uf29d": "blind", "\uf29e": "audio-description", "\uf2a0": "phone-volume", "\uf2a1": "braille", "\uf2a2": "assistive-listening-systems", "\uf2a3": "american-sign-language-interpreting", "\uf2a4": "deaf", "\uf2a7": "sign-language", "\uf2a8": "low-vision", "\uf2b5": "handshake", "\uf2b6": "envelope-open", "\uf2b9": "address-book", "\uf2bb": "address-card", "\uf2bd": "user-circle", "\uf2c1": "id-badge", "\uf2c2": "id-card", "\uf2c7": "thermometer-full", "\uf2c8": "thermometer-three-quarters", "\uf2c9": "thermometer-half", "\uf2ca": "thermometer-quarter", "\uf2cb": "thermometer-empty", "\uf2cc": "shower", "\uf2cd": "bath", "\uf2ce": "podcast", "\uf2d0": "window-maximize", "\uf2d1": "window-minimize", "\uf2d2": "window-restore", "\uf2d3": "times-square", "\uf2db": "microchip", "\uf2dc": "snowflake", "\uf2e1": "watch", "\uf2e2": "volume-slash", "\uf2e3": "utensil-fork", "\uf2e4": "utensil-knife", "\uf2e5": "utensil-spoon", "\uf2e6": "utensils-alt", "\uf2e7": "utensils", "\uf2e8": "usd-circle", "\uf2e9": "usd-square", "\uf2ea": "undo-alt", "\uf2eb": "trophy-alt", "\uf2ec": "triangle", "\uf2ed": "trash-alt", "\uf2ee": "times-hexagon", "\uf2f0": "times-octagon", "\uf2f1": "sync-alt", "\uf2f2": "stopwatch", "\uf2f3": "star-exclamation", "\uf2f4": "spade", "\uf2f5": "sign-out-alt", "\uf2f6": "sign-in-alt", "\uf2f7": "shield-check", "\uf2f8": "scrubber", "\uf2f9": "redo-alt", "\uf2fa": "rectangle-landscape", "\uf2fb": "rectangle-portrait", "\uf2fc": "rectangle-wide", "\uf2fd": "question-square", "\uf2fe": "poo", "\uf300": "plus-hexagon", "\uf301": "plus-octagon", "\uf302": "images", "\uf303": "pencil-alt", "\uf304": "pen", "\uf305": "pen-alt", "\uf306": "octagon", "\uf307": "minus-hexagon", "\uf308": "minus-octagon", "\uf309": "long-arrow-alt-down", "\uf30a": "long-arrow-alt-left", "\uf30b": "long-arrow-alt-right", "\uf30c": "long-arrow-alt-up", "\uf30d": "lock-alt", "\uf30e": "jack-o-lantern", "\uf30f": "info-square", "\uf310": "inbox-in", "\uf311": "inbox-out", "\uf312": "hexagon", "\uf313": "h1", "\uf314": "h2", "\uf315": "h3", "\uf316": "file-check", "\uf317": "file-times", "\uf318": "file-minus", "\uf319": "file-plus", "\uf31a": "file-exclamation", "\uf31c": "file-edit", "\uf31d": "expand-arrows", "\uf31e": "expand-arrows-alt", "\uf320": "expand-wide", "\uf321": "exclamation-square", "\uf322": "chevron-double-down", "\uf323": "chevron-double-left", "\uf324": "chevron-double-right", "\uf325": "chevron-double-up", "\uf326": "compress-wide", "\uf327": "club", "\uf328": "clipboard", "\uf329": "chevron-square-down", "\uf32a": "chevron-square-left", "\uf32b": "chevron-square-right", "\uf32c": "chevron-square-up", "\uf32d": "caret-circle-down", "\uf32e": "caret-circle-left", "\uf330": "caret-circle-right", "\uf331": "caret-circle-up", "\uf332": "camera-alt", "\uf333": "calendar-edit", "\uf334": "calendar-exclamation", "\uf335": "badge", "\uf336": "badge-check", "\uf337": "arrows-alt-h", "\uf338": "arrows-alt-v", "\uf339": "arrow-square-down", "\uf33a": "arrow-square-left", "\uf33b": "arrow-square-right", "\uf33c": "arrow-square-up", "\uf33d": "arrow-to-bottom", "\uf33e": "arrow-to-left", "\uf340": "arrow-to-right", "\uf341": "arrow-to-top", "\uf342": "arrow-from-bottom", "\uf343": "arrow-from-left", "\uf344": "arrow-from-right", "\uf345": "arrow-from-top", "\uf346": "arrow-alt-from-bottom", "\uf347": "arrow-alt-from-left", "\uf348": "arrow-alt-from-right", "\uf349": "arrow-alt-from-top", "\uf34a": "arrow-alt-to-bottom", "\uf34b": "arrow-alt-to-left", "\uf34c": "arrow-alt-to-right", "\uf34d": "arrow-alt-to-top", "\uf34e": "alarm-clock", "\uf350": "arrow-alt-square-down", "\uf351": "arrow-alt-square-left", "\uf352": "arrow-alt-square-right", "\uf353": "arrow-alt-square-up", "\uf354": "arrow-alt-down", "\uf355": "arrow-alt-left", "\uf356": "arrow-alt-right", "\uf357": "arrow-alt-up", "\uf358": "arrow-alt-circle-down", "\uf359": "arrow-alt-circle-left", "\uf35a": "arrow-alt-circle-right", "\uf35b": "arrow-alt-circle-up", "\uf35d": "external-link-alt", "\uf360": "external-link-square-alt", "\uf361": "retweet-alt", "\uf362": "exchange-alt", "\uf363": "repeat", "\uf364": "repeat-alt", "\uf365": "repeat-1", "\uf366": "repeat-1-alt", "\uf367": "share-all", "\uf376": "battery-bolt", "\uf377": "battery-slash", "\uf37e": "browser", "\uf381": "cloud-download-alt", "\uf382": "cloud-upload-alt", "\uf386": "code-commit", "\uf387": "code-merge", "\uf389": "credit-card-blank", "\uf38a": "credit-card-front", "\uf390": "desktop-alt", "\uf39b": "ellipsis-h-alt", "\uf39c": "ellipsis-v-alt", "\uf3a0": "film-alt", "\uf3a5": "gem", "\uf3b3": "industry-alt", "\uf3be": "level-down-alt", "\uf3bf": "level-up-alt", "\uf3c1": "lock-open", "\uf3c2": "lock-open-alt", "\uf3c5": "map-marker-alt", "\uf3c9": "microphone-alt", "\uf3cd": "mobile-alt", "\uf3ce": "mobile-android", "\uf3cf": "mobile-android-alt", "\uf3d1": "money-bill-alt", "\uf3dd": "phone-slash", "\uf3de": "plane-alt", "\uf3e0": "portrait", "\uf3e5": "reply", "\uf3ed": "shield-alt", "\uf3f0": "sliders-h-square", "\uf3f1": "sliders-v", "\uf3f2": "sliders-v-square", "\uf3f4": "spinner-third", "\uf3fa": "tablet-alt", "\uf3fb": "tablet-android", "\uf3fc": "tablet-android-alt", "\uf3fd": "tachometer-alt", "\uf3ff": "ticket-alt", "\uf400": "tree-alt", "\uf401": "tv-retro", "\uf406": "user-alt", "\uf40e": "window", "\uf40f": "window-alt", "\uf410": "window-close", "\uf422": "compress-alt", "\uf424": "expand-alt", "\uf432": "baseball", "\uf433": "baseball-ball", "\uf434": "basketball-ball", "\uf435": "basketball-hoop", "\uf436": "bowling-ball", "\uf437": "bowling-pins", "\uf438": "boxing-glove", "\uf439": "chess", "\uf43a": "chess-bishop", "\uf43b": "chess-bishop-alt", "\uf43c": "chess-board", "\uf43d": "chess-clock", "\uf43e": "chess-clock-alt", "\uf43f": "chess-king", "\uf440": "chess-king-alt", "\uf441": "chess-knight", "\uf442": "chess-knight-alt", "\uf443": "chess-pawn", "\uf444": "chess-pawn-alt", "\uf445": "chess-queen", "\uf446": "chess-queen-alt", "\uf447": "chess-rook", "\uf448": "chess-rook-alt", "\uf449": "cricket", "\uf44a": "curling", "\uf44b": "dumbbell", "\uf44c": "field-hockey", "\uf44e": "football-ball", "\uf44f": "football-helmet", "\uf450": "golf-ball", "\uf451": "golf-club", "\uf453": "hockey-puck", "\uf454": "hockey-sticks", "\uf455": "luchador", "\uf456": "pennant", "\uf458": "quidditch", "\uf45a": "racquet", "\uf45b": "shuttlecock", "\uf45c": "square-full", "\uf45d": "table-tennis", "\uf45e": "tennis-ball", "\uf45f": "volleyball-ball", "\uf460": "whistle", "\uf461": "allergies", "\uf462": "band-aid", "\uf463": "barcode-alt", "\uf464": "barcode-read", "\uf465": "barcode-scan", "\uf466": "box", "\uf467": "box-check", "\uf468": "boxes", "\uf469": "briefcase-medical", "\uf46a": "burn", "\uf46b": "capsules", "\uf46c": "clipboard-check", "\uf46d": "clipboard-list", "\uf46e": "conveyor-belt", "\uf46f": "conveyor-belt-alt", "\uf470": "diagnoses", "\uf471": "dna", "\uf472": "dolly", "\uf473": "dolly-empty", "\uf474": "dolly-flatbed", "\uf475": "dolly-flatbed-alt", "\uf476": "dolly-flatbed-empty", "\uf477": "file-medical", "\uf478": "file-medical-alt", "\uf479": "first-aid", "\uf47a": "forklift", "\uf47b": "hand-holding-box", "\uf47c": "hand-receiving", "\uf47d": "hospital-alt", "\uf47e": "hospital-symbol", "\uf47f": "id-card-alt", "\uf480": "inventory", "\uf481": "notes-medical", "\uf482": "pallet", "\uf483": "pallet-alt", "\uf484": "pills", "\uf485": "prescription-bottle", "\uf486": "prescription-bottle-alt", "\uf487": "procedures", "\uf488": "scanner", "\uf489": "scanner-keyboard", "\uf48a": "scanner-touchscreen", "\uf48b": "shipping-fast", "\uf48c": "shipping-timed", "\uf48d": "smoking", "\uf48e": "syringe", "\uf48f": "tablet-rugged", "\uf490": "tablets", "\uf491": "thermometer", "\uf492": "vial", "\uf493": "vials", "\uf494": "warehouse", "\uf495": "warehouse-alt", "\uf496": "weight", "\uf497": "x-ray", "\uf498": "blanket", "\uf499": "book-heart", "\uf49a": "box-alt", "\uf49b": "box-fragile", "\uf49c": "box-full", "\uf49d": "box-heart", "\uf49e": "box-open", "\uf49f": "box-up", "\uf4a0": "box-usd", "\uf4a1": "boxes-alt", "\uf4a2": "comment-alt-check", "\uf4a3": "comment-alt-dots", "\uf4a4": "comment-alt-edit", "\uf4a5": "comment-alt-exclamation", "\uf4a6": "comment-alt-lines", "\uf4a7": "comment-alt-minus", "\uf4a8": "comment-alt-plus", "\uf4a9": "comment-alt-slash", "\uf4aa": "comment-alt-smile", "\uf4ab": "comment-alt-times", "\uf4ac": "comment-check", "\uf4ad": "comment-dots", "\uf4ae": "comment-edit", "\uf4af": "comment-exclamation", "\uf4b0": "comment-lines", "\uf4b1": "comment-minus", "\uf4b2": "comment-plus", "\uf4b3": "comment-slash", "\uf4b4": "comment-smile", "\uf4b5": "comment-times", "\uf4b6": "comments-alt", "\uf4b7": "container-storage", "\uf4b8": "couch", "\uf4b9": "donate", "\uf4ba": "dove", "\uf4bb": "fragile", "\uf4bc": "hand-heart", "\uf4bd": "hand-holding", "\uf4be": "hand-holding-heart", "\uf4bf": "hand-holding-seedling", "\uf4c0": "hand-holding-usd", "\uf4c1": "hand-holding-water", "\uf4c2": "hands", "\uf4c3": "hands-heart", "\uf4c4": "hands-helping", "\uf4c5": "hands-usd", "\uf4c6": "handshake-alt", "\uf4c7": "heart-circle", "\uf4c8": "heart-square", "\uf4c9": "home-heart", "\uf4ca": "lamp", "\uf4cb": "leaf-heart", "\uf4cc": "loveseat", "\uf4cd": "parachute-box", "\uf4ce": "people-carry", "\uf4cf": "person-carry", "\uf4d0": "person-dolly", "\uf4d1": "person-dolly-empty", "\uf4d2": "phone-plus", "\uf4d3": "piggy-bank", "\uf4d4": "ramp-loading", "\uf4d6": "ribbon", "\uf4d7": "route", "\uf4d8": "seedling", "\uf4d9": "sign", "\uf4da": "smile-wink", "\uf4db": "tape", "\uf4dc": "truck-container", "\uf4dd": "truck-couch", "\uf4de": "truck-loading", "\uf4df": "truck-moving", "\uf4e0": "truck-ramp", "\uf4e1": "video-plus", "\uf4e2": "video-slash", "\uf4e3": "wine-glass", "\uf4fa": "user-alt-slash", "\uf4fb": "user-astronaut", "\uf4fc": "user-check", "\uf4fd": "user-clock", "\uf4fe": "user-cog", "\uf4ff": "user-edit", "\uf500": "user-friends", "\uf501": "user-graduate", "\uf502": "user-lock", "\uf503": "user-minus", "\uf504": "user-ninja", "\uf505": "user-shield", "\uf506": "user-slash", "\uf507": "user-tag", "\uf508": "user-tie", "\uf509": "users-cog", "\uf515": "balance-scale-left", "\uf516": "balance-scale-right", "\uf517": "blender", "\uf518": "book-open", "\uf519": "broadcast-tower", "\uf51a": "broom", "\uf51b": "chalkboard", "\uf51c": "chalkboard-teacher", "\uf51d": "church", "\uf51e": "coins", "\uf51f": "compact-disc", "\uf520": "crow", "\uf521": "crown", "\uf522": "dice", "\uf523": "dice-five", "\uf524": "dice-four", "\uf525": "dice-one", "\uf526": "dice-six", "\uf527": "dice-three", "\uf528": "dice-two", "\uf529": "divide", "\uf52a": "door-closed", "\uf52b": "door-open", "\uf52c": "equals", "\uf52d": "feather", "\uf52e": "frog", "\uf52f": "gas-pump", "\uf530": "glasses", "\uf531": "greater-than", "\uf532": "greater-than-equal", "\uf533": "helicopter", "\uf534": "infinity", "\uf535": "kiwi-bird", "\uf536": "less-than", "\uf537": "less-than-equal", "\uf538": "memory", "\uf539": "microphone-alt-slash", "\uf53a": "money-bill-wave", "\uf53b": "money-bill-wave-alt", "\uf53c": "money-check", "\uf53d": "money-check-alt", "\uf53e": "not-equal", "\uf53f": "palette", "\uf540": "parking", "\uf541": "percentage", "\uf542": "project-diagram", "\uf543": "receipt", "\uf544": "robot", "\uf545": "ruler", "\uf546": "ruler-combined", "\uf547": "ruler-horizontal", "\uf548": "ruler-vertical", "\uf549": "school", "\uf54a": "screwdriver", "\uf54b": "shoe-prints", "\uf54c": "skull", "\uf54d": "smoking-ban", "\uf54e": "store", "\uf54f": "store-alt", "\uf550": "stream", "\uf551": "stroopwafel", "\uf552": "toolbox", "\uf553": "tshirt", "\uf554": "walking", "\uf555": "wallet", "\uf556": "angry", "\uf557": "archway", "\uf558": "atlas", "\uf559": "award", "\uf55a": "backspace", "\uf55b": "bezier-curve", "\uf55c": "bong", "\uf55d": "brush", "\uf55e": "bus-alt", "\uf55f": "cannabis", "\uf560": "check-double", "\uf561": "cocktail", "\uf562": "concierge-bell", "\uf563": "cookie", "\uf564": "cookie-bite", "\uf565": "crop-alt", "\uf566": "digital-tachograph", "\uf567": "dizzy", "\uf568": "drafting-compass", "\uf569": "drum", "\uf56a": "drum-steelpan", "\uf56b": "feather-alt", "\uf56c": "file-contract", "\uf56d": "file-download", "\uf56e": "file-export", "\uf56f": "file-import", "\uf570": "file-invoice", "\uf571": "file-invoice-dollar", "\uf572": "file-prescription", "\uf573": "file-signature", "\uf574": "file-upload", "\uf575": "fill", "\uf576": "fill-drip", "\uf577": "fingerprint", "\uf578": "fish", "\uf579": "flushed", "\uf57a": "frown-open", "\uf57b": "glass-martini-alt", "\uf57c": "globe-africa", "\uf57d": "globe-americas", "\uf57e": "globe-asia", "\uf57f": "grimace", "\uf580": "grin", "\uf581": "grin-alt", "\uf582": "grin-beam", "\uf583": "grin-beam-sweat", "\uf584": "grin-hearts", "\uf585": "grin-squint", "\uf586": "grin-squint-tears", "\uf587": "grin-stars", "\uf588": "grin-tears", "\uf589": "grin-tongue", "\uf58a": "grin-tongue-squint", "\uf58b": "grin-tongue-wink", "\uf58c": "grin-wink", "\uf58d": "grip-horizontal", "\uf58e": "grip-vertical", "\uf58f": "headphones-alt", "\uf590": "headset", "\uf591": "highlighter", "\uf593": "hot-tub", "\uf594": "hotel", "\uf595": "joint", "\uf596": "kiss", "\uf597": "kiss-beam", "\uf598": "kiss-wink-heart", "\uf599": "laugh", "\uf59a": "laugh-beam", "\uf59b": "laugh-squint", "\uf59c": "laugh-wink", "\uf59d": "luggage-cart", "\uf59f": "map-marked", "\uf5a0": "map-marked-alt", "\uf5a1": "marker", "\uf5a2": "medal", "\uf5a4": "meh-blank", "\uf5a5": "meh-rolling-eyes", "\uf5a6": "monument", "\uf5a7": "mortar-pestle", "\uf5a9": "paint-brush-alt", "\uf5aa": "paint-roller", "\uf5ab": "passport", "\uf5ac": "pen-fancy", "\uf5ad": "pen-nib", "\uf5ae": "pencil-ruler", "\uf5af": "plane-arrival", "\uf5b0": "plane-departure", "\uf5b1": "prescription", "\uf5b3": "sad-cry", "\uf5b4": "sad-tear", "\uf5b6": "shuttle-van", "\uf5b7": "signature", "\uf5b8": "smile-beam", "\uf5b9": "smile-plus", "\uf5ba": "solar-panel", "\uf5bb": "spa", "\uf5bc": "splotch", "\uf5bd": "spray-can", "\uf5bf": "stamp", "\uf5c0": "star-half-alt", "\uf5c1": "suitcase-rolling", "\uf5c2": "surprise", "\uf5c3": "swatchbook", "\uf5c4": "swimmer", "\uf5c5": "swimming-pool", "\uf5c7": "tint-slash", "\uf5c8": "tired", "\uf5c9": "tooth", "\uf5ca": "umbrella-beach", "\uf5cb": "vector-square", "\uf5cd": "weight-hanging", "\uf5ce": "wine-glass-alt", "\uf5d0": "air-freshener", "\uf5d1": "apple-alt", "\uf5d2": "atom", "\uf5d3": "atom-alt", "\uf5d4": "backpack", "\uf5d5": "bell-school", "\uf5d6": "bell-school-slash", "\uf5d7": "bone", "\uf5d8": "bone-break", "\uf5d9": "book-alt", "\uf5da": "book-reader", "\uf5db": "books", "\uf5dc": "brain", "\uf5dd": "bus-school", "\uf5de": "car-alt", "\uf5df": "car-battery", "\uf5e0": "car-bump", "\uf5e1": "car-crash", "\uf5e2": "car-garage", "\uf5e3": "car-mechanic", "\uf5e4": "car-side", "\uf5e5": "car-tilt", "\uf5e6": "car-wash", "\uf5e7": "charging-station", "\uf5e8": "clipboard-prescription", "\uf5e9": "compass-slash", "\uf5ea": "diploma", "\uf5eb": "directions", "\uf5ec": "do-not-enter", "\uf5ed": "draw-circle", "\uf5ee": "draw-polygon", "\uf5ef": "draw-square", "\uf5f0": "ear", "\uf5f2": "engine-warning", "\uf5f3": "file-certificate", "\uf5f4": "gas-pump-slash", "\uf5f5": "glasses-alt", "\uf5f6": "globe-stand", "\uf5f8": "heart-rate", "\uf5f9": "inhaler", "\uf5fb": "kidneys", "\uf5fc": "laptop-code", "\uf5fd": "layer-group", "\uf5fe": "layer-minus", "\uf5ff": "layer-plus", "\uf600": "lips", "\uf601": "location", "\uf602": "location-circle", "\uf603": "location-slash", "\uf604": "lungs", "\uf605": "map-marker-alt-slash", "\uf606": "map-marker-check", "\uf607": "map-marker-edit", "\uf608": "map-marker-exclamation", "\uf609": "map-marker-minus", "\uf60a": "map-marker-plus", "\uf60b": "map-marker-question", "\uf60c": "map-marker-slash", "\uf60d": "map-marker-smile", "\uf60e": "map-marker-times", "\uf610": "microscope", "\uf611": "monitor-heart-rate", "\uf613": "oil-can", "\uf614": "oil-temp", "\uf615": "parking-circle", "\uf616": "parking-circle-slash", "\uf617": "parking-slash", "\uf618": "pencil-paintbrush", "\uf619": "poop", "\uf61a": "route-highway", "\uf61b": "route-interstate", "\uf61c": "ruler-triangle", "\uf61d": "scalpel", "\uf61e": "scalpel-path", "\uf61f": "shapes", "\uf620": "skeleton", "\uf621": "star-of-life", "\uf622": "steering-wheel", "\uf623": "stomach", "\uf624": "tachometer-alt-average", "\uf625": "tachometer-alt-fast", "\uf626": "tachometer-alt-fastest", "\uf627": "tachometer-alt-slow", "\uf628": "tachometer-alt-slowest", "\uf629": "tachometer-average", "\uf62a": "tachometer-fast", "\uf62b": "tachometer-fastest", "\uf62c": "tachometer-slow", "\uf62d": "tachometer-slowest", "\uf62e": "teeth", "\uf62f": "teeth-open", "\uf630": "theater-masks", "\uf631": "tire", "\uf632": "tire-flat", "\uf633": "tire-pressure-warning", "\uf634": "tire-rugged", "\uf635": "toothbrush", "\uf636": "traffic-cone", "\uf637": "traffic-light", "\uf638": "traffic-light-go", "\uf639": "traffic-light-slow", "\uf63a": "traffic-light-stop", "\uf63b": "truck-monster", "\uf63c": "truck-pickup", "\uf63d": "users-class", "\uf63e": "watch-fitness", "\uf640": "abacus", "\uf641": "ad", "\uf643": "analytics", "\uf644": "ankh", "\uf645": "badge-dollar", "\uf646": "badge-percent", "\uf647": "bible", "\uf648": "bullseye-arrow", "\uf649": "bullseye-pointer", "\uf64a": "business-time", "\uf64b": "cabinet-filing", "\uf64c": "calculator-alt", "\uf64d": "chart-line-down", "\uf64e": "chart-pie-alt", "\uf64f": "city", "\uf650": "comment-alt-dollar", "\uf651": "comment-dollar", "\uf652": "comments-alt-dollar", "\uf653": "comments-dollar", "\uf654": "cross", "\uf655": "dharmachakra", "\uf656": "empty-set", "\uf657": "envelope-open-dollar", "\uf658": "envelope-open-text", "\uf659": "file-chart-line", "\uf65a": "file-chart-pie", "\uf65b": "file-spreadsheet", "\uf65c": "file-user", "\uf65d": "folder-minus", "\uf65e": "folder-plus", "\uf65f": "folder-times", "\uf660": "folders", "\uf661": "function", "\uf662": "funnel-dollar", "\uf663": "gift-card", "\uf664": "gopuram", "\uf665": "hamsa", "\uf666": "haykal", "\uf667": "integral", "\uf668": "intersection", "\uf669": "jedi", "\uf66a": "journal-whills", "\uf66b": "kaaba", "\uf66c": "keynote", "\uf66d": "khanda", "\uf66e": "lambda", "\uf66f": "landmark", "\uf670": "lightbulb-dollar", "\uf671": "lightbulb-exclamation", "\uf672": "lightbulb-on", "\uf673": "lightbulb-slash", "\uf674": "mail-bulk", "\uf675": "megaphone", "\uf676": "menorah", "\uf677": "mind-share", "\uf678": "mosque", "\uf679": "om", "\uf67a": "omega", "\uf67b": "pastafarianism", "\uf67c": "peace", "\uf67d": "phone-office", "\uf67e": "pi", "\uf67f": "place-of-worship", "\uf680": "podium", "\uf681": "poll", "\uf682": "poll-h", "\uf683": "pray", "\uf684": "praying-hands", "\uf685": "presentation", "\uf686": "print-slash", "\uf687": "quran", "\uf688": "search-dollar", "\uf689": "search-location", "\uf68a": "shredder", "\uf68b": "sigma", "\uf68c": "signal-1", "\uf68d": "signal-2", "\uf68e": "signal-3", "\uf68f": "signal-4", "\uf690": "signal-alt", "\uf691": "signal-alt-1", "\uf692": "signal-alt-2", "\uf693": "signal-alt-3", "\uf694": "signal-alt-slash", "\uf695": "signal-slash", "\uf696": "socks", "\uf697": "square-root", "\uf698": "square-root-alt", "\uf699": "star-and-crescent", "\uf69a": "star-of-david", "\uf69b": "synagogue", "\uf69c": "tally", "\uf69e": "theta", "\uf69f": "tilde", "\uf6a0": "torah", "\uf6a1": "torii-gate", "\uf6a2": "union", "\uf6a3": "user-chart", "\uf6a4": "user-crown", "\uf6a5": "users-crown", "\uf6a6": "value-absolute", "\uf6a7": "vihara", "\uf6a8": "volume", "\uf6a9": "volume-mute", "\uf6aa": "wifi-1", "\uf6ab": "wifi-2", "\uf6ac": "wifi-slash", "\uf6ad": "yin-yang", "\uf6ae": "acorn", "\uf6b0": "alicorn", "\uf6b1": "apple-crate", "\uf6b2": "axe", "\uf6b3": "axe-battle", "\uf6b4": "badger-honey", "\uf6b5": "bat", "\uf6b6": "blender-phone", "\uf6b7": "book-dead", "\uf6b8": "book-spells", "\uf6b9": "bow-arrow", "\uf6ba": "campfire", "\uf6bb": "campground", "\uf6bc": "candle-holder", "\uf6bd": "candy-corn", "\uf6be": "cat", "\uf6bf": "cauldron", "\uf6c0": "chair", "\uf6c1": "chair-office", "\uf6c2": "claw-marks", "\uf6c3": "cloud-moon", "\uf6c4": "cloud-sun", "\uf6c5": "coffee-togo", "\uf6c6": "coffin", "\uf6c7": "corn", "\uf6c8": "cow", "\uf6cb": "dagger", "\uf6cd": "dice-d10", "\uf6ce": "dice-d12", "\uf6cf": "dice-d20", "\uf6d0": "dice-d4", "\uf6d1": "dice-d6", "\uf6d2": "dice-d8", "\uf6d3": "dog", "\uf6d4": "dog-leashed", "\uf6d5": "dragon", "\uf6d6": "drumstick", "\uf6d7": "drumstick-bite", "\uf6d8": "duck", "\uf6d9": "dungeon", "\uf6da": "elephant", "\uf6db": "eye-evil", "\uf6dd": "file-csv", "\uf6de": "fist-raised", "\uf6df": "flame", "\uf6e0": "flask-poison", "\uf6e1": "flask-potion", "\uf6e2": "ghost", "\uf6e3": "hammer", "\uf6e4": "hammer-war", "\uf6e5": "hand-holding-magic", "\uf6e6": "hanukiah", "\uf6e7": "hat-witch", "\uf6e8": "hat-wizard", "\uf6e9": "head-side", "\uf6ea": "head-vr", "\uf6eb": "helmet-battle", "\uf6ec": "hiking", "\uf6ed": "hippo", "\uf6ee": "hockey-mask", "\uf6ef": "hood-cloak", "\uf6f0": "horse", "\uf6f1": "house-damage", "\uf6f2": "hryvnia", "\uf6f3": "key-skeleton", "\uf6f4": "kite", "\uf6f5": "knife-kitchen", "\uf6f6": "leaf-maple", "\uf6f7": "leaf-oak", "\uf6f8": "mace", "\uf6f9": "mandolin", "\uf6fa": "mask", "\uf6fb": "monkey", "\uf6fc": "mountain", "\uf6fd": "mountains", "\uf6fe": "narwhal", "\uf6ff": "network-wired", "\uf700": "otter", "\uf701": "paw-alt", "\uf702": "paw-claws", "\uf703": "pegasus", "\uf705": "pie", "\uf706": "pig", "\uf707": "pumpkin", "\uf708": "rabbit", "\uf709": "rabbit-fast", "\uf70a": "ram", "\uf70b": "ring", "\uf70c": "running", "\uf70d": "scarecrow", "\uf70e": "scroll", "\uf70f": "scroll-old", "\uf710": "scythe", "\uf711": "sheep", "\uf712": "shield-cross", "\uf713": "shovel", "\uf714": "skull-crossbones", "\uf715": "slash", "\uf716": "snake", "\uf717": "spider", "\uf718": "spider-black-widow", "\uf719": "spider-web", "\uf71a": "squirrel", "\uf71b": "staff", "\uf71c": "sword", "\uf71d": "swords", "\uf71e": "toilet-paper", "\uf71f": "toilet-paper-alt", "\uf720": "tombstone", "\uf721": "tombstone-alt", "\uf722": "tractor", "\uf723": "treasure-chest", "\uf724": "trees", "\uf725": "turkey", "\uf726": "turtle", "\uf727": "unicorn", "\uf728": "user-injured", "\uf729": "vr-cardboard", "\uf72a": "wand", "\uf72b": "wand-magic", "\uf72c": "whale", "\uf72d": "wheat", "\uf72e": "wind", "\uf72f": "wine-bottle", "\uf732": "ballot", "\uf733": "ballot-check", "\uf734": "booth-curtain", "\uf735": "box-ballot", "\uf736": "calendar-star", "\uf737": "clipboard-list-check", "\uf738": "cloud-drizzle", "\uf739": "cloud-hail", "\uf73a": "cloud-hail-mixed", "\uf73b": "cloud-meatball", "\uf73c": "cloud-moon-rain", "\uf73d": "cloud-rain", "\uf73e": "cloud-rainbow", "\uf73f": "cloud-showers", "\uf740": "cloud-showers-heavy", "\uf741": "cloud-sleet", "\uf742": "cloud-snow", "\uf743": "cloud-sun-rain", "\uf744": "clouds", "\uf745": "clouds-moon", "\uf746": "clouds-sun", "\uf747": "democrat", "\uf748": "dewpoint", "\uf749": "eclipse", "\uf74a": "eclipse-alt", "\uf74b": "fire-smoke", "\uf74c": "flag-alt", "\uf74d": "flag-usa", "\uf74e": "fog", "\uf74f": "house-flood", "\uf750": "humidity", "\uf751": "hurricane", "\uf752": "landmark-alt", "\uf753": "meteor", "\uf754": "moon-cloud", "\uf755": "moon-stars", "\uf756": "person-booth", "\uf757": "person-sign", "\uf758": "podium-star", "\uf759": "poll-people", "\uf75a": "poo-storm", "\uf75b": "rainbow", "\uf75c": "raindrops", "\uf75e": "republican", "\uf75f": "smog", "\uf760": "smoke", "\uf761": "snow-blowing", "\uf762": "stars", "\uf763": "sun-cloud", "\uf764": "sun-dust", "\uf765": "sun-haze", "\uf766": "sunrise", "\uf767": "sunset", "\uf768": "temperature-frigid", "\uf769": "temperature-high", "\uf76a": "temperature-hot", "\uf76b": "temperature-low", "\uf76c": "thunderstorm", "\uf76d": "thunderstorm-moon", "\uf76e": "thunderstorm-sun", "\uf76f": "tornado", "\uf770": "volcano", "\uf771": "vote-nay", "\uf772": "vote-yea", "\uf773": "water", "\uf774": "water-lower", "\uf775": "water-rise", "\uf776": "wind-warning", "\uf777": "windsock", "\uf779": "angel", "\uf77c": "baby", "\uf77d": "baby-carriage", "\uf77e": "ball-pile", "\uf77f": "bells", "\uf780": "biohazard", "\uf781": "blog", "\uf782": "boot", "\uf783": "calendar-day", "\uf784": "calendar-week", "\uf786": "candy-cane", "\uf787": "carrot", "\uf788": "cash-register", "\uf78a": "chart-network", "\uf78b": "chimney", "\uf78c": "compress-arrows-alt", "\uf78e": "deer", "\uf78f": "deer-rudolph", "\uf792": "dreidel", "\uf793": "dumpster", "\uf794": "dumpster-fire", "\uf795": "ear-muffs", "\uf796": "ethernet", "\uf79a": "fireplace", "\uf79b": "frosty-head", "\uf79c": "gifts", "\uf79d": "gingerbread-man", "\uf79e": "glass-champagne", "\uf79f": "glass-cheers", "\uf7a0": "glass-whiskey", "\uf7a1": "glass-whiskey-rocks", "\uf7a2": "globe-europe", "\uf7a3": "globe-snow", "\uf7a4": "grip-lines", "\uf7a5": "grip-lines-vertical", "\uf7a6": "guitar", "\uf7a7": "hat-santa", "\uf7a8": "hat-winter", "\uf7a9": "heart-broken", "\uf7aa": "holly-berry", "\uf7ab": "horse-head", "\uf7ac": "ice-skate", "\uf7ad": "icicles", "\uf7ae": "igloo", "\uf7b2": "lights-holiday", "\uf7b4": "mistletoe", "\uf7b5": "mitten", "\uf7b6": "mug-hot", "\uf7b7": "mug-marshmallows", "\uf7b8": "ornament", "\uf7b9": "radiation", "\uf7ba": "radiation-alt", "\uf7bd": "restroom", "\uf7be": "rv", "\uf7bf": "satellite", "\uf7c0": "satellite-dish", "\uf7c1": "scarf", "\uf7c2": "sd-card", "\uf7c3": "shovel-snow", "\uf7c4": "sim-card", "\uf7c5": "skating", "\uf7c7": "ski-jump", "\uf7c8": "ski-lift", "\uf7c9": "skiing", "\uf7ca": "skiing-nordic", "\uf7cb": "sledding", "\uf7cc": "sleigh", "\uf7cd": "sms", "\uf7ce": "snowboarding", "\uf7cf": "snowflakes", "\uf7d0": "snowman", "\uf7d1": "snowmobile", "\uf7d2": "snowplow", "\uf7d4": "star-christmas", "\uf7d5": "stocking", "\uf7d7": "tenge", "\uf7d8": "toilet", "\uf7d9": "tools", "\uf7da": "tram", "\uf7db": "tree-christmas", "\uf7dc": "tree-decorated", "\uf7dd": "tree-large", "\uf7de": "truck-plow", "\uf7e2": "wreath", "\uf7e4": "fire-alt", "\uf7e5": "bacon", "\uf7e6": "book-medical", "\uf7e7": "book-user", "\uf7e8": "books-medical", "\uf7e9": "brackets", "\uf7ea": "brackets-curly", "\uf7eb": "bread-loaf", "\uf7ec": "bread-slice", "\uf7ed": "burrito", "\uf7ee": "chart-scatter", "\uf7ef": "cheese", "\uf7f0": "cheese-swiss", "\uf7f1": "cheeseburger", "\uf7f2": "clinic-medical", "\uf7f3": "clipboard-user", "\uf7f4": "comment-alt-medical", "\uf7f5": "comment-medical", "\uf7f6": "croissant", "\uf7f7": "crutch", "\uf7f8": "crutches", "\uf7f9": "debug", "\uf7fa": "disease", "\uf7fb": "egg", "\uf7fc": "egg-fried", "\uf7fd": "files-medical", "\uf7fe": "fish-cooked", "\uf7ff": "flower", "\uf800": "flower-daffodil", "\uf801": "flower-tulip", "\uf802": "folder-tree", "\uf803": "french-fries", "\uf804": "glass", "\uf805": "hamburger", "\uf806": "hand-middle-finger", "\uf807": "hard-hat", "\uf808": "head-side-brain", "\uf809": "head-side-medical", "\uf80a": "home-alt", "\uf80b": "home-lg", "\uf80c": "home-lg-alt", "\uf80d": "hospital-user", "\uf80e": "hospitals", "\uf80f": "hotdog", "\uf810": "ice-cream", "\uf811": "island-tropical", "\uf812": "laptop-medical", "\uf813": "mailbox", "\uf814": "meat", "\uf815": "pager", "\uf816": "pepper-hot", "\uf817": "pizza", "\uf818": "pizza-slice", "\uf819": "popcorn", "\uf81a": "print-search", "\uf81b": "rings-wedding", "\uf81c": "sack", "\uf81d": "sack-dollar", "\uf81e": "salad", "\uf81f": "sandwich", "\uf820": "sausage", "\uf821": "shish-kebab", "\uf822": "sickle", "\uf823": "soup", "\uf824": "steak", "\uf825": "stretcher", "\uf826": "taco", "\uf827": "tanakh", "\uf828": "tasks-alt", "\uf829": "trash-restore", "\uf82a": "trash-restore-alt", "\uf82b": "tree-palm", "\uf82c": "user-hard-hat", "\uf82d": "user-headset", "\uf82e": "user-md-chat", "\uf82f": "user-nurse", "\uf830": "users-medical", "\uf831": "walker", "\uf832": "webcam", "\uf833": "webcam-slash", "\uf83e": "wave-square", "\uf843": "alarm-exclamation", "\uf844": "alarm-plus", "\uf845": "alarm-snooze", "\uf846": "align-slash", "\uf847": "bags-shopping", "\uf848": "bell-exclamation", "\uf849": "bell-plus", "\uf84a": "biking", "\uf84b": "biking-mountain", "\uf84c": "border-all", "\uf84d": "border-bottom", "\uf84e": "border-inner", "\uf84f": "border-left", "\uf850": "border-none", "\uf851": "border-outer", "\uf852": "border-right", "\uf853": "border-style", "\uf854": "border-style-alt", "\uf855": "border-top", "\uf856": "bring-forward", "\uf857": "bring-front", "\uf858": "burger-soda", "\uf859": "car-building", "\uf85a": "car-bus", "\uf85b": "cars", "\uf85c": "coin", "\uf85d": "construction", "\uf85e": "digging", "\uf85f": "drone", "\uf860": "drone-alt", "\uf861": "dryer", "\uf862": "dryer-alt", "\uf863": "fan", "\uf864": "farm", "\uf865": "file-search", "\uf866": "font-case", "\uf867": "game-board", "\uf868": "game-board-alt", "\uf869": "glass-citrus", "\uf86a": "h4", "\uf86b": "hat-chef", "\uf86c": "horizontal-rule", "\uf86d": "icons", "\uf86e": "icons-alt", "\uf86f": "kerning", "\uf870": "line-columns", "\uf871": "line-height", "\uf872": "money-check-edit", "\uf873": "money-check-edit-alt", "\uf874": "mug", "\uf875": "mug-tea", "\uf876": "overline", "\uf877": "page-break", "\uf878": "paragraph-rtl", "\uf879": "phone-alt", "\uf87a": "phone-laptop", "\uf87b": "phone-square-alt", "\uf87c": "photo-video", "\uf87d": "remove-format", "\uf87e": "send-back", "\uf87f": "send-backward", "\uf880": "snooze", "\uf881": "sort-alpha-down-alt", "\uf882": "sort-alpha-up-alt", "\uf883": "sort-alt", "\uf884": "sort-amount-down-alt", "\uf885": "sort-amount-up-alt", "\uf886": "sort-numeric-down-alt", "\uf887": "sort-numeric-up-alt", "\uf888": "sort-shapes-down", "\uf889": "sort-shapes-down-alt", "\uf88a": "sort-shapes-up", "\uf88b": "sort-shapes-up-alt", "\uf88c": "sort-size-down", "\uf88d": "sort-size-down-alt", "\uf88e": "sort-size-up", "\uf88f": "sort-size-up-alt", "\uf890": "sparkles", "\uf891": "spell-check", "\uf892": "sunglasses", "\uf893": "text", "\uf894": "text-size", "\uf895": "trash-undo", "\uf896": "trash-undo-alt", "\uf897": "voicemail", "\uf898": "washer", "\uf899": "wave-sine", "\uf89a": "wave-triangle", "\uf89b": "wind-turbine" }; +/** + * @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; } \ No newline at end of file diff --git a/lib/ui/media.js b/lib/ui/media.js index e149af3..b7f8918 100644 --- a/lib/ui/media.js +++ b/lib/ui/media.js @@ -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>} + */ 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} 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} samples + * @param {(ctx: AudioContext) => void} ended + * @returns {Promise} + */ 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()); }); diff --git a/lib/ui/popup.js b/lib/ui/popup.js index f5d7a14..f6f1e32 100644 --- a/lib/ui/popup.js +++ b/lib/ui/popup.js @@ -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); } } diff --git a/lib/ui/tab.js b/lib/ui/tab.js index b334fd5..d583e07 100644 --- a/lib/ui/tab.js +++ b/lib/ui/tab.js @@ -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' : ''; + }); } }); }) diff --git a/lib/ui/tooltip.js b/lib/ui/tooltip.js index a666818..c189e35 100644 --- a/lib/ui/tooltip.js +++ b/lib/ui/tooltip.js @@ -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 + * ``` + * + * ``` + */ 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'); diff --git a/lib/utility.js b/lib/utility.js index 180f5c2..71ad8d6 100644 --- a/lib/utility.js +++ b/lib/utility.js @@ -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 } \ No newline at end of file diff --git a/lib/utility/cookie.js b/lib/utility/cookie.js index d73f18b..e7bac21 100644 --- a/lib/utility/cookie.js +++ b/lib/utility/cookie.js @@ -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); } \ No newline at end of file diff --git a/lib/utility/lgres.js b/lib/utility/lgres.js index d04237d..49d691d 100644 --- a/lib/utility/lgres.js +++ b/lib/utility/lgres.js @@ -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} + */ 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} + */ 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} + */ 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 = { diff --git a/lib/utility/request.js b/lib/utility/request.js index ef9a81c..81cc1e4 100644 --- a/lib/utility/request.js +++ b/lib/utility/request.js @@ -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.} [customHeaders] + * @property {RequestMode} [mode] + * @property {AbortSignal | null} [signal] + * @property {boolean} [diagnostic] + * @property {(this: XMLHttpRequestUpload, e: ProgressEvent) => any} [progress] + */ + +/** + * @param {string} url + * @param {RequestOptions} [options] + * @returns {Promise} + */ +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} + */ +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} + */ +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); } diff --git a/lib/utility/strings.js b/lib/utility/strings.js index 5cafa51..95d7601 100644 --- a/lib/utility/strings.js +++ b/lib/utility/strings.js @@ -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, ``); @@ -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(' ', ' '); } +/** + * @param {string} text + * @returns {string} + */ export function escapeEmoji(text) { if (text == null) { return ''; diff --git a/package.json b/package.json index 614e93f..8b0778d 100644 --- a/package.json +++ b/package.json @@ -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" } } diff --git a/tsconfig.json b/tsconfig.json index fd9241c..804e870 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -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" ] } \ No newline at end of file diff --git a/typedoc.json b/typedoc.json deleted file mode 100644 index 53db88a..0000000 --- a/typedoc.json +++ /dev/null @@ -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 -} \ No newline at end of file diff --git a/vite.build.js b/vite.build.js index 9f0b213..70abe4a 100644 --- a/vite.build.js +++ b/vite.build.js @@ -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` - }, - 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', + entry: { + [name]: path + }, + 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() + ] + }); +}