From d7d11ba516289d75250f98ae0a681073ef6abcb5 Mon Sep 17 00:00:00 2001 From: Ray-D-Song Date: Wed, 30 Oct 2024 17:29:24 +0800 Subject: [PATCH] todo: Optimize redundant requests --- packages/web/src/hooks/useMediaQuery.ts | 33 ++++++++++++++++ packages/web/src/pages/(layout)/index.tsx | 46 +++++++++++++++++++---- 2 files changed, 71 insertions(+), 8 deletions(-) create mode 100644 packages/web/src/hooks/useMediaQuery.ts diff --git a/packages/web/src/hooks/useMediaQuery.ts b/packages/web/src/hooks/useMediaQuery.ts new file mode 100644 index 0000000..f1f6b01 --- /dev/null +++ b/packages/web/src/hooks/useMediaQuery.ts @@ -0,0 +1,33 @@ +import { useEffect, useState } from 'react' + +export function useMediaQuery(query: string) { + const [matches, setMatches] = useState(false) + + useEffect(() => { + const mediaQuery = window.matchMedia(query) + setMatches(mediaQuery.matches) + + let timeoutId: NodeJS.Timeout + + const handler = (event: MediaQueryListEvent) => { + if (timeoutId) { + clearTimeout(timeoutId) + } + + timeoutId = setTimeout(() => { + setMatches(event.matches) + }, 100) + } + + mediaQuery.addEventListener('change', handler) + + return () => { + mediaQuery.removeEventListener('change', handler) + if (timeoutId) { + clearTimeout(timeoutId) + } + } + }, [query]) + + return matches +} diff --git a/packages/web/src/pages/(layout)/index.tsx b/packages/web/src/pages/(layout)/index.tsx index 55d4dc7..d13a61d 100644 --- a/packages/web/src/pages/(layout)/index.tsx +++ b/packages/web/src/pages/(layout)/index.tsx @@ -1,21 +1,51 @@ import { useRequest } from 'ahooks' +import { memo, useMemo } from 'react' +import { useMediaQuery } from '~/hooks/useMediaQuery' import { PageCardList } from '~/components/card-view' import PageDataPieCard from '~/components/page-data-pie-card' import R2UsageCard from '~/components/r2-usage-card' import { getRecentSavePage } from '~/data/page' +const MemoizedPageCardList = memo(PageCardList) + function ArchiveHome() { - const { data: pages } = useRequest(getRecentSavePage) + const { data: pages = [] } = useRequest(getRecentSavePage) + const isLargeScreen = useMediaQuery('(min-width: 1024px)') + const isMediumScreen = useMediaQuery('(min-width: 768px)') + + const columnCount = useMemo(() => { + if (isLargeScreen) + return 3 + if (isMediumScreen) + return 2 + return 1 + }, [isLargeScreen, isMediumScreen]) + + const reorganizedPages = useMemo(() => { + const result = Array.from({ length: columnCount }, () => [] as typeof pages) + + pages.forEach((page, index) => { + const columnIndex = Math.floor(index / Math.ceil(pages.length / columnCount)) + result[columnIndex].push(page) + }) + + return result + }, [pages, columnCount]) + return (
- index % 3 === 0)} onPageDelete={() => {}}> + {}}> - - index % 3 === 1)} onPageDelete={() => {}}> - - - index % 3 === 2)} onPageDelete={() => {}}> - + + {columnCount >= 2 && ( + {}}> + + + )} + {columnCount >= 3 && ( + {}}> + + )}
) }