Apps.tsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use client'
  2. import { useEffect, useRef } from 'react'
  3. import useSWRInfinite from 'swr/infinite'
  4. import { debounce } from 'lodash-es'
  5. import AppCard from './AppCard'
  6. import NewAppCard from './NewAppCard'
  7. import { AppListResponse } from '@/models/app'
  8. import { fetchAppList } from '@/service/apps'
  9. import { useSelector } from '@/context/app-context'
  10. const getKey = (pageIndex: number, previousPageData: AppListResponse) => {
  11. if (!pageIndex || previousPageData.has_more)
  12. return { url: 'apps', params: { page: pageIndex + 1, limit: 30 } }
  13. return null
  14. }
  15. const Apps = () => {
  16. const { data, isLoading, setSize, mutate } = useSWRInfinite(getKey, fetchAppList, { revalidateFirstPage: false })
  17. const loadingStateRef = useRef(false)
  18. const pageContainerRef = useSelector(state => state.pageContainerRef)
  19. const anchorRef = useRef<HTMLAnchorElement>(null)
  20. useEffect(() => {
  21. loadingStateRef.current = isLoading
  22. }, [isLoading])
  23. useEffect(() => {
  24. const onScroll = debounce(() => {
  25. if (!loadingStateRef.current) {
  26. const { scrollTop, clientHeight } = pageContainerRef.current!
  27. const anchorOffset = anchorRef.current!.offsetTop
  28. if (anchorOffset - scrollTop - clientHeight < 100) {
  29. setSize(size => size + 1)
  30. }
  31. }
  32. }, 50)
  33. pageContainerRef.current?.addEventListener('scroll', onScroll)
  34. return () => pageContainerRef.current?.removeEventListener('scroll', onScroll)
  35. }, [])
  36. return (
  37. <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'>
  38. {data?.map(({ data: apps }) => apps.map(app => (
  39. <AppCard key={app.id} app={app} onDelete={mutate} />
  40. )))}
  41. <NewAppCard ref={anchorRef} onSuccess={mutate} />
  42. </nav>
  43. )
  44. }
  45. export default Apps