From 3523ec334df30216bbe157c7ceefd64697034857 Mon Sep 17 00:00:00 2001 From: Wolfsblvt Date: Mon, 5 Aug 2024 01:06:37 +0200 Subject: [PATCH] Improve performance on fancy key selector init --- public/scripts/utils.js | 14 +++++++++----- public/scripts/world-info.js | 5 +++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/public/scripts/utils.js b/public/scripts/utils.js index adb29dd0c..011c861a7 100644 --- a/public/scripts/utils.js +++ b/public/scripts/utils.js @@ -1728,20 +1728,24 @@ export function select2ModifyOptions(element, items, { select = false, changeEve /** @type {Select2Option[]} */ const dataItems = items.map(x => typeof x === 'string' ? { id: getSelect2OptionId(x), text: x } : x); - const existingValues = []; + const optionsToSelect = []; + const newOptions = []; + dataItems.forEach(item => { // Set the value, creating a new option if necessary if (element.find('option[value=\'' + item.id + '\']').length) { - if (select) existingValues.push(item.id); + if (select) optionsToSelect.push(item.id); } else { // Create a DOM Option and optionally pre-select by default var newOption = new Option(item.text, item.id, select, select); // Append it to the select - element.append(newOption); - if (select) element.trigger('change', changeEventArgs); + newOptions.push(newOption); + if (select) optionsToSelect.push(item.id); } - if (existingValues.length) element.val(existingValues).trigger('change', changeEventArgs); }); + + element.append(newOptions); + if (optionsToSelect.length) element.val(optionsToSelect).trigger('change', changeEventArgs); } /** diff --git a/public/scripts/world-info.js b/public/scripts/world-info.js index 1de1cd419..dc58a0f0b 100644 --- a/public/scripts/world-info.js +++ b/public/scripts/world-info.js @@ -2293,6 +2293,9 @@ function getWorldEntry(name, data, entry) { } if (isFancyInput) { + // First initialize existing values as options, before initializing select2, to speed up performance + select2ModifyOptions(input, entry[entryPropName], { select: true, changeEventArgs: { skipReset: true, noSave: true } }); + input.select2({ ajax: dynamicSelect2DataViaAjax(() => worldEntryKeyOptionsCache), tags: true, @@ -2334,8 +2337,6 @@ function getWorldEntry(name, data, entry) { input.next('span.select2-container').find('textarea') .val(key).trigger('input'); }, { openDrawer: true }); - - select2ModifyOptions(input, entry[entryPropName], { select: true, changeEventArgs: { skipReset: true, noSave: true } }); } else { // Compatibility with mobile devices. On mobile we need a text input field, not a select option control, so we need its own event handlers