From eb160fe2230870bdf06f1323e61d1296245225e7 Mon Sep 17 00:00:00 2001 From: He4eT Date: Sun, 21 Jan 2024 00:19:12 +0100 Subject: [PATCH] pages/search: focus keyboard control --- pages/search/modules/inputHandlers.js | 30 +++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/pages/search/modules/inputHandlers.js b/pages/search/modules/inputHandlers.js index 6927c50..2aaf4a0 100644 --- a/pages/search/modules/inputHandlers.js +++ b/pages/search/modules/inputHandlers.js @@ -1,7 +1,37 @@ +const focusButtonsWithArrows = (e) => { + if (['ArrowUp', 'ArrowDown'].includes(e.key)) { + e.preventDefault() + + const buttons = document.querySelectorAll('#searchResults > button') + if (buttons.length === 0) { return } + + const currentIndex = [...buttons].indexOf(document.activeElement) + const newIndex = currentIndex === -1 + ? ({ + 'ArrowDown': 0, + 'ArrowUp': buttons.length - 1, + }[e.key]) + : (({ + 'ArrowDown': 1, + 'ArrowUp': -1, + }[e.key]) + currentIndex + buttons.length) % buttons.length + + buttons[newIndex].focus() + } +} + export const attachInputHandlers = (store) => { const searchBox = document.getElementById('searchbox') const actionbox = document.getElementById('actionbox') + document.addEventListener('keydown', (e) => { + focusButtonsWithArrows(e) + if (e.key === 'Escape') { + searchBox.focus() + } + }) + + searchBox.addEventListener('input', (e) => { store.actions.updateQuery(e.target.value) })