index.tsx 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. 'use client'
  2. import React, { useMemo, useState } from 'react'
  3. import { useRouter } from 'next/navigation'
  4. import { useTranslation } from 'react-i18next'
  5. import { useContext } from 'use-context-selector'
  6. import useSWR from 'swr'
  7. import { useDebounceFn } from 'ahooks'
  8. import Toast from '../../base/toast'
  9. import s from './style.module.css'
  10. import cn from '@/utils/classnames'
  11. import ExploreContext from '@/context/explore-context'
  12. import type { App } from '@/models/explore'
  13. import Category from '@/app/components/explore/category'
  14. import AppCard from '@/app/components/explore/app-card'
  15. import { fetchAppDetail, fetchAppList } from '@/service/explore'
  16. import { importDSL } from '@/service/apps'
  17. import { useTabSearchParams } from '@/hooks/use-tab-searchparams'
  18. import CreateAppModal from '@/app/components/explore/create-app-modal'
  19. import AppTypeSelector from '@/app/components/app/type-selector'
  20. import type { CreateAppModalProps } from '@/app/components/explore/create-app-modal'
  21. import Loading from '@/app/components/base/loading'
  22. import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
  23. import { useAppContext } from '@/context/app-context'
  24. import { getRedirection } from '@/utils/app-redirection'
  25. import Input from '@/app/components/base/input'
  26. import { DSLImportMode } from '@/models/app'
  27. import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'
  28. type AppsProps = {
  29. pageType?: PageType
  30. onSuccess?: () => void
  31. }
  32. export enum PageType {
  33. EXPLORE = 'explore',
  34. CREATE = 'create',
  35. }
  36. const Apps = ({
  37. pageType = PageType.EXPLORE,
  38. onSuccess,
  39. }: AppsProps) => {
  40. const { t } = useTranslation()
  41. const { isCurrentWorkspaceEditor } = useAppContext()
  42. const { push } = useRouter()
  43. const { hasEditPermission } = useContext(ExploreContext)
  44. const allCategoriesEn = t('explore.apps.allCategories', { lng: 'en' })
  45. const [keywords, setKeywords] = useState('')
  46. const [searchKeywords, setSearchKeywords] = useState('')
  47. const { run: handleSearch } = useDebounceFn(() => {
  48. setSearchKeywords(keywords)
  49. }, { wait: 500 })
  50. const handleKeywordsChange = (value: string) => {
  51. setKeywords(value)
  52. handleSearch()
  53. }
  54. const [currentType, setCurrentType] = useState<string>('')
  55. const [currCategory, setCurrCategory] = useTabSearchParams({
  56. defaultTab: allCategoriesEn,
  57. disableSearchParams: pageType !== PageType.EXPLORE,
  58. })
  59. const {
  60. data: { categories, allList },
  61. } = useSWR(
  62. ['/explore/apps'],
  63. () =>
  64. fetchAppList().then(({ categories, recommended_apps }) => ({
  65. categories,
  66. allList: recommended_apps.sort((a, b) => a.position - b.position),
  67. })),
  68. {
  69. fallbackData: {
  70. categories: [],
  71. allList: [],
  72. },
  73. },
  74. )
  75. const filteredList = useMemo(() => {
  76. if (currCategory === allCategoriesEn) {
  77. if (!currentType)
  78. return allList
  79. else if (currentType === 'chatbot')
  80. return allList.filter(item => (item.app.mode === 'chat' || item.app.mode === 'advanced-chat'))
  81. else if (currentType === 'agent')
  82. return allList.filter(item => (item.app.mode === 'agent-chat'))
  83. else
  84. return allList.filter(item => (item.app.mode === 'workflow'))
  85. }
  86. else {
  87. if (!currentType)
  88. return allList.filter(item => item.category === currCategory)
  89. else if (currentType === 'chatbot')
  90. return allList.filter(item => (item.app.mode === 'chat' || item.app.mode === 'advanced-chat') && item.category === currCategory)
  91. else if (currentType === 'agent')
  92. return allList.filter(item => (item.app.mode === 'agent-chat') && item.category === currCategory)
  93. else
  94. return allList.filter(item => (item.app.mode === 'workflow') && item.category === currCategory)
  95. }
  96. }, [currentType, currCategory, allCategoriesEn, allList])
  97. const searchFilteredList = useMemo(() => {
  98. if (!searchKeywords || !filteredList || filteredList.length === 0)
  99. return filteredList
  100. const lowerCaseSearchKeywords = searchKeywords.toLowerCase()
  101. return filteredList.filter(item =>
  102. item.app && item.app.name && item.app.name.toLowerCase().includes(lowerCaseSearchKeywords),
  103. )
  104. }, [searchKeywords, filteredList])
  105. const [currApp, setCurrApp] = React.useState<App | null>(null)
  106. const [isShowCreateModal, setIsShowCreateModal] = React.useState(false)
  107. const { handleCheckPluginDependencies } = usePluginDependencies()
  108. const onCreate: CreateAppModalProps['onConfirm'] = async ({
  109. name,
  110. icon_type,
  111. icon,
  112. icon_background,
  113. description,
  114. }) => {
  115. const { export_data, mode } = await fetchAppDetail(
  116. currApp?.app.id as string,
  117. )
  118. try {
  119. const app = await importDSL({
  120. mode: DSLImportMode.YAML_CONTENT,
  121. yaml_content: export_data,
  122. name,
  123. icon_type,
  124. icon,
  125. icon_background,
  126. description,
  127. })
  128. setIsShowCreateModal(false)
  129. Toast.notify({
  130. type: 'success',
  131. message: t('app.newApp.appCreated'),
  132. })
  133. if (onSuccess)
  134. onSuccess()
  135. if (app.app_id)
  136. await handleCheckPluginDependencies(app.app_id)
  137. localStorage.setItem(NEED_REFRESH_APP_LIST_KEY, '1')
  138. getRedirection(isCurrentWorkspaceEditor, { id: app.app_id, mode }, push)
  139. }
  140. catch (e) {
  141. Toast.notify({ type: 'error', message: t('app.newApp.appCreateFailed') })
  142. }
  143. }
  144. if (!categories || categories.length === 0) {
  145. return (
  146. <div className="flex h-full items-center">
  147. <Loading type="area" />
  148. </div>
  149. )
  150. }
  151. return (
  152. <div className={cn(
  153. 'flex flex-col',
  154. pageType === PageType.EXPLORE ? 'h-full border-l border-gray-200' : 'h-[calc(100%-56px)]',
  155. )}>
  156. {pageType === PageType.EXPLORE && (
  157. <div className='shrink-0 pt-6 px-12'>
  158. <div className={`mb-1 ${s.textGradient} text-xl font-semibold`}>{t('explore.apps.title')}</div>
  159. <div className='text-gray-500 text-sm'>{t('explore.apps.description')}</div>
  160. </div>
  161. )}
  162. <div className={cn(
  163. 'flex items-center justify-between mt-6',
  164. pageType === PageType.EXPLORE ? 'px-12' : 'px-8',
  165. )}>
  166. <>
  167. {pageType !== PageType.EXPLORE && (
  168. <>
  169. <AppTypeSelector value={currentType} onChange={setCurrentType}/>
  170. <div className='mx-2 w-[1px] h-3.5 bg-gray-200'/>
  171. </>
  172. )}
  173. <Category
  174. list={categories}
  175. value={currCategory}
  176. onChange={setCurrCategory}
  177. allCategoriesEn={allCategoriesEn}
  178. />
  179. </>
  180. <Input
  181. showLeftIcon
  182. showClearIcon
  183. wrapperClassName='w-[200px]'
  184. value={keywords}
  185. onChange={e => handleKeywordsChange(e.target.value)}
  186. onClear={() => handleKeywordsChange('')}
  187. />
  188. </div>
  189. <div className={cn(
  190. 'relative flex flex-1 pb-6 flex-col overflow-auto bg-gray-100 shrink-0 grow',
  191. pageType === PageType.EXPLORE ? 'mt-4' : 'mt-0 pt-2',
  192. )}>
  193. <nav
  194. className={cn(
  195. s.appList,
  196. 'grid content-start shrink-0',
  197. pageType === PageType.EXPLORE ? 'gap-4 px-6 sm:px-12' : 'gap-3 px-8 sm:!grid-cols-2 md:!grid-cols-3 lg:!grid-cols-4',
  198. )}>
  199. {searchFilteredList.map(app => (
  200. <AppCard
  201. key={app.app_id}
  202. isExplore={pageType === PageType.EXPLORE}
  203. app={app}
  204. canCreate={hasEditPermission}
  205. onCreate={() => {
  206. setCurrApp(app)
  207. setIsShowCreateModal(true)
  208. }}
  209. />
  210. ))}
  211. </nav>
  212. </div>
  213. {isShowCreateModal && (
  214. <CreateAppModal
  215. appIconType={currApp?.app.icon_type || 'emoji'}
  216. appIcon={currApp?.app.icon || ''}
  217. appIconBackground={currApp?.app.icon_background || ''}
  218. appIconUrl={currApp?.app.icon_url}
  219. appName={currApp?.app.name || ''}
  220. appDescription={currApp?.app.description || ''}
  221. show={isShowCreateModal}
  222. onConfirm={onCreate}
  223. onHide={() => setIsShowCreateModal(false)}
  224. />
  225. )}
  226. </div>
  227. )
  228. }
  229. export default React.memo(Apps)