Apps.tsx 7.6 KB

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