diff --git a/public/js/app.js b/public/js/app.js index 44fef42..711f5de 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -1,11 +1,3 @@ -function getCurrentWordFromCursor(s, cursor) { - return s.substring(s.lastIndexOf(' ', cursor - 1) + 1, cursor); -} - -function mySplice(s, idx, del, n) { - return s.substring(0, idx) + n + s.substring(idx + del); -} - document.addEventListener('alpine:init', () => { Alpine.data('tagsSuggestions', (initialSearch = '') => ({ items: [], @@ -19,9 +11,14 @@ document.addEventListener('alpine:init', () => { return this.items.toSorted((a, b) => b.count - a.count); }, + getCurrentWordFromCursor() { + let s = this.$refs.search.value; + return s.substring(s.lastIndexOf(' ', this.cursor - 1) + 1, this.cursor); + }, + async fetchSuggestions() { - const currentWord = getCurrentWordFromCursor(this.$refs.search.value, - this.cursor); + const currentWord = this.getCurrentWordFromCursor(); + if (!currentWord) return; if (currentWord === this.currentWord) { @@ -50,23 +47,31 @@ document.addEventListener('alpine:init', () => { await this.fetchSuggestions(); }, + insertSuggestionAtCursor() { + const position = Math.max(this.cursor - this.currentWord.length, 0); + const suggestion = this.items[this.activeItem ?? 0].display; + const oldValue = this.$refs.search.value; + + this.$refs.search.value = oldValue.substring(0, position) + + suggestion + ' ' + + oldValue.substring(position + this.currentWord.length); + this.cursor = position + suggestion.length + 1; + }, + autocompleteSuggestion() { if (this.items.length === 0) return; - const pos = Math.max(this.cursor - this.currentWord.length, 0); - const tag = this.items[this.activeItem ?? 0].display; + this.insertSuggestionAtCursor(); this.items = []; this.activeItem = null; - this.$refs.search.value = mySplice(this.$refs.search.value, pos, - this.currentWord.length, tag + ' '); - this.cursor = pos + tag.length + 1; this.currentWord = ''; this.open = false; + this.$refs.search.selectionStart = this.$refs.search.selectionEnd = + this.cursor; this.$refs.search.focus(); - this.$refs.search.setSelectionRange(this.cursor, this.cursor); }, autocompleteItem(evt) {