import _defineProperty from "@babel/runtime/helpers/defineProperty";
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

export const isFocusable = element => {
  if (element.tabIndex > 0 || element.tabIndex === 0 && element.getAttribute('tabIndex') !== null) {
    return true;
  }
  if (element.disabled) {
    return false;
  }
  switch (element.nodeName) {
    case 'A':
      return !!element.href && element.rel !== 'ignore';
    case 'INPUT':
      return element.type !== 'hidden' && element.type !== 'file';
    case 'BUTTON':
    case 'SELECT':
    case 'TEXTAREA':
      return true;
    default:
      return false;
  }
};
export default class Focuser {
  constructor() {
    _defineProperty(this, "ignoreFocusChange", false);
  }
  canIgnoreFocusChange() {
    return this.ignoreFocusChange;
  }
  focusFirstDescendant(element, options) {
    for (let i = 0; i < element.childNodes.length; i++) {
      const child = element.childNodes[i];
      if (options && typeof options.canSkip === 'function' && options.canSkip(child)) {
        continue;
      }
      if (this.attemptFocus(child) || this.focusFirstDescendant(child)) {
        return true;
      }
    }
    return false;
  }
  focusLastDescendant(element) {
    for (let i = element.childNodes.length - 1; i >= 0; i--) {
      const child = element.childNodes[i];
      if (this.attemptFocus(child) || this.focusLastDescendant(child)) {
        return true;
      }
    }
    return false;
  }
  attemptFocus(element) {
    if (!isFocusable(element)) {
      return false;
    }
    this.ignoreFocusChange = true;
    try {
      element.focus();
    } catch {}
    this.ignoreFocusChange = false;
    return document.activeElement === element;
  }
}