|
| 1 | +import { useState, useEffect, useRef, useMemo, useCallback } from 'react'; |
| 2 | + |
| 3 | +export interface NavItem { |
| 4 | + key: string; |
| 5 | + label: string; |
| 6 | + href: string; |
| 7 | + section: string; |
| 8 | +} |
| 9 | + |
| 10 | +interface Props { |
| 11 | + items: NavItem[]; |
| 12 | +} |
| 13 | + |
| 14 | +function fuzzyMatch(q: string, t: string): boolean { |
| 15 | + q = q.toLowerCase(); |
| 16 | + t = t.toLowerCase(); |
| 17 | + let qi = 0; |
| 18 | + for (let i = 0; i < t.length && qi < q.length; i++) { |
| 19 | + if (t[i] === q[qi]) qi++; |
| 20 | + } |
| 21 | + return qi === q.length; |
| 22 | +} |
| 23 | + |
| 24 | +const RECENT_KEY = 'recently_visited'; |
| 25 | +const MAX_RECENT = 5; |
| 26 | + |
| 27 | +export default function CommandPalette({ items }: Props) { |
| 28 | + const [open, setOpen] = useState(false); |
| 29 | + const [query, setQuery] = useState(''); |
| 30 | + const [selectedIndex, setSelectedIndex] = useState(0); |
| 31 | + const [recentRoutes, setRecentRoutes] = useState<string[]>([]); |
| 32 | + const inputRef = useRef<HTMLInputElement>(null); |
| 33 | + const listRef = useRef<HTMLDivElement>(null); |
| 34 | + |
| 35 | + // Record current page visit on mount |
| 36 | + useEffect(() => { |
| 37 | + try { |
| 38 | + const raw = localStorage.getItem(RECENT_KEY); |
| 39 | + const prev: string[] = raw ? JSON.parse(raw) : []; |
| 40 | + const current = window.location.pathname; |
| 41 | + const updated = [current, ...prev.filter(r => r !== current)].slice(0, MAX_RECENT); |
| 42 | + localStorage.setItem(RECENT_KEY, JSON.stringify(updated)); |
| 43 | + setRecentRoutes(updated); |
| 44 | + } catch { |
| 45 | + // ignore localStorage errors |
| 46 | + } |
| 47 | + }, []); |
| 48 | + |
| 49 | + // Listen for global Cmd+K and cp:open event |
| 50 | + useEffect(() => { |
| 51 | + const onKey = (e: KeyboardEvent) => { |
| 52 | + if ((e.metaKey || e.ctrlKey) && e.key === 'k') { |
| 53 | + e.preventDefault(); |
| 54 | + setOpen(true); |
| 55 | + } |
| 56 | + }; |
| 57 | + const onOpen = () => setOpen(true); |
| 58 | + document.addEventListener('keydown', onKey); |
| 59 | + document.addEventListener('cp:open', onOpen); |
| 60 | + return () => { |
| 61 | + document.removeEventListener('keydown', onKey); |
| 62 | + document.removeEventListener('cp:open', onOpen); |
| 63 | + }; |
| 64 | + }, []); |
| 65 | + |
| 66 | + // Focus input when opened, reset state |
| 67 | + useEffect(() => { |
| 68 | + if (open) { |
| 69 | + setQuery(''); |
| 70 | + setSelectedIndex(0); |
| 71 | + setTimeout(() => inputRef.current?.focus(), 0); |
| 72 | + } |
| 73 | + }, [open]); |
| 74 | + |
| 75 | + const displayItems = useMemo(() => { |
| 76 | + if (!query.trim()) { |
| 77 | + const recent = recentRoutes |
| 78 | + .map(route => items.find(i => i.href === route || (route.startsWith(i.href) && i.href !== '/'))) |
| 79 | + .filter((x): x is NavItem => x !== undefined); |
| 80 | + // Deduplicate |
| 81 | + const seen = new Set<string>(); |
| 82 | + return recent.filter(i => seen.has(i.key) ? false : (seen.add(i.key), true)); |
| 83 | + } |
| 84 | + return items.filter( |
| 85 | + item => fuzzyMatch(query, item.label) || fuzzyMatch(query, item.section) |
| 86 | + ); |
| 87 | + }, [query, items, recentRoutes]); |
| 88 | + |
| 89 | + const grouped = useMemo(() => { |
| 90 | + const result: Record<string, NavItem[]> = {}; |
| 91 | + for (const item of displayItems) { |
| 92 | + (result[item.section] ??= []).push(item); |
| 93 | + } |
| 94 | + return result; |
| 95 | + }, [displayItems]); |
| 96 | + |
| 97 | + // Flat ordered list for keyboard nav |
| 98 | + const flat = useMemo(() => displayItems, [displayItems]); |
| 99 | + |
| 100 | + const navigate = useCallback((item: NavItem) => { |
| 101 | + setOpen(false); |
| 102 | + window.location.href = item.href; |
| 103 | + }, []); |
| 104 | + |
| 105 | + const onKeyDown = (e: React.KeyboardEvent) => { |
| 106 | + if (e.key === 'Escape') { |
| 107 | + setOpen(false); |
| 108 | + } else if (e.key === 'ArrowDown') { |
| 109 | + e.preventDefault(); |
| 110 | + setSelectedIndex(i => Math.min(i + 1, flat.length - 1)); |
| 111 | + } else if (e.key === 'ArrowUp') { |
| 112 | + e.preventDefault(); |
| 113 | + setSelectedIndex(i => Math.max(i - 1, 0)); |
| 114 | + } else if (e.key === 'Enter') { |
| 115 | + const item = flat[selectedIndex]; |
| 116 | + if (item) navigate(item); |
| 117 | + } |
| 118 | + }; |
| 119 | + |
| 120 | + // Scroll selected item into view |
| 121 | + useEffect(() => { |
| 122 | + const el = listRef.current?.querySelector(`[data-idx="${selectedIndex}"]`); |
| 123 | + el?.scrollIntoView({ block: 'nearest' }); |
| 124 | + }, [selectedIndex]); |
| 125 | + |
| 126 | + // Reset selection when results change |
| 127 | + useEffect(() => { |
| 128 | + setSelectedIndex(0); |
| 129 | + }, [query]); |
| 130 | + |
| 131 | + if (!open) return null; |
| 132 | + |
| 133 | + const sectionOrder = ['WALLET', 'ASSETS', 'TRADE', 'PLUGINS']; |
| 134 | + const sections = [ |
| 135 | + ...sectionOrder.filter(s => grouped[s]), |
| 136 | + ...Object.keys(grouped).filter(s => !sectionOrder.includes(s)), |
| 137 | + ]; |
| 138 | + |
| 139 | + let flatIdx = 0; |
| 140 | + const sectionItems = sections.map(section => { |
| 141 | + const sectionNavItems = grouped[section].map(item => { |
| 142 | + const idx = flatIdx++; |
| 143 | + return { item, idx }; |
| 144 | + }); |
| 145 | + return { section, items: sectionNavItems }; |
| 146 | + }); |
| 147 | + |
| 148 | + const emptyState = flat.length === 0; |
| 149 | + |
| 150 | + return ( |
| 151 | + <div |
| 152 | + className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]" |
| 153 | + role="dialog" |
| 154 | + aria-modal="true" |
| 155 | + aria-label="Command palette" |
| 156 | + onKeyDown={onKeyDown} |
| 157 | + onClick={e => { if (e.target === e.currentTarget) setOpen(false); }} |
| 158 | + > |
| 159 | + {/* Backdrop */} |
| 160 | + <div className="absolute inset-0 bg-black/60" onClick={() => setOpen(false)} /> |
| 161 | + |
| 162 | + {/* Modal */} |
| 163 | + <div className="relative w-full max-w-lg mx-4 bg-gray-900 border border-gray-700 rounded-lg shadow-2xl overflow-hidden"> |
| 164 | + {/* Search input */} |
| 165 | + <div className="flex items-center gap-3 px-4 py-3 border-b border-gray-800"> |
| 166 | + <svg |
| 167 | + className="w-4 h-4 text-gray-500 shrink-0" |
| 168 | + fill="none" |
| 169 | + viewBox="0 0 24 24" |
| 170 | + strokeWidth={1.5} |
| 171 | + stroke="currentColor" |
| 172 | + > |
| 173 | + <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" /> |
| 174 | + </svg> |
| 175 | + <input |
| 176 | + ref={inputRef} |
| 177 | + type="text" |
| 178 | + role="combobox" |
| 179 | + aria-autocomplete="list" |
| 180 | + aria-controls="cp-listbox" |
| 181 | + aria-activedescendant={flat[selectedIndex] ? `cp-option-${selectedIndex}` : undefined} |
| 182 | + placeholder="Go to..." |
| 183 | + value={query} |
| 184 | + onChange={e => setQuery(e.target.value)} |
| 185 | + className="flex-1 bg-transparent text-gray-100 placeholder-gray-500 text-sm outline-none" |
| 186 | + /> |
| 187 | + <kbd className="text-xs text-gray-600 border border-gray-700 rounded px-1.5 py-0.5 font-mono"> |
| 188 | + esc |
| 189 | + </kbd> |
| 190 | + </div> |
| 191 | + |
| 192 | + {/* Results */} |
| 193 | + <div |
| 194 | + ref={listRef} |
| 195 | + id="cp-listbox" |
| 196 | + role="listbox" |
| 197 | + className="max-h-80 overflow-y-auto py-2" |
| 198 | + > |
| 199 | + {!query.trim() && flat.length > 0 && ( |
| 200 | + <p className="px-4 pb-1 text-xs text-gray-600 uppercase tracking-wider">Recent</p> |
| 201 | + )} |
| 202 | + {emptyState && ( |
| 203 | + <p className="px-4 py-6 text-center text-sm text-gray-500">No results found.</p> |
| 204 | + )} |
| 205 | + {sectionItems.map(({ section, items: sectionNavItems }) => ( |
| 206 | + <div key={section} role="group" aria-label={section}> |
| 207 | + {query.trim() && ( |
| 208 | + <p className="px-4 pt-2 pb-1 text-xs text-gray-600 uppercase tracking-wider"> |
| 209 | + {section} |
| 210 | + </p> |
| 211 | + )} |
| 212 | + {sectionNavItems.map(({ item, idx }) => ( |
| 213 | + <button |
| 214 | + key={item.key} |
| 215 | + id={`cp-option-${idx}`} |
| 216 | + role="option" |
| 217 | + aria-selected={idx === selectedIndex} |
| 218 | + data-idx={idx} |
| 219 | + onClick={() => navigate(item)} |
| 220 | + onMouseEnter={() => setSelectedIndex(idx)} |
| 221 | + className={[ |
| 222 | + 'w-full flex items-center gap-3 px-4 py-2 text-sm transition-colors text-left', |
| 223 | + idx === selectedIndex |
| 224 | + ? 'bg-mint-600/20 text-mint-400' |
| 225 | + : 'text-gray-300 hover:bg-gray-800', |
| 226 | + ].join(' ')} |
| 227 | + > |
| 228 | + <span className="flex-1">{item.label}</span> |
| 229 | + <span className="text-xs text-gray-600">{item.section}</span> |
| 230 | + </button> |
| 231 | + ))} |
| 232 | + </div> |
| 233 | + ))} |
| 234 | + </div> |
| 235 | + |
| 236 | + {/* Footer hint */} |
| 237 | + <div className="border-t border-gray-800 px-4 py-2 flex items-center gap-4 text-xs text-gray-600"> |
| 238 | + <span><kbd className="font-mono">↑↓</kbd> navigate</span> |
| 239 | + <span><kbd className="font-mono">↵</kbd> go</span> |
| 240 | + <span><kbd className="font-mono">esc</kbd> close</span> |
| 241 | + </div> |
| 242 | + </div> |
| 243 | + </div> |
| 244 | + ); |
| 245 | +} |
0 commit comments