add basic keyboard support

main
Tomasz Borychowski 2021-02-14 15:50:53 +00:00 committed by Ben Busby
parent 3ed0cf02bf
commit 5538ac862e
3 changed files with 52 additions and 2 deletions

View File

@ -60,3 +60,9 @@ header {
margin: 15px; margin: 15px;
display: block; display: block;
} }
#main>div:focus-within {
border-radius: 8px;
box-shadow: 0 0 6px 1px #2375e8;
}

43
app/static/js/keyboard.js Normal file
View File

@ -0,0 +1,43 @@
(function () {
let searchBar, results;
const keymap = {
ArrowUp: goUp,
ArrowDown: goDown,
k: goUp,
j: goDown,
'/': focusSearch,
};
let activeIdx = -1;
document.addEventListener('DOMContentLoaded', () => {
searchBar = document.querySelector('#search-bar');
results = document.querySelectorAll('#main>div>div>div>a');
});
document.addEventListener('keydown', (e) => {
if (typeof keymap[e.key] === 'function') {
e.preventDefault();
keymap[e.key]();
}
});
function goUp () {
if (activeIdx > 0) focusResult(activeIdx - 1);
else focusSearch();
}
function goDown () {
if (activeIdx < results.length - 1) focusResult(activeIdx + 1);
}
function focusResult (idx) {
activeIdx = idx;
results[activeIdx].scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
results[activeIdx].focus();
}
function focusSearch () {
activeIdx = -1;
searchBar.focus();
}
}());

View File

@ -5,8 +5,6 @@
<link rel="search" href="opensearch.xml" type="application/opensearchdescription+xml" title="Whoogle Search"> <link rel="search" href="opensearch.xml" type="application/opensearchdescription+xml" title="Whoogle Search">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="no-referrer"> <meta name="referrer" content="no-referrer">
<script type="text/javascript" src="static/js/autocomplete.js"></script>
<script type="text/javascript" src="static/js/utils.js"></script>
<link rel="stylesheet" href="static/css/{{ 'search-dark' if dark_mode else 'search' }}.css"> <link rel="stylesheet" href="static/css/{{ 'search-dark' if dark_mode else 'search' }}.css">
<link rel="stylesheet" href="static/css/header.css"> <link rel="stylesheet" href="static/css/header.css">
{% if dark_mode %} {% if dark_mode %}
@ -24,4 +22,7 @@
<a style="color: #685e79" href="https://github.com/benbusby/whoogle-search">View on GitHub</a> <a style="color: #685e79" href="https://github.com/benbusby/whoogle-search">View on GitHub</a>
</p> </p>
</footer> </footer>
<script src="static/js/autocomplete.js"></script>
<script src="static/js/utils.js"></script>
<script src="static/js/keyboard.js"></script>
</html> </html>