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.

list.tsx 9.5KB

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