Created
February 20, 2023 00:59
-
-
Save sslotsky/03a290263e038987b2ca968c19f65abc to your computer and use it in GitHub Desktop.
A qwik component to track the change in movement for both mouse and single-touch dragging. Accepts all div attributes as well as children.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
component$, | |
HTMLAttributes, | |
QRL, | |
Slot, | |
useSignal, | |
useTask$, | |
} from "@builder.io/qwik"; | |
interface Movement { | |
changeX: number; | |
changeY: number; | |
} | |
interface Props extends HTMLAttributes<HTMLDivElement> { | |
tracking: boolean; | |
callback$: QRL<(movement: Movement) => void>; | |
} | |
export default component$((props: Props) => { | |
const { tracking, callback$, ...divProps } = props; | |
const lastTouch = useSignal<[number, number]>(); | |
useTask$(({ track }) => { | |
track(() => tracking); | |
if (!tracking) { | |
lastTouch.value = undefined; | |
} | |
}); | |
return ( | |
<div | |
{...divProps} | |
onTouchMove$={(e) => { | |
if (tracking) { | |
const [touch] = e.changedTouches; | |
if (lastTouch.value) { | |
const [lastX, lastY] = lastTouch.value; | |
const changeX = touch.clientX - lastX; | |
const changeY = touch.clientY - lastY; | |
callback$({ changeX, changeY }); | |
} | |
lastTouch.value = [touch.clientX, touch.clientY]; | |
} | |
}} | |
onPointerMove$={(e) => { | |
if (tracking) { | |
callback$({ | |
changeX: e.movementX, | |
changeY: e.movementY, | |
}); | |
} | |
}} | |
> | |
<Slot /> | |
</div> | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage