diff --git a/src/pages/PostRedirect/index.tsx b/src/pages/PostRedirect/index.tsx index 4a6c8f6..1f45565 100644 --- a/src/pages/PostRedirect/index.tsx +++ b/src/pages/PostRedirect/index.tsx @@ -1,25 +1,43 @@ -import { useEffect } from "react"; +import { useEffect, useRef } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { getJSON } from "../../api"; -import { langQuery, useI18n } from "../../i18n"; +import { langQuery, useI18n, type Lang } from "../../i18n"; import { useLocalizedPath } from "../../useLocalizedPath"; +import { localizePath } from "../../languageRoutes"; import { MOCK_POSTS } from "../../mocks/mockPosts"; import { POST_STREAM_USES_MOCK } from "../../components/messageStream/hooks/usePostStream"; import { useToast } from "../../components/Toast"; +import { Skeleton } from "../../components/Skeleton"; import type { Post } from "../../types/post"; +function postLangToUiLang(code: string | undefined): Lang | null { + if (!code) return null; + const lc = code.trim().toLowerCase(); + if (lc === "zh" || lc === "zh-cn" || lc === "zh-hans") return "zh-CN"; + if (lc === "en") return "en"; + if (lc === "ja") return "ja"; + if (lc === "ko") return "ko"; + if (lc === "vi") return "vi"; + if (lc === "id") return "id"; + if (lc === "ms") return "ms"; + return null; +} + export function PostRedirect() { const { id } = useParams(); const { lang, t } = useI18n(); const navigate = useNavigate(); const lp = useLocalizedPath(); const { showToast } = useToast(); + const handledIdRef = useRef(null); useEffect(() => { if (!id) { navigate(lp("/browse"), { replace: true }); return; } + if (handledIdRef.current === id) return; + handledIdRef.current = id; if (POST_STREAM_USES_MOCK) { const post = MOCK_POSTS.find((p) => p.id === id); @@ -32,25 +50,47 @@ export function PostRedirect() { return; } - const goToPost = (post: Post) => { - navigate(lp(`/browse?post=${encodeURIComponent(post.id)}`), { - replace: true, - }); + const goToPostInLang = (post: Post, targetLang: Lang) => { + navigate( + localizePath(`/browse?post=${encodeURIComponent(post.id)}`, targetLang), + { replace: true }, + ); }; getJSON( `/api/posts/${id}?lang=${encodeURIComponent(langQuery(lang))}`, ) - .then(goToPost) + .then((post) => goToPostInLang(post, lang)) .catch(() => { getJSON(`/api/posts/${id}`) .then((post) => { + const sourceLang = + postLangToUiLang(post.sourceLanguage) || + postLangToUiLang(post.language) || + lang; showToast(t("postShownInOriginalLanguage")); - goToPost(post); + goToPostInLang(post, sourceLang); }) .catch(() => navigate(lp("/browse"), { replace: true })); }); }, [id, lang, navigate, lp, showToast, t]); - return
; + return ( +
+ {Array.from({ length: 6 }).map((_, i) => ( +
+ +
+ ))} +
+ ); }