polyfill.js 2.06 KB
Newer Older
1
2
/**
 * --------------------------------------------------------------------------
XhmikosR's avatar
4.3.1.    
XhmikosR committed
3
 * Bootstrap (v4.3.1): dom/polyfill.js
4
5
6
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * --------------------------------------------------------------------------
 */
7

8
9
10
import {
  getUID
} from '../util/index'
XhmikosR's avatar
XhmikosR committed
11

12
/* istanbul ignore next */
13
const Polyfill = (() => {
14
15
16
17
18
  // MSEdge resets defaultPrevented flag upon dispatchEvent call if at least one listener is attached
  const defaultPreventedPreservedOnDispatch = (() => {
    const e = new CustomEvent('Bootstrap', {
      cancelable: true
    })
19

20
21
22
23
24
25
26
    const element = document.createElement('div')
    element.addEventListener('Bootstrap', () => null)

    e.preventDefault()
    element.dispatchEvent(e)
    return e.defaultPrevented
  })()
27

28
29
  let find = Element.prototype.querySelectorAll
  let findOne = Element.prototype.querySelector
30

31
  const scopeSelectorRegex = /:scope\b/
32
33
  const supportScopeQuery = (() => {
    const element = document.createElement('div')
34

35
36
37
38
39
40
41
42
43
44
45
46
47
    try {
      element.querySelectorAll(':scope *')
    } catch (e) {
      return false
    }

    return true
  })()

  if (!supportScopeQuery) {
    find = function (selector) {
      if (!scopeSelectorRegex.test(selector)) {
        return this.querySelectorAll(selector)
48
      }
49
50

      const hasId = Boolean(this.id)
51

52
      if (!hasId) {
53
        this.id = getUID('scope')
54
      }
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

      let nodeList = null
      try {
        selector = selector.replace(scopeSelectorRegex, `#${this.id}`)
        nodeList = this.querySelectorAll(selector)
      } finally {
        if (!hasId) {
          this.removeAttribute('id')
        }
      }

      return nodeList
    }

    findOne = function (selector) {
      if (!scopeSelectorRegex.test(selector)) {
        return this.querySelector(selector)
      }

      const matches = find.call(this, selector)
75

76
77
78
79
80
81
      if (typeof matches[0] !== 'undefined') {
        return matches[0]
      }

      return null
    }
82
83
84
  }

  return {
85
86
87
    defaultPreventedPreservedOnDispatch,
    find,
    findOne
88
89
90
91
  }
})()

export default Polyfill