Execute “focus out” handler in tag input when clicking any other element

Apparently i was only testing that control with tab, because clicking
on any other non-focusable element (e.g., a table row) it did not add
the new tag and would not dispatch the “numerus-tag-out” custom element,
which is why i have seen it now.

This is equivalent to AlpineJS’s @click.outside, and i was already using
it for the multiselect dropdown.  The isConnected check is because i
probably found some cases in the dropdown’s handler, but i can not
remeber now, but since AlpineJS does it too, i guess it is important.
This commit is contained in:
jordi fita mas 2023-04-12 11:59:45 +02:00
parent d20573aa99
commit 8c592cfe5e
1 changed files with 3 additions and 0 deletions

View File

@ -345,12 +345,14 @@ class Tags extends HTMLDivElement {
this.search.addEventListener('keydown', this.onSearchKeydownHandler);
this.onFocusOutHandler = (e) => {
if (this.contains(e.target)) return;
if (!e.target.isConnected) return;
if (this.search.value && this.search.value.trim() !== '') {
this.createTag();
}
this.dispatchEvent(new CustomEvent("numerus-tags-out", {bubbles: true}))
};
window.addEventListener('focusin', this.onFocusOutHandler);
document.addEventListener('click', this.onFocusOutHandler);
this.rebuild();
}
@ -359,6 +361,7 @@ class Tags extends HTMLDivElement {
disconnectedCallback() {
if (this.initialized) {
this.removeTags();
document.removeEventListener('click', this.onFocusOutHandler);
window.removeEventListener('focusin', this.onFocusOutHandler);
this.onFocusOutHandler = null;
this.search.removeEventListener('keydown', this.onSearchKeydownHandler);