feat: add telegram-style resource stream

This commit is contained in:
TerryM
2026-05-25 05:25:57 +08:00
parent aaebd7ccd1
commit a784f159fe
45 changed files with 3201 additions and 1160 deletions

View File

@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import { renderHook } from "@testing-library/react";
import { useGroupedByDay } from "./useGroupedByDay";
import type { Post } from "../../../types/post";
function makePost(id: string, isoDate: string): Post {
return {
id,
categoryId: 1,
categorySlug: "x",
language: "zh-CN",
attachments: [],
isRecommended: false,
publishedAt: isoDate,
updatedAt: isoDate,
text: id,
};
}
describe("useGroupedByDay", () => {
it("groups posts by local date", () => {
const posts: Post[] = [
makePost("a", "2026-02-27T10:00:00.000Z"),
makePost("b", "2026-02-27T23:00:00.000Z"),
makePost("c", "2026-02-28T01:00:00.000Z"),
makePost("d", "2026-05-16T12:00:00.000Z"),
];
const { result } = renderHook(() => useGroupedByDay(posts, "zh-CN"));
expect(result.current.length).toBeGreaterThanOrEqual(2);
const allIds = result.current.flatMap((g) => g.items.map((p) => p.id));
expect(allIds).toEqual(["a", "b", "c", "d"]);
});
it("preserves input order within groups", () => {
const posts: Post[] = [
makePost("first", "2026-03-01T10:00:00.000Z"),
makePost("second", "2026-03-01T11:00:00.000Z"),
makePost("third", "2026-03-01T12:00:00.000Z"),
];
const { result } = renderHook(() => useGroupedByDay(posts, "en"));
expect(result.current).toHaveLength(1);
expect(result.current[0].items.map((p) => p.id)).toEqual([
"first",
"second",
"third",
]);
});
it("returns empty array for empty input", () => {
const { result } = renderHook(() => useGroupedByDay([], "zh-CN"));
expect(result.current).toEqual([]);
});
});

View File

@@ -0,0 +1,62 @@
import { useMemo } from "react";
import type { Post } from "../../../types/post";
export type DayGroup = {
dayKey: string;
dayLabel: string;
items: Post[];
};
function localeFor(lang: string): string {
if (lang === "zh-TW") return "zh-TW";
if (lang === "zh-CN") return "zh-CN";
return "en-US";
}
function dayKey(iso: string): string {
const d = new Date(iso);
return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
}
function dayLabel(iso: string, lang: string): string {
const d = new Date(iso);
const today = new Date();
const yesterday = new Date();
yesterday.setDate(today.getDate() - 1);
const isSameDay = (a: Date, b: Date) =>
a.getFullYear() === b.getFullYear() &&
a.getMonth() === b.getMonth() &&
a.getDate() === b.getDate();
if (isSameDay(d, today)) {
if (lang === "en") return "Today";
return "今天";
}
if (isSameDay(d, yesterday)) {
if (lang === "en") return "Yesterday";
return "昨天";
}
return new Intl.DateTimeFormat(localeFor(lang), {
month: "long",
day: "numeric",
}).format(d);
}
export function useGroupedByDay(posts: Post[], lang: string): DayGroup[] {
return useMemo(() => {
const groups: DayGroup[] = [];
const seen = new Map<string, DayGroup>();
for (const p of posts) {
const k = dayKey(p.publishedAt);
let g = seen.get(k);
if (!g) {
g = { dayKey: k, dayLabel: dayLabel(p.publishedAt, lang), items: [] };
seen.set(k, g);
groups.push(g);
}
g.items.push(p);
}
return groups;
}, [posts, lang]);
}
export { dayKey as _dayKey, dayLabel as _dayLabel };

View File

@@ -0,0 +1,160 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { getJSON } from "../../../api";
import { MOCK_POSTS } from "../../../mocks/mockPosts";
import type { Post, PostListResponse, PostScope } from "../../../types/post";
const PAGE_SIZE = 20;
const MOCK_DELAY_MS = 200;
const USE_MOCK = import.meta.env.VITE_USE_MOCK_POSTS !== "false";
export type PostStreamParams = {
scope: PostScope;
type?: string;
language?: string;
lang: string;
};
export type PostStreamResult = {
items: Post[];
isLoading: boolean;
error: string | null;
hasMore: boolean;
loadMore: () => void;
reset: () => void;
};
function postMatchesType(post: Post, type: string): boolean {
if (!type || type === "all") return true;
if (type === "text" || type === "link") {
return !!post.text && post.text.length > 0;
}
return post.attachments.some((a) => {
const ext = a.filename.split(".").pop()?.toLowerCase() ?? "";
if (type === "image")
return a.kind === "image" || a.mime.startsWith("image/");
if (type === "video")
return a.kind === "video" || a.mime.startsWith("video/");
if (type === "pdf") return ext === "pdf" || a.mime === "application/pdf";
if (type === "ppt")
return (
["ppt", "pptx", "key"].includes(ext) || a.mime.includes("presentation")
);
if (type === "archive")
return ["zip", "rar", "7z", "tar", "gz"].includes(ext);
return false;
});
}
function filterMock(params: PostStreamParams): Post[] {
return MOCK_POSTS.filter((p) => {
if (
params.scope.kind === "category" &&
p.categorySlug !== params.scope.slug
)
return false;
if (params.language && p.language !== params.language) return false;
if (!postMatchesType(p, params.type ?? "all")) return false;
return true;
}).sort(
(a, b) =>
new Date(b.publishedAt).getTime() - new Date(a.publishedAt).getTime(),
);
}
function buildRealUrl(params: PostStreamParams, cursor?: string): string {
const sp = new URLSearchParams();
sp.set("lang", params.lang);
sp.set("limit", String(PAGE_SIZE));
if (params.scope.kind === "category") sp.set("category", params.scope.slug);
if (params.type && params.type !== "all") sp.set("type", params.type);
if (params.language) sp.set("language", params.language);
if (cursor) sp.set("cursor", cursor);
return `/api/posts?${sp.toString()}`;
}
export function usePostStream(params: PostStreamParams): PostStreamResult {
const [items, setItems] = useState<Post[]>([]);
const [hasMore, setHasMore] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const reqIdRef = useRef(0);
const cursorRef = useRef<string | undefined>(undefined);
const hasMoreRef = useRef(true);
const loadingRef = useRef(false);
const fetchPage = useCallback(
async (resetting: boolean) => {
if (loadingRef.current) return;
if (!resetting && !hasMoreRef.current) return;
loadingRef.current = true;
setIsLoading(true);
setError(null);
const myReq = ++reqIdRef.current;
try {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, MOCK_DELAY_MS));
const all = filterMock(params);
const offset = resetting ? 0 : Number(cursorRef.current ?? "0");
const slice = all.slice(offset, offset + PAGE_SIZE);
const nextOffset = offset + slice.length;
const more = nextOffset < all.length;
if (myReq !== reqIdRef.current) return;
setItems((prev) => (resetting ? slice : [...prev, ...slice]));
const nextCursor = more ? String(nextOffset) : undefined;
cursorRef.current = nextCursor;
setHasMore(more);
hasMoreRef.current = more;
} else {
const url = buildRealUrl(
params,
resetting ? undefined : cursorRef.current,
);
const res = await getJSON<PostListResponse>(url);
if (myReq !== reqIdRef.current) return;
setItems((prev) => (resetting ? res.items : [...prev, ...res.items]));
cursorRef.current = res.nextCursor;
const more = !!res.nextCursor;
setHasMore(more);
hasMoreRef.current = more;
}
} catch (e) {
if (myReq !== reqIdRef.current) return;
setError(String(e));
} finally {
if (myReq === reqIdRef.current) setIsLoading(false);
loadingRef.current = false;
}
},
[params],
);
useEffect(() => {
setItems([]);
cursorRef.current = undefined;
setHasMore(true);
hasMoreRef.current = true;
fetchPage(true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
params.scope.kind,
params.scope.kind === "category" ? params.scope.slug : "",
params.type,
params.language,
params.lang,
]);
const loadMore = useCallback(() => {
fetchPage(false);
}, [fetchPage]);
const reset = useCallback(() => {
fetchPage(true);
}, [fetchPage]);
return { items, isLoading, error, hasMore, loadMore, reset };
}
export { USE_MOCK as POST_STREAM_USES_MOCK };