components/linyi/command-palette-block.tsx
lucide-reactmotion
"use client"; import * as React from "react";import { motion, AnimatePresence } from "motion/react";import { Search, Layers, Sparkles, SlidersHorizontal, Copy, SunMoon, Terminal, CornerDownLeft, X, Check,} from "lucide-react";import { cn } from "@/lib/cn";import { SPRING_SNAPPY, EASE_OUT } from "@/lib/motion"; export type CommandIconPreset = | "layers" | "sparkles" | "sliders" | "copy" | "theme" | "terminal"; export interface CommandItem { id: string; group: string; label: string; description?: string; shortcut?: string; keywords?: string[]; icon?: CommandIconPreset | React.ReactNode; disabled?: boolean;} export interface CommandPaletteProps { items?: CommandItem[]; groupOrder?: string[]; query?: string; onQueryChange?: (query: string) => void; onSelectItem?: (item: CommandItem) => void; placeholder?: string; emptyTitle?: string; emptyDescription?: string; showFeedback?: boolean; mode?: "inline" | "dialog"; open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; enableShortcut?: boolean; shortcutLabel?: string; footerHints?: React.ReactNode; compact?: boolean; className?: string;} const DEFAULT_ITEMS: CommandItem[] = [ { id: "lens", group: "组件", label: "WebGL 折射透镜", description: "光学玻璃折射与色散组件", shortcut: "M.01", keywords: ["webgl", "glass", "光学", "透镜"], icon: "sparkles", }, { id: "button", group: "组件", label: "液态玻璃按钮", description: "薄液态玻璃与 1px 边框流光主按钮", shortcut: "U.01", keywords: ["button", "玻璃", "按钮"], icon: "layers", }, { id: "bento", group: "组件", label: "Bento 指标大屏", description: "等宽数字与发丝网格卡片", shortcut: "B.03", keywords: ["bento", "metrics", "指标", "图表"], icon: "sliders", }, { id: "copy-tokens", group: "操作", label: "复制主题变量令牌", description: "导出纸面与暖曜石 CSS 变量", shortcut: "⌘C", keywords: ["tokens", "css", "复制", "变量"], icon: "copy", }, { id: "toggle-theme", group: "操作", label: "切换纸面 / 暖曜石外观", description: "预览深浅双主题色彩对比", shortcut: "⌘J", keywords: ["theme", "dark", "主题", "外观"], icon: "theme", }, { id: "install-cli", group: "操作", label: "生成安装命令行", description: "复制当前组件单文件安装脚本", shortcut: "⌘I", keywords: ["cli", "install", "安装", "命令"], icon: "terminal", },]; function CommandIcon({ icon }: { icon?: CommandItem["icon"] }) { const cls = "h-3.5 w-3.5 flex-shrink-0"; if (icon && typeof icon !== "string") { return <span className="inline-flex items-center justify-center flex-shrink-0">{icon}</span>; } switch (icon) { case "sparkles": return <Sparkles className={cls} aria-hidden="true" />; case "sliders": return <SlidersHorizontal className={cls} aria-hidden="true" />; case "copy": return <Copy className={cls} aria-hidden="true" />; case "theme": return <SunMoon className={cls} aria-hidden="true" />; case "terminal": return <Terminal className={cls} aria-hidden="true" />; default: return <Layers className={cls} aria-hidden="true" />; }} export function CommandPalette({ items = DEFAULT_ITEMS, groupOrder, query: controlledQuery, onQueryChange, onSelectItem, placeholder = "搜索组件、操作或编号...", emptyTitle, emptyDescription = "可尝试更换关键字或清空搜索条件", showFeedback = true, mode = "inline", open: controlledOpen, defaultOpen = false, onOpenChange, enableShortcut, shortcutLabel = "⌘K", footerHints, compact = false, className,}: CommandPaletteProps) { const uid = React.useId(); const inputRef = React.useRef<HTMLInputElement | null>(null); const [internalQuery, setInternalQuery] = React.useState(""); const [internalOpen, setInternalOpen] = React.useState(defaultOpen); const [activeIndex, setActiveIndex] = React.useState(0); const [lastExecuted, setLastExecuted] = React.useState<CommandItem | null>(null); const query = controlledQuery ?? internalQuery; const isDialog = mode === "dialog" && !compact; const isOpen = isDialog ? (controlledOpen ?? internalOpen) : true; const shortcutEnabled = enableShortcut ?? isDialog; const updateQuery = React.useCallback( (next: string) => { if (controlledQuery === undefined) setInternalQuery(next); onQueryChange?.(next); }, [controlledQuery, onQueryChange] ); const updateOpen = React.useCallback( (next: boolean) => { if (controlledOpen === undefined) setInternalOpen(next); onOpenChange?.(next); }, [controlledOpen, onOpenChange] ); React.useEffect(() => { if (!shortcutEnabled || compact) return; const onGlobalKeyDown = (e: KeyboardEvent) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); if (isDialog) { updateOpen(!isOpen); } else { inputRef.current?.focus(); } } else if (isDialog && isOpen && e.key === "Escape") { e.preventDefault(); updateOpen(false); } }; window.addEventListener("keydown", onGlobalKeyDown); return () => window.removeEventListener("keydown", onGlobalKeyDown); }, [shortcutEnabled, compact, isDialog, isOpen, updateOpen]); React.useEffect(() => { if (isDialog && isOpen) { const raf = requestAnimationFrame(() => inputRef.current?.focus()); return () => cancelAnimationFrame(raf); } }, [isDialog, isOpen]); const filtered = React.useMemo(() => { const q = query.trim().toLowerCase(); if (!q) return items; return items.filter((item) => { const haystack = [ item.label, item.description ?? "", item.group, item.shortcut ?? "", ...(item.keywords ?? []), ] .join(" ") .toLowerCase(); return haystack.includes(q); }); }, [items, query]); const visibleItems = compact ? filtered.slice(0, 3) : filtered; React.useEffect(() => { setActiveIndex(0); }, [query, items]); const executeItem = (item: CommandItem) => { if (item.disabled) return; setLastExecuted(item); onSelectItem?.(item); if (isDialog) { updateOpen(false); } }; const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.nativeEvent.isComposing) return; if (visibleItems.length === 0) { if (e.key === "Escape") { if (query) updateQuery(""); else if (isDialog) updateOpen(false); } return; } if (e.key === "ArrowDown") { e.preventDefault(); setActiveIndex((prev) => (prev + 1) % visibleItems.length); } else if (e.key === "ArrowUp") { e.preventDefault(); setActiveIndex((prev) => (prev - 1 + visibleItems.length) % visibleItems.length); } else if (e.key === "Home") { e.preventDefault(); setActiveIndex(0); } else if (e.key === "End") { e.preventDefault(); setActiveIndex(visibleItems.length - 1); } else if (e.key === "Enter") { e.preventDefault(); const target = visibleItems[activeIndex]; if (target) executeItem(target); } else if (e.key === "Escape") { if (query) { updateQuery(""); } else if (isDialog) { updateOpen(false); } } }; const groups = React.useMemo(() => { const discoveredOrder: string[] = []; if (groupOrder) { for (const g of groupOrder) { if (!discoveredOrder.includes(g)) discoveredOrder.push(g); } } for (const item of visibleItems) { if (!discoveredOrder.includes(item.group)) { discoveredOrder.push(item.group); } } return discoveredOrder .map((g) => ({ group: g, entries: visibleItems .map((item, flatIndex) => ({ item, flatIndex })) .filter((entry) => entry.item.group === g), })) .filter((g) => g.entries.length > 0); }, [visibleItems, groupOrder]); const listboxId = `${uid}-listbox`; const activeOptionId = visibleItems[activeIndex] ? `${uid}-opt-${visibleItems[activeIndex].id}` : undefined; if (compact) { return ( <div className={cn( "w-full max-w-[254px] overflow-hidden rounded-well border border-line-strong bg-surface shadow-panel", className )} > <div className="flex items-center gap-2 border-b border-line px-3 py-2"> <Search className="h-3.5 w-3.5 flex-shrink-0 text-fg-muted" aria-hidden="true" /> <input ref={inputRef} role="combobox" aria-expanded="true" aria-controls={listboxId} aria-activedescendant={activeOptionId} value={query} onChange={(e) => updateQuery(e.target.value)} onKeyDown={handleKeyDown} placeholder="搜索组件..." aria-label="命令搜索" className="min-w-0 flex-1 bg-transparent text-[11px] text-fg placeholder:text-fg-muted outline-none" /> <kbd className="rounded border border-line bg-surface-2 px-1 py-0.5 font-mono-num text-[9px] text-fg-muted"> {shortcutLabel} </kbd> </div> <div id={listboxId} className="space-y-0.5 p-1.5" role="listbox" aria-label="快捷命令"> {visibleItems.length === 0 ? ( <div className="px-2 py-3 text-center text-[10px] text-fg-muted">未找到匹配项</div> ) : ( visibleItems.map((item, idx) => { const active = idx === activeIndex; return ( <button key={item.id} id={`${uid}-opt-${item.id}`} type="button" role="option" disabled={item.disabled} aria-selected={active} onMouseEnter={() => setActiveIndex(idx)} onClick={() => executeItem(item)} className={cn( "flex w-full cursor-pointer items-center justify-between gap-2 rounded-[7px] px-2 py-1.5 text-left text-[11px] transition-colors disabled:opacity-45 disabled:cursor-not-allowed", active ? "bg-well text-fg" : "text-fg-secondary hover:bg-well/60" )} > <span className="flex min-w-0 items-center gap-1.5 truncate"> <span className={active ? "text-accent" : "text-fg-muted"}> <CommandIcon icon={item.icon} /> </span> <span className="truncate">{item.label}</span> </span> {item.shortcut && ( <span className="font-mono-num text-[9px] text-fg-muted">{item.shortcut}</span> )} </button> ); }) )} </div> {showFeedback && lastExecuted && ( <div className="flex items-center gap-1.5 border-t border-line bg-surface-2 px-2.5 py-1.5 text-[10px] text-success"> <Check className="h-3 w-3 flex-shrink-0" aria-hidden="true" /> <span className="truncate">已执行:{lastExecuted.label}</span> </div> )} </div> ); } const panelBody = ( <div className={cn("w-full max-w-lg space-y-3", className)}> <div className="overflow-hidden rounded-panel border border-line-strong bg-surface shadow-popover"> {/* Search Input Header */} <div className="flex items-center gap-2.5 border-b border-line px-4 py-3"> <Search className="h-4 w-4 flex-shrink-0 text-fg-muted" aria-hidden="true" /> <input ref={inputRef} role="combobox" aria-expanded="true" aria-controls={listboxId} aria-activedescendant={activeOptionId} value={query} onChange={(e) => updateQuery(e.target.value)} onKeyDown={handleKeyDown} placeholder={placeholder} aria-label="搜索命令与组件" className="min-w-0 flex-1 bg-transparent text-sm text-fg placeholder:text-fg-muted outline-none" /> {query && ( <button type="button" onClick={() => updateQuery("")} aria-label="清空搜索" className="flex h-6 w-6 cursor-pointer items-center justify-center rounded-pill text-fg-muted transition-colors hover:bg-well hover:text-fg" > <X className="h-3.5 w-3.5" aria-hidden="true" /> </button> )} <kbd className="rounded-control border border-line bg-surface-2 px-1.5 py-0.5 font-mono-num text-[10px] text-fg-muted"> {shortcutLabel} </kbd> </div> {/* Grouped Command List */} <div id={listboxId} className="no-scrollbar max-h-[280px] overflow-y-auto p-2" role="listbox" aria-label="命令结果列表" > {groups.length === 0 ? ( <div className="flex flex-col items-center justify-center gap-2 py-10 text-center"> <div className="text-xs font-medium text-fg"> {emptyTitle ?? (query ? `未找到与「${query}」匹配的指令` : "暂无可用指令")} </div> <p className="text-[11px] text-fg-muted">{emptyDescription}</p> {query && ( <button type="button" onClick={() => updateQuery("")} className="mt-1 cursor-pointer rounded-pill border border-line bg-surface-2 px-3 py-1 text-[11px] text-fg-secondary transition-colors hover:border-line-strong hover:text-fg" > 清空搜索条件 </button> )} </div> ) : ( <div className="space-y-2.5"> {groups.map(({ group, entries }) => ( <div key={group} role="group" aria-label={group} className="space-y-1"> <div className="px-2.5 py-1 text-[10px] font-medium tracking-wide text-fg-muted"> {group} </div> {entries.map(({ item, flatIndex }) => { const active = flatIndex === activeIndex; return ( <button key={item.id} id={`${uid}-opt-${item.id}`} type="button" role="option" disabled={item.disabled} aria-selected={active} onMouseEnter={() => setActiveIndex(flatIndex)} onClick={() => executeItem(item)} className={cn( "flex w-full cursor-pointer items-center justify-between gap-3 rounded-control px-2.5 py-2 text-left transition-colors disabled:opacity-45 disabled:cursor-not-allowed", active ? "bg-well text-fg" : "text-fg-secondary hover:bg-well/50" )} > <div className="flex min-w-0 items-center gap-2.5"> <span className={cn( "flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-[8px] border transition-colors", active ? "border-accent-border bg-accent-soft text-accent" : "border-line bg-surface-2 text-fg-muted" )} > <CommandIcon icon={item.icon} /> </span> <div className="min-w-0"> <div className="truncate text-xs font-medium text-fg">{item.label}</div> {item.description && ( <div className="truncate text-[11px] text-fg-muted"> {item.description} </div> )} </div> </div> <div className="flex flex-shrink-0 items-center gap-2"> {item.shortcut && ( <kbd className="rounded border border-line bg-surface px-1.5 py-0.5 font-mono-num text-[10px] text-fg-muted"> {item.shortcut} </kbd> )} {active && ( <CornerDownLeft className="h-3 w-3 text-accent" aria-hidden="true" /> )} </div> </button> ); })} </div> ))} </div> )} </div> {/* Footer Hints */} <div className="flex items-center justify-between border-t border-line bg-surface-2 px-4 py-2 text-[10px] text-fg-muted"> {footerHints ?? ( <div className="flex items-center gap-3 font-mono-num"> <span>↑↓ 移动</span> <span>↵ 执行</span> <span>ESC {isDialog ? "关闭" : "清空"}</span> </div> )} <span className="font-mono-num">共 {visibleItems.length} 项</span> </div> </div> {/* Execution Feedback Banner */} {showFeedback && !isDialog && ( <AnimatePresence mode="wait"> {lastExecuted && ( <motion.div key={lastExecuted.id} initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -4 }} transition={SPRING_SNAPPY} className="flex items-center justify-between gap-2 rounded-well border border-success-border bg-success-soft px-3.5 py-2 text-xs text-success" role="status" aria-live="polite" > <div className="flex items-center gap-2"> <Check className="h-3.5 w-3.5 flex-shrink-0" aria-hidden="true" /> <span> 已触发「{lastExecuted.label}」 {lastExecuted.shortcut ? `(${lastExecuted.shortcut})` : ""} </span> </div> <button type="button" onClick={() => setLastExecuted(null)} className="cursor-pointer rounded p-0.5 text-success/80 hover:text-success" aria-label="关闭反馈提示" > <X className="h-3.5 w-3.5" aria-hidden="true" /> </button> </motion.div> )} </AnimatePresence> )} </div> ); if (!isDialog) { return panelBody; } return ( <AnimatePresence> {isOpen && ( <div className="fixed inset-0 z-[var(--z-modal)] flex items-start justify-center px-4 pt-[12vh]" role="dialog" aria-modal="true" aria-label="命令面板" > <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={EASE_OUT} onClick={() => updateOpen(false)} className="fixed inset-0 bg-[var(--scrim-backdrop)] backdrop-blur-[2px]" /> <motion.div initial={{ opacity: 0, scale: 0.97, y: -8 }} animate={{ opacity: 1, scale: 1, y: 0 }} exit={{ opacity: 0, scale: 0.98, y: -6 }} transition={SPRING_SNAPPY} className="relative z-10 w-full max-w-lg" > {panelBody} </motion.div> </div> )} </AnimatePresence> );}