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
import { getUID } from '../util/index'
XhmikosR's avatar
XhmikosR committed
9

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

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

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

26
27
  let find = Element.prototype.querySelectorAll
  let findOne = Element.prototype.querySelector
28

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

33
34
    try {
      element.querySelectorAll(':scope *')
XhmikosR's avatar
XhmikosR committed
35
    } catch (error) {
36
37
38
39
40
41
42
43
44
45
      return false
    }

    return true
  })()

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

      const hasId = Boolean(this.id)
49

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

      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)
73

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

      return null
    }
80
81
82
  }

  return {
83
84
85
    defaultPreventedPreservedOnDispatch,
    find,
    findOne
86
87
88
89
  }
})()

export default Polyfill