import { Button } from '@heroui/button'; import { Input } from '@heroui/input'; import { Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, } from '@heroui/modal'; import clsx from 'clsx'; import { useEffect, useMemo, useRef, useState } from 'react'; import { TbCornerDownLeft, TbSearch } from 'react-icons/tb'; export type CommandPaletteCommand = { id: string; title: string; subtitle?: string; group?: string; }; export type CommandPaletteExecuteMode = 'open' | 'send'; export interface CommandPaletteProps { isOpen: boolean; onOpenChange: (open: boolean) => void; commands: CommandPaletteCommand[]; onExecute: (commandId: string, mode: CommandPaletteExecuteMode) => void; } const isMobileByViewport = () => { try { return window.innerWidth < 768; } catch { return false; } }; export default function CommandPalette (props: CommandPaletteProps) { const { isOpen, onOpenChange, commands, onExecute } = props; const inputRef = useRef(null); const [query, setQuery] = useState(''); const [activeIndex, setActiveIndex] = useState(0); const [mobile, setMobile] = useState(false); useEffect(() => { const update = () => setMobile(isMobileByViewport()); update(); window.addEventListener('resize', update); return () => window.removeEventListener('resize', update); }, []); useEffect(() => { if (!isOpen) return; setQuery(''); setActiveIndex(0); // 等 Modal 动画挂载后再 focus const t = window.setTimeout(() => inputRef.current?.focus(), 50); return () => window.clearTimeout(t); }, [isOpen]); const filtered = useMemo(() => { const q = query.trim().toLowerCase(); const list = !q ? commands : commands.filter((c) => { const hay = `${c.id} ${c.title} ${c.subtitle ?? ''} ${c.group ?? ''}`.toLowerCase(); return hay.includes(q); }); // 简单:优先 path 前缀命中 if (!q) return list; const starts = list.filter((c) => c.id.toLowerCase().startsWith(q)); const rest = list.filter((c) => !c.id.toLowerCase().startsWith(q)); return [...starts, ...rest]; }, [commands, query]); useEffect(() => { if (activeIndex >= filtered.length) setActiveIndex(0); }, [filtered.length, activeIndex]); const active = filtered[activeIndex]; const exec = (mode: CommandPaletteExecuteMode) => { if (!active) return; onExecute(active.id, mode); onOpenChange(false); }; const onKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'ArrowDown') { e.preventDefault(); setActiveIndex((i) => Math.min(i + 1, Math.max(0, filtered.length - 1))); return; } if (e.key === 'ArrowUp') { e.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); return; } if (e.key === 'Enter') { e.preventDefault(); // Shift+Enter 仅打开;Enter 打开并发送 exec(e.shiftKey ? 'open' : 'send'); return; } if (e.key === 'Escape') { e.preventDefault(); onOpenChange(false); } }; return ( {() => ( <> 命令面板 Ctrl/Cmd + K } radius='lg' variant='flat' classNames={{ inputWrapper: 'bg-content2/50 border border-default-200/50 dark:border-default-100/20', input: 'text-sm', }} />
{filtered.length === 0 && (
没有匹配的接口
)} {filtered.map((c, idx) => ( ))}
{mobile && ( )} )}
); }