258 lines
7.9 KiB
TypeScript
258 lines
7.9 KiB
TypeScript
import { ArrowUpIcon, LoaderIcon } from "lucide-react";
|
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import { matchPath } from "react-router-dom";
|
|
import PullToRefresh from "react-simple-pull-to-refresh";
|
|
import { Button } from "@/components/ui/button";
|
|
import { userServiceClient } from "@/connect";
|
|
import { useView } from "@/contexts/ViewContext";
|
|
import { DEFAULT_LIST_MEMOS_PAGE_SIZE } from "@/helpers/consts";
|
|
import { useInfiniteMemos } from "@/hooks/useMemoQueries";
|
|
import useResponsiveWidth from "@/hooks/useResponsiveWidth";
|
|
import { Routes } from "@/router";
|
|
import { State } from "@/types/proto/api/v1/common_pb";
|
|
import type { Memo } from "@/types/proto/api/v1/memo_service_pb";
|
|
import { useTranslate } from "@/utils/i18n";
|
|
import Empty from "../Empty";
|
|
import type { MemoRenderContext } from "../MasonryView";
|
|
import MasonryView from "../MasonryView";
|
|
import MemoEditor from "../MemoEditor";
|
|
import MemoFilters from "../MemoFilters";
|
|
import MemoSkeleton from "../MemoSkeleton";
|
|
|
|
interface Props {
|
|
renderer: (memo: Memo, context?: MemoRenderContext) => JSX.Element;
|
|
listSort?: (list: Memo[]) => Memo[];
|
|
state?: State;
|
|
orderBy?: string;
|
|
filter?: string;
|
|
pageSize?: number;
|
|
showCreator?: boolean;
|
|
}
|
|
|
|
/**
|
|
* Custom hook to auto-fetch more content when page isn't scrollable.
|
|
* This ensures users see content without needing to scroll on large screens.
|
|
*/
|
|
function useAutoFetchWhenNotScrollable({
|
|
hasNextPage,
|
|
isFetchingNextPage,
|
|
memoCount,
|
|
onFetchNext,
|
|
}: {
|
|
hasNextPage: boolean | undefined;
|
|
isFetchingNextPage: boolean;
|
|
memoCount: number;
|
|
onFetchNext: () => Promise<unknown>;
|
|
}) {
|
|
const autoFetchTimeoutRef = useRef<number | null>(null);
|
|
|
|
const isPageScrollable = useCallback(() => {
|
|
const documentHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
|
|
return documentHeight > window.innerHeight + 100;
|
|
}, []);
|
|
|
|
const checkAndFetchIfNeeded = useCallback(async () => {
|
|
if (autoFetchTimeoutRef.current) {
|
|
clearTimeout(autoFetchTimeoutRef.current);
|
|
}
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
|
|
const shouldFetch = !isPageScrollable() && hasNextPage && !isFetchingNextPage && memoCount > 0;
|
|
|
|
if (shouldFetch) {
|
|
await onFetchNext();
|
|
|
|
autoFetchTimeoutRef.current = window.setTimeout(() => {
|
|
void checkAndFetchIfNeeded();
|
|
}, 500);
|
|
}
|
|
}, [hasNextPage, isFetchingNextPage, memoCount, isPageScrollable, onFetchNext]);
|
|
|
|
useEffect(() => {
|
|
if (!isFetchingNextPage && memoCount > 0) {
|
|
void checkAndFetchIfNeeded();
|
|
}
|
|
}, [memoCount, isFetchingNextPage, checkAndFetchIfNeeded]);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
if (autoFetchTimeoutRef.current) {
|
|
clearTimeout(autoFetchTimeoutRef.current);
|
|
}
|
|
};
|
|
}, []);
|
|
}
|
|
|
|
const PagedMemoList = (props: Props) => {
|
|
const t = useTranslate();
|
|
const { md } = useResponsiveWidth();
|
|
const { layout } = useView();
|
|
|
|
// Show memo editor only on the root route
|
|
const showMemoEditor = Boolean(matchPath(Routes.ROOT, window.location.pathname));
|
|
|
|
// Use React Query's infinite query for pagination
|
|
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, refetch } = useInfiniteMemos({
|
|
state: props.state || State.NORMAL,
|
|
orderBy: props.orderBy || "display_time desc",
|
|
filter: props.filter,
|
|
pageSize: props.pageSize || DEFAULT_LIST_MEMOS_PAGE_SIZE,
|
|
});
|
|
|
|
// Flatten pages into a single array of memos
|
|
const memos = useMemo(() => data?.pages.flatMap((page) => page.memos) || [], [data]);
|
|
|
|
// Apply custom sorting if provided, otherwise use memos directly
|
|
const sortedMemoList = useMemo(() => (props.listSort ? props.listSort(memos) : memos), [memos, props.listSort]);
|
|
|
|
// Batch-fetch creators when new data arrives to improve performance
|
|
useEffect(() => {
|
|
if (!data?.pages || !props.showCreator) return;
|
|
|
|
const lastPage = data.pages[data.pages.length - 1];
|
|
if (!lastPage?.memos) return;
|
|
|
|
const uniqueCreators = Array.from(new Set(lastPage.memos.map((memo) => memo.creator)));
|
|
void Promise.allSettled(
|
|
uniqueCreators.map((creator) =>
|
|
userServiceClient.getUser({ name: creator }).catch(() => {
|
|
/* silently ignore errors */
|
|
}),
|
|
),
|
|
);
|
|
}, [data?.pages, props.showCreator]);
|
|
|
|
// Auto-fetch hook: fetches more content when page isn't scrollable
|
|
useAutoFetchWhenNotScrollable({
|
|
hasNextPage,
|
|
isFetchingNextPage,
|
|
memoCount: sortedMemoList.length,
|
|
onFetchNext: fetchNextPage,
|
|
});
|
|
|
|
// Infinite scroll: fetch more when user scrolls near bottom
|
|
useEffect(() => {
|
|
if (!hasNextPage) return;
|
|
|
|
const handleScroll = () => {
|
|
const nearBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 300;
|
|
if (nearBottom && !isFetchingNextPage) {
|
|
fetchNextPage();
|
|
}
|
|
};
|
|
|
|
window.addEventListener("scroll", handleScroll);
|
|
return () => window.removeEventListener("scroll", handleScroll);
|
|
}, [hasNextPage, isFetchingNextPage, fetchNextPage]);
|
|
|
|
const children = (
|
|
<div className="flex flex-col justify-start items-start w-full max-w-full">
|
|
{/* Show skeleton loader during initial load */}
|
|
{isLoading ? (
|
|
<div className="w-full flex flex-col justify-start items-center">
|
|
<MemoSkeleton showCreator={props.showCreator} count={4} />
|
|
</div>
|
|
) : (
|
|
<>
|
|
<MasonryView
|
|
memoList={sortedMemoList}
|
|
renderer={props.renderer}
|
|
prefixElement={
|
|
<>
|
|
{showMemoEditor ? (
|
|
<MemoEditor className="mb-2" cacheKey="home-memo-editor" placeholder={t("editor.any-thoughts")} />
|
|
) : undefined}
|
|
<MemoFilters />
|
|
</>
|
|
}
|
|
listMode={layout === "LIST"}
|
|
/>
|
|
|
|
{/* Loading indicator for pagination */}
|
|
{isFetchingNextPage && (
|
|
<div className="w-full flex flex-row justify-center items-center my-4">
|
|
<LoaderIcon className="animate-spin text-muted-foreground" />
|
|
</div>
|
|
)}
|
|
|
|
{/* Empty state or back-to-top button */}
|
|
{!isFetchingNextPage && (
|
|
<>
|
|
{!hasNextPage && sortedMemoList.length === 0 ? (
|
|
<div className="w-full mt-12 mb-8 flex flex-col justify-center items-center italic">
|
|
<Empty />
|
|
<p className="mt-2 text-muted-foreground">{t("message.no-data")}</p>
|
|
</div>
|
|
) : (
|
|
<div className="w-full opacity-70 flex flex-row justify-center items-center my-4">
|
|
<BackToTop />
|
|
</div>
|
|
)}
|
|
</>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
);
|
|
|
|
if (md) {
|
|
return children;
|
|
}
|
|
|
|
return (
|
|
<PullToRefresh
|
|
onRefresh={async () => {
|
|
await refetch();
|
|
}}
|
|
pullingContent={
|
|
<div className="w-full flex flex-row justify-center items-center my-4">
|
|
<LoaderIcon className="opacity-60" />
|
|
</div>
|
|
}
|
|
refreshingContent={
|
|
<div className="w-full flex flex-row justify-center items-center my-4">
|
|
<LoaderIcon className="animate-spin" />
|
|
</div>
|
|
}
|
|
>
|
|
{children}
|
|
</PullToRefresh>
|
|
);
|
|
};
|
|
|
|
const BackToTop = () => {
|
|
const t = useTranslate();
|
|
const [isVisible, setIsVisible] = useState(false);
|
|
|
|
useEffect(() => {
|
|
const handleScroll = () => {
|
|
const shouldShow = window.scrollY > 400;
|
|
setIsVisible(shouldShow);
|
|
};
|
|
|
|
window.addEventListener("scroll", handleScroll);
|
|
return () => window.removeEventListener("scroll", handleScroll);
|
|
}, []);
|
|
|
|
const scrollToTop = () => {
|
|
window.scrollTo({
|
|
top: 0,
|
|
behavior: "smooth",
|
|
});
|
|
};
|
|
|
|
// Don't render if not visible
|
|
if (!isVisible) {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<Button variant="ghost" onClick={scrollToTop}>
|
|
{t("router.back-to-top")}
|
|
<ArrowUpIcon className="ml-1 w-4 h-auto" />
|
|
</Button>
|
|
);
|
|
};
|
|
|
|
export default PagedMemoList;
|