index.tsx 7.4 KB

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