Skip to content

Commit

Permalink
Fix autocomplete closing before link event can propagate (#113)
Browse files Browse the repository at this point in the history
* fix autocomplete closing before link event can propagate

* use common bind format

* add comment
  • Loading branch information
kochis authored Jul 31, 2023
1 parent 6e30ee2 commit 029a6c7
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions src/ui/autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 029a6c7

Please sign in to comment.