"use client"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { copyText } from "@suphark/ui/lib/copy-text"; import { useCallback, useEffect, useRef, useState } from "react"; import { toast as sonner } from "sonner"; export interface CopyToClipboardLabels { success: string; failed: string; } export interface UseCopyToClipboardOptions { /** false = ไม่แสดง toast (แอปแสดง ✓ ที่ปุ่มเอง); object = ข้อความของแอป — ไม่ส่ง = `UiText.clipboard` ("คัดลอกแล้ว"/"คัดลอกไม่สำเร็จ") */ toast?: boolean | Partial; /** ms ที่ `isCopied`/`copiedKey` ค้างไว้หลังคัดลอก */ timeout?: number; } /** * คัดลอกข้อความ (มี fallback execCommand สำหรับ browser/webview ที่บล็อก clipboard API) * * const { copyToClipboard, copiedKey } = useCopyToClipboard({ toast: { success: "คัดลอกแล้ว", failed: "คัดลอกไม่สำเร็จ" } }); * copyToClipboard(row.value, row.id) // หลายปุ่มในหน้าเดียว → copiedKey บอกว่าปุ่มไหนเพิ่งคัดลอก * copyToClipboard(all, "all", { success: `คัดลอกทั้งชุด ${n} ค่า` }) // ข้อความเฉพาะครั้งนั้น */ export function useCopyToClipboard(options: UseCopyToClipboardOptions = {}) { const { toast = true, timeout = 2000 } = options; const [copiedKey, setCopiedKey] = useState(null); const timer = useRef | null>(null); const uiText = useUiText().clipboard; useEffect( () => () => { if (timer.current) clearTimeout(timer.current); }, [], ); const custom = typeof toast === "object" ? toast : undefined; const showToast = toast !== false; const success = custom?.success ?? uiText?.success ?? "คัดลอกแล้ว"; const failed = custom?.failed ?? uiText?.failed ?? "คัดลอกไม่สำเร็จ"; const copyToClipboard = useCallback( async ( text: string, key = "default", /** ทับข้อความ toast เฉพาะครั้งนี้ — ปุ่มหลายตัวที่ข้อความต่างกัน (ขอจาก Pi Config) */ labels?: Partial, ): Promise => { const ok = await copyText(text); if (timer.current) clearTimeout(timer.current); if (!ok) { setCopiedKey(null); if (showToast) sonner.error(labels?.failed ?? failed); return false; } setCopiedKey(key); if (showToast) sonner.success(labels?.success ?? success); timer.current = setTimeout(() => setCopiedKey(null), timeout); return true; }, [showToast, success, failed, timeout], ); return { isCopied: copiedKey !== null, copiedKey, copyToClipboard }; }