"use client";
import { type MouseEvent, type PointerEvent, useEffect, useRef } from "react";
const LONG_PRESS_MS = 500;
const MOVE_TOLERANCE_PX = 8;
/** หลังยกนิ้ว click ที่ตามมาจากการกดค้างมาภายในช่วงนี้ — เลยจากนี้ธงหมดอายุ (click จากคีย์บอร์ดครั้งถัดไปไม่ถูกกลืน) */
const FIRED_CLICK_WINDOW_MS = 400;
/**
* กดค้าง (≥ 500 ms โดยไม่ขยับเกิน 8 px) → เรียก `onLongPress` พร้อมตำแหน่งที่กด
* กระจาย `handlers` ลงบน element · `fired.current` เป็น true = click ถัดไปคือแรงที่ตามหลังการกดค้าง ให้ข้ามไป
* `ignore` = selector ของจุดที่ไม่นับ (ปุ่ม/ช่องติ๊กในแถวมี click ของตัวเอง กดค้างแล้วจะถูกสลับซ้ำ)
*
* const { fired, handlers } = useLongPress(() => select(id), { ignore: "button,input" });
*
{ if (fired.current) return; open(id); }} />
*/
export function useLongPress(
onLongPress: (point: { x: number; y: number }) => void,
{ enabled = true, ignore }: { enabled?: boolean; ignore?: string } = {},
) {
const timer = useRef | null>(null);
const origin = useRef<{ x: number; y: number } | null>(null);
const fired = useRef(false);
const expire = useRef | null>(null);
const cancel = () => {
if (timer.current) clearTimeout(timer.current);
timer.current = null;
};
const release = () => {
cancel();
// ยกนิ้วหลังกดค้างสำเร็จ: click ที่ตามมา (ถ้ามี) มาทันที — ไม่มาก็ล้างธงเอง
if (fired.current) {
if (expire.current) clearTimeout(expire.current);
expire.current = setTimeout(() => {
fired.current = false;
expire.current = null;
}, FIRED_CLICK_WINDOW_MS);
}
};
useEffect(
() => () => {
cancel();
if (expire.current) clearTimeout(expire.current);
},
[],
);
const handlers = {
onPointerDown: (event: PointerEvent) => {
// ล้างธงของการกดค้างรอบก่อนทุกครั้งที่เริ่มแตะใหม่ (แม้ปิดการกดค้างอยู่)
fired.current = false;
if (expire.current) clearTimeout(expire.current);
cancel();
if (!enabled) return;
// ปุ่มขวา/กลางของเมาส์ไม่นับ (คลิกขวาค้างไม่ใช่การกดค้าง)
if (event.button !== 0) return;
if (ignore && (event.target as Element).closest?.(ignore)) return;
const point = { x: event.clientX, y: event.clientY };
origin.current = point;
timer.current = setTimeout(() => {
timer.current = null;
fired.current = true;
onLongPress(point);
}, LONG_PRESS_MS);
},
onPointerMove: (event: PointerEvent) => {
const start = origin.current;
if (!start) return;
if (Math.hypot(event.clientX - start.x, event.clientY - start.y) > MOVE_TOLERANCE_PX) {
cancel();
}
},
onPointerUp: release,
onPointerCancel: release,
onPointerLeave: release,
// เมนูบริบทของเบราว์เซอร์มือถือเด้งตอนกดค้าง (Android ~400 ms ก่อนตัวจับเวลาครบ) — กันทั้งระหว่างรอและหลังสำเร็จ
onContextMenu: (event: MouseEvent) => {
if (fired.current || timer.current) event.preventDefault();
},
};
return { fired, handlers };
}