index.tsx 7.8 KB

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