Apps.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 { useSearchParams } from 'next/navigation'
  7. import AppCard from './AppCard'
  8. import NewAppCard from './NewAppCard'
  9. import type { AppListResponse } from '@/models/app'
  10. import { fetchAppList } from '@/service/apps'
  11. import { useSelector } from '@/context/app-context'
  12. import { NEED_REFRESH_APP_LIST_KEY, SPARK_FREE_QUOTA_PENDING } from '@/config'
  13. const getKey = (pageIndex: number, previousPageData: AppListResponse) => {
  14. if (!pageIndex || previousPageData.has_more)
  15. return { url: 'apps', params: { page: pageIndex + 1, limit: 30 } }
  16. return null
  17. }
  18. const Apps = () => {
  19. const { t } = useTranslation()
  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. const searchParams = useSearchParams()
  25. useEffect(() => {
  26. document.title = `${t('app.title')} - Dify`
  27. if (localStorage.getItem(NEED_REFRESH_APP_LIST_KEY) === '1') {
  28. localStorage.removeItem(NEED_REFRESH_APP_LIST_KEY)
  29. mutate()
  30. }
  31. if (
  32. localStorage.getItem(SPARK_FREE_QUOTA_PENDING) !== '1'
  33. && searchParams.get('type') === 'provider_apply_callback'
  34. && searchParams.get('provider') === 'spark'
  35. && searchParams.get('result') === 'success'
  36. )
  37. localStorage.setItem(SPARK_FREE_QUOTA_PENDING, '1')
  38. }, [])
  39. useEffect(() => {
  40. loadingStateRef.current = isLoading
  41. }, [isLoading])
  42. useEffect(() => {
  43. const onScroll = debounce(() => {
  44. if (!loadingStateRef.current) {
  45. const { scrollTop, clientHeight } = pageContainerRef.current!
  46. const anchorOffset = anchorRef.current!.offsetTop
  47. if (anchorOffset - scrollTop - clientHeight < 100)
  48. setSize(size => size + 1)
  49. }
  50. }, 50)
  51. pageContainerRef.current?.addEventListener('scroll', onScroll)
  52. return () => pageContainerRef.current?.removeEventListener('scroll', onScroll)
  53. }, [])
  54. return (
  55. <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'>
  56. {data?.map(({ data: apps }) => apps.map(app => (
  57. <AppCard key={app.id} app={app} onDelete={mutate} />
  58. )))}
  59. <NewAppCard ref={anchorRef} onSuccess={mutate} />
  60. </nav>
  61. )
  62. }
  63. export default Apps