client: handle touch events properly

This commit is contained in:
arne 2024-03-25 07:59:25 +01:00
commit 854c975cd0

View file

@ -47,15 +47,28 @@ const makeRipple = (position: [number, number], radius: number): void => {
// event handlers
const throttle = <X, Y>(fn: (...x: X[]) => Y, ms: number) => {
let lastExecutedAt = -1
return (...x: X[]) => {
const now = Date.now()
if (now - lastExecutedAt > ms) {
lastExecutedAt = now
fn(...x)
}
}
}
const at60fps = <X, Y>(fn: (...x: X[]) => Y) => throttle(fn, 1000 / 60)
// create a big ripple when touching the screen
canvas.addEventListener('mousedown', (e) => {
canvas.addEventListener('mousedown', at60fps((e) => {
// TODO Normalize x and y coords
const radius = MAX_RADIUS
makeRipple([
e.clientX / window.innerWidth,
e.clientY / window.innerHeight
], radius)
})
}))
// create a smaller ripple when moving over the screen
function* minDist(dist: number) {
@ -73,7 +86,7 @@ function* minDist(dist: number) {
const hasSpace = minDist(MAX_RADIUS / 6)
canvas.addEventListener('mousemove', (e) => {
canvas.addEventListener('mousemove', at60fps((e) => {
const shouldSpawn = hasSpace.next().value!
if (shouldSpawn([e.clientX, e.clientY])) {
const radius = MAX_RADIUS / 3*2
@ -82,10 +95,23 @@ canvas.addEventListener('mousemove', (e) => {
e.clientY / window.innerHeight
], radius)
}
})
}))
canvas.addEventListener('touchmove', at60fps((e) => {
const shouldSpawn = hasSpace.next().value!
const radius = MAX_RADIUS / 3*2
for (const touch of e.touches) {
if (shouldSpawn([touch.clientX, touch.clientY])) {
makeRipple([
touch.clientX / window.innerWidth,
touch.clientY / window.innerHeight
], radius)
}
}
}))
// react to incoming websocket messages
socket.addEventListener('message', (e) => {
socket.addEventListener('message', at60fps((e) => {
console.log('Received websocket message', e)
if (typeof e.data === 'string') {
// TODO: Validate message shape
@ -107,7 +133,7 @@ socket.addEventListener('message', (e) => {
} else {
console.warn('i received an odd message and i don\'t know what to do with it', e.data)
}
})
}))
// main loop