Skip to content

Instantly share code, notes, and snippets.

@jesperlandberg
Created January 1, 2022 19:30
Show Gist options
  • Save jesperlandberg/5176bd144e3ecba5c4d451f21f50d662 to your computer and use it in GitHub Desktop.
Save jesperlandberg/5176bd144e3ecba5c4d451f21f50d662 to your computer and use it in GitHub Desktop.
import { evt, store } from '@/core'
const { features, device } = store
const { isWindows, isFirefox } = device
export default function ({
el = window,
mouseMultiplier = .6,
touchMultiplier = 3,
firefoxMultiplier = 20,
keyStep = 120
} = {}) {
const LEFT = 37
const UP = 38
const RIGHT = 39
const DOWN = 40
const SPACE = 32
const multpliers = {
mouse: isWindows ? mouseMultiplier * 2 : mouseMultiplier,
firefox: isWindows ? firefoxMultiplier * 2 : firefoxMultiplier
}
const {
hasWheelEvent,
hasMouseWheelEvent,
hasTouch,
hasKeyDown
} = features
let x = 0
let y = 0
let dX = 0
let dY = 0
let tsX = 0
let tsY = 0
function notify(e) {
x += dX
y += dY
evt.emit('vs', { y, x, dY, dX, oE: e })
}
function onWheel(e) {
const { mouse, firefox } = multpliers
dX = e.wheelDeltaX || e.deltaX * -1
dY = e.wheelDeltaY || e.deltaY * -1
if (isFirefox && e.deltaMode === 1) {
dX *= firefox
dY *= firefox
}
dX *= mouse
dY *= mouse
notify(e)
}
function onMouseWheel(e) {
dX = e.wheelDeltaX ? e.wheelDeltaX : 0
dY = e.wheelDeltaY ? e.wheelDeltaY : e.wheelDelta
notify(e)
}
function onTouchStart(e) {
let t = e.targetTouches ? e.targetTouches[0] : e
tsX = t.pageX
tsY = t.pageY
}
function onTouchMove(e) {
if (preventTouch && e.target.classList.contains(unpreventTouchClass)) {
e.preventDefault()
}
let t = e.targetTouches ? e.targetTouches[0] : e
dX = (t.pageX - tsX) * touchMultiplier
dY = (t.pageY - tsY) * touchMultiplier
tsX = t.pageX
tsX = t.pageY
notify(e)
}
function onKeyDown(e) {
if (document.activeElement.nodeName === 'INPUT') return
dX = dY = 0
switch (e.keyCode) {
case UP:
dY = keyStep
break
case DOWN:
dY = -keyStep
break
case LEFT:
dX = keyStep
break
case RIGHT:
dX = -keyStep
break
case SPACE:
dY = (window.innerHeight - 40) * (e.shiftKey ? 1 : -1)
break
default:
return
}
notify(e)
}
function mount() {
hasWheelEvent && evt.on('wheel', el, onWheel, { passive: true })
hasMouseWheelEvent && evt.on('mousewheel', el, onMouseWheel, { passive: true })
if (hasTouch) {
evt.on('touchstart', el, onTouchStart, { passive: true })
evt.on('touchmove', el, onTouchMove, { passive: true })
}
hasKeyDown && evt.on('keydown', document, onKeyDown)
}
mount()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment