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.3KB

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