Allow result navigation w/ Tab and Shift+Tab

Closes #457
main
Ben Busby 2022-08-01 13:01:12 -06:00
parent 78614877f2
commit 839683b4e1
No known key found for this signature in database
GPG Key ID: B9B7231E01D924A1
1 changed files with 50 additions and 36 deletions

View File

@ -1,44 +1,58 @@
(function () { (function () {
let searchBar, results; let searchBar, results;
const keymap = { let shift = false;
ArrowUp: goUp, const keymap = {
ArrowDown: goDown, ArrowUp: goUp,
k: goUp, ArrowDown: goDown,
j: goDown, ShiftTab: goUp,
'/': focusSearch, Tab: goDown,
}; k: goUp,
let activeIdx = -1; j: goDown,
'/': focusSearch,
};
let activeIdx = -1;
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
searchBar = document.querySelector('#search-bar'); searchBar = document.querySelector('#search-bar');
results = document.querySelectorAll('#main>div>div>div>a'); results = document.querySelectorAll('#main>div>div>div>a');
}); });
document.addEventListener('keydown', (e) => { document.addEventListener('keydown', (e) => {
if (e.target.tagName === 'INPUT') return true; if (e.key === 'Shift') {
if (typeof keymap[e.key] === 'function') { shift = true;
e.preventDefault(); }
keymap[e.key]();
}
});
function goUp () { if (e.target.tagName === 'INPUT') return true;
if (activeIdx > 0) focusResult(activeIdx - 1); if (typeof keymap[e.key] === 'function') {
else focusSearch(); e.preventDefault();
}
function goDown () { keymap[`${shift && e.key == 'Tab' ? 'Shift' : ''}${e.key}`]();
if (activeIdx < results.length - 1) focusResult(activeIdx + 1); }
} });
function focusResult (idx) { document.addEventListener('keyup', (e) => {
activeIdx = idx; if (e.key === 'Shift') {
results[activeIdx].scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' }); shift = false;
results[activeIdx].focus(); }
} });
function focusSearch () { function goUp () {
activeIdx = -1; if (activeIdx > 0) focusResult(activeIdx - 1);
searchBar.focus(); 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();
}
}()); }());