"use client"; import { Button } from "@suphark/ui/components/shared/button/button"; import { DeleteButton } from "@suphark/ui/components/shared/button/delete-button"; import { ConfirmDialog } from "@suphark/ui/components/shared/confirm-dialog"; import { useSheetOnMobile } from "@suphark/ui/components/shared/ui-defaults"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@suphark/ui/components/ui/alert-dialog"; import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@suphark/ui/components/ui/dropdown-menu"; import type { Row } from "@tanstack/react-table"; import { Ellipsis } from "lucide-react"; import { useEffect, useState, useTransition } from "react"; import { toast } from "sonner"; import { ActionDelete, ActionEdit } from "../shared/semantic-icons"; interface ActionState { error?: string; data?: T; success?: string; } /** * dev only: open the edit dialog but nothing dialog-like shows up within 1s -> the app's EditDialog most likely * does not forward `open`/`onOpenChange` (a wrapper taking only `initialData`) — warn instead of failing silently */ function useWarnEditDialogNotOpened(open: boolean) { useEffect(() => { if (!open || process.env.NODE_ENV === "production") return; const id = setTimeout(() => { if (document.querySelector('[role="dialog"],[role="alertdialog"]')) return; console.warn( "[@suphark/ui] DataTableRowActions: EditDialog opened but no dialog appeared — EditDialog must pass `open` and `onOpenChange` through to its Dialog (see the EditDialog prop docs).", ); }, 1000); return () => clearTimeout(id); }, [open]); } interface DataTableRowActionsProps { row: Row; /** * รายการเมนูเพิ่มก่อน แก้ไข/ลบ — `DropdownMenuItem` ที่สั่งงานด้วย `onClick` เท่านั้น * **ห้ามวางกล่อง (Dialog/Sheet/AlertDialog) ไว้ในนี้** หรือใช้ `}>`: * กล่องจะอยู่ในเมนู เมนูปิดเมื่อคลิก = กล่องถูกถอดไปด้วย (กดแล้วไม่เปิด) — ให้รายการเมนูเปิด state แล้ววางกล่องนอก: * * const [open, setOpen] = useState(false); * <> * * setOpen(true)}>ตั้งราคา * * * * * (`suphark-ui-audit` กฎ `menu-item-trigger` จับแบบ Trigger render={}) */ children?: React.ReactNode; /** * กล่องแก้ไข — แพ็กเกจ mount `` นอกเมนูเมื่อกด "แก้ไข" * **ต้องส่ง `open`/`onOpenChange` ต่อให้กล่องจริง** (wrapper ที่รับแค่ `initialData` = เมนูแก้ไขไม่เปิดอะไร — dev เตือนใน console) * และคง identity ของ component (ประกาศนอก render หรือ useCallback/useMemo) ไม่งั้นกล่อง remount ทุก render * ไม่ส่ง = ไม่มีเมนู "แก้ไข" */ EditDialog?: React.ComponentType<{ initialData?: TData; open?: boolean; onOpenChange?: (open: boolean) => void; children?: React.ReactNode; }>; /** * Optional server action to call for deletion. * If not provided, the "Delete" action will not be shown. */ deleteAction?: (id: string) => Promise>; /** * The name of the resource to display in toast messages (e.g. "User Status"). */ resourceName: string; /** * The key to access the name/title of the item for display. Defaults to "name". */ nameKey?: keyof TData; /** * The key to access the unique ID of the item. Defaults to "id". */ idKey?: keyof TData; /** กล่องยืนยันการลบเป็นแผ่นล่างบนจอ < 768px (ปุ่ม 48px เต็มความกว้าง) — ค่าเริ่มต้น false · เมนู "…" เองเป็น dropdown เหมือนเดิม (children เป็น `DropdownMenuItem` ของแอป) */ sheetOnMobile?: boolean; } export function DataTableRowActions({ row, children, EditDialog, deleteAction, resourceName, nameKey = "name" as keyof TData, idKey = "id" as keyof TData, sheetOnMobile: sheetOnMobileProp, }: DataTableRowActionsProps) { const sheetOnMobile = useSheetOnMobile(sheetOnMobileProp); const text = useUiText(); // ชื่อชนิดข้อมูล (เช่น "โปรเจกต์") แทรกในข้อความลบ — ไม่ส่งมา = ข้อความไม่มีคำนี้ const resource = resourceName ? ` ${resourceName}` : ""; const fill = (template: string, name: string) => template.replace("{resource}", resource).replace("{name}", name); const item = row.original; const itemRecord = item as Record; const itemName = String( itemRecord[nameKey as string] ?? itemRecord.nameThai ?? itemRecord.name ?? "", ); const [isPending, startTransition] = useTransition(); const [isEditDialogOpen, setIsEditDialogOpen] = useState(false); useWarnEditDialogNotOpened(isEditDialogOpen); const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false); const handleDelete = () => { if (!deleteAction) return; // async + await ใน transition = isPending ค้างจนลบเสร็จ (ปุ่มหมุน/กดซ้ำไม่ได้) — เดิม callback คืนทันที ลบซ้ำได้ startTransition(async () => { const promise = deleteAction(String(itemRecord[idKey as string])).then((result) => { if (result.error) throw new Error(result.error); setIsDeleteDialogOpen(false); return result; }); toast.promise(promise, { loading: fill(text.table?.deleting ?? "กำลังลบ{resource} “{name}”…", itemName), success: fill(text.table?.deleted ?? "ลบ{resource} “{name}” แล้ว", itemName), error: (err: Error) => err.message, }); try { await promise; } catch { // แจ้งผ่าน toast.promise แล้ว } }); }; return (
} > {children} {children && (EditDialog || deleteAction) && } {EditDialog && ( setIsEditDialogOpen(true)}> {text.edit ?? "แก้ไข"} )} {EditDialog && deleteAction && } {deleteAction && ( setIsDeleteDialogOpen(true)} > {text.table?.delete ?? "ลบ"} )} {/* mount เฉพาะตอนเปิด — ไม่งั้นทุกแถว mount Dialog+ฟอร์มค้างไว้ (50 แถว = 50 ฟอร์ม) และ initialData stale */} {EditDialog && isEditDialogOpen && ( )} {deleteAction && sheetOnMobile && ( )} {deleteAction && !sheetOnMobile && ( {text.table?.deleteTitle ?? "ยืนยันการลบ"} {fill( text.table?.deleteDescription ?? "ลบ{resource} “{name}” แล้วกู้คืนไม่ได้", itemName, )} {text.cancel} )}
); }