Apps.tsx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. import { fetchDepts } from '@/service/common'
  32. import { TreeSelect as AntdTreeSelect } from 'antd'
  33. const getKey = (
  34. pageIndex: number,
  35. previousPageData: AppListResponse,
  36. activeTab: string,
  37. isCreatedByMe: boolean,
  38. tags: string[],
  39. keywords: string,
  40. dept: string,
  41. ) => {
  42. if (!pageIndex || previousPageData.has_more) {
  43. const params: any = { url: 'apps', params: { page: pageIndex + 1, limit: 30, name: keywords, is_created_by_me: isCreatedByMe } }
  44. if (activeTab !== 'all')
  45. params.params.mode = activeTab
  46. else
  47. delete params.params.mode
  48. if (tags.length)
  49. params.params.tag_ids = tags
  50. if (dept)
  51. params.params.dept = dept
  52. return params
  53. }
  54. return null
  55. }
  56. const Apps = () => {
  57. const { t } = useTranslation()
  58. const router = useRouter()
  59. const { isCurrentWorkspaceEditor, isCurrentWorkspaceDatasetOperator } = useAppContext()
  60. const showTagManagementModal = useTagStore(s => s.showTagManagementModal)
  61. const [activeTab, setActiveTab] = useTabSearchParams({
  62. defaultTab: 'all',
  63. })
  64. const { query: { tagIDs = [], keywords = '', isCreatedByMe: queryIsCreatedByMe = false }, setQuery } = useAppsQueryState()
  65. const [isCreatedByMe, setIsCreatedByMe] = useState(queryIsCreatedByMe)
  66. const [tagFilterValue, setTagFilterValue] = useState<string[]>(tagIDs)
  67. const [searchKeywords, setSearchKeywords] = useState(keywords)
  68. const setKeywords = useCallback((keywords: string) => {
  69. setQuery(prev => ({ ...prev, keywords }))
  70. }, [setQuery])
  71. const setTagIDs = useCallback((tagIDs: string[]) => {
  72. setQuery(prev => ({ ...prev, tagIDs }))
  73. }, [setQuery])
  74. const [dept, setDept] = useState<any>()
  75. const [optionsDept, setOptionsDept] = useState<any>([])
  76. useEffect(() => {
  77. fetchDepts({
  78. url: '/xxx',
  79. params: {
  80. page: 1,
  81. limit: 99999,
  82. },
  83. }).then((res: any) => {
  84. setOptionsDept(res.data || [])
  85. })
  86. }, [])
  87. const { data, isLoading, setSize, mutate } = useSWRInfinite(
  88. (pageIndex: number, previousPageData: AppListResponse) => getKey(pageIndex, previousPageData, activeTab, isCreatedByMe, tagIDs, searchKeywords, dept),
  89. fetchAppList,
  90. { revalidateFirstPage: true },
  91. )
  92. const anchorRef = useRef<HTMLDivElement>(null)
  93. const options = [
  94. { value: 'all', text: t('app.types.all'), icon: <RiApps2Line className='mr-1 h-[14px] w-[14px]' /> },
  95. { value: 'chat', text: t('app.types.chatbot'), icon: <RiMessage3Line className='mr-1 h-[14px] w-[14px]' /> },
  96. { value: 'agent-chat', text: t('app.types.agent'), icon: <RiRobot3Line className='mr-1 h-[14px] w-[14px]' /> },
  97. { value: 'completion', text: t('app.types.completion'), icon: <RiFile4Line className='mr-1 h-[14px] w-[14px]' /> },
  98. { value: 'advanced-chat', text: t('app.types.advanced'), icon: <RiMessage3Line className='mr-1 h-[14px] w-[14px]' /> },
  99. { value: 'workflow', text: t('app.types.workflow'), icon: <RiExchange2Line className='mr-1 h-[14px] w-[14px]' /> },
  100. ]
  101. useEffect(() => {
  102. document.title = `${t('common.menus.apps')} - Dify`
  103. if (localStorage.getItem(NEED_REFRESH_APP_LIST_KEY) === '1') {
  104. localStorage.removeItem(NEED_REFRESH_APP_LIST_KEY)
  105. mutate()
  106. }
  107. }, [mutate, t])
  108. useEffect(() => {
  109. if (isCurrentWorkspaceDatasetOperator)
  110. return router.replace('/datasets')
  111. }, [router, isCurrentWorkspaceDatasetOperator])
  112. useEffect(() => {
  113. const hasMore = data?.at(-1)?.has_more ?? true
  114. let observer: IntersectionObserver | undefined
  115. if (anchorRef.current) {
  116. observer = new IntersectionObserver((entries) => {
  117. if (entries[0].isIntersecting && !isLoading && hasMore)
  118. setSize((size: number) => size + 1)
  119. }, { rootMargin: '100px' })
  120. observer.observe(anchorRef.current)
  121. }
  122. return () => observer?.disconnect()
  123. }, [isLoading, setSize, anchorRef, mutate, data])
  124. const { run: handleSearch } = useDebounceFn(() => {
  125. setSearchKeywords(keywords)
  126. }, { wait: 500 })
  127. const handleKeywordsChange = (value: string) => {
  128. setKeywords(value)
  129. handleSearch()
  130. }
  131. const { run: handleTagsUpdate } = useDebounceFn(() => {
  132. setTagIDs(tagFilterValue)
  133. }, { wait: 500 })
  134. const handleTagsChange = (value: string[]) => {
  135. setTagFilterValue(value)
  136. handleTagsUpdate()
  137. }
  138. const handleCreatedByMeChange = useCallback(() => {
  139. const newValue = !isCreatedByMe
  140. setIsCreatedByMe(newValue)
  141. setQuery(prev => ({ ...prev, isCreatedByMe: newValue }))
  142. }, [isCreatedByMe, setQuery])
  143. return (
  144. <>
  145. <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]'>
  146. <TabSliderNew
  147. value={activeTab}
  148. onChange={setActiveTab}
  149. options={options}
  150. />
  151. <div className='flex items-center gap-2'>
  152. <AntdTreeSelect
  153. showSearch
  154. style={{ width: '200px' }}
  155. value={dept}
  156. dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
  157. placeholder="请选择部门"
  158. allowClear
  159. treeDefaultExpandAll
  160. onChange={v => setDept(v || '')}
  161. treeData={optionsDept}
  162. fieldNames={{ label: 'name', value: 'id' }}
  163. />
  164. <CheckboxWithLabel
  165. className='mr-2'
  166. label={t('app.showMyCreatedAppsOnly')}
  167. isChecked={isCreatedByMe}
  168. onChange={handleCreatedByMeChange}
  169. />
  170. <TagFilter type='app' value={tagFilterValue} onChange={handleTagsChange} />
  171. <Input
  172. showLeftIcon
  173. showClearIcon
  174. wrapperClassName='w-[200px]'
  175. value={keywords}
  176. onChange={e => handleKeywordsChange(e.target.value)}
  177. onClear={() => handleKeywordsChange('')}
  178. />
  179. </div>
  180. </div>
  181. {(data && data[0].total > 0)
  182. ? <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'>
  183. {isCurrentWorkspaceEditor
  184. && <NewAppCard onSuccess={mutate} />}
  185. {data.map(({ data: apps }) => apps.map(app => (
  186. <AppCard key={app.id} app={app} onRefresh={mutate} />
  187. )))}
  188. </div>
  189. : <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'>
  190. {isCurrentWorkspaceEditor
  191. && <NewAppCard className='z-10' onSuccess={mutate} />}
  192. <NoAppsFound />
  193. </div>}
  194. <CheckModal />
  195. <div ref={anchorRef} className='h-0'> </div>
  196. {showTagManagementModal && (
  197. <TagManagementModal type='app' show={showTagManagementModal} />
  198. )}
  199. </>
  200. )
  201. }
  202. export default Apps
  203. function NoAppsFound() {
  204. const { t } = useTranslation()
  205. function renderDefaultCard() {
  206. const defaultCards = Array.from({ length: 36 }, (_, index) => (
  207. <div key={index} className='inline-flex h-[160px] rounded-xl bg-background-default-lighter'></div>
  208. ))
  209. return defaultCards
  210. }
  211. return (
  212. <>
  213. {renderDefaultCard()}
  214. <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'>
  215. <span className='system-md-medium text-text-tertiary'>{t('app.newApp.noAppsFound')}</span>
  216. </div>
  217. </>
  218. )
  219. }