"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, CommandGroup, CommandInput, CommandItem, CommandList, } from "@suphark/ui/components/ui/command"; import { Popover, PopoverContent, PopoverTrigger } from "@suphark/ui/components/ui/popover"; import { cn } from "@suphark/ui/lib/utils"; import { Check } from "lucide-react"; import { type ReactNode, useEffect, useRef, useState } from "react"; export interface AsyncComboboxOption { value: string; label: string; /** บรรทัดรอง เช่น อีเมล, path ของหน่วยงาน */ description?: string | null; icon?: ReactNode; disabled?: boolean; } export interface AsyncComboboxProps { /** ค่าที่เลือก — `null` = ยังไม่เลือก */ value: string | null; /** เลือกแล้ว (ได้ option เต็มตัวด้วย — ผลค้นจาก server ไม่ได้อยู่ใน state ของแอป) */ onValueChange: (value: string | null, option: O | null) => void; /** * ค้นจาก server — เรียกหลังหยุดพิมพ์ `debounceMs` · ผลของคำค้นล่าสุดเท่านั้นที่แสดง * `signal` ถูก abort เมื่อพิมพ์ต่อ/ปิดกล่อง (ส่งต่อให้ `fetch` ได้เลย) */ search: (query: string, signal: AbortSignal) => Promise>; /** * option ของค่าที่เลือกอยู่ (ชื่อในปุ่ม) — ค่าที่มาจาก server ตอนเปิดหน้า (แก้ไขข้อมูลเดิม) * ไม่ส่ง = ใช้ option ที่ผู้ใช้เพิ่งเลือก (ไม่มีเลย = แสดง `value`) */ selectedOption?: O | null; /** หน่วงก่อนค้น (ms, ค่าเริ่มต้น 250) */ debounceMs?: number; /** ตัวอักษรขั้นต่ำก่อนค้น (ค่าเริ่มต้น 0 = เปิดกล่องแล้วค้นคำว่างทันที — แสดงรายการแนะนำ/ล่าสุด) */ minQuery?: number; placeholder?: string; searchPlaceholder?: string; /** ค้นไม่พบ — รับ `query` ที่พิมพ์ */ empty?: ReactNode | ((query: string) => ReactNode); ariaLabel?: string; id?: string; "aria-labelledby"?: string; "aria-describedby"?: string; "aria-invalid"?: boolean | "true" | "false"; disabled?: boolean; className?: string; } type State = | { status: "idle" } | { status: "loading"; query: string } | { status: "done"; query: string; options: ReadonlyArray } | { status: "error"; query: string }; /** * เลือกหนึ่งค่าโดยค้นจาก server (คน, ผู้ขาย, สินค้า ที่มีมากเกินจะส่งมาทั้งหมด) — หน้าตาเดียวกับ `Combobox` * debounce + abort คำค้นเก่า + สถานะกำลังค้น/ไม่พบ/ค้นไม่สำเร็จ (ประกาศให้โปรแกรมอ่านจอ) ให้ครบ * (รายการไม่มาก ส่งมาทั้งหมดได้ → `Combobox` ที่กรองในเครื่อง) * * { setUserId(id); setChosen(person); }} * search={async (q, signal) => (await fetch(`/api/people?q=${encodeURIComponent(q)}`, { signal }).then((r) => r.json())) * .map((p: Person) => ({ value: p.id, label: p.name, description: p.email }))} /> */ export function AsyncCombobox({ value, onValueChange, search, selectedOption, debounceMs = 250, minQuery = 0, placeholder: placeholderProp, searchPlaceholder: searchPlaceholderProp, empty, ariaLabel, id, "aria-labelledby": ariaLabelledby, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid, disabled, className, }: AsyncComboboxProps) { const ui = useUiText(); const text = ui.combobox; const placeholder = placeholderProp ?? text?.placeholder ?? "เลือก..."; const searchPlaceholder = searchPlaceholderProp ?? text?.searchPlaceholder ?? "ค้นหา..."; const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); const [state, setState] = useState>({ status: "idle" }); const [picked, setPicked] = useState(null); // search มักเป็นฟังก์ชันใหม่ทุก render — อ่านผ่าน ref ไม่ให้ค้นซ้ำทุกครั้งที่แอป render const searchRef = useRef(search); searchRef.current = search; const [retry, setRetry] = useState(0); const q = query.trim(); const tooShort = q.length < minQuery; // biome-ignore lint/correctness/useExhaustiveDependencies: retry ไม่ได้อ่านในนี้ — เป็นตัวสั่งค้นคำเดิมซ้ำ (ปุ่ม "ลองใหม่") useEffect(() => { if (!open || tooShort) return; const controller = new AbortController(); setState({ status: "loading", query: q }); const timer = setTimeout(() => { searchRef.current(q, controller.signal).then( (options) => { if (!controller.signal.aborted) setState({ status: "done", query: q, options }); }, () => { if (!controller.signal.aborted) setState({ status: "error", query: q }); }, ); }, debounceMs); return () => { clearTimeout(timer); controller.abort(); }; }, [open, q, tooShort, debounceMs, retry]); const current = value == null ? null : selectedOption?.value === value ? selectedOption : picked?.value === value ? picked : null; const shownLabel = value == null ? null : (current?.label ?? value); const choose = (option: O) => { setPicked(option); setOpen(false); setQuery(""); onValueChange(option.value, option); }; const options = state.status === "done" && state.query === q ? state.options : []; const loading = !tooShort && (state.status === "loading" || ("query" in state && state.query !== q)); const failed = !tooShort && state.status === "error" && state.query === q; const notFound = !tooShort && !loading && state.status === "done" && options.length === 0; const emptyNode = notFound ? (typeof empty === "function" ? empty(q) : empty) : null; const statusText = tooShort ? (text?.typeToSearch ?? "พิมพ์อย่างน้อย {count} ตัวอักษรเพื่อค้นหา").replace( "{count}", String(minQuery), ) : loading ? (text?.loading ?? "กำลังค้นหา…") : failed ? (text?.searchFailed ?? "ค้นหาไม่สำเร็จ") : notFound ? typeof emptyNode === "string" ? emptyNode : (text?.empty ?? "ไม่พบข้อมูล") : ""; return ( { setOpen(next); if (!next) setQuery(""); }} > } > {shownLabel ?? placeholder} {/* ช่องประกาศอยู่ตลอด เปลี่ยนแค่ข้อความ (โผล่มาพร้อมข้อความ โปรแกรมอ่านจอหลายตัวไม่อ่าน) */}
{statusText}
{(tooShort || loading || failed || notFound) && (
{/* ข้อความเดียวกับช่องประกาศด้านบน — ซ่อนจากโปรแกรมอ่านจอ ไม่ให้อ่านซ้ำ */} {failed && ( )}
)} {options.length > 0 && ( {options.map((option) => ( choose(option)} > {option.icon && ( {option.icon} )} {option.label} {option.description && ( {option.description} )} ))} )}
); }