Skip to content

Commit 7528ede

Browse files
committed
feat: add custom hook useTouchPrimary to detect primary touch input capability
1 parent 951e816 commit 7528ede

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

hooks/use-has-primary-touch.tsx

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { useEffect, useState } from "react";
2+
3+
export function useTouchPrimary() {
4+
const [isTouchPrimary, setIsTouchPrimary] = useState(false);
5+
6+
useEffect(() => {
7+
if (typeof window === "undefined") return;
8+
9+
const controller = new AbortController();
10+
const { signal } = controller;
11+
12+
const handleTouch = () => {
13+
const hasTouch = "ontouchstart" in window || navigator.maxTouchPoints > 0;
14+
const prefersTouch = window.matchMedia("(pointer: coarse)").matches;
15+
setIsTouchPrimary(hasTouch && prefersTouch);
16+
};
17+
18+
const mq = window.matchMedia("(pointer: coarse)");
19+
mq.addEventListener("change", handleTouch, { signal });
20+
window.addEventListener("pointerdown", handleTouch, { signal });
21+
22+
return () => controller.abort();
23+
}, []);
24+
25+
return isTouchPrimary;
26+
}

0 commit comments

Comments
 (0)