exports: [
  ".",
  "./global",
  "./style.css",
  "./types",
  "./utility"
]
This commit is contained in:
lchen committed 2026-11-18 13:44:06 +08:00
1 parent 934cd61c49
commit a0fe4cb7b1
3 files changed
+147 -88

No files matched your search

+138 -86
View File
@@ -42,7 +42,7 @@ if (dropdownGlobal == null) {
document.addEventListener('mousedown', e => {
let parent = e.target;
while (parent != null) {
while (parent instanceof Element) {
if (parent.classList.contains('ui-drop-box')) {
e.stopPropagation();
return;
@@ -60,6 +60,9 @@ if (dropdownGlobal == null) {
*/
function selectItems(itemlist) {
const label = this._var.label;
if (label == null) {
return;
}
const template = this._var.options.htmlTemplate;
const htmlkey = this._var.options.htmlKey;
const textkey = this._var.options.textKey;
@@ -82,7 +85,7 @@ function selectItems(itemlist) {
/**
* @private
* @param {string[]} searchkeys
* @param {string[] | undefined} searchkeys
* @param {string} textkey
* @param {string} key
* @param {DropdownItem[]} source
@@ -124,25 +127,26 @@ function getValue(it, valuekey, textkey) {
/**
* 下拉列表参数对象
* @typedef DropdownOptions
* @property {string} [textKey=text] - 文本关键字
* @property {string} [valueKey=value] - 值关键字
* @property {string} [htmlKey=html] - 源码显示的关键字
* @property {string} [childKey=children] - 子集合的关键字
* @property {(this: Dropdown, it: DropdownItem) => string} [htmlTemplate] - 模板创建函数
* @property {number} [maxLength=500] - 最大输入长度
* @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 {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] 获取文本的代理函数
*/
/**
@@ -162,17 +166,23 @@ function getValue(it, valuekey, textkey) {
export class Dropdown {
_var = {
/** @type {DropdownOptions} */
options: undefined,
/** @type {HTMLDivElement} */
options: {
textKey: 'text',
valueKey: 'value',
htmlKey: 'html',
childKey: 'children',
maxLength: 500
},
/** @type {HTMLDivElement | undefined} */
wrapper: undefined,
/** @type {HTMLDivElement} */
/** @type {HTMLDivElement | undefined} */
container: undefined,
/** @type {HTMLInputElement | HTMLLabelElement} */
/** @type {HTMLInputElement | HTMLLabelElement | undefined} */
label: undefined,
allChecked: false,
/** @type {DropdownItem[]} */
/** @type {DropdownItem[] | undefined} */
source: undefined,
/** @type {DropdownItem[]} */
/** @type {DropdownItem[] | undefined} */
currentSource: undefined,
/** @type {string | undefined} */
lastSelected: undefined,
@@ -188,7 +198,7 @@ export class Dropdown {
sourceFilter;
/** @type {((list: DropdownItem[]) => void) | undefined} */
onSelectedList;
/** @type {((it: DropdownItem) => void) | undefined} */
/** @type {((it: DropdownItem | undefined) => void) | undefined} */
onSelected;
/** @type {((this: Dropdown) => void) | undefined} */
onExpanded;
@@ -196,22 +206,25 @@ export class Dropdown {
onCollapsed;
/**
* @param {DropdownOptions} options
* @param {DropdownOptions} [options]
*/
constructor(options = {}) {
options.textKey ??= 'text';
options.valueKey ??= 'value';
options.htmlKey ??= 'html';
options.childKey ??= 'children';
options.maxLength ??= 500;
constructor(options) {
if (options != null) {
this._var.options = options;
const getText = options.getText;
}
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;
} else if (typeof GetTextByKey === 'function') {
r = GetTextByKey;
} else if (typeof global.GetTextByKey === 'function') {
r = global.GetTextByKey;
}
options.searchPlaceholder ??= r('searchHolder', 'Search...');
opts.searchPlaceholder ??= r('searchHolder', 'Search...');
}
create() {
@@ -242,7 +255,7 @@ export class Dropdown {
const count = source.length;
const valuekey = this._var.options.valueKey;
const textkey = this._var.options.textKey;
let index = source?.indexOf(this._var.selected);
let index = this._var.selected == null ? -1 : source?.indexOf(this._var.selected);
if (isNaN(index) || index < -1) {
index = -1;
} else if (index >= count) {
@@ -277,12 +290,12 @@ export class Dropdown {
}
const active = this._expanded;
const label = this._var.label;
if (active && label.ownerDocument.activeElement === label) {
if (active && label?.ownerDocument?.activeElement === label) {
return;
}
this._dropdown(!active);
if (!active && typeof this.onExpanded === 'function') {
setTimeout(() => this.onExpanded(), 120);
setTimeout(this.onExpanded.bind(this), 120);
}
});
@@ -294,18 +307,21 @@ export class Dropdown {
label.autocomplete = 'off';
label.draggable = false;
options.placeholder && label.setAttribute('placeholder', options.placeholder);
isPositive(options.maxLength) && label.setAttribute('maxlength', options.maxLength);
isPositive(options.tabIndex) && label.setAttribute('tabindex', options.tabIndex);
isPositive(options.maxLength) && label.setAttribute('maxlength', String(options.maxLength));
isPositive(options.tabIndex) && label.setAttribute('tabindex', String(options.tabIndex));
label.addEventListener('input', e => {
if (!(e.target instanceof HTMLInputElement)) {
return;
}
const key = e.target.value.toLowerCase();
const source = filterSource(options.searchKeys, options.textKey, key, this.source);
this._filllist(source);
this._var.container.classList.add('active');
this._var.container?.classList?.add('active');
});
label.addEventListener('blur', e => this.select(e.target.value));
label.addEventListener('blur', e => e.target instanceof HTMLInputElement && this.select(e.target.value));
label.addEventListener('mousedown', e => this._expanded && e.stopPropagation());
} else {
isPositive(options.tabIndex) && header.setAttribute('tabindex', options.tabIndex);
isPositive(options.tabIndex) && header.setAttribute('tabindex', String(options.tabIndex));
label = createElement('label', 'ui-drop-text');
}
this._var.label = label;
@@ -336,12 +352,15 @@ export class Dropdown {
if (this._var.wrapper == null) {
return;
}
const header = this._var.wrapper.querySelector('.ui-drop-header');
if (header != null) {
if (flag) {
this._var.wrapper.querySelector('.ui-drop-header').classList.add('disabled');
header.classList.add('disabled');
} else {
this._var.wrapper.querySelector('.ui-drop-header').classList.remove('disabled');
header.classList.remove('disabled');
}
/** @type {HTMLInputElement} */
}
/** @type {HTMLInputElement | null} */
const input = this._var.wrapper.querySelector('.ui-drop-text');
if (input != null) {
input.disabled = flag;
@@ -397,7 +416,7 @@ export class Dropdown {
/**
*
* @param {string} selected
* @param {string} [selected]
* @param {boolean} [silence]
* @param {boolean} [ignoreCase]
* @returns {boolean | undefined}
@@ -418,19 +437,21 @@ export class Dropdown {
const template = this._var.options.htmlTemplate;
const htmlkey = this._var.options.htmlKey;
let item = this.source.find(it => (ignoreCase ? String(getValue(it, valuekey, textkey)).toLowerCase() : String(getValue(it, valuekey, textkey))) === selected);
if (this._var.options.input) {
const label = this._var.label;
if (label != null) {
if (label instanceof HTMLInputElement) {
if (item == null) {
item = { [valuekey]: selected };
}
this._var.label.value = selected;
label.value = selected;
} else {
const expanded = this._expanded;
if (expanded) {
this._var.container.querySelectorAll('li[data-value].selected').forEach(li => li.classList.remove('selected'));
this._var.container?.querySelectorAll('li[data-value].selected')?.forEach(li => li.classList.remove('selected'));
}
if (item == null) {
this._var.selected = null;
this._var.label.innerText = ' ';
delete this._var.selected;
label.innerText = ' ';
return false;
}
let html;
@@ -440,23 +461,29 @@ export class Dropdown {
html = item[htmlkey];
}
if (html instanceof HTMLElement) {
this._var.label.replaceChildren(html.cloneNode(true));
label.replaceChildren(html.cloneNode(true));
} else if (typeof html === 'string') {
this._var.label.innerHTML = html;
label.innerHTML = html;
} else {
let text = item[textkey];
if (nullOrEmpty(text)) {
text = ' ';
}
this._var.label.innerText = text;
label.innerText = text;
}
if (expanded) {
for (let li of this._var.container.querySelectorAll('li[data-value]')) {
if ((ignoreCase ? li.dataset.value.toLowerCase() : li.dataset.value) === selected) {
const lis = this._var.container?.querySelectorAll('li[data-value]');
if (lis != null) {
for (let li of lis) {
if (!(li instanceof HTMLLIElement)) {
continue;
}
if ((ignoreCase ? li.dataset.value?.toLowerCase() : li.dataset.value) === selected) {
li.classList.add('selected');
break;
}
}
}
// const val = selected.replace(/"/g, '\\"');
// const li = this._var.container.querySelector(`li[data-value="${val}"]`);
// if (li != null) {
@@ -464,6 +491,7 @@ export class Dropdown {
// }
}
}
}
this._var.selected = item;
if (!silence && typeof this.onSelected === 'function') {
this.onSelected(item);
@@ -496,10 +524,12 @@ export class Dropdown {
source.forEach(it => delete it.__checked);
if (itemlist.length === 0) {
delete this._var.selectedList;
if (this._var.label != null) {
this._var.label.innerText = r('none', '( None )');
}
return false;
}
this._selectList(list, silence);
this._selectList(itemlist, silence);
}
get _expanded() { return this._var.container?.classList?.contains('active') }
@@ -515,14 +545,20 @@ export class Dropdown {
const input = createElement('input');
input.type = 'text';
input.className = 'ui-input';
isPositive(options.tabIndex) && input.setAttribute('tabindex', options.tabIndex);
isPositive(options.tabIndex) && input.setAttribute('tabindex', String(options.tabIndex));
!nullOrEmpty(options.searchPlaceholder) && input.setAttribute('placeholder', options.searchPlaceholder);
input.addEventListener('input', e => {
if (!(e.target instanceof HTMLInputElement)) {
return;
}
const key = e.target.value.toLowerCase();
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);
@@ -534,20 +570,22 @@ export class Dropdown {
}
// 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, e.target?.scrollTop), { passive: true });
if (!this.multiSelect) {
list.addEventListener('click', e => {
let li = e.target;
while (li.tagName !== 'LI') {
while (li instanceof Element && li.tagName !== 'LI') {
li = li.parentElement;
if (li == null) {
return;
}
}
if (li instanceof HTMLElement) {
const value = li.dataset.value;
if (this.select(value) !== false) {
dropdownGlobal.clear();
}
}
});
}
panel.appendChild(list);
@@ -555,14 +593,14 @@ export class Dropdown {
if (options.wrapper instanceof HTMLElement) {
options.wrapper.appendChild(panel);
} else {
this._var.wrapper.appendChild(panel);
this._var.wrapper?.appendChild(panel);
}
}
if (flag) {
let source = this.source;
if (!options.input && options.search) {
const search = panel.querySelector('.ui-drop-search > input');
if (!nullOrEmpty(search?.value)) {
if (search instanceof HTMLInputElement && !nullOrEmpty(search?.value)) {
source = filterSource(options.searchKeys, options.textKey, search.value, source);
}
}
@@ -570,7 +608,9 @@ export class Dropdown {
// slide direction
if (!options.slideFixed) {
const parent = options.wrapper ?? document.body;
/** @type {HTMLElement | null | undefined} */
let p = this._var.wrapper;
if (p != null) {
panel.style.minWidth = `${p.offsetWidth}px`;
const headerHeight = p.offsetHeight;
let top = p.offsetTop + headerHeight;
@@ -583,7 +623,7 @@ export class Dropdown {
}
p = this._var.wrapper;
if (p !== parent) {
while ((p = p.offsetParent) != null && p !== parent) {
while ((p = /** @type {HTMLElement} */(p?.offsetParent)) != null && p !== parent) {
top += p.offsetTop;
left += p.offsetLeft;
}
@@ -605,9 +645,10 @@ export class Dropdown {
panel.classList.remove('slide-up');
}
}
}
panel.classList.add('active');
this._var.dropTop = 0;
panel.querySelector('.ui-drop-list').dispatchEvent(new Event('scroll'));
panel.querySelector('.ui-drop-list')?.dispatchEvent(new Event('scroll'));
} else {
panel.classList.remove('active');
}
@@ -636,25 +677,32 @@ export class Dropdown {
this._var.dropTop = top;
const startIndex = top / DropdownItemHeight;
let array = this._var.currentSource;
if (array != null) {
if (startIndex + 20 < array.length) {
array = array.slice(startIndex, startIndex + 20);
} else {
array = array.slice(-20);
}
/** @type {HTMLDivElement} */
/** @type {HTMLDivElement | null} */
const content = list.querySelector('.drop-content');
if (content != null) {
content.replaceChildren();
this._dofilllist(content, array);
content.style.top = `${top + offset}px`;
}
}
}
}
/**
*
* @param {DropdownItem[]} source
*/
_filllist(source) {
const list = this._var.container.querySelector('.ui-drop-list');
const list = this._var.container?.querySelector('.ui-drop-list');
if (list == null) {
return;
}
list.replaceChildren();
const height = source.length * DropdownItemHeight;
this._var.dropHeight = height;
@@ -669,7 +717,7 @@ export class Dropdown {
label: r('allItem', '( All )'),
checked: this._var.allChecked,
customAttributes: { 'isall': '1' },
onchange: e => this._triggerselect(e.target)
onchange: e => this._triggerselect(/** @type {HTMLInputElement} */(e.target))
})
)
);
@@ -754,7 +802,7 @@ export class Dropdown {
const li = createElement('li');
li.dataset.value = val;
li.title = item[textkey];
if (!isNaN(item.__level) && item.__level > 0) {
if (isPositive(item.__level)) {
li.style.marginLeft = `${item.__level * 24}px`;
}
const wrapper = createElement('span', 'li-wrapper',
@@ -803,7 +851,7 @@ export class Dropdown {
'class': 'dataitem',
'data-value': val
},
onchange: e => this._triggerselect(e.target, item)
onchange: e => this._triggerselect(/** @type {HTMLInputElement} */(e.target), item)
});
wrapper.appendChild(box);
} else {
@@ -829,6 +877,7 @@ export class Dropdown {
_getSelectedList(source) {
const valuekey = this._var.options.valueKey;
const textkey = this._var.options.textKey;
/** @type {DropdownItem[]} */
const list = [];
source ??= this.source;
source.filter(it => it.__p == null).forEach(it => {
@@ -848,24 +897,25 @@ export class Dropdown {
/**
*
* @param {HTMLInputElement} checkbox
* @param {DropdownItem} item
* @param {DropdownItem} [item]
*/
_triggerselect(checkbox, item) {
/** @type {DropdownItem[]} */
let list;
const valuekey = this._var.options.valueKey;
const textkey = this._var.options.textKey;
const childkey = this._var.options.childKey;
const source = this.source;
if (checkbox.getAttribute('isall') === '1') {
if (item == null || checkbox.getAttribute('isall') === '1') {
const allchecked = this._var.allChecked = checkbox.checked;
/** @type {NodeListOf<HTMLInputElement>} */
const boxes = this._var.container.querySelectorAll('input.dataitem');
boxes.forEach(box => box.checked = allchecked);
/** @type {NodeListOf<HTMLInputElement> | undefined} */
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"]');
/** @type {HTMLInputElement | null | undefined} */
const all = this._var.container?.querySelector('input[isall="1"]');
const val = checkbox.dataset.value;
if (checkbox.checked) {
item.__checked = 1;
@@ -921,9 +971,9 @@ export class Dropdown {
}
}
// refresh selection
/** @type {NodeListOf<HTMLInputElement>} */
const checkboxes = this._var.container.querySelectorAll('input.dataitem');
checkboxes.forEach(c => {
/** @type {NodeListOf<HTMLInputElement> | undefined} */
const checkboxes = this._var.container?.querySelectorAll('input.dataitem');
checkboxes?.forEach(c => {
const val = c.dataset.value;
const it = source.filter(it => String(getValue(it, valuekey, textkey)) === val)[0];
if (it != null) {
@@ -942,7 +992,9 @@ export class Dropdown {
*/
_selectList(list, silence) {
if (this._var.allChecked) {
if (this._var.label != null) {
this._var.label.innerText = r('allItem', '( All )');
}
} else {
selectItems.call(this, list);
}
@@ -955,7 +1007,7 @@ export class Dropdown {
/**
*
* @param {HTMLElement} dom
* @param {(this: Dropdown, item: DropdownItem) => void} [trigger]
* @param {(this: Dropdown, item?: DropdownItem) => void} [trigger]
* @returns
*/
static resolve(dom = document.body, trigger) {
@@ -976,7 +1028,7 @@ export class Dropdown {
if (typeof trigger === 'function') {
drop.onSelected = item => trigger.call(drop, item);
}
sel.parentElement.replaceChild(drop.create(), sel);
sel.parentElement?.replaceChild(drop.create(), sel);
}
return dom;
}
+8 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@soft-qr/ui-lib",
"version": "1.0.10",
"version": "1.0.12",
"publishConfig": {
"registry": "https://git.soft.qr/api/packages/soft-qr/npm/"
},
@@ -16,7 +16,13 @@
"types": "./dist/ui.d.ts",
"import": "./dist/ui.js"
},
"./style.css": "./dist/ui.min.css"
"./global": "./dist/global.d.ts",
"./style.css": "./dist/ui.min.css",
"./types": "./dist/types.d.ts",
"./utility": {
"types": "./dist/utility.d.ts",
"import": "./dist/utility.js"
}
},
"browserslist": [
"last 1 versions",
+1
View File
@@ -81,6 +81,7 @@ for (const { name, path, rolldownOptions } of libraries) {
},
rolldownOptions,
sourcemap: true,
minify: false,
emptyOutDir: false
},
plugins: [