diff --git a/src/autocomplete.js b/src/autocomplete.js index efec9e0..7fc2674 100644 --- a/src/autocomplete.js +++ b/src/autocomplete.js @@ -11,6 +11,7 @@ export default class Autocomplete extends Controller { submitOnEnter: Boolean, url: String, minLength: Number, + options: Array, delay: { type: Number, default: 300 }, queryParam: { type: String, default: "q" }, } @@ -192,12 +193,10 @@ export default class Autocomplete extends Controller { } fetchResults = async (query) => { - if (!this.hasUrlValue) return - - const url = this.buildURL(query) try { this.element.dispatchEvent(new CustomEvent("loadstart")) - const html = await this.doFetch(url) + const html = await (this.hasOptionsValue ? this.fetchLocalOptions(query) : this.fetchRemoteResults(query)) + this.replaceResults(html) this.element.dispatchEvent(new CustomEvent("load")) this.element.dispatchEvent(new CustomEvent("loadend")) @@ -208,6 +207,28 @@ export default class Autocomplete extends Controller { } } + fetchLocalOptions = (query) => { + const parsedQuery = query.trim().toLowerCase() + const matchingOptions = this.optionsValue.filter(o => this.optionMatches(parsedQuery, o)) + + return matchingOptions.map(o => this.decorateResult(o)).join('\n') + } + + optionMatches(query, option) { + return option.toLowerCase().includes(query) + } + + decorateResult = (result) => { + return `