bootstrap/js/src/dom/polyfill.js

87 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-03-16 14:10:23 +00:00
/* istanbul ignore file */
/**
* --------------------------------------------------------------------------
2019-02-12 10:47:34 +00:00
* Bootstrap (v4.3.1): dom/polyfill.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
import { getUID } from '../util/index'
2019-02-19 21:52:04 +00:00
2019-03-16 14:10:23 +00:00
let find = Element.prototype.querySelectorAll
let findOne = Element.prototype.querySelector
2019-03-16 14:10:23 +00:00
// MSEdge resets defaultPrevented flag upon dispatchEvent call if at least one listener is attached
const defaultPreventedPreservedOnDispatch = (() => {
2020-03-09 13:34:07 +00:00
const e = new CustomEvent('Bootstrap', {
2019-03-16 14:10:23 +00:00
cancelable: true
})
2019-03-16 14:10:23 +00:00
const element = document.createElement('div')
element.addEventListener('Bootstrap', () => null)
2019-03-16 14:10:23 +00:00
e.preventDefault()
element.dispatchEvent(e)
return e.defaultPrevented
})()
const scopeSelectorRegex = /:scope\b/
const supportScopeQuery = (() => {
const element = document.createElement('div')
try {
element.querySelectorAll(':scope *')
2019-10-07 06:31:12 +00:00
} catch (_) {
2019-03-16 14:10:23 +00:00
return false
}
return true
})()
if (!supportScopeQuery) {
find = function (selector) {
if (!scopeSelectorRegex.test(selector)) {
return this.querySelectorAll(selector)
}
2019-03-16 14:10:23 +00:00
const hasId = Boolean(this.id)
2019-03-16 14:10:23 +00:00
if (!hasId) {
this.id = getUID('scope')
}
2019-03-16 14:10:23 +00:00
let nodeList = null
try {
selector = selector.replace(scopeSelectorRegex, `#${this.id}`)
nodeList = this.querySelectorAll(selector)
} finally {
if (!hasId) {
this.removeAttribute('id')
}
}
2019-03-16 14:10:23 +00:00
return nodeList
}
2019-03-16 14:10:23 +00:00
findOne = function (selector) {
if (!scopeSelectorRegex.test(selector)) {
return this.querySelector(selector)
}
const matches = find.call(this, selector)
if (typeof matches[0] !== 'undefined') {
return matches[0]
}
return null
}
}
export {
find,
findOne,
defaultPreventedPreservedOnDispatch
}