"use client"; import { Button } from "@suphark/ui/components/shared/button/button"; import { SwitcherChevron } from "@suphark/ui/components/shared/switcher-chevron"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "@suphark/ui/components/ui/command"; import { FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@suphark/ui/components/ui/form"; import { Popover, PopoverContent, PopoverTrigger } from "@suphark/ui/components/ui/popover"; import { commandContainsFilter } from "@suphark/ui/lib/command-filter"; import { cn } from "@suphark/ui/lib/utils"; import { Check } from "lucide-react"; import * as React from "react"; import { useEffect, useState, useTransition } from "react"; import type { FieldValues, Path } from "react-hook-form"; interface FormFieldComboboxProps { control: any; // Using any to bypass deep generic reconciliation errors with Control in RHF 7 name: Path; label: string; placeholder?: string; fetcher: () => Promise<{ label: string; value: string; subLabel?: string; [key: string]: any }[]>; /** * คีย์สำหรับแคชและตัดสินว่าต้องโหลดใหม่หรือไม่ * จำเป็นเมื่อส่ง fetcher เป็น arrow function แบบ inline (identity เปลี่ยนทุก render) * ถ้าไม่ส่ง จะใช้ตัว fetcher เองเป็นคีย์ตามเดิม */ fetcherKey?: string; disabled?: boolean; required?: boolean; className?: string; autoFocus?: boolean; onSelect?: (option: { label: string; value: string; [key: string]: any }) => void; } type CacheEntry = { label: string; value: string; subLabel?: string }[]; // cache ตัวเลือกข้าม mount: key เป็น string (`fetcherKey`) เก็บใน Map; key เป็นฟังก์ชัน (ไม่ส่ง fetcherKey) // เก็บใน WeakMap — inline arrow ที่ identity เปลี่ยนทุก render จะถูก GC ไม่โตค้างตลอดอายุแท็บ const stringCache = new Map(); const fnCache = new WeakMap(); const cacheGet = (key: string | object) => typeof key === "string" ? stringCache.get(key) : fnCache.get(key); const cacheSet = (key: string | object, data: CacheEntry) => { if (typeof key === "string") stringCache.set(key, data); else fnCache.set(key, data); }; export function FormFieldCombobox({ control, name, label, placeholder: placeholderProp, fetcher, fetcherKey, disabled, required, className, autoFocus, onSelect, }: FormFieldComboboxProps) { const text = useUiText(); const cacheKey = fetcherKey ?? fetcher; const [options, setOptions] = useState<{ label: string; value: string; subLabel?: string }[]>( () => cacheGet(cacheKey) || [], ); const [isLoading, startTransition] = useTransition(); const [open, setOpen] = React.useState(false); const [failed, setFailed] = React.useState(false); const placeholder = placeholderProp ?? text.combobox?.placeholder ?? "เลือก…"; // เก็บ fetcher ล่าสุดไว้ใน ref เพื่อไม่ให้ arrow function แบบ inline // (identity ใหม่ทุก render) ทำให้ยิงโหลดซ้ำทุกครั้งที่ฟอร์ม re-render const fetcherRef = React.useRef(fetcher); fetcherRef.current = fetcher; useEffect(() => { // แสดงค่าจากแคชก่อนเพื่อลดการกระพริบ แล้วค่อยโหลดค่าล่าสุดทับ const cached = cacheGet(cacheKey); if (cached) setOptions(cached); // ผลของ key เก่าที่มาทีหลัง (เปลี่ยน fetcherKey ระหว่างโหลด) ห้ามทับตัวเลือกของ key ใหม่ let stale = false; setFailed(false); startTransition(async () => { try { const data = await fetcherRef.current(); if (stale) return; setOptions(data); cacheSet(cacheKey, data); } catch (error) { if (stale) return; console.error("Failed to fetch combobox options:", error); // ไม่มีตัวเลือกให้เลือก = บอกผู้ใช้ในช่อง (เดิมเงียบ เหลือรายการว่าง "ไม่พบข้อมูล") setFailed(true); } }); return () => { stale = true; }; }, [cacheKey]); return ( ( {label} {required && *} {/* FormControl ครอบตัวปุ่ม (ไม่ใช่ Popover ที่ไม่มี DOM) — id/aria-invalid ไปถึงปุ่ม label จึงผูกกับช่อง */} } > {field.value ? options.find((option) => option.value === field.value)?.label : options.length === 0 && isLoading ? (text.loading ?? "กำลังโหลด…") : options.length === 0 && failed ? (text.actionFailed ?? "ดำเนินการไม่สำเร็จ") : placeholder} {text.combobox?.empty ?? "ไม่พบข้อมูล"} {options.map((option) => ( { // คลิกตัวที่เลือกอยู่ = คงค่าเดิม (เดิมล้างค่า) field.onChange(option.value); onSelect?.(option); setOpen(false); }} >
{option.label} {option.subLabel && ( {option.subLabel} )}
))}
)} /> ); }