From 029a6c738f2e785302e3e2301b8f0e3385b0ea17 Mon Sep 17 00:00:00 2001 From: Craig Kochis Date: Mon, 31 Jul 2023 14:05:54 -0400 Subject: [PATCH] Fix autocomplete closing before link event can propagate (#113) * fix autocomplete closing before link event can propagate * use common bind format * add comment --- src/ui/autocomplete.ts | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/ui/autocomplete.ts b/src/ui/autocomplete.ts index 48c70e45..692a9be1 100644 --- a/src/ui/autocomplete.ts +++ b/src/ui/autocomplete.ts @@ -74,6 +74,7 @@ class AutocompleteUI { inputField: HTMLInputElement; resultsList: HTMLElement; wrapper: HTMLElement; + poweredByLink?: HTMLElement; // create a new AutocompleteUI instance public static createAutocomplete(autocompleteOptions: RadarAutocompleteUIOptions): AutocompleteUI { @@ -127,7 +128,7 @@ class AutocompleteUI { // event listeners this.inputField.addEventListener('input', this.handleInput.bind(this)); - this.inputField.addEventListener('blur', () => this.close(), true); + this.inputField.addEventListener('blur', this.close.bind(this), true); this.inputField.addEventListener('keydown', this.handleKeyboardNavigation.bind(this)); // append to DOM @@ -256,6 +257,7 @@ class AutocompleteUI { const link = document.createElement('a'); link.href = 'https://radar.com?ref=powered_by_radar'; link.target = '_blank'; + this.poweredByLink = link; const poweredByText = document.createElement('span'); poweredByText.textContent = 'Powered by'; @@ -284,22 +286,25 @@ class AutocompleteUI { } this.wrapper.setAttribute(ARIA.EXPANDED, 'true'); - this.resultsList.removeAttribute("hidden"); + this.resultsList.removeAttribute('hidden'); this.isOpen = true; - // emit event } - public close() { + public close(e?: FocusEvent) { if (!this.isOpen) { return; } - this.wrapper.removeAttribute(ARIA.EXPANDED); - this.resultsList.setAttribute("hidden", ""); - this.highlightedIndex = -1; - this.isOpen = false; - this.clearResultsList(); - // emit event + // run this code async to allow link click to propagate before blur + // (add 100ms delay if closed from link click) + const linkClick = e && (e.relatedTarget === this.poweredByLink); + setTimeout(() => { + this.wrapper.removeAttribute(ARIA.EXPANDED); + this.resultsList.setAttribute('hidden', ''); + this.highlightedIndex = -1; + this.isOpen = false; + this.clearResultsList(); + }, linkClick ? 100 : 0); } public goTo(index: number) {