Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

index.tsx 15KB

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