diff --git a/examples/index.html b/examples/index.html index 8ed58e8..3825529 100644 --- a/examples/index.html +++ b/examples/index.html @@ -101,7 +101,19 @@ document.querySelector("auto-complete#custom-fetching-method").fetchResult = async (el, url) => (await fetch(url)).text(); +
+ + + + + + +
+
+ +
+ - + diff --git a/src/auto-complete-element.ts b/src/auto-complete-element.ts index 0e36f37..0f711f8 100644 --- a/src/auto-complete-element.ts +++ b/src/auto-complete-element.ts @@ -55,6 +55,14 @@ export default class AutocompleteElement extends HTMLElement { } } + get fetchOnEmpty(): boolean { + return this.hasAttribute('fetch-on-empty') + } + + set fetchOnEmpty(fetchOnEmpty: boolean) { + this.toggleAttribute('fetch-on-empty', fetchOnEmpty) + } + fetchResult = fragment static get observedAttributes(): string[] { diff --git a/src/autocomplete.ts b/src/autocomplete.ts index 6d5a99b..6124cb8 100644 --- a/src/autocomplete.ts +++ b/src/autocomplete.ts @@ -187,7 +187,7 @@ export default class Autocomplete { fetchResults(): void { const query = this.input.value.trim() - if (!query) { + if (!query && !this.container.fetchOnEmpty) { this.container.open = false return } diff --git a/test/test.js b/test/test.js index 28edacf..94981f0 100644 --- a/test/test.js +++ b/test/test.js @@ -269,6 +269,51 @@ describe('auto-complete element', function () { assert.equal(`5 results. first is the top result: Press Enter to activate.`, feedback.innerHTML) }) }) + + describe('fetch on empty enabled', () => { + let container + beforeEach(function () { + document.body.innerHTML = ` +
+ + + + + +
+ ` + container = document.querySelector('auto-complete') + container.fetchResult = async () => ` +
  • Mock Custom Fetch Result 1
  • +
  • Mock Custom Fetch Result 2
  • ` + }) + + it('should fetch result when value is empty', async function () { + const input = container.querySelector('input') + const popup = container.querySelector(`#popup`) + const feedback = container.querySelector(`#popup-feedback`) + + triggerInput(input, '') + await once(container, 'loadend') + + assert.equal(2, popup.children.length) + assert.equal(popup.querySelector('li').textContent, 'Mock Custom Fetch Result 1') + assert.equal(feedback.textContent, '') + }) + + it('does not fetch result when value is empty, if fetch-on-empty removed', async function () { + const input = container.querySelector('input') + const popup = container.querySelector(`#popup`) + const feedback = container.querySelector(`#popup-feedback`) + container.fetchOnEmpty = false + + triggerInput(input, '') + await new Promise(resolve => setTimeout(resolve, 100)) + + assert.equal(0, popup.children.length) + assert.equal(feedback.textContent, '') + }) + }) }) function waitForElementToChange(el) {