use-touch.mjs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { ref } from "vue";
  2. function getDirection(x, y) {
  3. if (x > y) {
  4. return "horizontal";
  5. }
  6. if (y > x) {
  7. return "vertical";
  8. }
  9. return "";
  10. }
  11. function useTouch() {
  12. const startX = ref(0);
  13. const startY = ref(0);
  14. const deltaX = ref(0);
  15. const deltaY = ref(0);
  16. const offsetX = ref(0);
  17. const offsetY = ref(0);
  18. const direction = ref("");
  19. const isVertical = () => direction.value === "vertical";
  20. const isHorizontal = () => direction.value === "horizontal";
  21. const reset = () => {
  22. deltaX.value = 0;
  23. deltaY.value = 0;
  24. offsetX.value = 0;
  25. offsetY.value = 0;
  26. direction.value = "";
  27. };
  28. const start = (event) => {
  29. reset();
  30. startX.value = event.touches[0].clientX;
  31. startY.value = event.touches[0].clientY;
  32. };
  33. const move = (event) => {
  34. const touch = event.touches[0];
  35. deltaX.value = (touch.clientX < 0 ? 0 : touch.clientX) - startX.value;
  36. deltaY.value = touch.clientY - startY.value;
  37. offsetX.value = Math.abs(deltaX.value);
  38. offsetY.value = Math.abs(deltaY.value);
  39. const LOCK_DIRECTION_DISTANCE = 10;
  40. if (!direction.value || offsetX.value < LOCK_DIRECTION_DISTANCE && offsetY.value < LOCK_DIRECTION_DISTANCE) {
  41. direction.value = getDirection(offsetX.value, offsetY.value);
  42. }
  43. };
  44. return {
  45. move,
  46. start,
  47. reset,
  48. startX,
  49. startY,
  50. deltaX,
  51. deltaY,
  52. offsetX,
  53. offsetY,
  54. direction,
  55. isVertical,
  56. isHorizontal
  57. };
  58. }
  59. export {
  60. useTouch
  61. };