From cc25efc5f44f9324ea61ed5df79b511b61527f4c Mon Sep 17 00:00:00 2001 From: Lucas Gabriel Vuotto Date: Mon, 28 Apr 2025 14:19:01 +0000 Subject: [PATCH] site: rework {up,down} arrow handling Allows it to work when setting the cursor via the pointer. --- public/js/app.js | 29 +++++++++++++++++++---------- templates/_search.html.ep | 4 ++-- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/public/js/app.js b/public/js/app.js index cf08e02..4741b4c 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -38,13 +38,14 @@ document.addEventListener('alpine:init', () => { return; } + this.activeItem = null; this.items = await response.json(); this.open = true; }, - fetchSuggestionsOnInput(evt) { + async fetchSuggestionsOnInput(evt) { this.cursor = evt.target.selectionStart; - this.fetchSuggestions(); + await this.fetchSuggestions(); }, autocompleteSuggestion() { @@ -54,6 +55,7 @@ document.addEventListener('alpine:init', () => { const pos = Math.max(this.cursor - this.currentWord.length, 0); const tag = this.items[this.activeItem ?? 0].display; + this.items = []; this.activeItem = null; this.search = mySplice(this.search, pos, this.currentWord.length, tag + ' '); @@ -87,20 +89,27 @@ document.addEventListener('alpine:init', () => { this.activeItem = this.getListItemIndexOf(evt.currentTarget); }, - previousItem(evt) { + moveActiveItem(evt, amount, defaultValue) { const len = this.items.length; - let item = this.activeItem === null ? -1 : this.activeItem - 1; - item = item % len; + if (len === 0) + returrn; + + let item = this.activeItem === null ? + defaultValue : (this.activeItem + amount) % len; if (item < 0) item += len; + this.activeItem = item; }, - nextItem(evt) { - const len = this.items.length; - let item = this.activeItem === null ? 0 : this.activeItem + 1; - item = item % len; - this.activeItem = item; + async moveActiveItemBackward(evt) { + await this.fetchSuggestionsOnInput(evt); + this.moveActiveItem(evt, -1, -1); + }, + + async moveActiveItemForward(evt) { + await this.fetchSuggestionsOnInput(evt); + this.moveActiveItem(evt, 1, 0); }, })); }); diff --git a/templates/_search.html.ep b/templates/_search.html.ep index f531988..8d9b3fb 100644 --- a/templates/_search.html.ep +++ b/templates/_search.html.ep @@ -13,8 +13,8 @@ @input.debounce="fetchSuggestionsOnInput" @keydown.tab="autocompleteItem" @keydown.enter="autocompleteItem" - @keydown.up.prevent="previousItem" - @keydown.down.prevent="nextItem" + @keydown.up.prevent="moveActiveItemBackward" + @keydown.down.prevent="moveActiveItemForward" @keydown.escape="open = false">