"use client"; import { SearchTrigger } from "@suphark/ui/components/shared/search-trigger"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandShortcut, } from "@suphark/ui/components/ui/command"; import { useRouter } from "next/navigation"; import { type ReactNode, useEffect, useRef, useState, useTransition } from "react"; export interface CommandPaletteItem { href: string; label: string; /** ชื่อกลุ่ม (แสดงเป็น shortcut ท้ายรายการ และใช้ค้นหา) */ group?: string; icon?: ReactNode; /** คำค้นเพิ่มเติมนอกจาก label/group/href */ keywords?: string[]; } export interface CommandPaletteSectionItem { id: string; /** ไปหน้า (router.push / `onNavigate`) — ไม่ส่งถ้าเป็น action ล้วน */ href?: string; /** action ฝั่ง client (สร้างงาน, สลับ sidebar …) — เรียกหลังปิดกล่อง; ถ้ามีทั้งคู่ เรียก onClick ก่อนแล้วไป href */ onClick?: () => void; /** ชื่อเดิม (ยังใช้ได้) — ของใหม่ใช้ `onClick` ให้ตรงกับ ActionMenu */ onSelect?: () => void; label: string; description?: string; icon?: ReactNode; /** ป้ายคีย์ลัดท้ายรายการ (แสดงอย่างเดียว เช่น "G H") */ shortcut?: string; } export interface CommandPaletteSection { key: string; heading: string; items: CommandPaletteSectionItem[]; } export interface CommandPaletteText { placeholder: string; title: string; description: string; empty: string; searching: string; /** หัวกลุ่ม "หน้า" */ pages: string; } const DEFAULT_TEXT: CommandPaletteText = { placeholder: "ค้นหาหรือสั่งงาน…", title: "ค้นหา", description: "พิมพ์เพื่อค้นหาหน้าและข้อมูล", empty: "ไม่พบผลลัพธ์", searching: "กำลังค้นหา…", pages: "หน้า", }; /** ⌘ บน Mac, Ctrl ที่อื่น — อ่านฝั่ง client หลัง mount เท่านั้น (กัน hydration mismatch) */ /** * ค้นหาแบบ ⌘K / Ctrl+K ทั้งแอป: หน้าในเมนู (แอปกรองสิทธิ์มาแล้ว) กรองฝั่ง client + ส่วนจาก server action * (`search`) เมื่อพิมพ์ ≥ `minQuery` ตัว (debounce; ผลของ query ล่าสุดเท่านั้นที่แสดง) + ส่วนที่แอปคำนวณเองฝั่ง client * (`filter(query)` — ข้อมูลใน memory/offline-first, รายการ action ที่มี `onSelect`) แสดงก่อนผลจาก server * เปิด/ปิดคุมจากภายนอกได้ (`open`/`onOpenChange`) และซ่อนปุ่มเรียกของแพ็กเกจ (`showTrigger={false}`) เมื่อแอปมีปุ่ม/คีย์ลัดเอง * ปุ่มเรียก: `compact` = ไอคอนใน header, ค่าเริ่มต้น = ปุ่มเต็มกว้าง + Kbd ใน `sidebarHeader` ของ AppShell * ข้อความรับเป็น prop `text` (ค่าเริ่มต้นจาก `UiText.palette` หรือไทย) — ไม่พึ่ง i18n ของแอป * ยกจาก Pi Auth (features/console/command-palette) ให้ Pi Done/DueBell ใช้ร่วม */ export function CommandPalette({ pages, search, filter, compact = false, showTrigger = true, open: controlledOpen, onOpenChange, shortcut = "k", minQuery = 2, debounceMs = 150, text: textProp, onNavigate, highlightMatches = false, className, }: { pages: CommandPaletteItem[]; /** server action ของแอป — คืน section ตามลำดับที่ต้องการแสดง */ search?: (query: string) => Promise; /** * section ที่แอปคำนวณเองฝั่ง client ทุกครั้งที่ query เปลี่ยน (query ว่างก็เรียก — ใช้แสดงรายการ action/ล่าสุด); * ไม่ debounce เพราะไม่มี IO — ให้ memo ฝั่งแอปถ้าชุดข้อมูลใหญ่ */ filter?: (query: string) => CommandPaletteSection[]; compact?: boolean; /** ซ่อนปุ่มเรียกของแพ็กเกจ (แอปเปิดเองผ่าน `open` หรือคีย์ลัด) */ showTrigger?: boolean; /** คุมการเปิดจากภายนอก (ใช้คู่ `onOpenChange`) — ไม่ส่ง = คุมเองในตัว */ open?: boolean; onOpenChange?: (open: boolean) => void; /** ตัวอักษรคีย์ลัดร่วมกับ ⌘/Ctrl (ค่าเริ่มต้น "k"); `null` = ไม่ดักคีย์ลัด (แอปดักเอง) */ shortcut?: string | null; minQuery?: number; debounceMs?: number; text?: Partial; /** ค่าเริ่มต้น router.push + ปิดกล่อง — ครอบเพื่อ prefetch/analytics แล้วเรียกต่อเองได้ */ onNavigate?: (href: string) => void; /** * เน้นคำที่พิมพ์ในชื่อรายการ (ตัวหนา สีเข้ม ไม่มีพื้น) — ค่าเริ่มต้น false เหมือนเดิม * ใช้เมื่อผลค้นหาเป็นข้อความยาว (ชื่องาน) ที่ผู้ใช้ต้องเห็นว่าตรงตรงไหน (ขอโดย pi-done) */ highlightMatches?: boolean; className?: string; }) { const ui = useUiText(); const text: CommandPaletteText = { ...DEFAULT_TEXT, ...ui.palette, ...textProp }; const router = useRouter(); const [uncontrolledOpen, setUncontrolledOpen] = useState(false); const open = controlledOpen ?? uncontrolledOpen; const setOpen = (next: boolean) => { if (controlledOpen === undefined) setUncontrolledOpen(next); onOpenChange?.(next); }; const [query, setQuery] = useState(""); const [result, setResult] = useState<{ query: string; sections: CommandPaletteSection[] } | null>( null, ); const [pending, start] = useTransition(); // คีย์ลัดจากที่ไหนก็ได้ในแอป const openRef = useRef(open); openRef.current = open; const setOpenRef = useRef(setOpen); setOpenRef.current = setOpen; useEffect(() => { if (!shortcut) return; const key = shortcut.toLowerCase(); // เทียบตำแหน่งปุ่ม (e.code) สำหรับตัวอักษร/ตัวเลข — แป้นไทย Ctrl+K ให้ e.key = "า" แต่ e.code ยังเป็น "KeyK" const code = /^[a-z]$/.test(key) ? `Key${key.toUpperCase()}` : /^\d$/.test(key) ? `Digit${key}` : null; const onKey = (e: KeyboardEvent) => { // ต้องมี Ctrl/⌘ และไม่ใช่ AltGr (Windows ส่ง AltGr เป็น ctrl+alt — พิมพ์อักษรพิเศษในบางภาษา) if (!(e.metaKey || e.ctrlKey) || e.altKey) return; // palette ตัวอื่น (เช่น 2 ตัวในหน้าเดียว) จัดการปุ่มนี้ไปแล้ว — เปิดได้ทีละตัว if (e.defaultPrevented) return; const pressed = typeof e.key === "string" ? e.key.toLowerCase() : ""; // autofill ส่ง keydown ที่ไม่มี key // อักษรละติน/ตัวเลขเทียบตาม e.key (เคารพแป้นอย่าง Dvorak) — แป้นที่ไม่ใช่ละติน (ไทย "า") ใช้ตำแหน่งปุ่ม e.code const latin = /^[a-z0-9]$/.test(pressed); const matches = latin ? pressed === key : pressed === key || (code !== null && e.code === code); if (!matches) return; e.preventDefault(); setOpenRef.current(!openRef.current); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [shortcut]); const q = query.trim(); const shouldSearch = Boolean(search) && q.length >= minQuery; // ค้นหาฝั่ง server หลังหยุดพิมพ์ — เก็บ query คู่กับผล ผลที่ไม่ตรง query ปัจจุบันไม่แสดง useEffect(() => { if (!search || !shouldSearch) return; const handle = setTimeout(() => { start(async () => { try { const sections = await search(q); setResult({ query: q, sections }); } catch { setResult({ query: q, sections: [] }); } }); }, debounceMs); return () => clearTimeout(handle); }, [q, search, shouldSearch, debounceMs]); const localSections = filter ? filter(q) : []; const remoteSections = shouldSearch && result?.query === q ? result.sections : []; const sections = [...localSections, ...remoteSections]; const ql = q.toLowerCase(); const visiblePages = ql ? pages.filter((p) => `${p.label} ${p.group ?? ""} ${p.href} ${(p.keywords ?? []).join(" ")}` .toLowerCase() .includes(ql), ) : pages; const nothing = visiblePages.length === 0 && sections.every((s) => s.items.length === 0); function close() { setOpen(false); setQuery(""); } function go(href: string) { close(); if (onNavigate) onNavigate(href); else router.push(href); } function pick(item: CommandPaletteSectionItem) { close(); (item.onClick ?? item.onSelect)?.(); if (item.href) { if (onNavigate) onNavigate(item.href); else router.push(item.href); } } return ( <> {showTrigger && ( setOpen(true)} /> )} (o ? setOpen(true) : close())} title={text.title} description={text.description} > {nothing && ( {pending && shouldSearch ? text.searching : text.empty} )} {visiblePages.length > 0 && ( {visiblePages.map((p) => ( go(p.href)}> {p.icon} {highlightMatches ? : p.label} {p.group && {p.group}} ))} )} {sections.map( (s) => s.items.length > 0 && ( {s.items.map((it) => ( pick(it)} > {it.icon} {highlightMatches ? : it.label} {it.description && ( · {it.description} )} {it.shortcut && {it.shortcut}} ))} ), )} {pending && shouldSearch && !nothing && (
{text.searching}
)}
); } /** ข้อความที่ส่วนตรงกับ `query` (ไม่สนตัวพิมพ์) เป็น `` — query ว่าง = ข้อความเดิม */ export function MatchText({ text, query }: { text: string; query: string }) { const needle = query.trim().toLowerCase(); if (!needle) return <>{text}; const haystack = text.toLowerCase(); const parts: ReactNode[] = []; let from = 0; let at = haystack.indexOf(needle, from); while (at !== -1) { if (at > from) parts.push(text.slice(from, at)); parts.push( {text.slice(at, at + needle.length)} , ); from = at + needle.length; at = haystack.indexOf(needle, from); } if (from < text.length) parts.push(text.slice(from)); return <>{parts}; }