Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS: use more "modern" APIs #32095

Merged
merged 7 commits into from Nov 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 0 additions & 4 deletions .eslintrc.json
Expand Up @@ -49,15 +49,11 @@
"unicorn/no-null": "off",
"unicorn/no-unused-properties": "error",
"unicorn/no-useless-undefined": "off",
"unicorn/prefer-array-find": "off",
"unicorn/prefer-dataset": "off",
"unicorn/prefer-includes": "off",
"unicorn/prefer-node-append": "off",
"unicorn/prefer-node-remove": "off",
"unicorn/prefer-number-properties": "off",
"unicorn/prefer-optional-catch-binding": "off",
"unicorn/prefer-query-selector": "off",
"unicorn/prefer-set-has": "off",
"unicorn/prevent-abbreviations": "off"
}
}
12 changes: 6 additions & 6 deletions build/build-plugins.js
Expand Up @@ -125,17 +125,17 @@ const getConfigByPluginKey = pluginKey => {
}
}

const utilObjects = [
const utilObjects = new Set([
'Util',
'Sanitizer'
]
])

const domObjects = [
const domObjects = new Set([
'Data',
'EventHandler',
'Manipulator',
'SelectorEngine'
]
])

const build = async plugin => {
console.log(`Building ${plugin} plugin...`)
Expand All @@ -144,11 +144,11 @@ const build = async plugin => {
const pluginFilename = path.basename(bsPlugins[plugin])
let pluginPath = rootPath

if (utilObjects.includes(plugin)) {
if (utilObjects.has(plugin)) {
pluginPath = `${rootPath}/util/`
}

if (domObjects.includes(plugin)) {
if (domObjects.has(plugin)) {
pluginPath = `${rootPath}/dom/`
}

Expand Down
2 changes: 1 addition & 1 deletion js/src/carousel.js
Expand Up @@ -419,7 +419,7 @@ class Carousel {
return
}

const elementInterval = parseInt(element.getAttribute('data-bs-interval'), 10)
const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10)

if (elementInterval) {
this._config.defaultInterval = this._config.defaultInterval || this._config.interval
Expand Down
4 changes: 2 additions & 2 deletions js/src/collapse.js
Expand Up @@ -150,8 +150,8 @@ class Collapse {

const container = SelectorEngine.findOne(this._selector)
if (actives) {
const tempActiveData = actives.filter(elem => container !== elem)
activesData = tempActiveData[0] ? Data.getData(tempActiveData[0], DATA_KEY) : null
const tempActiveData = actives.find(elem => container !== elem)
activesData = tempActiveData ? Data.getData(tempActiveData, DATA_KEY) : null

if (activesData && activesData._isTransitioning) {
return
Expand Down
14 changes: 7 additions & 7 deletions js/src/dom/event-handler.js
Expand Up @@ -22,7 +22,7 @@ const customEvents = {
mouseenter: 'mouseover',
mouseleave: 'mouseout'
}
const nativeEvents = [
const nativeEvents = new Set([
'click',
'dblclick',
'mouseup',
Expand Down Expand Up @@ -69,7 +69,7 @@ const nativeEvents = [
'error',
'abort',
'scroll'
]
])

/**
* ------------------------------------------------------------------------
Expand Down Expand Up @@ -151,7 +151,7 @@ function normalizeParams(originalTypeEvent, handler, delegationFn) {
typeEvent = custom
}

const isNative = nativeEvents.indexOf(typeEvent) > -1
const isNative = nativeEvents.has(typeEvent)

if (!isNative) {
typeEvent = originalTypeEvent
Expand Down Expand Up @@ -210,7 +210,7 @@ function removeNamespacedHandlers(element, events, typeEvent, namespace) {
const storeElementEvent = events[typeEvent] || {}

Object.keys(storeElementEvent).forEach(handlerKey => {
if (handlerKey.indexOf(namespace) > -1) {
if (handlerKey.includes(namespace)) {
const event = storeElementEvent[handlerKey]

removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector)
Expand All @@ -235,7 +235,7 @@ const EventHandler = {
const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn)
const inNamespace = typeEvent !== originalTypeEvent
const events = getEvent(element)
const isNamespace = originalTypeEvent.charAt(0) === '.'
const isNamespace = originalTypeEvent.startsWith('.')

if (typeof originalHandler !== 'undefined') {
// Simplest case: handler is passed, remove that listener ONLY.
Expand All @@ -257,7 +257,7 @@ const EventHandler = {
Object.keys(storeElementEvent).forEach(keyHandlers => {
const handlerKey = keyHandlers.replace(stripUidRegex, '')

if (!inNamespace || originalTypeEvent.indexOf(handlerKey) > -1) {
if (!inNamespace || originalTypeEvent.includes(handlerKey)) {
const event = storeElementEvent[keyHandlers]

removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector)
Expand All @@ -273,7 +273,7 @@ const EventHandler = {
const $ = getjQuery()
const typeEvent = event.replace(stripNameRegex, '')
const inNamespace = event !== typeEvent
const isNative = nativeEvents.indexOf(typeEvent) > -1
const isNative = nativeEvents.has(typeEvent)

let jQueryEvent
let bubbles = true
Expand Down
6 changes: 3 additions & 3 deletions js/src/modal.js
Expand Up @@ -474,7 +474,7 @@ class Modal {
const actualPadding = element.style.paddingRight
const calculatedPadding = window.getComputedStyle(element)['padding-right']
Manipulator.setDataAttribute(element, 'bs-padding-right', actualPadding)
element.style.paddingRight = `${parseFloat(calculatedPadding) + this._scrollbarWidth}px`
element.style.paddingRight = `${Number.parseFloat(calculatedPadding) + this._scrollbarWidth}px`
})

// Adjust sticky content margin
Expand All @@ -483,15 +483,15 @@ class Modal {
const actualMargin = element.style.marginRight
const calculatedMargin = window.getComputedStyle(element)['margin-right']
Manipulator.setDataAttribute(element, 'bs-margin-right', actualMargin)
element.style.marginRight = `${parseFloat(calculatedMargin) - this._scrollbarWidth}px`
element.style.marginRight = `${Number.parseFloat(calculatedMargin) - this._scrollbarWidth}px`
})

// Adjust body padding
const actualPadding = document.body.style.paddingRight
const calculatedPadding = window.getComputedStyle(document.body)['padding-right']

Manipulator.setDataAttribute(document.body, 'bs-padding-right', actualPadding)
document.body.style.paddingRight = `${parseFloat(calculatedPadding) + this._scrollbarWidth}px`
document.body.style.paddingRight = `${Number.parseFloat(calculatedPadding) + this._scrollbarWidth}px`
}

document.body.classList.add(CLASS_NAME_OPEN)
Expand Down
4 changes: 2 additions & 2 deletions js/src/tooltip.js
Expand Up @@ -39,7 +39,7 @@ const DATA_KEY = 'bs.tooltip'
const EVENT_KEY = `.${DATA_KEY}`
const CLASS_PREFIX = 'bs-tooltip'
const BSCLS_PREFIX_REGEX = new RegExp(`(^|\\s)${CLASS_PREFIX}\\S+`, 'g')
const DISALLOWED_ATTRIBUTES = ['sanitize', 'allowList', 'sanitizeFn']
const DISALLOWED_ATTRIBUTES = new Set(['sanitize', 'allowList', 'sanitizeFn'])

const DefaultType = {
animation: 'boolean',
Expand Down Expand Up @@ -679,7 +679,7 @@ class Tooltip {
const dataAttributes = Manipulator.getDataAttributes(this.element)

Object.keys(dataAttributes).forEach(dataAttr => {
if (DISALLOWED_ATTRIBUTES.indexOf(dataAttr) !== -1) {
if (DISALLOWED_ATTRIBUTES.has(dataAttr)) {
delete dataAttributes[dataAttr]
}
})
Expand Down
6 changes: 3 additions & 3 deletions js/src/util/index.js
Expand Up @@ -71,8 +71,8 @@ const getTransitionDurationFromElement = element => {
transitionDelay
} = window.getComputedStyle(element)

const floatTransitionDuration = parseFloat(transitionDuration)
const floatTransitionDelay = parseFloat(transitionDelay)
const floatTransitionDuration = Number.parseFloat(transitionDuration)
const floatTransitionDelay = Number.parseFloat(transitionDelay)

// Return 0 if element or transition duration is not found
if (!floatTransitionDuration && !floatTransitionDelay) {
Expand All @@ -83,7 +83,7 @@ const getTransitionDurationFromElement = element => {
transitionDuration = transitionDuration.split(',')[0]
transitionDelay = transitionDelay.split(',')[0]

return (parseFloat(transitionDuration) + parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER
return (Number.parseFloat(transitionDuration) + Number.parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER
}

const triggerTransitionEnd = element => {
Expand Down
10 changes: 5 additions & 5 deletions js/src/util/sanitizer.js
Expand Up @@ -5,7 +5,7 @@
* --------------------------------------------------------------------------
*/

const uriAttrs = [
const uriAttrs = new Set([
'background',
'cite',
'href',
Expand All @@ -14,7 +14,7 @@ const uriAttrs = [
'poster',
'src',
'xlink:href'
]
])

const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i

Expand All @@ -35,8 +35,8 @@ const DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|vid
const allowedAttribute = (attr, allowedAttributeList) => {
const attrName = attr.nodeName.toLowerCase()

if (allowedAttributeList.indexOf(attrName) !== -1) {
if (uriAttrs.indexOf(attrName) !== -1) {
if (allowedAttributeList.includes(attrName)) {
if (uriAttrs.has(attrName)) {
return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN))
}

Expand Down Expand Up @@ -107,7 +107,7 @@ export function sanitizeHtml(unsafeHtml, allowList, sanitizeFn) {
const el = elements[i]
const elName = el.nodeName.toLowerCase()

if (allowlistKeys.indexOf(elName) === -1) {
if (!allowlistKeys.includes(elName)) {
el.parentNode.removeChild(el)

continue
Expand Down
12 changes: 6 additions & 6 deletions js/tests/unit/modal.spec.js
Expand Up @@ -87,21 +87,21 @@ describe('Modal', () => {
].join('')

const fixedEl = fixtureEl.querySelector('.fixed-top')
const originalPadding = parseInt(window.getComputedStyle(fixedEl).paddingRight, 10)
const originalPadding = Number.parseInt(window.getComputedStyle(fixedEl).paddingRight, 10)
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)

modalEl.addEventListener('shown.bs.modal', () => {
const expectedPadding = originalPadding + modal._getScrollbarWidth()
const currentPadding = parseInt(window.getComputedStyle(modalEl).paddingRight, 10)
const currentPadding = Number.parseInt(window.getComputedStyle(modalEl).paddingRight, 10)

expect(fixedEl.getAttribute('data-bs-padding-right')).toEqual('0px', 'original fixed element padding should be stored in data-bs-padding-right')
expect(currentPadding).toEqual(expectedPadding, 'fixed element padding should be adjusted while opening')
modal.toggle()
})

modalEl.addEventListener('hidden.bs.modal', () => {
const currentPadding = parseInt(window.getComputedStyle(modalEl).paddingRight, 10)
const currentPadding = Number.parseInt(window.getComputedStyle(modalEl).paddingRight, 10)

expect(fixedEl.getAttribute('data-bs-padding-right')).toEqual(null, 'data-bs-padding-right should be cleared after closing')
expect(currentPadding).toEqual(originalPadding, 'fixed element padding should be reset after closing')
Expand All @@ -118,21 +118,21 @@ describe('Modal', () => {
].join('')

const stickyTopEl = fixtureEl.querySelector('.sticky-top')
const originalMargin = parseInt(window.getComputedStyle(stickyTopEl).marginRight, 10)
const originalMargin = Number.parseInt(window.getComputedStyle(stickyTopEl).marginRight, 10)
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)

modalEl.addEventListener('shown.bs.modal', () => {
const expectedMargin = originalMargin - modal._getScrollbarWidth()
const currentMargin = parseInt(window.getComputedStyle(stickyTopEl).marginRight, 10)
const currentMargin = Number.parseInt(window.getComputedStyle(stickyTopEl).marginRight, 10)

expect(stickyTopEl.getAttribute('data-bs-margin-right')).toEqual('0px', 'original sticky element margin should be stored in data-bs-margin-right')
expect(currentMargin).toEqual(expectedMargin, 'sticky element margin should be adjusted while opening')
modal.toggle()
})

modalEl.addEventListener('hidden.bs.modal', () => {
const currentMargin = parseInt(window.getComputedStyle(stickyTopEl).marginRight, 10)
const currentMargin = Number.parseInt(window.getComputedStyle(stickyTopEl).marginRight, 10)

expect(stickyTopEl.getAttribute('data-bs-margin-right')).toEqual(null, 'data-bs-margin-right should be cleared after closing')
expect(currentMargin).toEqual(originalMargin, 'sticky element margin should be reset after closing')
Expand Down
1 change: 0 additions & 1 deletion site/.eslintrc.json
Expand Up @@ -36,7 +36,6 @@
"unicorn/no-for-loop": "off",
"unicorn/no-null": "off",
"unicorn/prefer-dataset": "off",
"unicorn/prefer-includes": "off",
"unicorn/prefer-node-append": "off",
"unicorn/prefer-query-selector": "off",
"unicorn/prevent-abbreviations": "off"
Expand Down
16 changes: 1 addition & 15 deletions site/assets/js/search.js
Expand Up @@ -20,19 +20,6 @@
}
})

function getOrigin() {
var location = window.location
var origin = location.origin

if (!origin) {
var port = location.port ? ':' + location.port : ''

origin = location.protocol + '//' + location.hostname + port
}

return origin
}

window.docsearch({
apiKey: '5990ad008512000bba2cf951ccf0332f',
indexName: 'bootstrap',
Expand All @@ -42,10 +29,9 @@
},
transformData: function (hits) {
return hits.map(function (hit) {
var currentUrl = getOrigin()
var liveUrl = 'https://v5.getbootstrap.com/'

hit.url = currentUrl.lastIndexOf(liveUrl, 0) === 0 ?
hit.url = window.location.origin.startsWith(liveUrl) ?
// On production, return the result as is
hit.url :
// On development or Netlify, replace `hit.url` with a trailing slash,
Expand Down