"use client"; import { ConfirmDialog, type ConfirmSpec, normalizeConfirm, } from "@suphark/ui/components/shared/confirm-dialog"; import { type ReactNode, useCallback, useState } from "react"; /** * `window.confirm` แบบ promise บน ConfirmDialog — สำหรับโค้ดฝั่ง client ที่ไม่ใช่ server action * (เช่น กดลบแล้วเรียก fetch/mutation เอง) — ยกมาจาก DueBell * * const { confirm, confirmDialog } = useConfirm(); * async function remove() { * if (!(await confirm({ description: "ลบรายการนี้?", destructive: true }))) return; * … * } * return <>{confirmDialog}; * * ต้อง render `confirmDialog` ในต้นไม้ของ component ที่เรียก hook (ครั้งเดียวต่อ hook) * เรียก `confirm` ซ้ำขณะกล่องเปิดอยู่ → คำขอเดิม resolve(false) แล้วแสดงคำขอใหม่แทน */ export function useConfirm( options: { /** กล่องยืนยันเป็นแผ่นล่างบนจอ < 768px (ดู `ConfirmDialog sheetOnMobile`) — ค่าเริ่มต้น false */ sheetOnMobile?: boolean; } = {}, ): { confirm: (spec: ConfirmSpec) => Promise; confirmDialog: ReactNode; } { const [request, setRequest] = useState<{ options: Exclude; resolve: (ok: boolean) => void; } | null>(null); const confirm = useCallback( (spec: ConfirmSpec) => new Promise((resolve) => { setRequest((prev) => { prev?.resolve(false); return { options: normalizeConfirm(spec), resolve }; }); }), [], ); function settle(ok: boolean) { request?.resolve(ok); setRequest(null); } const confirmDialog = request ? ( !open && settle(false)} title={request.options.title} description={request.options.description} confirmLabel={request.options.confirmLabel} cancelLabel={request.options.cancelLabel} destructive={request.options.destructive} requireText={request.options.requireText} requireTextLabel={request.options.requireTextLabel} sheetOnMobile={options.sheetOnMobile} onConfirm={() => settle(true)} /> ) : null; return { confirm, confirmDialog }; }