"use client"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@suphark/ui/components/ui/form"; import { Input } from "@suphark/ui/components/ui/input"; import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, } from "@suphark/ui/components/ui/input-group"; import { Textarea } from "@suphark/ui/components/ui/textarea"; import { useCopyToClipboard } from "@suphark/ui/hooks/use-copy-to-clipboard"; import { useSelectOnFocus } from "@suphark/ui/hooks/use-select-on-focus"; import { cn } from "@suphark/ui/lib/utils"; import { Check, CircleAlert, Copy } from "lucide-react"; import type { ComponentProps } from "react"; import { lazy, Suspense, useState } from "react"; import type { ControllerRenderProps, FieldValues, Path, PathValue } from "react-hook-form"; import { RequiredHint } from "./required-hint"; // --- Types --- type BaseProps = { control: any; name: Path; label: string; required?: boolean; description?: string; suffix?: string; }; // Variant 1: Standard Input type StandardInputProps = BaseProps & { variant?: "default"; enableCopy?: boolean; isNumeric?: boolean; /** เลือกข้อความทั้งหมดเมื่อคลิก/Tab เข้าช่อง (เหมาะกับ `isNumeric` ที่ค่าเริ่มต้น 0) — คลิกซ้ำในช่องที่ focus อยู่ = วางเคอร์เซอร์ตามปกติ */ selectOnFocus?: boolean; } & Omit, "required" | "form" | "name" | "value" | "onChange">; // Variant 2: Autocomplete export type { AutocompleteOption } from "./form-field-autocomplete"; type AutocompleteProps = BaseProps & { variant: "autocomplete"; data: import("./form-field-autocomplete").AutocompleteOption[]; emptyMessage?: string; placeholder?: string; disabled?: boolean; }; // Variant 3: Unique Check type UniqueCheckProps = BaseProps & { variant: "unique-check"; existingValues: string[] | ((value: string) => boolean); uniqueErrorMessage?: string; enableCopy?: boolean; } & Omit, "required" | "form" | "name" | "value">; // Variant 4: Textarea type TextareaProps = BaseProps & { variant: "textarea"; } & Omit, "required" | "form" | "name">; export type FormFieldInputProps = | StandardInputProps | AutocompleteProps | UniqueCheckProps | TextareaProps; // --- Helper Components --- // variant autocomplete ใช้ cmdk (+ Radix Dialog ที่ cmdk พ่วงมา) — แยกไฟล์และโหลดแบบ lazy // ไม่งั้นทุกฟอร์มที่ใช้ FormFieldInput ธรรมดาต้องพก cmdk ไปด้วย const LazyAutocompleteInput = lazy(() => import("./form-field-autocomplete").then((m) => ({ default: m.AutocompleteInput })), ) as unknown as typeof import("./form-field-autocomplete").AutocompleteInput; function AutocompleteInput( props: ComponentProps>, ) { return ( } > ); } function UniqueCheckInput({ field, existingValues, uniqueErrorMessage = "ข้อมูลนี้มีอยู่ในระบบแล้ว", enableCopy, ...props }: { field: ControllerRenderProps>; existingValues: string[] | ((value: string) => boolean); uniqueErrorMessage?: string; enableCopy?: boolean; } & Omit, "value">) { const value = field.value as string; const { isCopied, copyToClipboard } = useCopyToClipboard(); const copyLabel = useUiText().copy; // Determine if duplicate let isDuplicate = false; if (value) { if (Array.isArray(existingValues)) { isDuplicate = existingValues.includes(value); } else { isDuplicate = existingValues(value); } } return (
{isDuplicate && ( )} {enableCopy && ( copyToClipboard(String(field.value || ""))} type="button" title={copyLabel} aria-label={copyLabel} > {isCopied ? : } )} {isDuplicate && (

{uniqueErrorMessage}

)}
); } // --- Main Component --- /** ช่องกรอกที่มีปุ่มคัดลอก — แยกเป็น component เพื่อให้เรียก hook ที่ระดับบนสุดตาม rules of hooks */ function CopyableInput(props: ComponentProps) { const { isCopied, copyToClipboard } = useCopyToClipboard(); const copyLabel = useUiText().copy; return ( copyToClipboard(String(props.value || ""))} type="button" title={copyLabel} aria-label={copyLabel} > {isCopied ? : } ); } /** ใส่จุลภาคคั่นหลักพันที่ส่วนจำนวนเต็ม คงส่วนทศนิยมตามที่พิมพ์ ("1234.50" → "1,234.50") */ function groupThousands(text: string): string { if (text === "" || text === "-") return text; const [intPart = "", decimalPart] = text.split("."); const negative = intPart.startsWith("-"); const digits = negative ? intPart.slice(1) : intPart; const grouped = digits === "" ? "" : Number(digits).toLocaleString("en-US"); return `${negative ? "-" : ""}${grouped}${decimalPart !== undefined ? `.${decimalPart}` : ""}`; } function numberToText(value: unknown): string { if (value === undefined || value === null || value === "") return ""; return String(value); } /** * ช่องตัวเลข (`isNumeric`) — ค่าในฟอร์มเป็น number เสมอ (ว่าง = undefined) ส่วนข้อความที่กำลังพิมพ์ * ("2.", "2.50", "-") เก็บไว้ในช่องเองจนกว่าจะออกจากช่อง — ค่า 0 แสดงเป็น "0" ไม่ใช่ช่องว่าง */ function NumericTextInput({ field, enableCopy, suffix, inputProps, ...slotProps }: { field: ControllerRenderProps>; enableCopy?: boolean; suffix?: string; inputProps: ComponentProps; } & Pick, "id" | "aria-describedby" | "aria-invalid">) { const [draft, setDraft] = useState(null); const draftValue = draft === null || draft === "" || draft === "-" ? undefined : Number(draft); // ข้อความที่พิมพ์ยังตรงกับค่าในฟอร์ม → แสดงตามที่พิมพ์; ค่าถูกเปลี่ยนจากข้างนอก (reset/setValue) → แสดงค่าใหม่ const draftMatches = draft !== null && (draftValue === undefined ? field.value === undefined || field.value === null || field.value === "" : draftValue === field.value); const display = groupThousands(draftMatches ? draft : numberToText(field.value)); const onChange = (event: React.ChangeEvent) => { const raw = event.target.value.replace(/,/g, "").trim(); if (!/^-?\d*\.?\d*$/.test(raw)) return; setDraft(raw); const next = raw === "" || raw === "-" || raw === "." || raw === "-." ? undefined : Number(raw); field.onChange(next as PathValue>); }; const onBlur = () => { setDraft(null); field.onBlur(); }; const props = { ...inputProps, // id/aria-* จาก FormControl — ให้ label และข้อความ error ผูกกับช่อง ...slotProps, name: field.name, ref: field.ref, disabled: field.disabled ?? inputProps.disabled, type: "text", inputMode: "decimal" as const, value: display, onChange, onBlur, }; if (enableCopy) return ; if (suffix) { return ( {suffix} ); } return ; } export function FormFieldInput({ control, name, label, required, ...props }: FormFieldInputProps) { const standard = props.variant === undefined || props.variant === "default" ? (props as StandardInputProps) : undefined; const selectHandlers = useSelectOnFocus(standard?.selectOnFocus ?? false, { onFocus: standard?.onFocus, onMouseUp: standard?.onMouseUp, onPointerDown: standard?.onPointerDown, }); return ( ( {label}{" "} {required ? ( ) : null} {required ? : null} {(() => { if (props.variant === "autocomplete") { const { data, emptyMessage, ...rest } = props as AutocompleteProps; return ( ); } else if (props.variant === "unique-check") { const { existingValues, uniqueErrorMessage, variant, enableCopy, ...rest } = props as UniqueCheckProps; return ( ); } else if (props.variant === "textarea") { const { variant, ...rest } = props as TextareaProps; return (