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

71 lines
1.6 KiB
JavaScript
Raw 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'
import Consts from '../_consts'
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 20:50:57 +02:00
let prev_touch_event_name
let touch_timeout
2021-08-09 18:04:09 +02:00
const SET_TOUCH_SCREEN = (bool, event_name) => {
if (touch_timeout || event_name === prev_touch_event_name) {
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 20:50:57 +02:00
prev_touch_event_name = event_name
2021-08-09 18:04:09 +02:00
// prevent firing touch and mouse events together
if (!touch_timeout) {
touch_timeout = setTimeout(() => {
2022-05-03 20:50:57 +02:00
clearTimeout(touch_timeout)
touch_timeout = null
}, 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)