This commit is contained in:
lchen committed 2026-11-23 10:41:08 +08:00
1 parent a0fe4cb7b1
commit 5cb14ffd44
11 files changed
+157 -96

No files matched your search

+1
View File
@@ -28,3 +28,4 @@ desktop.ini
docs docs
jsdoc jsdoc
package-lock.json package-lock.json
@*.cmd
+6 -3
View File
@@ -9,11 +9,14 @@ export interface OptionParamBase {
getText?: GetTextCallback; getText?: GetTextCallback;
} }
export type MarkRequired<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
export interface NotifyOption { export interface NotifyOption {
message: string | HTMLElement; message: string | Node;
parent?: HTMLElement; parent?: HTMLElement;
title?: string; title?: string;
type?: "success" | "warning" | "error"; type?: "success" | "warning" | "error";
icon?: string;
persistent?: boolean; persistent?: boolean;
timeout?: number; timeout?: number;
onDismissed?: (auto?: boolean) => void; onDismissed?: (auto?: boolean) => void;
@@ -147,9 +150,9 @@ export interface CheckboxOptions {
/** 图片高度 */ /** 图片高度 */
imageHeight?: number; imageHeight?: number;
/** 选中时显示的元素 */ /** 选中时显示的元素 */
checkedNode?: HTMLElement; checkedNode?: Element;
/** 未选中时显示的元素 */ /** 未选中时显示的元素 */
uncheckedNode?: HTMLElement; uncheckedNode?: Element;
/** 自定义 html 属性 */ /** 自定义 html 属性 */
customAttributes?: { [key: string]: string }; customAttributes?: { [key: string]: string };
/** /**
+27 -17
View File
@@ -113,23 +113,22 @@ function notify(opts) {
timer && clearTimeout(timer); timer && clearTimeout(timer);
closeNotify(wrapper, opts?.onDismissed); closeNotify(wrapper, opts?.onDismissed);
}); });
let type; const typeClass = opts?.type ?? 'success';
let typeClass; let fontIcon = opts?.icon;
switch (opts?.type) { if (fontIcon == null) {
case 'warning': switch (typeClass) {
type = 'exclamation-circle'; case 'warning':
typeClass = 'warning'; fontIcon = 'exclamation-circle';
break; break;
case 'error': case 'error':
type = 'times-circle'; fontIcon = 'times-circle';
typeClass = 'error'; break;
break; default:
default: fontIcon = 'check-circle';
type = opts?.type ?? 'check-circle'; break;
typeClass = 'success'; }
break;
} }
const icon = createIcon('fa-solid', type); const icon = createIcon('fa-solid', fontIcon);
icon.classList.add('ui-notify-type', typeClass); icon.classList.add('ui-notify-type', typeClass);
const title = opts?.title; const title = opts?.title;
const wrapper = createElement('div', 'ui-notify', const wrapper = createElement('div', 'ui-notify',
@@ -153,7 +152,18 @@ function notify(opts) {
closeNotify(wrapper, opts?.onDismissed, true); closeNotify(wrapper, opts?.onDismissed, true);
}, opts?.timeout || 3000); }, opts?.timeout || 3000);
} }
(opts?.parent ?? document.body).appendChild(wrapper); const parent = opts?.parent ?? document.body;
let top = 0;
(/** @type {NodeListOf<HTMLElement>} */ (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); setTimeout(() => wrapper.classList.add('active'), 10);
return wrapper; return wrapper;
} }
+1 -1
View File
@@ -3,7 +3,7 @@ import { createElement } from "../functions";
import { createIcon } from "./icon"; import { createIcon } from "./icon";
import { isPositive, nullOrEmpty } from '../utility'; import { isPositive, nullOrEmpty } from '../utility';
/** @typedef {import('../types').CheckboxOptions} CheckboxOptions */ /** @import { CheckboxOptions } from '../types' */
/** /**
* @private * @private
+44 -69
View File
@@ -1,16 +1,29 @@
import './css/dropdown.scss'; import './css/dropdown.scss';
import { r as lang } from "../utility/lgres"; import { r as lang } from "../utility/lgres";
import { contains, nullOrEmpty } from "../utility/strings"; import { contains, nullOrEmpty } from "../utility/strings";
import { global, isPositive, throttle } from "../utility"; import { mergeOptions, global, isPositive, throttle } from "../utility";
import { createElement } from "../functions"; import { createElement } from "../functions";
import { createCheckbox } from "./checkbox"; import { createCheckbox } from "./checkbox";
import { createIcon } from "./icon" import { createIcon } from "./icon"
/** @import { DropdownOptions } from './dropdown.types' */
/** @satisfies {Partial<DropdownOptions>} */
const DEFAULT_OPTIONS = {
textKey: 'text',
valueKey: 'value',
htmlKey: 'html',
childKey: 'children',
maxLength: 500
};
/** @typedef {import('../types').MarkRequired<DropdownOptions, keyof typeof DEFAULT_OPTIONS>} ResolvedDropdownOptions */
const SymbolDropdown = Symbol.for('ui-dropdown'); const SymbolDropdown = Symbol.for('ui-dropdown');
const DropdownItemHeight = 30; const DropdownItemHeight = 30;
let r = lang; let r = lang;
let dropdownGlobal = global[SymbolDropdown]; let dropdownGlobal = /** @type {Record<symbol, any | undefined>} */ (/** @type {unknown} */ (global))[SymbolDropdown];
if (dropdownGlobal == null) { if (dropdownGlobal == null) {
// init // 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 => { document.addEventListener('mousedown', e => {
let parent = e.target; let parent = e.target;
@@ -124,31 +141,6 @@ function getValue(it, valuekey, textkey) {
return value; 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 * @typedef DropdownItemBase
@@ -165,14 +157,8 @@ function getValue(it, valuekey, textkey) {
export class Dropdown { export class Dropdown {
_var = { _var = {
/** @type {DropdownOptions} */ /** @type {ResolvedDropdownOptions} */
options: { options: DEFAULT_OPTIONS,
textKey: 'text',
valueKey: 'value',
htmlKey: 'html',
childKey: 'children',
maxLength: 500
},
/** @type {HTMLDivElement | undefined} */ /** @type {HTMLDivElement | undefined} */
wrapper: undefined, wrapper: undefined,
/** @type {HTMLDivElement | undefined} */ /** @type {HTMLDivElement | undefined} */
@@ -210,14 +196,9 @@ export class Dropdown {
*/ */
constructor(options) { constructor(options) {
if (options != null) { if (options != null) {
this._var.options = options; this._var.options = mergeOptions(DEFAULT_OPTIONS, options);
} }
const opts = this._var.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; const getText = opts.getText;
if (typeof getText === 'function') { if (typeof getText === 'function') {
r = getText; r = getText;
@@ -398,11 +379,19 @@ export class Dropdown {
if (!Array.isArray(list)) { if (!Array.isArray(list)) {
return []; return [];
} }
return list.reduce((array, item) => [ return list.reduce(
...array, /**
(id == null ? item : { __p: String(id), __level: level, ...item }), * @private
...reduceItems(item[childkey], item[valuekey], level + 1) * @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); this._var.source = reduceItems(list);
if (this._expanded) { if (this._expanded) {
@@ -521,7 +510,6 @@ export class Dropdown {
return item; return item;
}); });
this._var.allChecked = false; this._var.allChecked = false;
source.forEach(it => delete it.__checked);
if (itemlist.length === 0) { if (itemlist.length === 0) {
delete this._var.selectedList; delete this._var.selectedList;
if (this._var.label != null) { if (this._var.label != null) {
@@ -555,22 +543,12 @@ export class Dropdown {
const source = filterSource(options.searchKeys, options.textKey, key, this.source); const source = filterSource(options.searchKeys, options.textKey, key, this.source);
this._filllist(source); this._filllist(source);
}); });
input.addEventListener('blur', e => {
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')); search.append(input, createIcon('fa-light', 'search'));
panel.appendChild(search); panel.appendChild(search);
} }
// list // list
const list = createElement('div', 'ui-drop-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) { if (!this.multiSelect) {
list.addEventListener('click', e => { list.addEventListener('click', e => {
let li = e.target; let li = e.target;
@@ -731,7 +709,7 @@ export class Dropdown {
const childkey = this._var.options.childKey; const childkey = this._var.options.childKey;
const allchecked = this._var.allChecked; const allchecked = this._var.allChecked;
const selectedlist = this.selectedList; const selectedlist = this.selectedList;
source.forEach((item, i) => { source.forEach((item) => {
const val = String(getValue(item, valuekey, textkey)); const val = String(getValue(item, valuekey, textkey));
if (multiselect) { if (multiselect) {
const selected = selectedlist.some(s => String(getValue(s, valuekey, textkey)) === val); 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)); const indeterminate = selectedlist.some(s => this._contains(String(getValue(s, valuekey, textkey)), item, valuekey, textkey, childkey));
if (indeterminate) { if (indeterminate) {
item.__checked = 2; item.__checked = 2;
} else {
delete item.__checked;
} }
} }
} }
@@ -871,15 +851,14 @@ export class Dropdown {
} }
/** /**
* @param {DropdownItem[]} [source]
* @returns {DropdownItem[]} * @returns {DropdownItem[]}
*/ */
_getSelectedList(source) { _getSelectedList() {
const valuekey = this._var.options.valueKey; const valuekey = this._var.options.valueKey;
const textkey = this._var.options.textKey; const textkey = this._var.options.textKey;
/** @type {DropdownItem[]} */ /** @type {DropdownItem[]} */
const list = []; const list = [];
source ??= this.source; const source = this._var.currentSource ?? this.source;
source.filter(it => it.__p == null).forEach(it => { source.filter(it => it.__p == null).forEach(it => {
const key = String(getValue(it, valuekey, textkey)); const key = String(getValue(it, valuekey, textkey));
if (it.__checked === 1) { if (it.__checked === 1) {
@@ -1013,12 +992,8 @@ export class Dropdown {
static resolve(dom = document.body, trigger) { static resolve(dom = document.body, trigger) {
const selects = dom.querySelectorAll('select'); const selects = dom.querySelectorAll('select');
for (let sel of selects) { for (let sel of selects) {
const source = [...sel.children].map( const source = /** @type {Array<HTMLOptionElement>} */ ([...sel.children]).map(
/** it => /** @type {DropdownItem} */({ value: it.value, text: it.innerText }));
* @param {HTMLOptionElement} it
* @returns {DropdownItem}
*/
it => ({ value: it.value, text: it.innerText }));
const drop = new Dropdown({ const drop = new Dropdown({
selected: sel.value, selected: sel.value,
disabled: sel.disabled, disabled: sel.disabled,
+50
View File
@@ -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;
}
+1 -2
View File
@@ -17,12 +17,11 @@ function createUse(type, id) {
const path = c.path || const path = c.path ||
(typeof global._network !== 'undefined' ? global._network.root : (typeof global._network !== 'undefined' ? global._network.root :
(typeof global._net !== 'undefined' ? global._net.root : '')); (typeof global._net !== 'undefined' ? global._net.root : ''));
const ver = c.resver == null ? '' : `?${c.resver}`;
const use = document.createElementNS(svgns, 'use'); const use = document.createElementNS(svgns, 'use');
if (id?.length === 1 && id.charCodeAt(0) > 0xf000) { if (id?.length === 1 && id.charCodeAt(0) > 0xf000) {
id = dict[id]; 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; return use;
} }
+1 -2
View File
@@ -6,8 +6,7 @@ import { createElement } from "../functions";
import { createIcon, changeIcon } from "./icon"; import { createIcon, changeIcon } from "./icon";
import { requestAnimationFrame } from "../ui"; import { requestAnimationFrame } from "../ui";
/** @typedef {import('../types').PopupOptions} PopupOptions */ /** @import { PopupOptions, PopupRectParam } from '../types' */
/** @typedef {import('../types').PopupRectParam} PopupRectParam */
const ResizeMods = { const ResizeMods = {
right: 1, right: 1,
+24
View File
@@ -5,6 +5,29 @@ import { nullOrEmpty, contains, endsWith, padStart, formatUrl, escapeHtml, escap
const g = typeof window !== 'undefined' ? window : self; const g = typeof window !== 'undefined' ? window : self;
/** @import { MarkRequired } from './types' */
/**
* 合并参数
* @template {object} T 可选参数类型
* @template {Partial<T>} D 部分缺省值的选项类型
* @param {D} defaults 默认参数
* @param {T} opts 传入的待合并参数
* @returns {MarkRequired<T, Extract<keyof D, keyof T>>} 返回已合并的拥有默认值的参数
*/
function mergeOptions(defaults, opts) {
/** @type {Record<string, unknown>} */
const result = { ...defaults };
if (opts) {
for (const [key, value] of Object.entries(opts)) {
if (value !== undefined) {
result[key] = value;
}
}
}
return /** @type {MarkRequired<T, Extract<keyof D, keyof T>>} */ (result);
}
/** /**
* @param {any} n * @param {any} n
* @returns {n is number} * @returns {n is number}
@@ -157,6 +180,7 @@ export {
isPositive, isPositive,
isMobile, isMobile,
// functions // functions
mergeOptions,
throttle, throttle,
debounce, debounce,
truncate, truncate,
+1 -1
View File
@@ -2,7 +2,7 @@ import { getCookie } from "./cookie";
import { get } from "./request"; import { get } from "./request";
import { nullOrEmpty } from "./strings"; import { nullOrEmpty } from "./strings";
/** @typedef {import('../types').LanguageResource} LanguageResource */ /** @import { LanguageResource } from '../types' */
const g = typeof window !== 'undefined' ? window : self; const g = typeof window !== 'undefined' ? window : self;
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@soft-qr/ui-lib", "name": "@soft-qr/ui-lib",
"version": "1.0.12", "version": "1.1.5",
"publishConfig": { "publishConfig": {
"registry": "https://git.soft.qr/api/packages/soft-qr/npm/" "registry": "https://git.soft.qr/api/packages/soft-qr/npm/"
}, },