"use client"; import { useSheetOnMobile } from "@suphark/ui/components/shared/ui-defaults"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@suphark/ui/components/ui/alert-dialog"; import { Checkbox } from "@suphark/ui/components/ui/checkbox"; import { Input } from "@suphark/ui/components/ui/input"; import { Label } from "@suphark/ui/components/ui/label"; import { useFrozenWhileOpen } from "@suphark/ui/hooks/use-frozen-while-open"; import { useLazyDrawer } from "@suphark/ui/hooks/use-lazy-drawer"; import { useIsMobile } from "@suphark/ui/hooks/use-mobile"; import { cn } from "@suphark/ui/lib/utils"; import { createContext, type ReactNode, useCallback, useContext, useId, useMemo, useRef, useState, } from "react"; import { Button } from "./button/button"; import { type ConfirmSpec, normalizeConfirm } from "./confirm-dialog"; import { useUiText } from "./ui-text"; type BaseSpec = Exclude; /** `alert()` — ปุ่มเดียว (ตกลง) */ export type AlertSpec = ConfirmSpec; /** `prompt()` — ช่องกรอกข้อความ resolve string หรือ null เมื่อยกเลิก */ export type PromptSpec = | string | (BaseSpec & { defaultValue?: string; placeholder?: string; }); export interface ChoiceOption { label: ReactNode; value: string; variant?: "default" | "destructive" | "outline"; } /** `choose()` — ปุ่มหลายทางเลือก resolve value ของปุ่มที่กด หรือ null เมื่อยกเลิก */ export interface ChoiceSpec extends Omit { choices: ChoiceOption[]; } export interface ChecklistOption { label: ReactNode; value: string; description?: ReactNode; defaultChecked?: boolean; } /** `checklist()` — ติ๊กเลือกหลายรายการ resolve value[] ที่เลือก หรือ null เมื่อยกเลิก */ export interface ChecklistSpec extends BaseSpec { options: ChecklistOption[]; } export interface Dialogs { alert: (spec: AlertSpec) => Promise; confirm: (spec: ConfirmSpec) => Promise; prompt: (spec: PromptSpec) => Promise; choose: (spec: ChoiceSpec) => Promise; checklist: (spec: ChecklistSpec) => Promise; } type Mode = "alert" | "confirm" | "prompt" | "choice" | "checklist"; type Request = BaseSpec & { mode: Mode; placeholder?: string; choices?: ChoiceOption[]; options?: ChecklistOption[]; }; type Result = boolean | string | string[] | null; const DialogsContext = createContext(null); /** * กล่องโต้ตอบแบบ promise ทั้งแอป (แทน `window.alert/confirm/prompt`) — ครอบครั้งเดียวที่ root แล้วเรียก * `useDialogs()` จากที่ไหนก็ได้ โดยไม่ต้อง render อะไรในต้นไม้ของผู้เรียก (ต่างจาก `useConfirm()`) * * const dialogs = useDialogs(); * if (!(await dialogs.confirm({ description: "ลบโครงการนี้?", destructive: true }))) return; * const name = await dialogs.prompt({ description: "ชื่อโครงการใหม่", defaultValue: project.name }); * const action = await dialogs.choose({ description: "ทำอย่างไรกับงานข้างใน?", choices: [ * { label: "ลบทั้งหมด", value: "delete", variant: "destructive" }, * { label: "ย้ายไป Inbox", value: "inbox" }, * ] }); * const picked = await dialogs.checklist({ description: "เลือกคอลัมน์", options: [{ label: "ชื่อ", value: "name", defaultChecked: true }] }); * * เปิดคำขอใหม่ขณะกล่องเปิดอยู่ → คำขอเดิม resolve เป็นค่ายกเลิก (false/null) แล้วแสดงคำขอใหม่แทน * ข้อความค่าเริ่มต้น (หัว/ปุ่ม) มาจาก `UiText` — ส่ง `title`/`confirmLabel`/`cancelLabel` เพื่อปรับต่อครั้ง */ export function DialogsProvider({ children, sheetOnMobile: sheetOnMobileProp, }: { children: ReactNode; /** * จอ < 768px แสดงทุกโหมด (alert/confirm/prompt/choose/checklist) เป็นแผ่นล่าง: ตัวเลือก/ช่องติ๊กเป็นแถว 48px, * ปุ่มหลักเต็มความกว้างอยู่บน ปุ่มยกเลิกล่างสุด, ปัดลงเพื่อยกเลิก — จอกว้างเป็นกล่องกลางจอเหมือนเดิม · ค่าเริ่มต้น false */ sheetOnMobile?: boolean; }) { const sheetOnMobile = useSheetOnMobile(sheetOnMobileProp); const text = useUiText(); const isMobile = useIsMobile(); const [request, setRequest] = useState(null); // Drawer โหลดเมื่อต้องใช้ — provider อยู่ใน root layout จอกว้างจึงไม่ต้องโหลดโค้ดแผ่นล่างเลย (0.96.0) const drawer = useLazyDrawer(sheetOnMobile && isMobile); // ตรึงแบบ (แผ่นล่าง/กล่องกลาง) ระหว่างเปิด — หมุนจอแล้วไม่ remount ช่องที่กำลังพิมพ์ const sheet = useFrozenWhileOpen(sheetOnMobile && isMobile && drawer !== null, request !== null); const [promptValue, setPromptValue] = useState(""); const [checked, setChecked] = useState([]); const resolveRef = useRef<((value: Result) => void) | null>(null); const open = useCallback((next: Request, resolve: (value: Result) => void) => { // คำขอที่ค้างอยู่ถือว่ายกเลิก resolveRef.current?.(next.mode === "confirm" || next.mode === "alert" ? false : null); resolveRef.current = resolve; setRequest(next); }, []); const typeToConfirmId = useId(); const settle = useCallback((value: Result) => { resolveRef.current?.(value); resolveRef.current = null; setRequest(null); setPromptValue(""); setChecked([]); }, []); const dialogs = useMemo( () => ({ alert: (spec) => new Promise((resolve) => { open({ ...normalizeConfirm(spec), mode: "alert" }, () => resolve()); }), confirm: (spec) => new Promise((resolve) => { setPromptValue(""); // ช่องพิมพ์ยืนยัน (requireText) เริ่มว่างทุกครั้ง open({ ...normalizeConfirm(spec), mode: "confirm" }, (value) => resolve(value === true)); }), prompt: (spec) => new Promise((resolve) => { const options = typeof spec === "string" ? { description: spec } : spec; setPromptValue(options.defaultValue ?? ""); open({ ...options, mode: "prompt" }, (value) => resolve(typeof value === "string" ? value : null), ); }), choose: (spec) => new Promise((resolve) => { open({ ...spec, mode: "choice" }, (value) => resolve(typeof value === "string" ? value : null), ); }), checklist: (spec) => new Promise((resolve) => { setChecked(spec.options.filter((o) => o.defaultChecked).map((o) => o.value)); open({ ...spec, mode: "checklist" }, (value) => resolve(Array.isArray(value) ? value : null), ); }), }), [open], ); const cancelValue: Result = request?.mode === "confirm" ? false : null; const titleByMode: Record = { alert: text.alertTitle ?? "แจ้งให้ทราบ", confirm: text.confirmTitle ?? "ยืนยันการทำรายการ", prompt: text.promptTitle ?? "กรอกข้อมูล", choice: text.chooseTitle ?? "เลือกการทำรายการ", checklist: text.checklistTitle ?? "เลือกรายการ", }; const confirmLabelByMode: Record = { alert: text.ok ?? "ตกลง", confirm: text.confirm ?? "ยืนยัน", prompt: text.save, choice: "", checklist: text.confirm ?? "ยืนยัน", }; const confirmResult = (): Result => { if (!request) return null; if (request.mode === "prompt") return promptValue; if (request.mode === "checklist") return checked; return true; }; // ส่วนเนื้อ (ช่องกรอก/ช่องพิมพ์ยืนยัน/รายการติ๊ก) ใช้ร่วมกันทั้งกล่องกลางจอและแผ่นล่าง const fields = request ? ( <> {request.mode === "prompt" && ( setPromptValue(event.target.value)} className={cn(sheet && "h-11")} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); settle(promptValue); } }} /> )} {request.mode === "confirm" && request.requireText && ( // พิมพ์ข้อความยืนยันก่อนกด (เหมือน ConfirmDialog — เดิม useDialogs().confirm ข้าม requireText ไปเงียบ ๆ)
setPromptValue(event.target.value)} autoComplete="off" spellCheck={false} className={cn(sheet && "h-11")} />
)} {request.mode === "checklist" && (
{request.options?.map((option) => { const isChecked = checked.includes(option.value); return ( ); })}
)} ) : null; const confirmDisabled = request?.mode === "confirm" && Boolean(request.requireText) && promptValue.trim() !== request.requireText; if (sheet && drawer) { const { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } = drawer; return ( {children} !o && settle(cancelValue)} showSwipeHandle > {request && ( {request.title ?? titleByMode[request.mode]} {request.description} {fields && (
{fields}
)}
{request.mode === "choice" ? ( request.choices?.map((choice) => ( )) ) : ( )} {request.mode !== "alert" && ( )}
)}
); } return ( {children} !o && settle(cancelValue)}> {request && ( // choose(): ยกเลิก + หลายตัวเลือกบนแถวเดียว — กว้างขึ้น (28rem) และขึ้นบรรทัดใหม่เมื่อป้ายยาว // (ต้องมี data-[size=default]: เหมือนคลาสของ AlertDialogContent ให้ twMerge แทนที่ — `sm:max-w-md` เฉย ๆ แพ้ specificity ยังกว้าง 24rem) // (เดิมปุ่มล้นกรอบ 24rem เช่น "ยกเลิก / Move tasks to No Section / Delete tasks") {request.title ?? titleByMode[request.mode]} {request.description} {fields} *]:max-w-full")} > {request.mode !== "alert" && ( {request.cancelLabel ?? text.cancel} )} {request.mode === "choice" ? ( request.choices?.map((choice) => ( settle(choice.value)} > {choice.label} )) ) : ( settle(confirmResult())} > {request.confirmLabel ?? confirmLabelByMode[request.mode]} )} )} ); } /** ใช้ได้ทุกที่ใต้ `DialogsProvider` */ export function useDialogs(): Dialogs { const dialogs = useContext(DialogsContext); if (!dialogs) { throw new Error("useDialogs() ต้องอยู่ใต้ (ครอบที่ root layout)"); } return dialogs; }