Apps.tsx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 { 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 { data, isLoading, setSize, mutate } = useSWRInfinite(getKey, fetchAppList, { revalidateFirstPage: false })
  20. const loadingStateRef = useRef(false)
  21. const pageContainerRef = useSelector(state => state.pageContainerRef)
  22. const anchorRef = useRef<HTMLAnchorElement>(null)
  23. useEffect(() => {
  24. document.title = `${t('app.title')} - Dify`
  25. if (localStorage.getItem(NEED_REFRESH_APP_LIST_KEY) === '1') {
  26. localStorage.removeItem(NEED_REFRESH_APP_LIST_KEY)
  27. mutate()
  28. }
  29. }, [])
  30. useEffect(() => {
  31. loadingStateRef.current = isLoading
  32. }, [isLoading])
  33. useEffect(() => {
  34. const onScroll = debounce(() => {
  35. if (!loadingStateRef.current) {
  36. const { scrollTop, clientHeight } = pageContainerRef.current!
  37. const anchorOffset = anchorRef.current!.offsetTop
  38. if (anchorOffset - scrollTop - clientHeight < 100)
  39. setSize(size => size + 1)
  40. }
  41. }, 50)
  42. pageContainerRef.current?.addEventListener('scroll', onScroll)
  43. return () => pageContainerRef.current?.removeEventListener('scroll', onScroll)
  44. }, [])
  45. return (
  46. <nav className='grid content-start grid-cols-1 gap-4 px-12 pt-8 sm:grid-cols-2 lg:grid-cols-4 grow shrink-0'>
  47. {data?.map(({ data: apps }) => apps.map(app => (
  48. <AppCard key={app.id} app={app} onDelete={mutate} />
  49. )))}
  50. <NewAppCard ref={anchorRef} onSuccess={mutate} />
  51. </nav>
  52. )
  53. }
  54. export default Apps