"use client"; import { FormControl, FormField, FormItem, FormMessage } from "@suphark/ui/components/ui/form"; import { Label } from "@suphark/ui/components/ui/label"; import { RadioGroup, RadioGroupItem } from "@suphark/ui/components/ui/radio-group"; import { cn } from "@suphark/ui/lib/utils"; import { type ReactNode, useId } from "react"; import type { Control, FieldValues, Path } from "react-hook-form"; type RadioCardOption = { value: string; label: string; description?: string; icon?: ReactNode; colorClass?: string; }; interface FormFieldRadioCardsProps { control?: Control; /** กับ react-hook-form = ชื่อ field; ไม่มี `control` = `name` ของ RadioGroup (ส่งค่าใน FormData ของ server action) */ name?: Path | string; value?: string; /** ค่าเริ่มต้นเมื่อไม่มี control และไม่คุม value เอง (ฟอร์ม server action) */ defaultValue?: string; onValueChange?: (value: string) => void; label?: string; options: RadioCardOption[]; disabled?: boolean; className?: string; size?: "sm" | "md" | "lg"; /** * `grid` (ค่าเริ่มต้น) = การ์ดสี่เหลี่ยมไอคอนกลาง จุดเลือกมุมขวาบน; * `row` = การ์ดแนวนอน: ปุ่มวิทยุจริงซ้าย, ไอคอน+ชื่อบรรทัดบน, คำอธิบายบรรทัดล่าง (แบบ Pi Auth เลือกประเภทแอป) */ layout?: "grid" | "row"; /** ชื่อกลุ่มสำหรับ screen reader เมื่อไม่แสดง `label` (ส่งต่อไป RadioGroup) */ "aria-label"?: string; } export function FormFieldRadioCards({ control, name, value: propValue, defaultValue, onValueChange: propOnValueChange, label, options, disabled, className, size = "md", layout = "grid", "aria-label": ariaLabel, }: FormFieldRadioCardsProps) { const baseId = useId(); const renderContent = ( value: string | null | undefined, onChange: (val: string) => void, groupName?: string, ) => (
{label && } { if (val !== null) onChange(String(val)); }} value={value} // base-ui-ok: ค่าเริ่มต้นของฟอร์ม server action — ไม่ถูกเปลี่ยนหลัง mount defaultValue={value === undefined ? defaultValue : undefined} disabled={disabled} className={cn( "grid grid-cols-1 gap-4", layout === "grid" ? "md:grid-cols-2" : "gap-3 sm:grid-cols-2", className, )} > {options.map((option) => { const id = `${baseId}-${option.value}`; if (layout === "row") { return ( ); } return (
); })}
); if (control && name) { return ( } render={({ field }) => ( {renderContent(field.value ?? null, field.onChange)} )} /> ); } // ไม่มี control: คุม value เอง (`value` + `onValueChange`) หรือปล่อย uncontrolled ด้วย `name` + `defaultValue` (server action) return renderContent(propValue, propOnValueChange ?? (() => {}), name); }