index.tsx 7.4 KB

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