import { balBrowser } from "../browser";
import { isDescendant, waitAfterIdleCallback } from "../helpers";
import { ListenerAbstract } from "../types/listener";
export class BalFocusListener extends ListenerAbstract {
  constructor() {
    super(...arguments);
    this.onFocusin = (ev) => {
      this.notify({ ev, isFocusIn: true, isFocusOut: false });
    };
    this.onFocusout = async (ev) => {
      await waitAfterIdleCallback();
      if (balBrowser.hasDocument && this.el) {
        const target = document.activeElement;
        if (target && !isDescendant(this.el, target)) {
          this.notify({ ev, isFocusIn: false, isFocusOut: true });
        }
      }
    };
  }
  connect(el) {
    super.connect(el);
    if (this.el) {
      this.el.addEventListener('focusin', this.onFocusin);
      this.el.addEventListener('focusout', this.onFocusout);
    }
  }
  disconnect() {
    super.disconnect();
    if (this.el) {
      this.el.removeEventListener('focusin', this.onFocusin);
      this.el.removeEventListener('focusout', this.onFocusout);
    }
  }
}
