From 4402521051e9816df10b98ce5f4f49399f790ed8 Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Mon, 15 Feb 2021 12:10:09 +0100 Subject: [PATCH] Highlight matching string in autosuggest entries. --- public/js/autosuggest.js | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/public/js/autosuggest.js b/public/js/autosuggest.js index 22a36aa2..46407c4d 100644 --- a/public/js/autosuggest.js +++ b/public/js/autosuggest.js @@ -116,22 +116,33 @@ class AutoSuggest { fillContainer(response) { this.selectedIndex = 0; + let query = this.input.value.trim().replace(/[\-\[\]{}()*+?.,\\\/^\$|#]/g, ' '); + let query_tokens = query.split(/ +/).sort((a,b) => a.length - b.length); + response.items.forEach((item, i) => { let node = document.createElement('li'); - let text = document.createTextNode(item.label); + node.innerHTML = this.highlightMatches(query_tokens, item.label); node.jsondata = item; node.addEventListener('click', event => { this.appendCallback(event.target.jsondata); this.closeContainer(); this.clearInput(); }); - node.appendChild(text); this.container.appendChild(node); if (this.container.children.length === 1) { node.className = 'selected'; } }); }; + + highlightMatches(query_tokens, item) { + let itemTokens = item.split(/ +/); + let queryTokens = new RegExp('(' + query_tokens.join('\|') + ')', 'i'); + itemTokens.forEach((token, index) => { + item = item.replace(token, token.replace(queryTokens, ($1, match) => '' + match + '')); + }); + return item; + }; } class TagAutoSuggest extends AutoSuggest {