Apps.tsx 7.6 KB

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