feat: wire public posts api

This commit is contained in:
TerryM
2026-05-26 12:07:13 +08:00
parent f482a2ec38
commit d3c30795dc
19 changed files with 299 additions and 163 deletions

View File

@@ -1,30 +1,41 @@
import { useEffect } from "react";
import { Navigate, useParams } from "react-router-dom";
import { useNavigate, useParams } from "react-router-dom";
import { getJSON } from "../api";
import { langQuery, useI18n } from "../i18n";
import { MOCK_POSTS } from "../mocks/mockPosts";
import { POST_STREAM_USES_MOCK } from "../components/messageStream/hooks/usePostStream";
import type { Post } from "../types/post";
export function PostRedirect() {
const { id } = useParams();
// Real-API branch placeholder: when backend ships /api/posts/:id, fetch and
// navigate to /category/<categorySlug>#post-<id>. For now mock lookup.
const post = id ? MOCK_POSTS.find((p) => p.id === id) : undefined;
const { lang } = useI18n();
const navigate = useNavigate();
useEffect(() => {
if (post) {
requestAnimationFrame(() => {
document
.getElementById(`post-${post.id}`)
?.scrollIntoView({ behavior: "smooth", block: "center" });
});
if (!id) {
navigate("/browse", { replace: true });
return;
}
}, [post]);
if (!POST_STREAM_USES_MOCK && !post) {
// TODO: replace with real fetch when /api/posts/:id ships.
return <Navigate to="/browse" replace />;
}
if (!post) return <Navigate to="/browse" replace />;
return (
<Navigate to={`/category/${post.categorySlug}#post-${post.id}`} replace />
);
if (POST_STREAM_USES_MOCK) {
const post = MOCK_POSTS.find((p) => p.id === id);
navigate(
post ? `/category/${post.categorySlug}#post-${post.id}` : "/browse",
{ replace: true },
);
return;
}
getJSON<Post>(
`/api/posts/${id}?lang=${encodeURIComponent(langQuery(lang))}`,
)
.then((post) => {
navigate(`/category/${post.categorySlug}#post-${post.id}`, {
replace: true,
});
})
.catch(() => navigate("/browse", { replace: true }));
}, [id, lang, navigate]);
return <div className="text-neutral-400"></div>;
}