Refactor filtering allowing to link search results via URL hash

This commit is contained in:
Andrea Cardaci 2018-05-29 11:50:36 +02:00
parent b457967d07
commit 125f410e01
2 changed files with 40 additions and 18 deletions

View File

@ -23,23 +23,20 @@
</div> </div>
<script> <script>
var searchBox = document.querySelector('#bin-search'); function filter(query) {
var searchMessage = document.querySelector('#search-message'); // consistently update URL and search box
searchMessage.style.display = 'none'; var searchBox = document.getElementById('bin-search');
searchBox.value = query;
location.hash = query;
// ensure height during filtering // determine the query type
var binTableWrapper = document.querySelector('#bin-table-wrapper');
binTableWrapper.style.height = binTableWrapper.clientHeight + 'px';
searchBox.addEventListener('input', function () {
var query = searchBox.value.toLowerCase().trim();
var queryType = query[0]; var queryType = query[0];
var noResults = true;
if (queryType === '/') { if (queryType === '/') {
query = query.slice(1); query = query.slice(1);
} }
// filter rows
var noResults = true;
document.querySelectorAll('#bin-table tbody tr').forEach(function (row) { document.querySelectorAll('#bin-table tbody tr').forEach(function (row) {
var binName = row.children[0].firstElementChild.innerText.toLowerCase(); var binName = row.children[0].firstElementChild.innerText.toLowerCase();
var functions = row.children[1].firstElementChild.innerText.toLowerCase(); var functions = row.children[1].firstElementChild.innerText.toLowerCase();
@ -53,9 +50,25 @@
} }
}); });
searchMessage.style.display = noResults ? '' : 'none'; // update the search message visibility
var searchMessage = document.getElementById('search-message');
searchMessage.style.display = noResults ? 'initial' : 'none';
}
(function () {
var searchBox = document.getElementById('bin-search');
// ensure height during filtering
var binTableWrapper = document.getElementById('bin-table-wrapper');
binTableWrapper.style.height = binTableWrapper.clientHeight + 'px';
// handle user input
searchBox.addEventListener('input', function () {
var query = searchBox.value.toLowerCase().trim();
filter(query);
}); });
// focus search box on keydown
addEventListener('keydown', function (event) { addEventListener('keydown', function (event) {
if (event.key.toLowerCase().match(/^[\/a-z]$/) && if (event.key.toLowerCase().match(/^[\/a-z]$/) &&
!(event.ctrlKey || event.altKey || event.metaKey)) { !(event.ctrlKey || event.altKey || event.metaKey)) {
@ -63,4 +76,12 @@
} }
}); });
// filter on load according to the URL
var query = decodeURIComponent(location.hash.slice(1));
filter(query);
if (query) {
searchBox.value = query;
searchBox.focus();
}
})();
</script> </script>

View File

@ -95,6 +95,7 @@ h2, h3, h4, h5, h5 {
} }
#search-message { #search-message {
display: none;
text-align: center; text-align: center;
padding: 1em; padding: 1em;
} }