You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Apps.tsx 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. 'use client'
  2. import { useCallback, useEffect, useRef, useState } from 'react'
  3. import {
  4. useRouter,
  5. } from 'next/navigation'
  6. import useSWRInfinite from 'swr/infinite'
  7. import { useTranslation } from 'react-i18next'
  8. import { useDebounceFn } from 'ahooks'
  9. import {
  10. RiApps2Line,
  11. RiDragDropLine,
  12. RiExchange2Line,
  13. RiFile4Line,
  14. RiMessage3Line,
  15. RiRobot3Line,
  16. } from '@remixicon/react'
  17. import AppCard from './AppCard'
  18. import NewAppCard from './NewAppCard'
  19. import useAppsQueryState from './hooks/use-apps-query-state'
  20. import { useDSLDragDrop } from './hooks/use-dsl-drag-drop'
  21. import type { AppListResponse } from '@/models/app'
  22. import { fetchAppList } from '@/service/apps'
  23. import { useAppContext } from '@/context/app-context'
  24. import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
  25. import { CheckModal } from '@/hooks/use-pay'
  26. import TabSliderNew from '@/app/components/base/tab-slider-new'
  27. import { useTabSearchParams } from '@/hooks/use-tab-searchparams'
  28. import Input from '@/app/components/base/input'
  29. import { useStore as useTagStore } from '@/app/components/base/tag-management/store'
  30. import TagManagementModal from '@/app/components/base/tag-management'
  31. import TagFilter from '@/app/components/base/tag-management/filter'
  32. import CheckboxWithLabel from '@/app/components/datasets/create/website/base/checkbox-with-label'
  33. import CreateFromDSLModal from '@/app/components/app/create-from-dsl-modal'
  34. const getKey = (
  35. pageIndex: number,
  36. previousPageData: AppListResponse,
  37. activeTab: string,
  38. isCreatedByMe: boolean,
  39. tags: string[],
  40. keywords: string,
  41. ) => {
  42. if (!pageIndex || previousPageData.has_more) {
  43. const params: any = { url: 'apps', params: { page: pageIndex + 1, limit: 30, name: keywords, is_created_by_me: isCreatedByMe } }
  44. if (activeTab !== 'all')
  45. params.params.mode = activeTab
  46. else
  47. delete params.params.mode
  48. if (tags.length)
  49. params.params.tag_ids = tags
  50. return params
  51. }
  52. return null
  53. }
  54. const Apps = () => {
  55. const { t } = useTranslation()
  56. const router = useRouter()
  57. const { isCurrentWorkspaceEditor, isCurrentWorkspaceDatasetOperator } = useAppContext()
  58. const showTagManagementModal = useTagStore(s => s.showTagManagementModal)
  59. const [activeTab, setActiveTab] = useTabSearchParams({
  60. defaultTab: 'all',
  61. })
  62. const { query: { tagIDs = [], keywords = '', isCreatedByMe: queryIsCreatedByMe = false }, setQuery } = useAppsQueryState()
  63. const [isCreatedByMe, setIsCreatedByMe] = useState(queryIsCreatedByMe)
  64. const [tagFilterValue, setTagFilterValue] = useState<string[]>(tagIDs)
  65. const [searchKeywords, setSearchKeywords] = useState(keywords)
  66. const newAppCardRef = useRef<HTMLDivElement>(null)
  67. const containerRef = useRef<HTMLDivElement>(null)
  68. const [showCreateFromDSLModal, setShowCreateFromDSLModal] = useState(false)
  69. const [droppedDSLFile, setDroppedDSLFile] = useState<File | undefined>()
  70. const setKeywords = useCallback((keywords: string) => {
  71. setQuery(prev => ({ ...prev, keywords }))
  72. }, [setQuery])
  73. const setTagIDs = useCallback((tagIDs: string[]) => {
  74. setQuery(prev => ({ ...prev, tagIDs }))
  75. }, [setQuery])
  76. const handleDSLFileDropped = useCallback((file: File) => {
  77. setDroppedDSLFile(file)
  78. setShowCreateFromDSLModal(true)
  79. }, [])
  80. const { dragging } = useDSLDragDrop({
  81. onDSLFileDropped: handleDSLFileDropped,
  82. containerRef,
  83. enabled: isCurrentWorkspaceEditor,
  84. })
  85. const { data, isLoading, error, setSize, mutate } = useSWRInfinite(
  86. (pageIndex: number, previousPageData: AppListResponse) => getKey(pageIndex, previousPageData, activeTab, isCreatedByMe, tagIDs, searchKeywords),
  87. fetchAppList,
  88. {
  89. revalidateFirstPage: true,
  90. shouldRetryOnError: false,
  91. dedupingInterval: 500,
  92. errorRetryCount: 3,
  93. },
  94. )
  95. const anchorRef = useRef<HTMLDivElement>(null)
  96. const options = [
  97. { value: 'all', text: t('app.types.all'), icon: <RiApps2Line className='mr-1 h-[14px] w-[14px]' /> },
  98. { value: 'workflow', text: t('app.types.workflow'), icon: <RiExchange2Line className='mr-1 h-[14px] w-[14px]' /> },
  99. { value: 'advanced-chat', text: t('app.types.advanced'), icon: <RiMessage3Line className='mr-1 h-[14px] w-[14px]' /> },
  100. { value: 'chat', text: t('app.types.chatbot'), icon: <RiMessage3Line className='mr-1 h-[14px] w-[14px]' /> },
  101. { value: 'agent-chat', text: t('app.types.agent'), icon: <RiRobot3Line className='mr-1 h-[14px] w-[14px]' /> },
  102. { value: 'completion', text: t('app.types.completion'), icon: <RiFile4Line className='mr-1 h-[14px] w-[14px]' /> },
  103. ]
  104. useEffect(() => {
  105. if (localStorage.getItem(NEED_REFRESH_APP_LIST_KEY) === '1') {
  106. localStorage.removeItem(NEED_REFRESH_APP_LIST_KEY)
  107. mutate()
  108. }
  109. }, [mutate, t])
  110. useEffect(() => {
  111. if (isCurrentWorkspaceDatasetOperator)
  112. return router.replace('/datasets')
  113. }, [router, isCurrentWorkspaceDatasetOperator])
  114. useEffect(() => {
  115. const hasMore = data?.at(-1)?.has_more ?? true
  116. let observer: IntersectionObserver | undefined
  117. if (error) {
  118. if (observer)
  119. observer.disconnect()
  120. return
  121. }
  122. if (anchorRef.current) {
  123. observer = new IntersectionObserver((entries) => {
  124. if (entries[0].isIntersecting && !isLoading && !error && hasMore)
  125. setSize((size: number) => size + 1)
  126. }, { rootMargin: '100px' })
  127. observer.observe(anchorRef.current)
  128. }
  129. return () => observer?.disconnect()
  130. }, [isLoading, setSize, anchorRef, mutate, data, error])
  131. const { run: handleSearch } = useDebounceFn(() => {
  132. setSearchKeywords(keywords)
  133. }, { wait: 500 })
  134. const handleKeywordsChange = (value: string) => {
  135. setKeywords(value)
  136. handleSearch()
  137. }
  138. const { run: handleTagsUpdate } = useDebounceFn(() => {
  139. setTagIDs(tagFilterValue)
  140. }, { wait: 500 })
  141. const handleTagsChange = (value: string[]) => {
  142. setTagFilterValue(value)
  143. handleTagsUpdate()
  144. }
  145. const handleCreatedByMeChange = useCallback(() => {
  146. const newValue = !isCreatedByMe
  147. setIsCreatedByMe(newValue)
  148. setQuery(prev => ({ ...prev, isCreatedByMe: newValue }))
  149. }, [isCreatedByMe, setQuery])
  150. return (
  151. <>
  152. <div ref={containerRef} className='relative flex h-0 shrink-0 grow flex-col overflow-y-auto bg-background-body'>
  153. {dragging && (
  154. <div className="absolute inset-0 z-50 m-0.5 rounded-2xl border-2 border-dashed border-components-dropzone-border-accent bg-[rgba(21,90,239,0.14)] p-2">
  155. </div>
  156. )}
  157. <div className='sticky top-0 z-10 flex flex-wrap items-center justify-between gap-y-2 bg-background-body px-12 pb-2 pt-4 leading-[56px]'>
  158. <TabSliderNew
  159. value={activeTab}
  160. onChange={setActiveTab}
  161. options={options}
  162. />
  163. <div className='flex items-center gap-2'>
  164. <CheckboxWithLabel
  165. className='mr-2'
  166. label={t('app.showMyCreatedAppsOnly')}
  167. isChecked={isCreatedByMe}
  168. onChange={handleCreatedByMeChange}
  169. />
  170. <TagFilter type='app' value={tagFilterValue} onChange={handleTagsChange} />
  171. <Input
  172. showLeftIcon
  173. showClearIcon
  174. wrapperClassName='w-[200px]'
  175. value={keywords}
  176. onChange={e => handleKeywordsChange(e.target.value)}
  177. onClear={() => handleKeywordsChange('')}
  178. />
  179. </div>
  180. </div>
  181. {(data && data[0].total > 0)
  182. ? <div className='relative grid grow grid-cols-1 content-start gap-4 px-12 pt-2 sm:grid-cols-1 md:grid-cols-2 xl:grid-cols-4 2xl:grid-cols-5 2k:grid-cols-6'>
  183. {isCurrentWorkspaceEditor
  184. && <NewAppCard ref={newAppCardRef} onSuccess={mutate} />}
  185. {data.map(({ data: apps }) => apps.map(app => (
  186. <AppCard key={app.id} app={app} onRefresh={mutate} />
  187. )))}
  188. </div>
  189. : <div className='relative grid grow grid-cols-1 content-start gap-4 overflow-hidden px-12 pt-2 sm:grid-cols-1 md:grid-cols-2 xl:grid-cols-4 2xl:grid-cols-5 2k:grid-cols-6'>
  190. {isCurrentWorkspaceEditor
  191. && <NewAppCard ref={newAppCardRef} className='z-10' onSuccess={mutate} />}
  192. <NoAppsFound />
  193. </div>}
  194. {isCurrentWorkspaceEditor && (
  195. <div
  196. className={`flex items-center justify-center gap-2 py-4 ${dragging ? 'text-text-accent' : 'text-text-quaternary'}`}
  197. role="region"
  198. aria-label={t('app.newApp.dropDSLToCreateApp')}
  199. >
  200. <RiDragDropLine className="h-4 w-4" />
  201. <span className="system-xs-regular">{t('app.newApp.dropDSLToCreateApp')}</span>
  202. </div>
  203. )}
  204. <CheckModal />
  205. <div ref={anchorRef} className='h-0'> </div>
  206. {showTagManagementModal && (
  207. <TagManagementModal type='app' show={showTagManagementModal} />
  208. )}
  209. </div>
  210. {showCreateFromDSLModal && (
  211. <CreateFromDSLModal
  212. show={showCreateFromDSLModal}
  213. onClose={() => {
  214. setShowCreateFromDSLModal(false)
  215. setDroppedDSLFile(undefined)
  216. }}
  217. onSuccess={() => {
  218. setShowCreateFromDSLModal(false)
  219. setDroppedDSLFile(undefined)
  220. mutate()
  221. }}
  222. droppedFile={droppedDSLFile}
  223. />
  224. )}
  225. </>
  226. )
  227. }
  228. export default Apps
  229. function NoAppsFound() {
  230. const { t } = useTranslation()
  231. function renderDefaultCard() {
  232. const defaultCards = Array.from({ length: 36 }, (_, index) => (
  233. <div key={index} className='inline-flex h-[160px] rounded-xl bg-background-default-lighter'></div>
  234. ))
  235. return defaultCards
  236. }
  237. return (
  238. <>
  239. {renderDefaultCard()}
  240. <div className='absolute bottom-0 left-0 right-0 top-0 flex items-center justify-center bg-gradient-to-t from-background-body to-transparent'>
  241. <span className='system-md-medium text-text-tertiary'>{t('app.newApp.noAppsFound')}</span>
  242. </div>
  243. </>
  244. )
  245. }