From ce2dfdecb230d851b2dbc85fe233f39dabf429d5 Mon Sep 17 00:00:00 2001 From: MAEDA Go Date: Thu, 18 Jun 2026 17:34:44 +0900 Subject: [PATCH] Cache mention autocomplete responses to avoid redundant requests --- app/assets/javascripts/application-legacy.js | 47 ++++++++++++++++++-- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/app/assets/javascripts/application-legacy.js b/app/assets/javascripts/application-legacy.js index 211dd3e0a..feabd4412 100644 --- a/app/assets/javascripts/application-legacy.js +++ b/app/assets/javascripts/application-legacy.js @@ -1347,6 +1347,27 @@ function inlineAutoComplete(element) { xhr.send(); }, 200); + const autocompleteSearchCache = {}; + const latestAutocompleteSearchQuery = {}; + + const cachedAutocompleteSearch = function(url, text) { + const cache = autocompleteSearchCache[url]; + + if (!cache) { + return null; + } + + if (text === cache.query) { + return cache.results; + } + + if (cache.query && text.startsWith(cache.query) && cache.results.length === 0) { + return []; + } + + return null; + } + const tribute = new Tribute({ collection: [ { @@ -1404,11 +1425,29 @@ function inlineAutoComplete(element) { }, values: function (text, cb) { const url = getDataSource('users'); - if (url) { - remoteSearch(url + encodeURIComponent(text), function (users) { - return cb(users); - }); + + if (!url) { + return cb([]); + } + + const cachedUsers = cachedAutocompleteSearch(url, text); + if (cachedUsers !== null) { + return cb(cachedUsers); } + + latestAutocompleteSearchQuery[url] = text; + + remoteSearch(url + encodeURIComponent(text), function (users) { + if (latestAutocompleteSearchQuery[url] !== text) { + return; + } + + autocompleteSearchCache[url] = { + query: text, + results: users + }; + return cb(users); + }); }, menuItemTemplate: function (user) { return sanitizeHTML(user.original.name); -- 2.50.1