|
| 1 | +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; |
| 2 | +import { useNavigate } from 'react-router-dom'; |
| 3 | +import { Input, Overlay } from '@tiny-design/react'; |
| 4 | +import { useLocaleContext } from '../../context/locale-context'; |
| 5 | +import { getGuideMenu, getThemeMenu, getComponentMenu, RouterItem } from '../../routers'; |
| 6 | +import './command-palette.scss'; |
| 7 | + |
| 8 | +interface SearchItem { |
| 9 | + title: string; |
| 10 | + route: string; |
| 11 | + section: string; |
| 12 | + fullPath: string; |
| 13 | +} |
| 14 | + |
| 15 | +interface CommandPaletteProps { |
| 16 | + open: boolean; |
| 17 | + onOpenChange: (open: boolean) => void; |
| 18 | +} |
| 19 | + |
| 20 | +function flattenMenuItems( |
| 21 | + items: RouterItem[], |
| 22 | + section: string, |
| 23 | + pathPrefix: string, |
| 24 | +): SearchItem[] { |
| 25 | + const result: SearchItem[] = []; |
| 26 | + for (const item of items) { |
| 27 | + if (item.children) { |
| 28 | + for (const child of item.children) { |
| 29 | + if (child.route) { |
| 30 | + result.push({ |
| 31 | + title: child.title, |
| 32 | + route: child.route, |
| 33 | + section: item.title, |
| 34 | + fullPath: `${pathPrefix}/${child.route}`, |
| 35 | + }); |
| 36 | + } |
| 37 | + } |
| 38 | + } else if (item.route) { |
| 39 | + result.push({ |
| 40 | + title: item.title, |
| 41 | + route: item.route, |
| 42 | + section, |
| 43 | + fullPath: `${pathPrefix}/${item.route}`, |
| 44 | + }); |
| 45 | + } |
| 46 | + } |
| 47 | + return result; |
| 48 | +} |
| 49 | + |
| 50 | +export const CommandPalette = ({ open, onOpenChange }: CommandPaletteProps): React.ReactElement => { |
| 51 | + const [query, setQuery] = useState(''); |
| 52 | + const [activeIndex, setActiveIndex] = useState(0); |
| 53 | + const inputRef = useRef<HTMLInputElement>(null); |
| 54 | + const resultListRef = useRef<HTMLDivElement>(null); |
| 55 | + const navigate = useNavigate(); |
| 56 | + const { siteLocale } = useLocaleContext(); |
| 57 | + |
| 58 | + const searchIndex = useMemo(() => { |
| 59 | + const guideItems = flattenMenuItems(getGuideMenu(siteLocale), siteLocale.nav.guide, '/guide'); |
| 60 | + const themeItems = flattenMenuItems(getThemeMenu(siteLocale), siteLocale.nav.theme, '/theme'); |
| 61 | + const componentItems = flattenMenuItems( |
| 62 | + getComponentMenu(siteLocale), |
| 63 | + siteLocale.nav.components, |
| 64 | + '/components', |
| 65 | + ); |
| 66 | + return [...guideItems, ...themeItems, ...componentItems]; |
| 67 | + }, [siteLocale]); |
| 68 | + |
| 69 | + const filteredItems = useMemo(() => { |
| 70 | + if (!query.trim()) return searchIndex; |
| 71 | + const q = query.toLowerCase(); |
| 72 | + return searchIndex.filter((item) => item.title.toLowerCase().includes(q)); |
| 73 | + }, [query, searchIndex]); |
| 74 | + |
| 75 | + const groupedItems = useMemo(() => { |
| 76 | + const groups: { section: string; items: SearchItem[] }[] = []; |
| 77 | + for (const item of filteredItems) { |
| 78 | + const last = groups[groups.length - 1]; |
| 79 | + if (last && last.section === item.section) { |
| 80 | + last.items.push(item); |
| 81 | + } else { |
| 82 | + groups.push({ section: item.section, items: [item] }); |
| 83 | + } |
| 84 | + } |
| 85 | + return groups; |
| 86 | + }, [filteredItems]); |
| 87 | + |
| 88 | + const close = useCallback(() => { |
| 89 | + onOpenChange(false); |
| 90 | + }, [onOpenChange]); |
| 91 | + |
| 92 | + const selectItem = useCallback( |
| 93 | + (item: SearchItem) => { |
| 94 | + navigate(item.fullPath); |
| 95 | + close(); |
| 96 | + }, |
| 97 | + [navigate, close], |
| 98 | + ); |
| 99 | + |
| 100 | + // Reset state when closing |
| 101 | + useEffect(() => { |
| 102 | + if (!open) { |
| 103 | + setQuery(''); |
| 104 | + setActiveIndex(0); |
| 105 | + } |
| 106 | + }, [open]); |
| 107 | + |
| 108 | + // Reset active index when query changes |
| 109 | + useEffect(() => { |
| 110 | + setActiveIndex(0); |
| 111 | + }, [query]); |
| 112 | + |
| 113 | + // Global Cmd/Ctrl+K shortcut |
| 114 | + useEffect(() => { |
| 115 | + const handleKeyDown = (e: KeyboardEvent) => { |
| 116 | + if ((e.metaKey || e.ctrlKey) && e.key === 'k') { |
| 117 | + e.preventDefault(); |
| 118 | + onOpenChange(!open); |
| 119 | + } |
| 120 | + }; |
| 121 | + document.addEventListener('keydown', handleKeyDown); |
| 122 | + return () => document.removeEventListener('keydown', handleKeyDown); |
| 123 | + }, [open, onOpenChange]); |
| 124 | + |
| 125 | + // Scroll active item into view |
| 126 | + useEffect(() => { |
| 127 | + if (!resultListRef.current) return; |
| 128 | + const activeEl = resultListRef.current.querySelector('[data-active="true"]'); |
| 129 | + if (activeEl) { |
| 130 | + activeEl.scrollIntoView({ block: 'nearest' }); |
| 131 | + } |
| 132 | + }, [activeIndex]); |
| 133 | + |
| 134 | + const handleInputKeyDown = (e: React.KeyboardEvent) => { |
| 135 | + const total = filteredItems.length; |
| 136 | + if (total === 0) return; |
| 137 | + |
| 138 | + switch (e.key) { |
| 139 | + case 'ArrowDown': |
| 140 | + e.preventDefault(); |
| 141 | + setActiveIndex((prev) => (prev + 1) % total); |
| 142 | + break; |
| 143 | + case 'ArrowUp': |
| 144 | + e.preventDefault(); |
| 145 | + setActiveIndex((prev) => (prev - 1 + total) % total); |
| 146 | + break; |
| 147 | + case 'Enter': |
| 148 | + e.preventDefault(); |
| 149 | + if (filteredItems[activeIndex]) { |
| 150 | + selectItem(filteredItems[activeIndex]); |
| 151 | + } |
| 152 | + break; |
| 153 | + case 'Escape': |
| 154 | + e.preventDefault(); |
| 155 | + close(); |
| 156 | + break; |
| 157 | + } |
| 158 | + }; |
| 159 | + |
| 160 | + const handleEntered = () => { |
| 161 | + inputRef.current?.focus(); |
| 162 | + }; |
| 163 | + |
| 164 | + let flatIndex = 0; |
| 165 | + |
| 166 | + return ( |
| 167 | + <Overlay isShow={open} clickCallback={close} onEntered={handleEntered} zIndex={1001}> |
| 168 | + <div className="command-palette" onClick={(e) => e.stopPropagation()}> |
| 169 | + <div className="command-palette__input-wrapper"> |
| 170 | + <Input |
| 171 | + ref={inputRef} |
| 172 | + className="command-palette__input" |
| 173 | + value={query} |
| 174 | + onChange={(e) => setQuery(e.target.value)} |
| 175 | + onKeyDown={handleInputKeyDown} |
| 176 | + placeholder={siteLocale.commandPalette.placeholder} |
| 177 | + size="lg" |
| 178 | + prefix={ |
| 179 | + <svg |
| 180 | + width="18" |
| 181 | + height="18" |
| 182 | + viewBox="0 0 24 24" |
| 183 | + fill="none" |
| 184 | + stroke="currentColor" |
| 185 | + strokeWidth="2" |
| 186 | + strokeLinecap="round" |
| 187 | + strokeLinejoin="round"> |
| 188 | + <circle cx="11" cy="11" r="8" /> |
| 189 | + <line x1="21" y1="21" x2="16.65" y2="16.65" /> |
| 190 | + </svg> |
| 191 | + } |
| 192 | + /> |
| 193 | + </div> |
| 194 | + <div className="command-palette__results" ref={resultListRef}> |
| 195 | + {filteredItems.length === 0 ? ( |
| 196 | + <div className="command-palette__empty">{siteLocale.commandPalette.noResults}</div> |
| 197 | + ) : ( |
| 198 | + groupedItems.map((group) => ( |
| 199 | + <div key={group.section} className="command-palette__group"> |
| 200 | + <div className="command-palette__group-label">{group.section}</div> |
| 201 | + {group.items.map((item) => { |
| 202 | + const idx = flatIndex++; |
| 203 | + const isActive = idx === activeIndex; |
| 204 | + return ( |
| 205 | + <div |
| 206 | + key={item.fullPath} |
| 207 | + className={`command-palette__item${isActive ? ' command-palette__item_active' : ''}`} |
| 208 | + data-active={isActive} |
| 209 | + onMouseEnter={() => setActiveIndex(idx)} |
| 210 | + onClick={() => selectItem(item)}> |
| 211 | + <span className="command-palette__item-title">{item.title}</span> |
| 212 | + <span className="command-palette__item-path">{item.fullPath}</span> |
| 213 | + </div> |
| 214 | + ); |
| 215 | + })} |
| 216 | + </div> |
| 217 | + )) |
| 218 | + )} |
| 219 | + </div> |
| 220 | + </div> |
| 221 | + </Overlay> |
| 222 | + ); |
| 223 | +}; |
0 commit comments