"use client"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { errorMessage, failedResult } from "@suphark/ui/lib/action-result"; import { useCallback, useEffect, useRef, useState } from "react"; import { toast } from "sonner"; type Status = "waiting" | "committing" | "done"; export interface UndoableActionOptions { /** ทำจริง (เช่นเรียก server action ลบ) เมื่อหมดเวลาโดยไม่มีใครกดเลิกทำ — โยน error หรือคืน `{ ok: false, error }` = ล้มเหลว */ commit: (ids: Id[]) => unknown; /** เวลารอก่อนทำจริง (ms) ค่าเริ่มต้น 6000 — sonner หยุดนับเมื่อชี้/โฟกัส toast หรือสลับแท็บ */ timeout?: number; /** ข้อความ toast ตามจำนวนในชุด (ค่าเริ่มต้น "ลบแล้ว" / "ลบ N รายการแล้ว") */ message?: (count: number) => string; } /** * "เลิกทำ" แทน "แน่ใจไหม?" สำหรับการลบ/เก็บที่ย้อนได้: `run(id)` ซ่อนรายการทันที (กรองด้วย `isPending`) + * toast "ลบแล้ว · เลิกทำ" → หมดเวลา/ปิด toast = เรียก `commit` จริง · เลิกทำ = รายการกลับมา * · หลายรายการในช่วงที่ toast ยังอยู่รวมเป็นชุดเดียว ("ลบ 3 รายการแล้ว") · `commit` ล้มเหลว = รายการกลับมา + toast ข้อผิดพลาด * · ปิดแท็บ/รีเฟรช = ทำจริงทันทีตั้งแต่ beforeunload + เบราว์เซอร์ถามก่อนออก · ออกจากหน้า (pagehide) หรือ component ถูกถอด = ทำจริงทันที * ของที่ย้อนไม่ได้ (ลบถาวร, ส่งอีเมล) ยังใช้ ConfirmDialog — ต้องมี ``/`` ในหน้า * * const undoable = useUndoableAction({ commit: (ids) => deleteOrders(ids) }); * const visible = orders.filter((o) => !undoable.isPending(o.id)); * undoable.run(order.id) }]} /> */ export function useUndoableAction({ commit, timeout = 6000, message, }: UndoableActionOptions) { const text = useUiText().undo; const [status, setStatus] = useState>(new Map()); const batch = useRef<{ toastId: string | number; ids: Id[]; settled: boolean } | null>(null); const commitRef = useRef(commit); commitRef.current = commit; const textRef = useRef({ text, message }); textRef.current = { text, message }; const setMany = useCallback((ids: Id[], next: Status | null) => { setStatus((prev) => { const map = new Map(prev); for (const id of ids) { if (next === null) map.delete(id); else map.set(id, next); } return map; }); }, []); /** ทำจริงทั้งชุด (ครั้งเดียวต่อชุด) */ const settle = useCallback( async (current: { ids: Id[]; settled: boolean }) => { if (current.settled) return; current.settled = true; if (batch.current === current) batch.current = null; const ids = [...current.ids]; setMany(ids, "committing"); const fallback = textRef.current.text?.failed ?? "ทำรายการไม่สำเร็จ"; try { const failed = failedResult(await commitRef.current(ids), fallback); if (failed) throw new Error(failed); setMany(ids, "done"); } catch (err) { setMany(ids, null); toast.error(errorMessage(err, fallback)); } }, [setMany], ); const undo = useCallback(() => { const current = batch.current; if (!current || current.settled) return; current.settled = true; batch.current = null; setMany(current.ids, null); toast.dismiss(current.toastId); }, [setMany]); const run = useCallback( (id: Id, options?: { message?: string }) => { const current = batch.current && !batch.current.settled ? batch.current : { toastId: `undo-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, ids: [] as Id[], settled: false, }; batch.current = current; if (!current.ids.includes(id)) current.ids.push(id); setMany([id], "waiting"); const { text: t, message: msg } = textRef.current; const label = options?.message && current.ids.length === 1 ? options.message : (msg?.(current.ids.length) ?? (current.ids.length === 1 ? (t?.done ?? "ลบแล้ว") : (t?.deletedMany ?? "ลบ {count} รายการแล้ว").replace( "{count}", String(current.ids.length), ))); toast(label, { id: current.toastId, duration: timeout, action: { label: t?.undo ?? "เลิกทำ", onClick: () => undo() }, onAutoClose: () => void settle(current), onDismiss: () => void settle(current), }); }, [setMany, settle, timeout, undo], ); // ออกจากหน้า / ถอด component = ทำจริงทันที useEffect(() => { const flush = () => { const current = batch.current; if (current && !current.settled) { toast.dismiss(current.toastId); void settle(current); } }; // ปิดแท็บ/รีเฟรชระหว่างรอ: เริ่มทำจริงตั้งแต่ beforeunload และให้เบราว์เซอร์ถาม "ออกจากหน้านี้?" // — request มีเวลาวิ่งระหว่างกล่องถามค้างอยู่ (pagehide อย่างเดียว fetch มักถูกยกเลิกพร้อมหน้า = การลบหาย) const beforeUnload = (event: BeforeUnloadEvent) => { const current = batch.current; if (!current || current.settled) return; flush(); event.preventDefault(); event.returnValue = ""; }; window.addEventListener("beforeunload", beforeUnload); window.addEventListener("pagehide", flush); return () => { window.removeEventListener("beforeunload", beforeUnload); window.removeEventListener("pagehide", flush); flush(); }; }, [settle]); return { run, undo, /** รายการนี้ถูกสั่งลบแล้ว (รอเวลา/กำลังทำ/ทำแล้ว) — ใช้กรองออกจากรายการ */ isPending: (id: Id) => status.has(id), /** สถานะของรายการ (`undefined` = ปกติ) */ statusOf: (id: Id) => status.get(id), }; }