Refactor ComboBoxWidget; enhance createOption and sortOptions functions, update onAdd parameter in render_combobox macro for improved usability and maintainability

This commit is contained in:
Yaro Kasear 2025-06-20 11:55:36 -05:00
parent b182e30c43
commit 3c9806bd34
3 changed files with 62 additions and 19 deletions

View file

@ -1,11 +1,28 @@
console.log('ComboBoxWidget loaded');
const ComboBoxWidget = (() => {
let tempIdCounter = -1;
function createOption(text, value = null) {
const option = document.createElement('option');
option.textContent = text;
option.value = value ?? (tempIdCounter--);
return option;
}
function sortOptions(selectElement) {
const sorted = Array.from(selectElement.options)
.sort((a, b) => a.text.localeCompare(b.text));
selectElement.innerHTML = '';
sorted.forEach(option => selectElement.appendChild(option));
}
function initComboBox(ns, config = {}) {
const input = document.querySelector(`#${ns}-input`);
const list = document.querySelector(`#${ns}-list`);
const addBtn = document.querySelector(`#${ns}-add`);
const removeBtn = document.querySelector(`#${ns}-remove`);
let currentlyEditing = null;
let tempIdCounter = -1;
if (!input || !list || !addBtn || !removeBtn) {
console.warn(`ComboBoxWidget: Missing elements for namespace '${ns}'`);
@ -58,15 +75,12 @@ const ComboBoxWidget = (() => {
}
currentlyEditing = null;
} else {
const option = document.createElement('option');
option.textContent = newItem;
option.value = tempIdCounter--;
if (config.onAdd) {
config.onAdd(option);
config.onAdd(newItem, list, createOption);
} else {
const option = createOption(newItem);
list.appendChild(option);
}
list.appendChild(option);
}
input.value = '';
@ -93,16 +107,11 @@ const ComboBoxWidget = (() => {
removeBtn.disabled = true;
updateAddButtonIcon();
});
function sortOptions(selectElement) {
const sorted = Array.from(selectElement.options)
.sort((a, b) => a.text.localeCompare(b.text));
selectElement.innerHTML = '';
sorted.forEach(option => selectElement.appendChild(option));
}
}
return {
initComboBox
initComboBox,
createOption,
sortOptions
};
})();