Apps.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 { fetchDepts } from '@/service/common'
  31. import { TreeSelect as AntdTreeSelect } from 'antd'
  32. import { SimpleSelect } from '@/app/components/base/select'
  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. authType: number,
  42. creator: string,
  43. ) => {
  44. if (!pageIndex || previousPageData.has_more) {
  45. const params: any = { url: 'apps', params: { page: pageIndex + 1, limit: 30, name: keywords, is_created_by_me: isCreatedByMe } }
  46. if (activeTab !== 'all')
  47. params.params.mode = activeTab
  48. else
  49. delete params.params.mode
  50. if (tags.length)
  51. params.params.tag_ids = tags
  52. if (dept)
  53. params.params.creator_dept = dept
  54. if (authType)
  55. params.params.auth_type = authType
  56. if (creator)
  57. params.params.creator = creator
  58. return params
  59. }
  60. return null
  61. }
  62. const Apps = () => {
  63. const { t } = useTranslation()
  64. const router = useRouter()
  65. const { isCurrentWorkspaceEditor, isCurrentWorkspaceDatasetOperator } = useAppContext()
  66. const showTagManagementModal = useTagStore(s => s.showTagManagementModal)
  67. const [activeTab, setActiveTab] = useTabSearchParams({
  68. defaultTab: 'all',
  69. })
  70. const { query: { tagIDs = [], keywords = '', isCreatedByMe: queryIsCreatedByMe = false }, setQuery } = useAppsQueryState()
  71. const [isCreatedByMe, setIsCreatedByMe] = useState(queryIsCreatedByMe)
  72. const [tagFilterValue, setTagFilterValue] = useState<string[]>(tagIDs)
  73. const [searchKeywords, setSearchKeywords] = useState(keywords)
  74. const setKeywords = useCallback((keywords: string) => {
  75. setQuery(prev => ({ ...prev, keywords }))
  76. }, [setQuery])
  77. const setTagIDs = useCallback((tagIDs: string[]) => {
  78. setQuery(prev => ({ ...prev, tagIDs }))
  79. }, [setQuery])
  80. const [dept, setDept] = useState<any>()
  81. const [optionsDept, setOptionsDept] = useState<any>([])
  82. useEffect(() => {
  83. fetchDepts({
  84. url: '/depts',
  85. }).then((res: any) => {
  86. setOptionsDept(res.data || [])
  87. })
  88. }, [])
  89. const [authType, setAuthType] = useState<any>('')
  90. const optionsAuthType = [
  91. { name: '创建', value: '1' },
  92. { name: '编辑', value: '2' },
  93. { name: '授权编辑', value: '3' },
  94. { name: '授权可见', value: '4' },
  95. ]
  96. const [creator, setCreator] = useState('')
  97. const [searchCreator, setSearchCreator] = useState('')
  98. const { run: handleSearchCreator } = useDebounceFn(() => {
  99. setSearchCreator(creator)
  100. }, { wait: 500 })
  101. const handleCreatorChange = (value: string) => {
  102. setCreator(value)
  103. handleSearchCreator()
  104. }
  105. const { data, isLoading, setSize, mutate } = useSWRInfinite(
  106. (pageIndex: number, previousPageData: AppListResponse) => getKey(pageIndex, previousPageData, activeTab, isCreatedByMe, tagIDs, searchKeywords, dept, authType, searchCreator),
  107. fetchAppList,
  108. { revalidateFirstPage: true },
  109. )
  110. const anchorRef = useRef<HTMLDivElement>(null)
  111. const options = [
  112. { value: 'all', text: t('app.types.all'), icon: <RiApps2Line className='mr-1 h-[14px] w-[14px]' /> },
  113. { value: 'chat', text: t('app.types.chatbot'), icon: <RiMessage3Line className='mr-1 h-[14px] w-[14px]' /> },
  114. { value: 'agent-chat', text: t('app.types.agent'), icon: <RiRobot3Line className='mr-1 h-[14px] w-[14px]' /> },
  115. { value: 'completion', text: t('app.types.completion'), icon: <RiFile4Line className='mr-1 h-[14px] w-[14px]' /> },
  116. { value: 'advanced-chat', text: t('app.types.advanced'), icon: <RiMessage3Line className='mr-1 h-[14px] w-[14px]' /> },
  117. { value: 'workflow', text: t('app.types.workflow'), icon: <RiExchange2Line className='mr-1 h-[14px] w-[14px]' /> },
  118. ]
  119. useEffect(() => {
  120. document.title = `${t('common.menus.apps')} - Dify`
  121. if (localStorage.getItem(NEED_REFRESH_APP_LIST_KEY) === '1') {
  122. localStorage.removeItem(NEED_REFRESH_APP_LIST_KEY)
  123. mutate()
  124. }
  125. }, [mutate, t])
  126. useEffect(() => {
  127. if (isCurrentWorkspaceDatasetOperator)
  128. return router.replace('/datasets')
  129. }, [router, isCurrentWorkspaceDatasetOperator])
  130. useEffect(() => {
  131. const hasMore = data?.at(-1)?.has_more ?? true
  132. let observer: IntersectionObserver | undefined
  133. if (anchorRef.current) {
  134. observer = new IntersectionObserver((entries) => {
  135. if (entries[0].isIntersecting && !isLoading && hasMore)
  136. setSize((size: number) => size + 1)
  137. }, { rootMargin: '100px' })
  138. observer.observe(anchorRef.current)
  139. }
  140. return () => observer?.disconnect()
  141. }, [isLoading, setSize, anchorRef, mutate, data])
  142. const { run: handleSearch } = useDebounceFn(() => {
  143. setSearchKeywords(keywords)
  144. }, { wait: 500 })
  145. const handleKeywordsChange = (value: string) => {
  146. setKeywords(value)
  147. handleSearch()
  148. }
  149. const { run: handleTagsUpdate } = useDebounceFn(() => {
  150. setTagIDs(tagFilterValue)
  151. }, { wait: 500 })
  152. const handleTagsChange = (value: string[]) => {
  153. setTagFilterValue(value)
  154. handleTagsUpdate()
  155. }
  156. const handleCreatedByMeChange = useCallback(() => {
  157. const newValue = !isCreatedByMe
  158. setIsCreatedByMe(newValue)
  159. setQuery(prev => ({ ...prev, isCreatedByMe: newValue }))
  160. }, [isCreatedByMe, setQuery])
  161. return (
  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. <Input
  171. showLeftIcon
  172. showClearIcon
  173. wrapperClassName='w-[200px]'
  174. value={creator}
  175. onChange={e => handleCreatorChange(e.target.value)}
  176. onClear={() => handleCreatorChange('')}
  177. placeholder="请输入创建人"
  178. />
  179. <SimpleSelect
  180. wrapperClassName="h-[32px] w-[200px]"
  181. defaultValue={authType}
  182. onSelect={(i) => {
  183. setAuthType(i.value)
  184. }}
  185. items={optionsAuthType}
  186. allowSearch={false}
  187. placeholder="请选择权限类型"
  188. />
  189. <AntdTreeSelect
  190. showSearch
  191. style={{ width: '200px' }}
  192. value={dept}
  193. dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
  194. placeholder="请选择部门"
  195. allowClear
  196. treeDefaultExpandAll
  197. onChange={v => setDept(v || '')}
  198. treeData={optionsDept}
  199. fieldNames={{ label: 'dept_name', value: 'dept_id' }}
  200. />
  201. {/* <CheckboxWithLabel */}
  202. {/* className='mr-2' */}
  203. {/* label={t('app.showMyCreatedAppsOnly')} */}
  204. {/* isChecked={isCreatedByMe} */}
  205. {/* onChange={handleCreatedByMeChange} */}
  206. {/* /> */}
  207. <TagFilter type='app' value={tagFilterValue} onChange={handleTagsChange} />
  208. <Input
  209. showLeftIcon
  210. showClearIcon
  211. wrapperClassName='w-[200px]'
  212. value={keywords}
  213. onChange={e => handleKeywordsChange(e.target.value)}
  214. onClear={() => handleKeywordsChange('')}
  215. />
  216. </div>
  217. </div>
  218. {(data && data[0].total > 0)
  219. ? <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'>
  220. {isCurrentWorkspaceEditor
  221. && <NewAppCard onSuccess={mutate} />}
  222. {data.map(({ data: apps }) => apps.map(app => (
  223. <AppCard key={app.id} app={app} onRefresh={mutate} />
  224. )))}
  225. </div>
  226. : <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'>
  227. {isCurrentWorkspaceEditor
  228. && <NewAppCard className='z-10' onSuccess={mutate} />}
  229. <NoAppsFound />
  230. </div>}
  231. <CheckModal />
  232. <div ref={anchorRef} className='h-0'> </div>
  233. {showTagManagementModal && (
  234. <TagManagementModal type='app' show={showTagManagementModal} />
  235. )}
  236. </>
  237. )
  238. }
  239. export default Apps
  240. function NoAppsFound() {
  241. const { t } = useTranslation()
  242. function renderDefaultCard() {
  243. const defaultCards = Array.from({ length: 36 }, (_, index) => (
  244. <div key={index} className='inline-flex h-[160px] rounded-xl bg-background-default-lighter'></div>
  245. ))
  246. return defaultCards
  247. }
  248. return (
  249. <>
  250. {renderDefaultCard()}
  251. <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'>
  252. <span className='system-md-medium text-text-tertiary'>{t('app.newApp.noAppsFound')}</span>
  253. </div>
  254. </>
  255. )
  256. }
  257. export const GetAppAuth = (row: any) => {
  258. const { currentWorkspace, userProfile } = useAppContext()
  259. let isCreate = false
  260. let isEdit = false
  261. let isOperation = false
  262. if (row) {
  263. isCreate = currentWorkspace.role === 'owner' || row.created_by === userProfile.id
  264. isEdit = isCreate || currentWorkspace.role === 'admin' || (row.edit_auth === 2 && currentWorkspace.role === 'leader' && row.dept_id === userProfile.dept_id)
  265. isOperation = isEdit || (row.edit_auth === 2 && row.dept_id === userProfile.dept_id)
  266. }
  267. return {
  268. isCreate,
  269. isEdit,
  270. isOperation,
  271. }
  272. }