Apps.tsx 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. 'use client'
  2. import { useCallback, useEffect, useRef, useState } from 'react'
  3. import { useRouter } from 'next/navigation'
  4. import useSWRInfinite from 'swr/infinite'
  5. import { useTranslation } from 'react-i18next'
  6. import { useDebounceFn } from 'ahooks'
  7. import {
  8. RiApps2Line,
  9. RiExchange2Line,
  10. RiMessage3Line,
  11. RiRobot3Line,
  12. } from '@remixicon/react'
  13. import AppCard from './AppCard'
  14. import NewAppCard from './NewAppCard'
  15. import useAppsQueryState from './hooks/useAppsQueryState'
  16. import type { AppListResponse } from '@/models/app'
  17. import { fetchAppList } from '@/service/apps'
  18. import { useAppContext } from '@/context/app-context'
  19. import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
  20. import { CheckModal } from '@/hooks/use-pay'
  21. import TabSliderNew from '@/app/components/base/tab-slider-new'
  22. import { useTabSearchParams } from '@/hooks/use-tab-searchparams'
  23. import Input from '@/app/components/base/input'
  24. import { useStore as useTagStore } from '@/app/components/base/tag-management/store'
  25. import TagManagementModal from '@/app/components/base/tag-management'
  26. import TagFilter from '@/app/components/base/tag-management/filter'
  27. import CheckboxWithLabel from '@/app/components/datasets/create/website/base/checkbox-with-label'
  28. const getKey = (
  29. pageIndex: number,
  30. previousPageData: AppListResponse,
  31. activeTab: string,
  32. isCreatedByMe: boolean,
  33. tags: string[],
  34. keywords: string,
  35. ) => {
  36. if (!pageIndex || previousPageData.has_more) {
  37. const params: any = { url: 'apps', params: { page: pageIndex + 1, limit: 30, name: keywords, is_created_by_me: isCreatedByMe } }
  38. if (activeTab !== 'all')
  39. params.params.mode = activeTab
  40. else
  41. delete params.params.mode
  42. if (tags.length)
  43. params.params.tag_ids = tags
  44. return params
  45. }
  46. return null
  47. }
  48. const Apps = () => {
  49. const { t } = useTranslation()
  50. const router = useRouter()
  51. const { isCurrentWorkspaceEditor, isCurrentWorkspaceDatasetOperator } = useAppContext()
  52. const showTagManagementModal = useTagStore(s => s.showTagManagementModal)
  53. const [activeTab, setActiveTab] = useTabSearchParams({
  54. defaultTab: 'all',
  55. })
  56. const { query: { tagIDs = [], keywords = '', isCreatedByMe: queryIsCreatedByMe = false }, setQuery } = useAppsQueryState()
  57. const [isCreatedByMe, setIsCreatedByMe] = useState(queryIsCreatedByMe)
  58. const [tagFilterValue, setTagFilterValue] = useState<string[]>(tagIDs)
  59. const [searchKeywords, setSearchKeywords] = useState(keywords)
  60. const setKeywords = useCallback((keywords: string) => {
  61. setQuery(prev => ({ ...prev, keywords }))
  62. }, [setQuery])
  63. const setTagIDs = useCallback((tagIDs: string[]) => {
  64. setQuery(prev => ({ ...prev, tagIDs }))
  65. }, [setQuery])
  66. const { data, isLoading, setSize, mutate } = useSWRInfinite(
  67. (pageIndex: number, previousPageData: AppListResponse) => getKey(pageIndex, previousPageData, activeTab, isCreatedByMe, tagIDs, searchKeywords),
  68. fetchAppList,
  69. { revalidateFirstPage: true },
  70. )
  71. const anchorRef = useRef<HTMLDivElement>(null)
  72. const options = [
  73. { value: 'all', text: t('app.types.all'), icon: <RiApps2Line className='w-[14px] h-[14px] mr-1' /> },
  74. { value: 'chat', text: t('app.types.chatbot'), icon: <RiMessage3Line className='w-[14px] h-[14px] mr-1' /> },
  75. { value: 'agent-chat', text: t('app.types.agent'), icon: <RiRobot3Line className='w-[14px] h-[14px] mr-1' /> },
  76. { value: 'workflow', text: t('app.types.workflow'), icon: <RiExchange2Line className='w-[14px] h-[14px] mr-1' /> },
  77. ]
  78. useEffect(() => {
  79. document.title = `${t('common.menus.apps')} - Dify`
  80. if (localStorage.getItem(NEED_REFRESH_APP_LIST_KEY) === '1') {
  81. localStorage.removeItem(NEED_REFRESH_APP_LIST_KEY)
  82. mutate()
  83. }
  84. }, [mutate, t])
  85. useEffect(() => {
  86. if (isCurrentWorkspaceDatasetOperator)
  87. return router.replace('/datasets')
  88. }, [router, isCurrentWorkspaceDatasetOperator])
  89. useEffect(() => {
  90. const hasMore = data?.at(-1)?.has_more ?? true
  91. let observer: IntersectionObserver | undefined
  92. if (anchorRef.current) {
  93. observer = new IntersectionObserver((entries) => {
  94. if (entries[0].isIntersecting && !isLoading && hasMore)
  95. setSize((size: number) => size + 1)
  96. }, { rootMargin: '100px' })
  97. observer.observe(anchorRef.current)
  98. }
  99. return () => observer?.disconnect()
  100. }, [isLoading, setSize, anchorRef, mutate, data])
  101. const { run: handleSearch } = useDebounceFn(() => {
  102. setSearchKeywords(keywords)
  103. }, { wait: 500 })
  104. const handleKeywordsChange = (value: string) => {
  105. setKeywords(value)
  106. handleSearch()
  107. }
  108. const { run: handleTagsUpdate } = useDebounceFn(() => {
  109. setTagIDs(tagFilterValue)
  110. }, { wait: 500 })
  111. const handleTagsChange = (value: string[]) => {
  112. setTagFilterValue(value)
  113. handleTagsUpdate()
  114. }
  115. const handleCreatedByMeChange = useCallback(() => {
  116. const newValue = !isCreatedByMe
  117. setIsCreatedByMe(newValue)
  118. setQuery(prev => ({ ...prev, isCreatedByMe: newValue }))
  119. }, [isCreatedByMe, setQuery])
  120. return (
  121. <>
  122. <div className='sticky top-0 flex justify-between items-center pt-4 px-12 pb-2 leading-[56px] bg-background-body z-10 flex-wrap gap-y-2'>
  123. <TabSliderNew
  124. value={activeTab}
  125. onChange={setActiveTab}
  126. options={options}
  127. />
  128. <div className='flex items-center gap-2'>
  129. <CheckboxWithLabel
  130. className='mr-2'
  131. label={t('app.showMyCreatedAppsOnly')}
  132. isChecked={isCreatedByMe}
  133. onChange={handleCreatedByMeChange}
  134. />
  135. <TagFilter type='app' value={tagFilterValue} onChange={handleTagsChange} />
  136. <Input
  137. showLeftIcon
  138. showClearIcon
  139. wrapperClassName='w-[200px]'
  140. value={keywords}
  141. onChange={e => handleKeywordsChange(e.target.value)}
  142. onClear={() => handleKeywordsChange('')}
  143. />
  144. </div>
  145. </div>
  146. {(data && data[0].total > 0)
  147. ? <div className='grid content-start grid-cols-1 sm:grid-cols-1 md:grid-cols-2 xl:grid-cols-4 2xl:grid-cols-5 2k:grid-cols-6 gap-4 px-12 pt-2 grow relative'>
  148. {isCurrentWorkspaceEditor
  149. && <NewAppCard onSuccess={mutate} />}
  150. {data.map(({ data: apps }) => apps.map(app => (
  151. <AppCard key={app.id} app={app} onRefresh={mutate} />
  152. )))}
  153. </div>
  154. : <div className='grid content-start grid-cols-1 sm:grid-cols-1 md:grid-cols-2 xl:grid-cols-4 2xl:grid-cols-5 2k:grid-cols-6 gap-4 px-12 pt-2 grow relative overflow-hidden'>
  155. {isCurrentWorkspaceEditor
  156. && <NewAppCard className='z-10' onSuccess={mutate} />}
  157. <NoAppsFound />
  158. </div>}
  159. <CheckModal />
  160. <div ref={anchorRef} className='h-0'> </div>
  161. {showTagManagementModal && (
  162. <TagManagementModal type='app' show={showTagManagementModal} />
  163. )}
  164. </>
  165. )
  166. }
  167. export default Apps
  168. function NoAppsFound() {
  169. const { t } = useTranslation()
  170. function renderDefaultCard() {
  171. const defaultCards = Array.from({ length: 36 }, (_, index) => (
  172. <div key={index} className='h-[160px] inline-flex rounded-xl bg-background-default-lighter'></div>
  173. ))
  174. return defaultCards
  175. }
  176. return (
  177. <>
  178. {renderDefaultCard()}
  179. <div className='absolute top-0 left-0 right-0 bottom-0 flex items-center justify-center bg-gradient-to-t from-background-body to-transparent'>
  180. <span className='system-md-medium text-text-tertiary'>{t('app.newApp.noAppsFound')}</span>
  181. </div>
  182. </>
  183. )
  184. }