Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. 'use client'
  2. import type { FC } from 'react'
  3. import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
  4. import { useRouter } from 'next/navigation'
  5. import Modal from '@/app/components/base/modal'
  6. import Input from '@/app/components/base/input'
  7. import { useDebounce, useKeyPress } from 'ahooks'
  8. import { getKeyboardKeyCodeBySystem, isEventTargetInputArea, isMac } from '@/app/components/workflow/utils/common'
  9. import { selectWorkflowNode } from '@/app/components/workflow/utils/node-navigation'
  10. import { RiSearchLine } from '@remixicon/react'
  11. import { Actions as AllActions, type SearchResult, matchAction, searchAnything } from './actions'
  12. import { GotoAnythingProvider, useGotoAnythingContext } from './context'
  13. import { useQuery } from '@tanstack/react-query'
  14. import { useGetLanguage } from '@/context/i18n'
  15. import { useTranslation } from 'react-i18next'
  16. import InstallFromMarketplace from '../plugins/install-plugin/install-from-marketplace'
  17. import type { Plugin } from '../plugins/types'
  18. import { Command } from 'cmdk'
  19. import CommandSelector from './command-selector'
  20. import { SlashCommandProvider } from './actions/commands'
  21. type Props = {
  22. onHide?: () => void
  23. }
  24. const GotoAnything: FC<Props> = ({
  25. onHide,
  26. }) => {
  27. const router = useRouter()
  28. const defaultLocale = useGetLanguage()
  29. const { isWorkflowPage } = useGotoAnythingContext()
  30. const { t } = useTranslation()
  31. const [show, setShow] = useState<boolean>(false)
  32. const [searchQuery, setSearchQuery] = useState<string>('')
  33. const [cmdVal, setCmdVal] = useState<string>('_')
  34. const inputRef = useRef<HTMLInputElement>(null)
  35. // Filter actions based on context
  36. const Actions = useMemo(() => {
  37. // Create a filtered copy of actions based on current page context
  38. if (isWorkflowPage) {
  39. // Include all actions on workflow pages
  40. return AllActions
  41. }
  42. else {
  43. const { app, knowledge, plugin, slash } = AllActions
  44. return { app, knowledge, plugin, slash }
  45. }
  46. }, [isWorkflowPage])
  47. const [activePlugin, setActivePlugin] = useState<Plugin>()
  48. // Handle keyboard shortcuts
  49. const handleToggleModal = useCallback((e: KeyboardEvent) => {
  50. // Allow closing when modal is open, even if focus is in the search input
  51. if (!show && isEventTargetInputArea(e.target as HTMLElement))
  52. return
  53. e.preventDefault()
  54. setShow((prev) => {
  55. if (!prev) {
  56. // Opening modal - reset search state
  57. setSearchQuery('')
  58. }
  59. return !prev
  60. })
  61. }, [show])
  62. useKeyPress(`${getKeyboardKeyCodeBySystem('ctrl')}.k`, handleToggleModal, {
  63. exactMatch: true,
  64. useCapture: true,
  65. })
  66. useKeyPress(['esc'], (e) => {
  67. if (show) {
  68. e.preventDefault()
  69. setShow(false)
  70. setSearchQuery('')
  71. }
  72. })
  73. const searchQueryDebouncedValue = useDebounce(searchQuery.trim(), {
  74. wait: 300,
  75. })
  76. const isCommandsMode = searchQuery.trim() === '@' || searchQuery.trim() === '/'
  77. || (searchQuery.trim().startsWith('@') && !matchAction(searchQuery.trim(), Actions))
  78. || (searchQuery.trim().startsWith('/') && !matchAction(searchQuery.trim(), Actions))
  79. const searchMode = useMemo(() => {
  80. if (isCommandsMode) return 'commands'
  81. const query = searchQueryDebouncedValue.toLowerCase()
  82. const action = matchAction(query, Actions)
  83. return action
  84. ? (action.key === '/' ? '@command' : action.key)
  85. : 'general'
  86. }, [searchQueryDebouncedValue, Actions, isCommandsMode])
  87. const { data: searchResults = [], isLoading, isError, error } = useQuery(
  88. {
  89. queryKey: [
  90. 'goto-anything',
  91. 'search-result',
  92. searchQueryDebouncedValue,
  93. searchMode,
  94. isWorkflowPage,
  95. defaultLocale,
  96. Object.keys(Actions).sort().join(','),
  97. ],
  98. queryFn: async () => {
  99. const query = searchQueryDebouncedValue.toLowerCase()
  100. const action = matchAction(query, Actions)
  101. return await searchAnything(defaultLocale, query, action)
  102. },
  103. enabled: !!searchQueryDebouncedValue && !isCommandsMode,
  104. staleTime: 30000,
  105. gcTime: 300000,
  106. },
  107. )
  108. // Prevent automatic selection of the first option when cmdVal is not set
  109. const clearSelection = () => {
  110. setCmdVal('_')
  111. }
  112. const handleCommandSelect = useCallback((commandKey: string) => {
  113. setSearchQuery(`${commandKey} `)
  114. clearSelection()
  115. setTimeout(() => {
  116. inputRef.current?.focus()
  117. }, 0)
  118. }, [])
  119. // Handle navigation to selected result
  120. const handleNavigate = useCallback((result: SearchResult) => {
  121. setShow(false)
  122. setSearchQuery('')
  123. switch (result.type) {
  124. case 'command': {
  125. // Execute slash commands
  126. const action = Actions.slash
  127. action?.action?.(result)
  128. break
  129. }
  130. case 'plugin':
  131. setActivePlugin(result.data)
  132. break
  133. case 'workflow-node':
  134. // Handle workflow node selection and navigation
  135. if (result.metadata?.nodeId)
  136. selectWorkflowNode(result.metadata.nodeId, true)
  137. break
  138. default:
  139. if (result.path)
  140. router.push(result.path)
  141. }
  142. }, [router])
  143. // Group results by type
  144. const groupedResults = useMemo(() => searchResults.reduce((acc, result) => {
  145. if (!acc[result.type])
  146. acc[result.type] = []
  147. acc[result.type].push(result)
  148. return acc
  149. }, {} as { [key: string]: SearchResult[] }),
  150. [searchResults])
  151. const emptyResult = useMemo(() => {
  152. if (searchResults.length || !searchQuery.trim() || isLoading || isCommandsMode)
  153. return null
  154. const isCommandSearch = searchMode !== 'general'
  155. const commandType = isCommandSearch ? searchMode.replace('@', '') : ''
  156. if (isError) {
  157. return (
  158. <div className="flex items-center justify-center py-8 text-center text-text-tertiary">
  159. <div>
  160. <div className='text-sm font-medium text-red-500'>{t('app.gotoAnything.searchTemporarilyUnavailable')}</div>
  161. <div className='mt-1 text-xs text-text-quaternary'>
  162. {t('app.gotoAnything.servicesUnavailableMessage')}
  163. </div>
  164. </div>
  165. </div>
  166. )
  167. }
  168. return (
  169. <div className="flex items-center justify-center py-8 text-center text-text-tertiary">
  170. <div>
  171. <div className='text-sm font-medium'>
  172. {isCommandSearch
  173. ? (() => {
  174. const keyMap: Record<string, string> = {
  175. app: 'app.gotoAnything.emptyState.noAppsFound',
  176. plugin: 'app.gotoAnything.emptyState.noPluginsFound',
  177. knowledge: 'app.gotoAnything.emptyState.noKnowledgeBasesFound',
  178. node: 'app.gotoAnything.emptyState.noWorkflowNodesFound',
  179. }
  180. return t(keyMap[commandType] || 'app.gotoAnything.noResults')
  181. })()
  182. : t('app.gotoAnything.noResults')
  183. }
  184. </div>
  185. <div className='mt-1 text-xs text-text-quaternary'>
  186. {isCommandSearch
  187. ? t('app.gotoAnything.emptyState.tryDifferentTerm')
  188. : t('app.gotoAnything.emptyState.trySpecificSearch', { shortcuts: Object.values(Actions).map(action => action.shortcut).join(', ') })
  189. }
  190. </div>
  191. </div>
  192. </div>
  193. )
  194. }, [searchResults, searchQuery, Actions, searchMode, isLoading, isError, isCommandsMode])
  195. const defaultUI = useMemo(() => {
  196. if (searchQuery.trim())
  197. return null
  198. return (<div className="flex items-center justify-center py-12 text-center text-text-tertiary">
  199. <div>
  200. <div className='text-sm font-medium'>{t('app.gotoAnything.searchTitle')}</div>
  201. <div className='mt-3 space-y-1 text-xs text-text-quaternary'>
  202. <div>{t('app.gotoAnything.searchHint')}</div>
  203. <div>{t('app.gotoAnything.commandHint')}</div>
  204. </div>
  205. </div>
  206. </div>)
  207. }, [searchQuery, Actions])
  208. useEffect(() => {
  209. if (show) {
  210. requestAnimationFrame(() => {
  211. inputRef.current?.focus()
  212. })
  213. }
  214. }, [show])
  215. return (
  216. <>
  217. <SlashCommandProvider />
  218. <Modal
  219. isShow={show}
  220. onClose={() => {
  221. setShow(false)
  222. setSearchQuery('')
  223. clearSelection()
  224. onHide?.()
  225. }}
  226. closable={false}
  227. className='!w-[480px] !p-0'
  228. highPriority={true}
  229. >
  230. <div className='flex flex-col rounded-2xl border border-components-panel-border bg-components-panel-bg shadow-xl'>
  231. <Command
  232. className='outline-none'
  233. value={cmdVal}
  234. onValueChange={setCmdVal}
  235. disablePointerSelection
  236. >
  237. <div className='flex items-center gap-3 border-b border-divider-subtle bg-components-panel-bg-blur px-4 py-3'>
  238. <RiSearchLine className='h-4 w-4 text-text-quaternary' />
  239. <div className='flex flex-1 items-center gap-2'>
  240. <Input
  241. ref={inputRef}
  242. value={searchQuery}
  243. placeholder={t('app.gotoAnything.searchPlaceholder')}
  244. onChange={(e) => {
  245. setSearchQuery(e.target.value)
  246. if (!e.target.value.startsWith('@') && !e.target.value.startsWith('/'))
  247. clearSelection()
  248. }}
  249. className='flex-1 !border-0 !bg-transparent !shadow-none'
  250. wrapperClassName='flex-1 !border-0 !bg-transparent'
  251. autoFocus
  252. />
  253. {searchMode !== 'general' && (
  254. <div className='flex items-center gap-1 rounded bg-blue-50 px-2 py-[2px] text-xs font-medium text-blue-600 dark:bg-blue-900/40 dark:text-blue-300'>
  255. <span>{searchMode.replace('@', '').toUpperCase()}</span>
  256. </div>
  257. )}
  258. </div>
  259. <div className='text-xs text-text-quaternary'>
  260. <span className='system-kbd rounded bg-gray-200 px-1 py-[2px] font-mono text-gray-700 dark:bg-gray-800 dark:text-gray-100'>
  261. {isMac() ? '⌘' : 'Ctrl'}
  262. </span>
  263. <span className='system-kbd ml-1 rounded bg-gray-200 px-1 py-[2px] font-mono text-gray-700 dark:bg-gray-800 dark:text-gray-100'>
  264. K
  265. </span>
  266. </div>
  267. </div>
  268. <Command.List className='max-h-[275px] min-h-[240px] overflow-y-auto'>
  269. {isLoading && (
  270. <div className="flex items-center justify-center py-8 text-center text-text-tertiary">
  271. <div className="flex items-center gap-2">
  272. <div className="h-4 w-4 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"></div>
  273. <span className="text-sm">{t('app.gotoAnything.searching')}</span>
  274. </div>
  275. </div>
  276. )}
  277. {isError && (
  278. <div className="flex items-center justify-center py-8 text-center text-text-tertiary">
  279. <div>
  280. <div className="text-sm font-medium text-red-500">{t('app.gotoAnything.searchFailed')}</div>
  281. <div className="mt-1 text-xs text-text-quaternary">
  282. {error.message}
  283. </div>
  284. </div>
  285. </div>
  286. )}
  287. {!isLoading && !isError && (
  288. <>
  289. {isCommandsMode ? (
  290. <CommandSelector
  291. actions={Actions}
  292. onCommandSelect={handleCommandSelect}
  293. searchFilter={searchQuery.trim().substring(1)}
  294. commandValue={cmdVal}
  295. onCommandValueChange={setCmdVal}
  296. />
  297. ) : (
  298. Object.entries(groupedResults).map(([type, results], groupIndex) => (
  299. <Command.Group key={groupIndex} heading={(() => {
  300. const typeMap: Record<string, string> = {
  301. 'app': 'app.gotoAnything.groups.apps',
  302. 'plugin': 'app.gotoAnything.groups.plugins',
  303. 'knowledge': 'app.gotoAnything.groups.knowledgeBases',
  304. 'workflow-node': 'app.gotoAnything.groups.workflowNodes',
  305. 'command': 'app.gotoAnything.groups.commands',
  306. }
  307. return t(typeMap[type] || `${type}s`)
  308. })()} className='p-2 capitalize text-text-secondary'>
  309. {results.map(result => (
  310. <Command.Item
  311. key={`${result.type}-${result.id}`}
  312. value={result.title}
  313. className='flex cursor-pointer items-center gap-3 rounded-md p-3 will-change-[background-color] aria-[selected=true]:bg-state-base-hover data-[selected=true]:bg-state-base-hover'
  314. onSelect={() => handleNavigate(result)}
  315. >
  316. {result.icon}
  317. <div className='min-w-0 flex-1'>
  318. <div className='truncate font-medium text-text-secondary'>
  319. {result.title}
  320. </div>
  321. {result.description && (
  322. <div className='mt-0.5 truncate text-xs text-text-quaternary'>
  323. {result.description}
  324. </div>
  325. )}
  326. </div>
  327. <div className='text-xs capitalize text-text-quaternary'>
  328. {result.type}
  329. </div>
  330. </Command.Item>
  331. ))}
  332. </Command.Group>
  333. ))
  334. )}
  335. {!isCommandsMode && emptyResult}
  336. {!isCommandsMode && defaultUI}
  337. </>
  338. )}
  339. </Command.List>
  340. {(!!searchResults.length || isError) && (
  341. <div className='border-t border-divider-subtle bg-components-panel-bg-blur px-4 py-2 text-xs text-text-tertiary'>
  342. <div className='flex items-center justify-between'>
  343. <span>
  344. {isError ? (
  345. <span className='text-red-500'>{t('app.gotoAnything.someServicesUnavailable')}</span>
  346. ) : (
  347. <>
  348. {t('app.gotoAnything.resultCount', { count: searchResults.length })}
  349. {searchMode !== 'general' && (
  350. <span className='ml-2 opacity-60'>
  351. {t('app.gotoAnything.inScope', { scope: searchMode.replace('@', '') })}
  352. </span>
  353. )}
  354. </>
  355. )}
  356. </span>
  357. <span className='opacity-60'>
  358. {searchMode !== 'general'
  359. ? t('app.gotoAnything.clearToSearchAll')
  360. : t('app.gotoAnything.useAtForSpecific')
  361. }
  362. </span>
  363. </div>
  364. </div>
  365. )}
  366. </Command>
  367. </div>
  368. </Modal>
  369. {
  370. activePlugin && (
  371. <InstallFromMarketplace
  372. manifest={activePlugin}
  373. uniqueIdentifier={activePlugin.latest_package_identifier}
  374. onClose={() => setActivePlugin(undefined)}
  375. onSuccess={() => setActivePlugin(undefined)}
  376. />
  377. )
  378. }
  379. </>
  380. )
  381. }
  382. /**
  383. * GotoAnything component with context provider
  384. */
  385. const GotoAnythingWithContext: FC<Props> = (props) => {
  386. return (
  387. <GotoAnythingProvider>
  388. <GotoAnything {...props} />
  389. </GotoAnythingProvider>
  390. )
  391. }
  392. export default GotoAnythingWithContext