Apps.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use client'
  2. import { useEffect, useRef } from 'react'
  3. import useSWRInfinite from 'swr/infinite'
  4. import { debounce } from 'lodash-es'
  5. import { useTranslation } from 'react-i18next'
  6. import AppCard from './AppCard'
  7. import NewAppCard from './NewAppCard'
  8. import type { AppListResponse } from '@/models/app'
  9. import { fetchAppList } from '@/service/apps'
  10. import { useAppContext, useSelector } from '@/context/app-context'
  11. import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
  12. const getKey = (pageIndex: number, previousPageData: AppListResponse) => {
  13. if (!pageIndex || previousPageData.has_more)
  14. return { url: 'apps', params: { page: pageIndex + 1, limit: 30 } }
  15. return null
  16. }
  17. const Apps = () => {
  18. const { t } = useTranslation()
  19. const { isCurrentWorkspaceManager } = useAppContext()
  20. const { data, isLoading, setSize, mutate } = useSWRInfinite(getKey, fetchAppList, { revalidateFirstPage: false })
  21. const loadingStateRef = useRef(false)
  22. const pageContainerRef = useSelector(state => state.pageContainerRef)
  23. const anchorRef = useRef<HTMLAnchorElement>(null)
  24. useEffect(() => {
  25. document.title = `${t('app.title')} - Dify`
  26. if (localStorage.getItem(NEED_REFRESH_APP_LIST_KEY) === '1') {
  27. localStorage.removeItem(NEED_REFRESH_APP_LIST_KEY)
  28. mutate()
  29. }
  30. }, [])
  31. useEffect(() => {
  32. loadingStateRef.current = isLoading
  33. }, [isLoading])
  34. useEffect(() => {
  35. const onScroll = debounce(() => {
  36. if (!loadingStateRef.current) {
  37. const { scrollTop, clientHeight } = pageContainerRef.current!
  38. const anchorOffset = anchorRef.current!.offsetTop
  39. if (anchorOffset - scrollTop - clientHeight < 100)
  40. setSize(size => size + 1)
  41. }
  42. }, 50)
  43. pageContainerRef.current?.addEventListener('scroll', onScroll)
  44. return () => pageContainerRef.current?.removeEventListener('scroll', onScroll)
  45. }, [])
  46. return (
  47. <nav className='grid content-start grid-cols-1 gap-4 px-12 pt-8 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 grow shrink-0'>
  48. {data?.map(({ data: apps }) => apps.map(app => (
  49. <AppCard key={app.id} app={app} onDelete={mutate} />
  50. )))}
  51. { isCurrentWorkspaceManager
  52. && <NewAppCard ref={anchorRef} onSuccess={mutate} />}
  53. </nav>
  54. )
  55. }
  56. export default Apps