webpack-bootstrap-ui-kit/src/js/main/touch.js

70 lines
1.5 KiB
JavaScript
Raw Permalink Normal View History

2021-08-09 18:04:09 +02:00
// touch/mouse detection
2022-05-03 20:50:57 +02:00
import Events from '../_events'
2021-08-09 18:04:09 +02:00
export default ((W) => {
2022-05-03 20:50:57 +02:00
const NAME = '_main.touch'
const D = document
const BODY = D.body
2021-08-09 18:04:09 +02:00
2022-05-03 21:44:33 +02:00
let prevTouchEventName
let touchTimeout
const SET_TOUCH_SCREEN = (bool, eventName) => {
if (touchTimeout || eventName === prevTouchEventName) {
2022-05-03 20:50:57 +02:00
return
2021-08-09 18:04:09 +02:00
}
if (bool) {
2022-05-03 20:50:57 +02:00
console.log(`${NAME}: Touch screen enabled`)
2021-08-09 18:04:09 +02:00
2022-05-03 20:50:57 +02:00
BODY.classList.add('is-touch')
BODY.classList.remove('is-mouse')
2021-08-09 18:04:09 +02:00
2022-05-03 20:50:57 +02:00
W.dispatchEvent(new Event(Events.TOUCHENABLE))
2021-08-09 18:04:09 +02:00
} else {
2022-05-03 20:50:57 +02:00
console.log(`${NAME}: Touch screen disabled`)
2021-08-09 18:04:09 +02:00
2022-05-03 20:50:57 +02:00
BODY.classList.add('is-mouse')
BODY.classList.remove('is-touch')
2021-08-09 18:04:09 +02:00
2022-05-03 20:50:57 +02:00
W.dispatchEvent(new Event(Events.TOUCHDISABLED))
2021-08-09 18:04:09 +02:00
}
2022-05-03 21:44:33 +02:00
prevTouchEventName = eventName
2021-08-09 18:04:09 +02:00
// prevent firing touch and mouse events together
2022-05-03 21:44:33 +02:00
if (!touchTimeout) {
touchTimeout = setTimeout(() => {
clearTimeout(touchTimeout)
touchTimeout = null
2022-05-03 20:50:57 +02:00
}, 500)
2021-08-09 18:04:09 +02:00
}
2022-05-03 20:50:57 +02:00
}
2021-08-09 18:04:09 +02:00
SET_TOUCH_SCREEN(
2022-05-03 20:50:57 +02:00
'ontouchstart' in W ||
2021-08-18 20:51:15 +02:00
navigator.MaxTouchPoints > 0 ||
navigator.msMaxTouchPoints > 0 ||
2022-05-03 20:50:57 +02:00
W.matchMedia('(hover: none)').matches,
'init'
)
2021-08-09 18:04:09 +02:00
2022-05-03 20:50:57 +02:00
D.addEventListener('touchend', (e) => {
let touch = false
if (e.type !== 'click') {
touch = true
2021-08-09 18:04:09 +02:00
}
2022-05-03 20:50:57 +02:00
SET_TOUCH_SCREEN(touch, 'click-touchend')
})
2021-08-09 18:04:09 +02:00
// disable touch on mouse events
2022-05-03 20:50:57 +02:00
D.addEventListener('click', (e) => {
let touch = false
if (e.type !== 'click') {
touch = true
2021-08-09 18:04:09 +02:00
}
2022-05-03 20:50:57 +02:00
SET_TOUCH_SCREEN(touch, 'click-touchend')
})
})(window)