diff --git a/static/js/widget.js b/static/js/widget.js index 12d3527..f880f9b 100644 --- a/static/js/widget.js +++ b/static/js/widget.js @@ -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 }; })(); diff --git a/templates/fragments/_combobox_fragment.html b/templates/fragments/_combobox_fragment.html index a65f943..98d5ba8 100644 --- a/templates/fragments/_combobox_fragment.html +++ b/templates/fragments/_combobox_fragment.html @@ -24,7 +24,7 @@