"use client"; import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, } from "@suphark/ui/components/ui/input-group"; import { focusFieldOf } from "@suphark/ui/lib/focus-after-remove"; import { cn } from "@suphark/ui/lib/utils"; import type { LucideIcon } from "lucide-react"; import { Search, X } from "lucide-react"; import { type CSSProperties, type KeyboardEvent, useDeferredValue, useId, useMemo, useRef, useState, } from "react"; import { SelectionButton } from "./selection-button"; export interface IconPickerItem { name: T; icon: LucideIcon; labelTh: string; labelEn: string; keywords?: readonly string[]; /** หมวด — ใช้กับ `categories` (ปุ่มกรองตามหมวด) */ category?: string; } export interface IconPickerCategory { value: string; label: string; } export interface IconPickerText { searchPlaceholder: string; searchLabel: string; clear: string; preview: string; /** รับชื่อคำค้น */ empty: (query: string) => string; showAll: string; /** ปุ่มหมวด "ทั้งหมด" */ allCategories: string; } const TEXT: Record<"th" | "en", IconPickerText> = { th: { searchPlaceholder: "ค้นหาไอคอน (เช่น บ้าน, house, รถ)…", searchLabel: "ค้นหาไอคอน", clear: "ล้างการค้นหา", preview: "ตัวอย่างไอคอนและสี", empty: (q) => `ไม่พบไอคอนที่ตรงกับ “${q}”`, showAll: "แสดงไอคอนทั้งหมด", allCategories: "ทั้งหมด", }, en: { searchPlaceholder: "Search icons (e.g. house, car, coffee)…", searchLabel: "Search icons", clear: "Clear search", preview: "Icon & color preview", empty: (q) => `No icons found for “${q}”`, showAll: "Show all icons", allCategories: "All", }, }; export interface IconPickerProps { value: T | null | undefined; onChange: (name: T) => void; /** ชุดไอคอนของแอป (แพ็กเกจไม่ bundle ชุดใด — ไม่ดึง lucide ทั้งก้อน) */ icons: ReadonlyArray>; /** ภาษาของ label/ข้อความ (ค่าเริ่มต้น th) */ language?: "th" | "en"; /** ทับข้อความบางส่วน */ text?: Partial; /** ปุ่มกรองตามหมวด (ตาม `item.category`) — ค้นหาเมื่อพิมพ์ครอบทุกหมวด */ categories?: ReadonlyArray; /** โฟกัสช่องค้นหาเมื่อแสดง (ใช้ใน popover) */ autoFocusSearch?: boolean; /** สีของประเภทรายการ (dynamic จากผู้ใช้) — ไอคอนที่เลือกและ preview ใช้ inline style จากสีนี้ */ accentColor?: string; /** ความสูงของกริด (ค่าเริ่มต้น h-36) */ heightClassName?: string; /** คอลัมน์ของกริด (ค่าเริ่มต้น grid-cols-6 sm:grid-cols-8) */ columnsClassName?: string; className?: string; } /** ทำให้เทียบได้: ตัวพิมพ์เล็ก + ตัด "-" ของชื่อ lucide (map-pin = "map pin") */ function normalize(value: string): string { return value.toLowerCase().replace(/[-_]+/g, " "); } /** * คะแนนความตรงของไอคอนกับคำค้น (คั่นคำด้วยช่องว่าง ทุกคำต้องเจอ) — 0 = ไม่ตรง * ชื่อ/ป้ายตรงทั้งคำ > ขึ้นต้นด้วยคำค้น > มีคำค้นอยู่ (ป้าย/ชื่อ ก่อนคำค้นเสริม) */ export function iconSearchScore(item: IconPickerItem, query: string): number { const words = normalize(query).trim().split(/\s+/).filter(Boolean); if (words.length === 0) return 1; const primary = [normalize(item.name), normalize(item.labelTh), normalize(item.labelEn)]; const extra = (item.keywords ?? []).map(normalize); let score = 0; for (const word of words) { let best = 0; for (const field of primary) { if (field === word) best = Math.max(best, 6); else if (field.startsWith(word)) best = Math.max(best, 4); else if (field.includes(word)) best = Math.max(best, 3); } for (const field of extra) { if (field === word) best = Math.max(best, 3); else if (field.includes(word)) best = Math.max(best, 2); } if (best === 0) return 0; score += best; } return score; } /** * เลือกไอคอนจากชุดที่แอปส่งมา: ค้นหา (labelTh/labelEn/keywords/name หลายคำ เรียงตามความตรง, ผ่าน useDeferredValue) * + ปุ่มกรองตามหมวด + กริด SelectionButton (ลูกศรเลื่อนในกริด) + preview ไอคอนที่เลือกพร้อมสี * ชุดมาตรฐาน 300+ ตัวพร้อมคำค้นไทย: `ICON_CATALOG` จาก `@suphark/ui/icons` (หรือใช้ `IconSelect` ที่ครบในตัว) */ export function IconPicker({ value, onChange, icons, language = "th", text: textProp, categories, autoFocusSearch = false, accentColor, heightClassName = "h-36", columnsClassName = "grid-cols-6 sm:grid-cols-8", className, }: IconPickerProps) { const text: IconPickerText = { ...TEXT[language], ...textProp }; const [query, setQuery] = useState(""); const [category, setCategory] = useState(null); const deferred = useDeferredValue(query); const listId = useId(); const gridRef = useRef(null); const [focusIndex, setFocusIndex] = useState(null); const selected = icons.find((i) => i.name === value); const labelOf = (i: IconPickerItem) => (language === "en" ? i.labelEn : i.labelTh); const filtered = useMemo(() => { const q = deferred.trim(); if (!q) return category ? icons.filter((i) => i.category === category) : icons; return icons .map((item, index) => ({ item, index, score: iconSearchScore(item, q) })) .filter((r) => r.score > 0) .sort((a, b) => b.score - a.score || a.index - b.index) .map((r) => r.item); }, [icons, deferred, category]); // ช่องที่รับ Tab ช่องเดียว (roving tabindex): ไอคอนที่เลือก ไม่มีก็ช่องแรก — ลูกศรเลื่อนในกริด const selectedIndex = filtered.findIndex((i) => i.name === value); const tabIndexAt = focusIndex !== null && focusIndex < filtered.length ? focusIndex : selectedIndex >= 0 ? selectedIndex : 0; const moveFocus = (e: KeyboardEvent, from: number) => { const grid = gridRef.current; if (!grid) return; const cols = Math.max( 1, getComputedStyle(grid).gridTemplateColumns.split(" ").filter(Boolean).length, ); const last = filtered.length - 1; const keys: Record = { ArrowRight: Math.min(from + 1, last), ArrowLeft: Math.max(from - 1, 0), ArrowDown: Math.min(from + cols, last), ArrowUp: Math.max(from - cols, 0), Home: 0, End: last, }; const next = keys[e.key]; if (next === undefined) return; e.preventDefault(); setFocusIndex(next); grid.querySelectorAll("[data-icon-option]")[next]?.focus(); }; const accentStyle: CSSProperties | undefined = accentColor ? { backgroundColor: `${accentColor}18`, borderColor: `${accentColor}99`, color: accentColor } : undefined; return (
{selected && (

{text.preview}

{labelOf(selected)}

)} { setQuery(e.target.value); setFocusIndex(null); }} autoFocus={autoFocusSearch} placeholder={text.searchPlaceholder} aria-label={text.searchLabel} aria-controls={listId} autoComplete="off" spellCheck={false} /> {query && ( { focusFieldOf(e.currentTarget); setQuery(""); }} aria-label={text.clear} > )} {categories && categories.length > 0 && !query && (
{[{ value: null, label: text.allCategories }, ...categories].map((c) => ( ))}
)}
{filtered.length > 0 ? ( filtered.map((item, index) => { const isSelected = value === item.name; const title = `${labelOf(item)} (${item.name})`; return ( moveFocus(e, index)} onFocus={() => setFocusIndex(index)} onClick={() => onChange(item.name)} className="aspect-square h-auto w-full p-0" aria-label={title} title={title} style={isSelected ? accentStyle : undefined} > ); }) ) : (

{text.empty(deferred.trim())}

)}
); }