summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/vue_shared/directives/autofocusonshow.js
blob: 4659ec20ceb3def0986f98469c68b1bce0945a5e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * Input/Textarea Autofocus Directive for Vue
 */
export default {
  /**
   * Set focus when element is rendered, but
   * is not visible, using IntersectionObserver
   *
   * @param {Element} el Target element
   */
  inserted(el) {
    if ('IntersectionObserver' in window) {
      // Element visibility is dynamic, so we attach observer
      el.visibilityObserver = new IntersectionObserver(entries => {
        entries.forEach(entry => {
          // Combining `intersectionRatio > 0` and
          // element's `offsetParent` presence will
          // deteremine if element is truely visible
          if (entry.intersectionRatio > 0 && entry.target.offsetParent) {
            entry.target.focus();
          }
        });
      });

      // Bind the observer.
      el.visibilityObserver.observe(el, { root: document.documentElement });
    }
  },
  /**
   * Detach observer on unbind hook.
   *
   * @param {Element} el Target element
   */
  unbind(el) {
    if (el.visibilityObserver) {
      el.visibilityObserver.disconnect();
    }
  },
};