index.tsx 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 Input from '@/app/components/base/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_type,
  108. icon,
  109. icon_background,
  110. description,
  111. }) => {
  112. const { export_data } = await fetchAppDetail(
  113. currApp?.app.id as string,
  114. )
  115. try {
  116. const app = await importApp({
  117. data: export_data,
  118. name,
  119. icon_type,
  120. icon,
  121. icon_background,
  122. description,
  123. })
  124. setIsShowCreateModal(false)
  125. Toast.notify({
  126. type: 'success',
  127. message: t('app.newApp.appCreated'),
  128. })
  129. if (onSuccess)
  130. onSuccess()
  131. localStorage.setItem(NEED_REFRESH_APP_LIST_KEY, '1')
  132. getRedirection(isCurrentWorkspaceEditor, app, push)
  133. }
  134. catch (e) {
  135. Toast.notify({ type: 'error', message: t('app.newApp.appCreateFailed') })
  136. }
  137. }
  138. if (!categories || categories.length === 0) {
  139. return (
  140. <div className="flex h-full items-center">
  141. <Loading type="area" />
  142. </div>
  143. )
  144. }
  145. return (
  146. <div className={cn(
  147. 'flex flex-col',
  148. pageType === PageType.EXPLORE ? 'h-full border-l border-gray-200' : 'h-[calc(100%-56px)]',
  149. )}>
  150. {pageType === PageType.EXPLORE && (
  151. <div className='shrink-0 pt-6 px-12'>
  152. <div className={`mb-1 ${s.textGradient} text-xl font-semibold`}>{t('explore.apps.title')}</div>
  153. <div className='text-gray-500 text-sm'>{t('explore.apps.description')}</div>
  154. </div>
  155. )}
  156. <div className={cn(
  157. 'flex items-center justify-between mt-6',
  158. pageType === PageType.EXPLORE ? 'px-12' : 'px-8',
  159. )}>
  160. <>
  161. {pageType !== PageType.EXPLORE && (
  162. <>
  163. <AppTypeSelector value={currentType} onChange={setCurrentType}/>
  164. <div className='mx-2 w-[1px] h-3.5 bg-gray-200'/>
  165. </>
  166. )}
  167. <Category
  168. list={categories}
  169. value={currCategory}
  170. onChange={setCurrCategory}
  171. allCategoriesEn={allCategoriesEn}
  172. />
  173. </>
  174. <Input
  175. showLeftIcon
  176. showClearIcon
  177. wrapperClassName='w-[200px]'
  178. value={keywords}
  179. onChange={e => handleKeywordsChange(e.target.value)}
  180. onClear={() => handleKeywordsChange('')}
  181. />
  182. </div>
  183. <div className={cn(
  184. 'relative flex flex-1 pb-6 flex-col overflow-auto bg-gray-100 shrink-0 grow',
  185. pageType === PageType.EXPLORE ? 'mt-4' : 'mt-0 pt-2',
  186. )}>
  187. <nav
  188. className={cn(
  189. s.appList,
  190. 'grid content-start shrink-0',
  191. 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',
  192. )}>
  193. {searchFilteredList.map(app => (
  194. <AppCard
  195. key={app.app_id}
  196. isExplore={pageType === PageType.EXPLORE}
  197. app={app}
  198. canCreate={hasEditPermission}
  199. onCreate={() => {
  200. setCurrApp(app)
  201. setIsShowCreateModal(true)
  202. }}
  203. />
  204. ))}
  205. </nav>
  206. </div>
  207. {isShowCreateModal && (
  208. <CreateAppModal
  209. appIconType={currApp?.app.icon_type || 'emoji'}
  210. appIcon={currApp?.app.icon || ''}
  211. appIconBackground={currApp?.app.icon_background || ''}
  212. appIconUrl={currApp?.app.icon_url}
  213. appName={currApp?.app.name || ''}
  214. appDescription={currApp?.app.description || ''}
  215. show={isShowCreateModal}
  216. onConfirm={onCreate}
  217. onHide={() => setIsShowCreateModal(false)}
  218. />
  219. )}
  220. </div>
  221. )
  222. }
  223. export default React.memo(Apps)