diff --git a/.gitignore b/.gitignore index 432369e..ae9a595 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,4 @@ desktop.ini docs jsdoc package-lock.json +@*.cmd diff --git a/lib/types.d.ts b/lib/types.d.ts index b7f3fb1..1dd1baa 100644 --- a/lib/types.d.ts +++ b/lib/types.d.ts @@ -9,11 +9,14 @@ export interface OptionParamBase { getText?: GetTextCallback; } +export type MarkRequired = Omit & Required>; + export interface NotifyOption { - message: string | HTMLElement; + message: string | Node; parent?: HTMLElement; title?: string; type?: "success" | "warning" | "error"; + icon?: string; persistent?: boolean; timeout?: number; onDismissed?: (auto?: boolean) => void; @@ -147,9 +150,9 @@ export interface CheckboxOptions { /** 图片高度 */ imageHeight?: number; /** 选中时显示的元素 */ - checkedNode?: HTMLElement; + checkedNode?: Element; /** 未选中时显示的元素 */ - uncheckedNode?: HTMLElement; + uncheckedNode?: Element; /** 自定义 html 属性 */ customAttributes?: { [key: string]: string }; /** diff --git a/lib/ui.js b/lib/ui.js index 80ba123..b5123fd 100644 --- a/lib/ui.js +++ b/lib/ui.js @@ -113,23 +113,22 @@ function notify(opts) { timer && clearTimeout(timer); closeNotify(wrapper, opts?.onDismissed); }); - let type; - let typeClass; - switch (opts?.type) { - case 'warning': - type = 'exclamation-circle'; - typeClass = 'warning'; - break; - case 'error': - type = 'times-circle'; - typeClass = 'error'; - break; - default: - type = opts?.type ?? 'check-circle'; - typeClass = 'success'; - break; + const typeClass = opts?.type ?? 'success'; + let fontIcon = opts?.icon; + if (fontIcon == null) { + switch (typeClass) { + case 'warning': + fontIcon = 'exclamation-circle'; + break; + case 'error': + fontIcon = 'times-circle'; + break; + default: + fontIcon = 'check-circle'; + break; + } } - const icon = createIcon('fa-solid', type); + const icon = createIcon('fa-solid', fontIcon); icon.classList.add('ui-notify-type', typeClass); const title = opts?.title; const wrapper = createElement('div', 'ui-notify', @@ -153,7 +152,18 @@ function notify(opts) { closeNotify(wrapper, opts?.onDismissed, true); }, opts?.timeout || 3000); } - (opts?.parent ?? document.body).appendChild(wrapper); + const parent = opts?.parent ?? document.body; + let top = 0; + (/** @type {NodeListOf} */ (parent.querySelectorAll('.ui-notify'))).forEach(n =>{ + const t = n.offsetTop + n.offsetHeight; + if (t > top) { + top = t; + } + }); + if (top > 0) { + wrapper.style.top = `${top + 10}px`; + } + parent.appendChild(wrapper); setTimeout(() => wrapper.classList.add('active'), 10); return wrapper; } diff --git a/lib/ui/checkbox.js b/lib/ui/checkbox.js index 7528d72..0e64e8b 100644 --- a/lib/ui/checkbox.js +++ b/lib/ui/checkbox.js @@ -3,7 +3,7 @@ import { createElement } from "../functions"; import { createIcon } from "./icon"; import { isPositive, nullOrEmpty } from '../utility'; -/** @typedef {import('../types').CheckboxOptions} CheckboxOptions */ +/** @import { CheckboxOptions } from '../types' */ /** * @private diff --git a/lib/ui/dropdown.js b/lib/ui/dropdown.js index 0660420..559edca 100644 --- a/lib/ui/dropdown.js +++ b/lib/ui/dropdown.js @@ -1,16 +1,29 @@ import './css/dropdown.scss'; import { r as lang } from "../utility/lgres"; import { contains, nullOrEmpty } from "../utility/strings"; -import { global, isPositive, throttle } from "../utility"; +import { mergeOptions, global, isPositive, throttle } from "../utility"; import { createElement } from "../functions"; import { createCheckbox } from "./checkbox"; import { createIcon } from "./icon" +/** @import { DropdownOptions } from './dropdown.types' */ + +/** @satisfies {Partial} */ +const DEFAULT_OPTIONS = { + textKey: 'text', + valueKey: 'value', + htmlKey: 'html', + childKey: 'children', + maxLength: 500 +}; + +/** @typedef {import('../types').MarkRequired} ResolvedDropdownOptions */ + const SymbolDropdown = Symbol.for('ui-dropdown'); const DropdownItemHeight = 30; let r = lang; -let dropdownGlobal = global[SymbolDropdown]; +let dropdownGlobal = /** @type {Record} */ (/** @type {unknown} */ (global))[SymbolDropdown]; if (dropdownGlobal == null) { // init @@ -38,7 +51,11 @@ if (dropdownGlobal == null) { } } }) - global[SymbolDropdown] = dropdownGlobal; + Object.defineProperty(global, SymbolDropdown, { + value: dropdownGlobal, + writable: true, + configurable: true + }); document.addEventListener('mousedown', e => { let parent = e.target; @@ -124,31 +141,6 @@ function getValue(it, valuekey, textkey) { return value; } -/** - * 下拉列表参数对象 - * @typedef DropdownOptions - * @property {string} textKey 文本关键字 - * @property {string} valueKey 值关键字 - * @property {string} htmlKey 源码显示的关键字 - * @property {string} childKey 子集合的关键字 - * @property {number} maxLength 最大输入长度 - * @property {(this: Dropdown, it: DropdownItem) => string} [htmlTemplate] 模板创建函数 - * @property {boolean} [multiSelect] 是否允许多选 - * @property {string} [selected] 选中值 - * @property {string[]} [selectedList] 选中的数组 - * @property {boolean} [disabled] 是否禁用 - * @property {boolean} [input] 是否支持输入 - * @property {boolean} [search] 是否支持搜索 - * @property {string[]} [searchKeys] 搜索的关键字数组 - * @property {string} [searchPlaceholder] 搜索提示文本,默认值取语言资源 `searchHolder` "Search..." - * @property {number} [tabIndex] 焦点索引 - * @property {string} [placeholder] 输入框的提示文本 - * @property {boolean} [slideFixed] 是否固定为向下展开 - * @property {HTMLElement} [wrapper] 父元素,默认添加到头元素之后 - * @property {boolean} [ignoreAll] 是否忽略 All 选项 - * @property {import('../types').GetTextCallback} [getText] 获取文本的代理函数 - */ - /** * 数据项基础类型 * @typedef DropdownItemBase @@ -165,14 +157,8 @@ function getValue(it, valuekey, textkey) { export class Dropdown { _var = { - /** @type {DropdownOptions} */ - options: { - textKey: 'text', - valueKey: 'value', - htmlKey: 'html', - childKey: 'children', - maxLength: 500 - }, + /** @type {ResolvedDropdownOptions} */ + options: DEFAULT_OPTIONS, /** @type {HTMLDivElement | undefined} */ wrapper: undefined, /** @type {HTMLDivElement | undefined} */ @@ -210,14 +196,9 @@ export class Dropdown { */ constructor(options) { if (options != null) { - this._var.options = options; + this._var.options = mergeOptions(DEFAULT_OPTIONS, options); } const opts = this._var.options; - opts.textKey ??= 'text'; - opts.valueKey ??= 'value'; - opts.htmlKey ??= 'html'; - opts.childKey ??= 'children'; - opts.maxLength ??= 500; const getText = opts.getText; if (typeof getText === 'function') { r = getText; @@ -398,11 +379,19 @@ export class Dropdown { if (!Array.isArray(list)) { return []; } - return list.reduce((array, item) => [ - ...array, - (id == null ? item : { __p: String(id), __level: level, ...item }), - ...reduceItems(item[childkey], item[valuekey], level + 1) - ], []); + return list.reduce( + /** + * @private + * @param {DropdownItem[]} array + * @param {DropdownItem} item + * @returns {DropdownItem[]} + */ + (array, item) => [ + ...array, + (id == null ? item : { __p: String(id), __level: level, ...item }), + ...reduceItems(item[childkey], item[valuekey], level + 1) + ], + []); } this._var.source = reduceItems(list); if (this._expanded) { @@ -521,7 +510,6 @@ export class Dropdown { return item; }); this._var.allChecked = false; - source.forEach(it => delete it.__checked); if (itemlist.length === 0) { delete this._var.selectedList; if (this._var.label != null) { @@ -555,22 +543,12 @@ export class Dropdown { const source = filterSource(options.searchKeys, options.textKey, key, this.source); this._filllist(source); }); - input.addEventListener('blur', e => { - if (!(e.target instanceof HTMLInputElement)) { - return; - } - 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); } // list const list = createElement('div', 'ui-drop-list'); - list.addEventListener('scroll', e => throttle(this._onlistscroll, 10, this, list, e.target?.scrollTop), { passive: true }); + list.addEventListener('scroll', e => throttle(this._onlistscroll, 10, this, list, /** @type {Element} */(e.target)?.scrollTop), { passive: true }); if (!this.multiSelect) { list.addEventListener('click', e => { let li = e.target; @@ -731,7 +709,7 @@ export class Dropdown { const childkey = this._var.options.childKey; const allchecked = this._var.allChecked; const selectedlist = this.selectedList; - source.forEach((item, i) => { + source.forEach((item) => { const val = String(getValue(item, valuekey, textkey)); if (multiselect) { const selected = selectedlist.some(s => String(getValue(s, valuekey, textkey)) === val); @@ -742,6 +720,8 @@ export class Dropdown { const indeterminate = selectedlist.some(s => this._contains(String(getValue(s, valuekey, textkey)), item, valuekey, textkey, childkey)); if (indeterminate) { item.__checked = 2; + } else { + delete item.__checked; } } } @@ -871,15 +851,14 @@ export class Dropdown { } /** - * @param {DropdownItem[]} [source] * @returns {DropdownItem[]} */ - _getSelectedList(source) { + _getSelectedList() { const valuekey = this._var.options.valueKey; const textkey = this._var.options.textKey; /** @type {DropdownItem[]} */ const list = []; - source ??= this.source; + const source = this._var.currentSource ?? this.source; source.filter(it => it.__p == null).forEach(it => { const key = String(getValue(it, valuekey, textkey)); if (it.__checked === 1) { @@ -1013,12 +992,8 @@ export class Dropdown { static resolve(dom = document.body, trigger) { const selects = dom.querySelectorAll('select'); for (let sel of selects) { - const source = [...sel.children].map( - /** - * @param {HTMLOptionElement} it - * @returns {DropdownItem} - */ - it => ({ value: it.value, text: it.innerText })); + const source = /** @type {Array} */ ([...sel.children]).map( + it => /** @type {DropdownItem} */({ value: it.value, text: it.innerText })); const drop = new Dropdown({ selected: sel.value, disabled: sel.disabled, diff --git a/lib/ui/dropdown.types.d.ts b/lib/ui/dropdown.types.d.ts new file mode 100644 index 0000000..80f85ed --- /dev/null +++ b/lib/ui/dropdown.types.d.ts @@ -0,0 +1,50 @@ +import type { GetTextCallback } from '../types'; + +/** 下拉列表参数对象 */ +interface DropdownOptions { + /** 文本关键字 */ + textKey?: string; + /** 值关键字 */ + valueKey?: string; + /** 源码显示的关键字 */ + htmlKey?: string; + /** 子集合的关键字 */ + childKey?: string; + /** 最大输入长度 */ + maxLength?: number; + /** + * 模板创建函数 + * @param this 当前Dropdown + * @param it 下拉项目 + * @returns 返回渲染的字符串 + */ + htmlTemplate?: (this: Dropdown, it: DropdownItem) => string; + /** 是否允许多选 */ + multiSelect?: boolean; + /** 选中值 */ + selected?: string; + /** 选中的数组 */ + selectedList?: string[]; + /** 是否禁用 */ + disabled?: boolean; + /** 是否支持输入 */ + input?: boolean; + /** 是否支持搜索 */ + search?: boolean; + /** 搜索的关键字数组 */ + searchKeys?: string[]; + /** 搜索提示文本,默认值取语言资源 `searchHolder` "Search..." */ + searchPlaceholder?: string; + /** 焦点索引 */ + tabIndex?: number; + /** 输入框的提示文本 */ + placeholder?: string; + /** 是否固定为向下展开 */ + slideFixed?: boolean; + /** 父元素,默认添加到头元素之后 */ + wrapper?: HTMLElement; + /** 是否忽略 All 选项 */ + ignoreAll?: boolean; + /** 获取文本的代理函数 */ + getText?: GetTextCallback; +} diff --git a/lib/ui/icon.js b/lib/ui/icon.js index 7de34f2..ad3f4fc 100644 --- a/lib/ui/icon.js +++ b/lib/ui/icon.js @@ -17,12 +17,11 @@ function createUse(type, id) { const path = c.path || (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) { id = dict[id]; } - use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', `${path}fonts/${type}.svg${ver}#${id}`); + use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', `${path}fonts/${type}.svg#${id}`); return use; } diff --git a/lib/ui/popup.js b/lib/ui/popup.js index f6f1e32..f988e72 100644 --- a/lib/ui/popup.js +++ b/lib/ui/popup.js @@ -6,8 +6,7 @@ import { createElement } from "../functions"; import { createIcon, changeIcon } from "./icon"; import { requestAnimationFrame } from "../ui"; -/** @typedef {import('../types').PopupOptions} PopupOptions */ -/** @typedef {import('../types').PopupRectParam} PopupRectParam */ +/** @import { PopupOptions, PopupRectParam } from '../types' */ const ResizeMods = { right: 1, diff --git a/lib/utility.js b/lib/utility.js index 71ad8d6..505b1e4 100644 --- a/lib/utility.js +++ b/lib/utility.js @@ -5,6 +5,29 @@ import { nullOrEmpty, contains, endsWith, padStart, formatUrl, escapeHtml, escap const g = typeof window !== 'undefined' ? window : self; +/** @import { MarkRequired } from './types' */ + +/** + * 合并参数 + * @template {object} T 可选参数类型 + * @template {Partial} D 部分缺省值的选项类型 + * @param {D} defaults 默认参数 + * @param {T} opts 传入的待合并参数 + * @returns {MarkRequired>} 返回已合并的拥有默认值的参数 + */ +function mergeOptions(defaults, opts) { + /** @type {Record} */ + const result = { ...defaults }; + if (opts) { + for (const [key, value] of Object.entries(opts)) { + if (value !== undefined) { + result[key] = value; + } + } + } + return /** @type {MarkRequired>} */ (result); +} + /** * @param {any} n * @returns {n is number} @@ -157,6 +180,7 @@ export { isPositive, isMobile, // functions + mergeOptions, throttle, debounce, truncate, diff --git a/lib/utility/lgres.js b/lib/utility/lgres.js index 49d691d..8741c42 100644 --- a/lib/utility/lgres.js +++ b/lib/utility/lgres.js @@ -2,7 +2,7 @@ import { getCookie } from "./cookie"; import { get } from "./request"; import { nullOrEmpty } from "./strings"; -/** @typedef {import('../types').LanguageResource} LanguageResource */ +/** @import { LanguageResource } from '../types' */ const g = typeof window !== 'undefined' ? window : self; diff --git a/package.json b/package.json index 611f3aa..7291687 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@soft-qr/ui-lib", - "version": "1.0.12", + "version": "1.1.5", "publishConfig": { "registry": "https://git.soft.qr/api/packages/soft-qr/npm/" },