From 1934edebd50e5993cc23fcd3334ff1422cb69a75 Mon Sep 17 00:00:00 2001 From: lezi-fun <177434121+lezi-fun@users.noreply.github.com> Date: Tue, 11 Aug 2026 11:32:15 +0800 Subject: [PATCH] feat: i18n (i18next + react-i18next) zh/en + hydration fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - i18next + react-i18next: zh/en locales, language detection (localStorage > navigator > zh), settings language switcher - Components i18n'd: Navbar, Feed, NewPost, Modals, SettingsPage, SettingsProfile, AccountSecurity, RecoveryCodes - Fix hydration mismatch (spinner restart): forum name via cookie (Server Component reads cookie, SSR outputs name, no inline script DOM injection); remove createPortal in RecoveryCodes modal; i18n sync init (initImmediate) so SSR/CSR text matches - LoadingScreen: React-state name rendering (no script-injected nodes) - Fix double spinner in Feed; DM icon emoji → SVG in ConversationList # Conflicts: # components/AppProvider.js # components/NewPost.js --- app/HomeClient.js | 64 ++++++++++++ app/layout.js | 13 +-- app/page.js | 74 +++---------- bun.lock | 12 +++ components/AccountSecurity.js | 26 ++--- components/AppProvider.js | 25 +++-- components/Feed.js | 34 +++--- components/I18nInit.js | 12 +++ components/LoadingScreen.js | 12 ++- components/Modals.js | 38 +++---- components/Navbar.js | 18 ++-- components/NewPost.js | 20 ++-- components/RecoveryCodes.js | 30 +++--- components/SettingsPage.js | 12 ++- components/SettingsProfile.js | 26 ++++- components/chat/ConversationList.js | 3 +- lib/i18n.js | 41 ++++++++ locales/en.json | 154 ++++++++++++++++++++++++++++ locales/zh.json | 151 +++++++++++++++++++++++++++ package.json | 4 +- 20 files changed, 600 insertions(+), 169 deletions(-) create mode 100644 app/HomeClient.js create mode 100644 components/I18nInit.js create mode 100644 lib/i18n.js create mode 100644 locales/en.json create mode 100644 locales/zh.json diff --git a/app/HomeClient.js b/app/HomeClient.js new file mode 100644 index 0000000..ab2687d --- /dev/null +++ b/app/HomeClient.js @@ -0,0 +1,64 @@ +'use client'; + +// 主页客户端组件:SPA 视图调度 (feed/post/new/admin/settings/messages) +import { useState } from 'react'; +import AppProvider, { useApp } from '@/components/AppProvider'; +import Navbar from '@/components/Navbar'; +import Sidebar from '@/components/Sidebar'; +import Feed from '@/components/Feed'; +import PostDetail from '@/components/PostDetail'; +import NewPost from '@/components/NewPost'; +import AdminPage from '@/components/AdminPage'; +import SettingsPage from '@/components/SettingsPage'; +import UserProfile from '@/components/UserProfile'; +import CustomPage from '@/components/CustomPage'; +import MessagesPage from '@/components/MessagesPage'; +import ChatManager from '@/components/chat/ChatManager'; +import Modals from '@/components/Modals'; +import LoadingScreen from '@/components/LoadingScreen'; + +function HomeInner() { + const { view, currentPostId, currentUsername, currentPageName, ready, forumName, forumNameLoaded } = useApp(); + const [modal, setModal] = useState(null); // null | login | register | report + const [reportPostId, setReportPostId] = useState(null); + + const openModal = (m) => setModal(m); + const openReport = (postId) => { setReportPostId(postId); setModal('report'); }; + + // 初始化未完成:显示全屏加载页,避免未加载完的界面闪烁 + if (!ready) { + return ; + } + + return ( +
+ + +
+ + +
+ + {/* 独立页面 */} +
+ {view === 'post' && currentPostId && } + {view === 'user' && currentUsername && } + {view === 'custom' && currentPageName && } + {view === 'new' && } + {view === 'admin' && } + {view === 'settings' && } + {view === 'messages' && } +
+ + setModal(null)} reportPostId={reportPostId} /> +
+ ); +} + +export default function HomeClient({ cachedName = '' }) { + return ( + + + + ); +} diff --git a/app/layout.js b/app/layout.js index 1e4f768..34cef08 100644 --- a/app/layout.js +++ b/app/layout.js @@ -2,6 +2,7 @@ import './globals.css'; import CustomCssLoader from '@/components/CustomCssLoader'; import { ToastProvider } from '@/components/Toast'; +import I18nInit from '@/components/I18nInit'; export const metadata = { // 初始标题由客户端 AppProvider 接管(加载时轮换 Loading.,完成后显示论坛名) @@ -24,17 +25,11 @@ export default function RootLayout({ children }) { document.documentElement.setAttribute('data-theme', t); } catch (e) {} try { var n = localStorage.getItem('forumlify-forum-name'); if (n) document.title = n; } catch (e) {} - document.addEventListener('DOMContentLoaded', function () { - try { - var n2 = localStorage.getItem('forumlify-forum-name'); - if (n2) { - var el = document.getElementById('loadingTitle'); - if (el && !el.textContent) { el.textContent = n2; document.title = n2; } - } - } catch (e) {} - }); + // 加载页论坛名不再由脚本注入 DOM——由 Server Component 读 cookie 首帧输出, + // React 状态渲染,SSR/客户端一致,无 hydration mismatch })();` }} /> + {children} diff --git a/app/page.js b/app/page.js index 8079024..359c7bb 100644 --- a/app/page.js +++ b/app/page.js @@ -1,65 +1,17 @@ -'use client'; +// 主页:Server Component —— 从 cookie 读取缓存论坛名(SSR 首帧即输出), +// 其余逻辑在客户端 HomeClient 中 +import { cookies } from 'next/headers'; +import HomeClient from './HomeClient'; -// 主页:SPA 视图调度 (feed/post/new/admin/settings/messages) -import { useState } from 'react'; -import AppProvider, { useApp } from '@/components/AppProvider'; -import Navbar from '@/components/Navbar'; -import Sidebar from '@/components/Sidebar'; -import Feed from '@/components/Feed'; -import PostDetail from '@/components/PostDetail'; -import NewPost from '@/components/NewPost'; -import AdminPage from '@/components/AdminPage'; -import SettingsPage from '@/components/SettingsPage'; -import UserProfile from '@/components/UserProfile'; -import CustomPage from '@/components/CustomPage'; -import MessagesPage from '@/components/MessagesPage'; -import ChatManager from '@/components/chat/ChatManager'; -import Modals from '@/components/Modals'; -import LoadingScreen from '@/components/LoadingScreen'; - -function HomeInner() { - const { view, currentPostId, currentUsername, currentPageName, ready, forumName, forumNameLoaded } = useApp(); - const [modal, setModal] = useState(null); // null | login | register | report - const [reportPostId, setReportPostId] = useState(null); - - const openModal = (m) => setModal(m); - const openReport = (postId) => { setReportPostId(postId); setModal('report'); }; - - // 初始化未完成:显示全屏加载页,避免未加载完的界面闪烁 - if (!ready) { - return ; - } - - return ( -
- - - -
- - -
- - {/* 独立页面 */} -
- {view === 'post' && currentPostId && } - {view === 'user' && currentUsername && } - {view === 'custom' && currentPageName && } - {view === 'new' && } - {view === 'admin' && } - {view === 'settings' && } - {view === 'messages' && } -
- - setModal(null)} reportPostId={reportPostId} /> -
- ); -} +// cookies() 是动态 API:禁止静态优化,每次请求 SSR +export const dynamic = 'force-dynamic'; export default function Home() { - return ( - - - - ); + let cachedName = ''; + try { + cachedName = decodeURIComponent(cookies().get('forumlify-name')?.value || ''); + } catch (e) { + cachedName = ''; + } + return ; } diff --git a/bun.lock b/bun.lock index 1ce5a42..11046dc 100644 --- a/bun.lock +++ b/bun.lock @@ -7,12 +7,14 @@ "dependencies": { "aws4fetch": "^1.0.20", "bcryptjs": "^3.0.3", + "i18next": "^26.3.6", "jsonwebtoken": "^9.0.2", "marked": "^18.0.9", "next": "16", "pg": "^8.11.3", "react": "19", "react-dom": "19", + "react-i18next": "^17.0.11", }, "devDependencies": { "@opennextjs/cloudflare": "^1.20.2", @@ -132,6 +134,8 @@ "@aws/lambda-invoke-store": ["@aws/lambda-invoke-store@0.3.0", "https://registry.npmmirror.com/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz", {}, "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ=="], + "@babel/runtime": ["@babel/runtime@7.29.7", "https://registry.npmmirror.com/@babel/runtime/-/runtime-7.29.7.tgz", {}, "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw=="], + "@cloudflare/kv-asset-handler": ["@cloudflare/kv-asset-handler@0.5.0", "https://registry.npmmirror.com/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz", {}, "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg=="], "@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.16.1", "https://registry.npmmirror.com/@cloudflare/unenv-preset/-/unenv-preset-2.16.1.tgz", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw=="], @@ -572,12 +576,16 @@ "hasown": ["hasown@2.0.4", "https://registry.npmmirror.com/hasown/-/hasown-2.0.4.tgz", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], + "html-parse-stringify": ["html-parse-stringify@4.0.1", "https://registry.npmmirror.com/html-parse-stringify/-/html-parse-stringify-4.0.1.tgz", {}, "sha512-0zHsZJrK7S3K2aucXWL6ycoYJ/iNtIcFHC/nYQgFklPtrv5LpJctIiSCroWZWeuoXvuyFdzp6KzjJQ+OT5MfFw=="], + "http-errors": ["http-errors@2.0.1", "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.1.tgz", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], "human-signals": ["human-signals@2.1.0", "https://registry.npmmirror.com/human-signals/-/human-signals-2.1.0.tgz", {}, "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw=="], "humanize-ms": ["humanize-ms@1.2.1", "https://registry.npmmirror.com/humanize-ms/-/humanize-ms-1.2.1.tgz", { "dependencies": { "ms": "^2.0.0" } }, "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ=="], + "i18next": ["i18next@26.3.6", "https://registry.npmmirror.com/i18next/-/i18next-26.3.6.tgz", { "peerDependencies": { "typescript": "^5 || ^6 || ^7" }, "optionalPeers": ["typescript"] }, "sha512-Bu5Z2nAXgfVyM8xvW3jk9EKRIuX37PudsrBViThNFx7CR7aaYTpP01cxNB/E4c4UUzTDiAZRstEhsRfPOL/8xA=="], + "iconv-lite": ["iconv-lite@0.7.3", "https://registry.npmmirror.com/iconv-lite/-/iconv-lite-0.7.3.tgz", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], "ignore": ["ignore@5.3.2", "https://registry.npmmirror.com/ignore/-/ignore-5.3.2.tgz", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], @@ -730,6 +738,8 @@ "react-dom": ["react-dom@19.2.8", "https://registry.npmmirror.com/react-dom/-/react-dom-19.2.8.tgz", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.8" } }, "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ=="], + "react-i18next": ["react-i18next@17.0.11", "https://registry.npmmirror.com/react-i18next/-/react-i18next-17.0.11.tgz", { "dependencies": { "@babel/runtime": "^7.29.2", "html-parse-stringify": "^4.0.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "i18next": ">= 26.2.0", "react": ">= 16.8.0", "react-dom": "*", "react-native": "*", "typescript": "^5 || ^6 || ^7" }, "optionalPeers": ["react-dom", "react-native", "typescript"] }, "sha512-cDtkXgxjuFTWUH6V+aQn1Ve5vDiUztCNPWW5GtSHDccsgRXO1nE6QFWCEmc1KAutrb3OUv87wFShJL5RhUwPXg=="], + "router": ["router@2.2.0", "https://registry.npmmirror.com/router/-/router-2.2.0.tgz", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="], "safe-buffer": ["safe-buffer@5.2.1", "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.2.1.tgz", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], @@ -806,6 +816,8 @@ "urlpattern-polyfill": ["urlpattern-polyfill@10.1.0", "https://registry.npmmirror.com/urlpattern-polyfill/-/urlpattern-polyfill-10.1.0.tgz", {}, "sha512-IGjKp/o0NL3Bso1PymYURCJxMPNAf/ILOpendP9f5B6e1rTJgdgiOvgfoT8VxCAdY+Wisb9uhGaJJf3yZ2V9nw=="], + "use-sync-external-store": ["use-sync-external-store@1.6.0", "https://registry.npmmirror.com/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="], + "vary": ["vary@1.1.2", "https://registry.npmmirror.com/vary/-/vary-1.1.2.tgz", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], "web-streams-polyfill": ["web-streams-polyfill@4.0.0-beta.3", "https://npmreg.proxy.ustclug.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", {}, "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug=="], diff --git a/components/AccountSecurity.js b/components/AccountSecurity.js index f08e8bd..c24bdcd 100644 --- a/components/AccountSecurity.js +++ b/components/AccountSecurity.js @@ -2,11 +2,13 @@ // 账户安全:修改密码 + 修改邮箱 import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; import { API } from '@/lib/api'; import { useApp } from './AppProvider'; export default function AccountSecurity() { const { currentUser } = useApp(); + const { t } = useTranslation(); const [oldPassword, setOldPassword] = useState(''); const [newPassword, setNewPassword] = useState(''); const [pwStatus, setPwStatus] = useState(null); @@ -15,11 +17,11 @@ export default function AccountSecurity() { const [emailStatus, setEmailStatus] = useState(null); const changePassword = async () => { - if (!oldPassword || !newPassword) { alert('请填写完整信息'); return; } - if (newPassword.length < 6) { alert('新密码至少6位'); return; } + if (!oldPassword || !newPassword) { alert(t('security.fillAll')); return; } + if (newPassword.length < 6) { alert(t('security.pwMin')); return; } try { await API.updatePassword(currentUser.id, oldPassword, newPassword); - setPwStatus({ ok: true, msg: '✅ 密码修改成功' }); + setPwStatus({ ok: true, msg: t('security.pwChanged') }); setOldPassword(''); setNewPassword(''); } catch (err) { @@ -28,10 +30,10 @@ export default function AccountSecurity() { }; const changeEmail = async () => { - if (!emailPassword || !newEmail) { alert('请填写完整信息'); return; } + if (!emailPassword || !newEmail) { alert(t('security.fillAll')); return; } try { await API.updateEmail(currentUser.id, emailPassword, newEmail); - setEmailStatus({ ok: true, msg: '✅ 邮箱修改成功' }); + setEmailStatus({ ok: true, msg: t('security.emailChanged') }); setEmailPassword(''); setNewEmail(''); } catch (err) { @@ -41,30 +43,30 @@ export default function AccountSecurity() { return (
-

🔒 账户安全

+

🔒 {t('security.title')}

- + setOldPassword(e.target.value)} />
- + setNewPassword(e.target.value)} />
- + {pwStatus &&
{pwStatus.msg}
}
- + setEmailPassword(e.target.value)} />
- + setNewEmail(e.target.value)} />
- + {emailStatus &&
{emailStatus.msg}
}
); diff --git a/components/AppProvider.js b/components/AppProvider.js index 828341c..b208f6a 100644 --- a/components/AppProvider.js +++ b/components/AppProvider.js @@ -10,11 +10,10 @@ export function useApp() { return useContext(AppContext); } -export default function AppProvider({ children }) { +export default function AppProvider({ children, cachedName = '' }) { const [currentUser, setCurrentUser] = useState(null); - // 固定初始值(SSR/客户端一致,避免 hydration mismatch 导致加载圈重启); - // 缓存论坛名由 useEffect 读取,首帧显示靠内联脚本(body 首个子元素) - const [forumName, setForumName] = useState('Forumlify'); + // 论坛名初始值来自 cookie(SSR 首帧即输出,SSR/客户端一致 → 无 hydration mismatch) + const [forumName, setForumName] = useState(cachedName || 'Forumlify'); const [theme, setThemeState] = useState('light'); const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom const [currentPostId, setCurrentPostId] = useState(null); @@ -23,12 +22,19 @@ export default function AppProvider({ children }) { const [sort, setSort] = useState('latest'); const [refreshKey, setRefreshKey] = useState(0); const [ready, setReady] = useState(false); // 初始加载完成标记(控制加载页/淡入) - // 固定 false(避免 hydration mismatch);有缓存时由 useEffect 立即置 true - const [forumNameLoaded, setForumNameLoaded] = useState(false); + // 有 cookie 缓存名即视为已加载(SSR/客户端一致) + const [forumNameLoaded, setForumNameLoaded] = useState(!!cachedName); const loadedRef = useRef(false); const refresh = useCallback(() => setRefreshKey((k) => k + 1), []); + // 论坛名写 cookie(SSR 可读 → 首帧输出,无需内联脚本注入 DOM) + const syncForumNameCookie = useCallback((name) => { + try { + document.cookie = 'forumlify-name=' + encodeURIComponent(name) + '; path=/; max-age=31536000'; + } catch (e) {} + }, []); + // 主题 useEffect(() => { const t = getTheme(); @@ -60,12 +66,13 @@ export default function AppProvider({ children }) { // 初始化:读取缓存论坛名(立即显示),恢复登录、加载服务器论坛名 useEffect(() => { - // 缓存论坛名(hydrate 后立即生效,首帧显示由内联脚本完成) + // 缓存论坛名(hydrate 后立即生效;SSR 首帧已由 cookie 输出) try { const cached = localStorage.getItem('forumlify-forum-name'); if (cached) { setForumName(cached); setForumNameLoaded(true); + syncForumNameCookie(cached); } } catch (e) {} @@ -88,6 +95,7 @@ export default function AppProvider({ children }) { if (s.forum_name) { setForumName(s.forum_name); localStorage.setItem('forumlify-forum-name', s.forum_name); + syncForumNameCookie(s.forum_name); } // 先标记论坛名已收到(加载页原地淡入名字),稍后切换主页 setForumNameLoaded(true); @@ -243,7 +251,8 @@ export default function AppProvider({ children }) { // 同步更新 元素(防止 Next.js metadata 覆盖) const titleEl = document.querySelector('title'); if (titleEl) titleEl.textContent = name; - }, []); + syncForumNameCookie(name); + }, [syncForumNameCookie]); const value = { currentUser, setCurrentUser, diff --git a/components/Feed.js b/components/Feed.js index d3294b5..805a666 100644 --- a/components/Feed.js +++ b/components/Feed.js @@ -2,6 +2,7 @@ // 信息流:帖子列表 + 排序 tab + 发布新帖按钮 import { useEffect, useState, useCallback, useRef } from 'react'; +import { useTranslation } from 'react-i18next'; import { API } from '@/lib/api'; import { useApp } from './AppProvider'; import { Icon } from './Icons'; @@ -15,6 +16,7 @@ function avatar(username) { export default function Feed({ onOpenModal, onReport }) { const { currentUser, sort, setSort, openPost, openUser, navigate, refreshKey } = useApp(); + const { t } = useTranslation(); const [posts, setPosts] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); @@ -57,12 +59,12 @@ export default function Feed({ onOpenModal, onReport }) { useEffect(() => { setPage(1); }, [sort]); const handleDelete = async (postId) => { - if (!confirm('确定要删除这条帖子吗?')) return; + if (!confirm(t('feed.confirmDelete'))) return; try { await API.deletePost(postId); load(page); } catch (err) { - alert('删除失败:' + err.message); + alert(t('feed.deleteFailed', { msg: err.message })); } }; @@ -70,26 +72,26 @@ export default function Feed({ onOpenModal, onReport }) { <main id="feed"> <div className="feed-header"> <div className="feed-header-left"> - <button className={'tab' + (sort === 'latest' ? ' active' : '')} onClick={() => setSort('latest')}>最新发布</button> - <button className={'tab' + (sort === 'hot' ? ' active' : '')} onClick={() => setSort('hot')}>最新回复</button> + <button className={'tab' + (sort === 'latest' ? ' active' : '')} onClick={() => setSort('latest')}>{t('feed.latest')}</button> + <button className={'tab' + (sort === 'hot' ? ' active' : '')} onClick={() => setSort('hot')}>{t('feed.hot')}</button> </div> <button className="btn-primary fab-btn" onClick={() => { - if (!currentUser) { alert('请先登录'); return; } + if (!currentUser) { alert(t('newPost.pleaseLogin')); return; } navigate('new'); }} > - <Icon name="plus" /> 发布新帖 + <Icon name="plus" /> {t('feed.newPost')} </button> </div> <div id="postList" ref={postListRef}> {posts === null ? ( - <div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div> + <div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />{t('feed.loading')}</div> ) : error ? ( - <div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>加载失败:{error}</div> + <div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>{t('feed.loadFailed', { msg: error })}</div> ) : posts.length === 0 ? ( - <div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>✨ 还没有帖子,快来发布第一条吧!</div> + <div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>{t('feed.empty')}</div> ) : ( posts.map((p) => { const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : ''; @@ -97,7 +99,7 @@ export default function Feed({ onOpenModal, onReport }) { <div key={p.id} className="post-card" style={{ cursor: 'pointer' }} onClick={() => openPost(p.id)}> {p.is_pinned && ( - <div style={{ fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}>📌 置顶</div> + <div style={{ fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}>{t('feed.pinned')}</div> )} <div className="post-header"> <img src={avatar(p.username)} className="post-avatar" alt="" /> @@ -106,14 +108,14 @@ export default function Feed({ onOpenModal, onReport }) { style={{ cursor: 'pointer', color: 'var(--primary)' }} onClick={(e) => { e.stopPropagation(); openUser(p.username); }} > - {p.username || '匿名用户'} + {p.username || t('feed.anonymous')} </span> <span className="post-time">{time}</span> {p.edited_at && ( - <span style={{ fontSize: 11, color: 'var(--text-light)', marginLeft: 6 }}>(已编辑)</span> + <span style={{ fontSize: 11, color: 'var(--text-light)', marginLeft: 6 }}>{t('feed.deleted')}</span> )} </div> - <div className="post-title">{p.title || '无标题'}</div> + <div className="post-title">{p.title || t('feed.noTitle')}</div> <div className="post-content" dangerouslySetInnerHTML={{ __html: renderMarkdown(p.content) }} /> {p.images && p.images.length > 0 && ( <div className="post-images"> @@ -128,17 +130,17 @@ export default function Feed({ onOpenModal, onReport }) { </span> <button className="action-report" onClick={(e) => { e.stopPropagation(); - if (!currentUser) { alert('请先登录'); return; } + if (!currentUser) { alert(t('newPost.pleaseLogin')); return; } onReport(p.id); }}> - <Icon name="flag" size={14} /> 举报 + <Icon name="flag" size={14} /> {t('feed.report')} </button> {currentUser && (currentUser.id === p.user_id || currentUser.role === 'admin') && ( <button className="action-delete" onClick={(e) => { e.stopPropagation(); handleDelete(p.id); }}> - <Icon name="trash" size={14} /> 删除 + <Icon name="trash" size={14} /> {t('feed.delete')} </button> )} </div> diff --git a/components/I18nInit.js b/components/I18nInit.js new file mode 100644 index 0000000..459160b --- /dev/null +++ b/components/I18nInit.js @@ -0,0 +1,12 @@ +'use client'; + +// i18n 客户端初始化(挂在 layout,hydrate 后执行) +import { useEffect } from 'react'; +import { initI18n } from '@/lib/i18n'; + +export default function I18nInit() { + useEffect(() => { + initI18n(); + }, []); + return null; +} diff --git a/components/LoadingScreen.js b/components/LoadingScreen.js index 3c21e56..ce4d636 100644 --- a/components/LoadingScreen.js +++ b/components/LoadingScreen.js @@ -1,15 +1,17 @@ 'use client'; // 全屏加载页:初始化未完成时显示转圈,加载完成后淡出 -// - 名字容器用 dangerouslySetInnerHTML(空):React 完全不管理其文本内容, -// 内联脚本(body 首个子元素,DOMContentLoaded)填入缓存名后不会被 React -// 检测/重写 → 无 hydration mismatch,加载圈不会重启,名字不会二次出现 -export default function LoadingScreen() { +// 论坛名:容器由 React 渲染(SSR 即有),内联脚本在 DOMContentLoaded 时 +// 填充缓存名 → 首帧显示;suppressHydrationWarning 让 React 跳过该元素 +// 的文本检查(保留脚本填入的内容),hydrate 后由 AppProvider 状态接管。 +export default function LoadingScreen({ forumName, forumNameLoaded }) { return ( <div className="loading-screen"> <div className="loading-inner"> <div className="loading-spinner" /> - <div className="loading-title loading-title-appear" id="loadingTitle" dangerouslySetInnerHTML={{ __html: '' }} /> + <div className="loading-title loading-title-appear" id="loadingTitle" suppressHydrationWarning> + {forumNameLoaded && forumName} + </div> <div className="loading-sub">加载中...</div> </div> </div> diff --git a/components/Modals.js b/components/Modals.js index bc0f78d..a70dbf9 100644 --- a/components/Modals.js +++ b/components/Modals.js @@ -2,6 +2,7 @@ // 登录/注册/举报 模态框 import { useState, useEffect } from 'react'; +import { useTranslation } from 'react-i18next'; import { API, generateCaptcha } from '@/lib/api'; import { useApp } from './AppProvider'; import { Icon } from './Icons'; @@ -9,6 +10,7 @@ import CaptchaImage from './CaptchaImage'; export default function Modals({ modal, onClose, reportPostId }) { const { login, register, currentUser, refresh } = useApp(); + const { t } = useTranslation(); // 登录表单 const [loginEmail, setLoginEmail] = useState(''); @@ -90,11 +92,11 @@ export default function Modals({ modal, onClose, reportPostId }) { <div className="modal active" onClick={close}> <div className="modal-content"> <span className="close" onClick={onClose}><Icon name="close" size={20} /></span> - <h2 style={{ marginBottom: 16 }}>登录</h2> - <input type="email" placeholder="邮箱" value={loginEmail} onChange={(e) => setLoginEmail(e.target.value)} /> - <input type="password" placeholder="密码" value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)} + <h2 style={{ marginBottom: 16 }}>{t('auth.login')}</h2> + <input type="email" placeholder={t('auth.email')} value={loginEmail} onChange={(e) => setLoginEmail(e.target.value)} /> + <input type="password" placeholder={t('auth.password')} value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') handleLogin(); }} /> - <button className="btn-primary" style={{ width: '100%' }} onClick={handleLogin}>登录</button> + <button className="btn-primary" style={{ width: '100%' }} onClick={handleLogin}>{t('auth.login')}</button> </div> </div> )} @@ -103,19 +105,19 @@ export default function Modals({ modal, onClose, reportPostId }) { <div className="modal active" onClick={close}> <div className="modal-content"> <span className="close" onClick={onClose}><Icon name="close" size={20} /></span> - <h2 style={{ marginBottom: 16 }}>注册</h2> - <input type="text" placeholder="用户名" value={regUsername} onChange={(e) => setRegUsername(e.target.value)} /> - <input type="email" placeholder="邮箱" value={regEmail} onChange={(e) => setRegEmail(e.target.value)} /> - <input type="password" placeholder="密码(至少6位)" value={regPassword} onChange={(e) => setRegPassword(e.target.value)} /> + <h2 style={{ marginBottom: 16 }}>{t('auth.register')}</h2> + <input type="text" placeholder={t('auth.username')} value={regUsername} onChange={(e) => setRegUsername(e.target.value)} /> + <input type="email" placeholder={t('auth.email')} value={regEmail} onChange={(e) => setRegEmail(e.target.value)} /> + <input type="password" placeholder={t('auth.passwordHint')} value={regPassword} onChange={(e) => setRegPassword(e.target.value)} /> <div className="captcha-row" style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '12px 0' }}> {regCaptcha ? ( <CaptchaImage captcha={regCaptcha} onRefresh={() => { setRegCaptcha(generateCaptcha()); setRegCaptchaInput(''); }} /> ) : ( - <span style={{ color: 'var(--text-light)' }}>验证码加载中...</span> + <span style={{ color: 'var(--text-light)' }}>{t('newPost.captchaLoading')}</span> )} <input type="text" placeholder="答案" style={{ width: 80, background: 'var(--bg)', color: 'var(--text)', border: '1px solid var(--border)', padding: '8px 12px', borderRadius: 4 }} value={regCaptchaInput} onChange={(e) => setRegCaptchaInput(e.target.value)} /> </div> - <button className="btn-primary" style={{ width: '100%' }} onClick={handleRegister}>注册</button> + <button className="btn-primary" style={{ width: '100%' }} onClick={handleRegister}>{t('auth.register')}</button> </div> </div> )} @@ -124,20 +126,20 @@ export default function Modals({ modal, onClose, reportPostId }) { <div className="modal active" onClick={close}> <div className="modal-content"> <span className="close" onClick={onClose}><Icon name="close" size={20} /></span> - <h2 style={{ marginBottom: 16 }}><Icon name="shieldAlert" size={20} /> 举报帖子</h2> - <p style={{ fontSize: 14, color: '#64748b', marginBottom: 12 }}>请选择举报原因:</p> + <h2 style={{ marginBottom: 16 }}><Icon name="shieldAlert" size={20} /> {t('post.reportTitle')}</h2> + <p style={{ fontSize: 14, color: '#64748b', marginBottom: 12 }}>{t('post.reportReason')}</p> <select style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, marginBottom: 16, background: 'var(--bg)', color: 'var(--text)' }} value={reportReason} onChange={(e) => setReportReason(e.target.value)} > - <option value="spam">垃圾广告</option> - <option value="abuse">人身攻击</option> - <option value="illegal">违法内容</option> - <option value="nsfw">不适当内容</option> - <option value="other">其他</option> + <option value="spam">{t('report.spam')}</option> + <option value="abuse">{t('report.abuse')}</option> + <option value="illegal">{t('report.illegal')}</option> + <option value="nsfw">{t('report.nsfw')}</option> + <option value="other">{t('report.other')}</option> </select> - <button className="btn-primary" style={{ width: '100%' }} onClick={handleReport}>提交举报</button> + <button className="btn-primary" style={{ width: '100%' }} onClick={handleReport}>{t('post.submitReport')}</button> </div> </div> )} diff --git a/components/Navbar.js b/components/Navbar.js index 9dd3f7e..6934c5d 100644 --- a/components/Navbar.js +++ b/components/Navbar.js @@ -2,6 +2,7 @@ // 导航栏:论坛名、自定义页面链接、登录/注册、私信、用户菜单、主题切换 import { useState, useEffect } from 'react'; +import { useTranslation } from 'react-i18next'; import { useApp } from './AppProvider'; import { Icon } from './Icons'; import { API } from '@/lib/api'; @@ -9,6 +10,7 @@ import { DMButton } from './chat/ChatManager'; export default function Navbar({ onOpenModal }) { const { currentUser, forumName, theme, toggleTheme, navigate, openCustomPage, logout } = useApp(); + const { t } = useTranslation(); const [menuOpen, setMenuOpen] = useState(false); const [customPages, setCustomPages] = useState([]); @@ -77,8 +79,8 @@ export default function Navbar({ onOpenModal }) { <div id="userMenu"> {!currentUser ? ( <div id="authButtons"> - <button className="btn-ghost" onClick={() => onOpenModal('login')}>登录</button> - <button className="btn-primary" onClick={() => onOpenModal('register')}>注册</button> + <button className="btn-ghost" onClick={() => onOpenModal('login')}>{t('nav.login')}</button> + <button className="btn-primary" onClick={() => onOpenModal('register')}>{t('nav.register')}</button> </div> ) : ( <div id="userDropdown" style={{ display: 'block' }}> @@ -91,14 +93,14 @@ export default function Navbar({ onOpenModal }) { {menuOpen && ( <div className="dropdown-menu show" onClick={(e) => e.stopPropagation()}> <a href="#" onClick={openMessages}> - <Icon name="message" /> 消息 + <Icon name="message" /> {t('nav.messages')} </a> <a href="#" onClick={(e) => { e.preventDefault(); goPage('settings'); }}> - <Icon name="settings" /> 设置 + <Icon name="settings" /> {t('nav.settings')} </a> {currentUser.role === 'admin' && ( <a href="#" onClick={(e) => { e.preventDefault(); goPage('admin'); }}> - <Icon name="shieldAlert" /> 管理后台 + <Icon name="shieldAlert" /> {t('nav.admin')} </a> )} <hr /> @@ -110,20 +112,20 @@ export default function Navbar({ onOpenModal }) { setMenuOpen(false); }} > - <Icon name={theme === 'dark' ? 'sun' : 'moon'} /> {theme === 'dark' ? '亮色模式' : '暗色模式'} + <Icon name={theme === 'dark' ? 'sun' : 'moon'} /> {theme === 'dark' ? t('nav.lightMode') : t('nav.darkMode')} </a> <hr /> <a href="#" onClick={(e) => { e.preventDefault(); - if (confirm('确定要退出吗?')) { + if (confirm(t('nav.logoutConfirm'))) { setMenuOpen(false); logout(); } }} > - <Icon name="logout" /> 退出 + <Icon name="logout" /> {t('nav.logout')} </a> </div> )} diff --git a/components/NewPost.js b/components/NewPost.js index 62a5c0e..d9c35ed 100644 --- a/components/NewPost.js +++ b/components/NewPost.js @@ -1,7 +1,8 @@ 'use client'; -// 发布新帖页 +// 发帖页 import { useState, useEffect, useRef } from 'react'; +import { useTranslation } from 'react-i18next'; import { API, generateCaptcha, uploadImage } from '@/lib/api'; import { useApp } from './AppProvider'; import { Icon } from './Icons'; @@ -10,6 +11,7 @@ import CaptchaImage from './CaptchaImage'; export default function NewPost() { const { currentUser, navigate, refresh } = useApp(); + const { t } = useTranslation(); const { toast } = useToast(); const [title, setTitle] = useState(''); const [content, setContent] = useState(''); @@ -85,19 +87,19 @@ export default function NewPost() { return ( <div className="page-slide active"> <div className="page-header" style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}> - <h2><Icon name="plus" size={20} /> 发布新帖</h2> + <h2><Icon name="plus" size={20} /> {t('newPost.title')}</h2> </div> <div style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}> <input type="text" - placeholder="标题" + placeholder={t('newPost.title')} style={{ width: '100%', padding: '10px 14px', border: '1.5px solid var(--border)', borderRadius: 6, fontSize: 15, fontWeight: 600, marginBottom: 12, fontFamily: 'inherit', background: 'var(--bg)', color: 'var(--text)' }} value={title} onChange={(e) => setTitle(e.target.value)} /> <textarea rows={6} - placeholder="说点什么..." + placeholder={t('newPost.content')} style={{ width: '100%', padding: 12, border: '1.5px solid var(--border)', borderRadius: 6, fontSize: 15, fontFamily: 'inherit', resize: 'vertical', background: 'var(--bg)', color: 'var(--text)' }} value={content} onChange={(e) => setContent(e.target.value)} @@ -116,7 +118,7 @@ export default function NewPost() { onDrop={(e) => { e.preventDefault(); setDragOver(false); if (e.dataTransfer.files) handleFiles(Array.from(e.dataTransfer.files)); }} > <div style={{ fontSize: 13, color: 'var(--text-secondary)' }}> - {uploading ? '上传中...' : (dragOver ? '松开上传' : '📷 点击或拖拽上传图片')} + {uploading ? t('newPost.uploading') : (dragOver ? t('newPost.drop') : '📷 ' + t('newPost.dropHint'))} </div> </div> <input @@ -132,18 +134,18 @@ export default function NewPost() { {captcha ? ( <CaptchaImage captcha={captcha} onRefresh={() => { setCaptcha(generateCaptcha()); setCaptchaInput(''); }} /> ) : ( - <span style={{ color: 'var(--text-light)' }}>验证码加载中...</span> + <span style={{ color: 'var(--text-light)' }}>{t('newPost.captchaLoading')}</span> )} <input type="text" - placeholder="答案" - style={{ width: 80, padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4 }} + placeholder={t('newPost.answer')} + style={{ width: 80, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }} value={captchaInput} onChange={(e) => setCaptchaInput(e.target.value)} /> </div> <button className="btn-primary" style={{ padding: '10px 32px', fontSize: 15 }} onClick={handleSubmit}> - {uploading ? '上传中...' : '发布帖子'} + {uploading ? t('newPost.uploading') : t('newPost.publish')} </button> </div> </div> diff --git a/components/RecoveryCodes.js b/components/RecoveryCodes.js index 9c53c9f..8bf440c 100644 --- a/components/RecoveryCodes.js +++ b/components/RecoveryCodes.js @@ -2,10 +2,11 @@ // 恢复码管理:查看 + 重新生成 import { useState, useEffect } from 'react'; -import { createPortal } from 'react-dom'; +import { useTranslation } from 'react-i18next'; import { API } from '@/lib/api'; export default function RecoveryCodes() { + const { t } = useTranslation(); const [count, setCount] = useState(0); const [modal, setModal] = useState(null); // null | {codes, isNew} @@ -15,13 +16,13 @@ export default function RecoveryCodes() { useEffect(loadCount, []); const regenerate = async () => { - if (!confirm('重新生成将使所有旧恢复码失效,确定继续吗?')) return; + if (!confirm(t('recovery.confirmRegenerate'))) return; try { const d = await API.generateRecoveryCodes(); setModal({ codes: d.codes || [], isNew: true }); loadCount(); } catch (err) { - alert('生成失败:' + err.message); + alert(t('recovery.genFailed', { msg: err.message })); } }; @@ -32,35 +33,34 @@ export default function RecoveryCodes() { setModal({ codes: d.codes || [], isNew: false }); loadCount(); } catch (err) { - alert('获取失败:' + err.message); + alert(t('recovery.fetchFailed', { msg: err.message })); } }; return ( <div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}> - <h3 style={{ fontSize: 16, marginBottom: 8 }}>🔑 恢复码</h3> - <p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>用于忘记密码时重置账户。每个恢复码只能使用一次。</p> + <h3 style={{ fontSize: 16, marginBottom: 8 }}>🔑 {t('recovery.title')}</h3> + <p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>{t('recovery.desc')}</p> <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}> - <button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={view}>📋 查看恢复码</button> - <button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={regenerate}>🔄 重新生成</button> + <button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={view}>📋 {t('recovery.view')}</button> + <button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={regenerate}>🔄 {t('recovery.regenerate')}</button> </div> - <div id="recoveryCodesStatus" style={{ fontSize: 13, color: 'var(--text-light)', marginTop: 8 }}>剩余 {count} 个可用恢复码</div> + <div id="recoveryCodesStatus" style={{ fontSize: 13, color: 'var(--text-light)', marginTop: 8 }}>{t('recovery.remaining', { count })}</div> - {modal && typeof document !== 'undefined' && createPortal( + {modal && ( <div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) setModal(null); }}> <div className="modal-content" style={{ maxWidth: 480, position: 'relative' }}> <span className="close" style={{ position: 'absolute', top: 12, right: 16, fontSize: 24, cursor: 'pointer', color: 'var(--text-light)' }} onClick={() => setModal(null)}>×</span> - <h2 style={{ marginBottom: 12 }}>{modal.isNew ? '🆕 新恢复码' : '🔑 恢复码'}</h2> - <p style={{ fontSize: 13, color: '#ef4444', marginBottom: 12 }}>⚠️ 请妥善保存这些恢复码,关闭窗口后无法再次查看。</p> + <h2 style={{ marginBottom: 12 }}>{modal.isNew ? t('recovery.newCodes') : t('recovery.title')}</h2> + <p style={{ fontSize: 13, color: '#ef4444', marginBottom: 12 }}>{t('recovery.saveWarning')}</p> <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}> {modal.codes.map((c, i) => ( <code key={i} style={{ background: 'var(--bg)', padding: '8px 12px', borderRadius: 6, fontSize: 13, textAlign: 'center', userSelect: 'all' }}>{c}</code> ))} </div> - <button className="btn-primary" style={{ width: '100%', padding: 10, marginTop: 16 }} onClick={() => setModal(null)}>我已保存</button> + <button className="btn-primary" style={{ width: '100%', padding: 10, marginTop: 16 }} onClick={() => setModal(null)}>{t('recovery.saved')}</button> </div> - </div>, - document.body + </div> )} </div> ); diff --git a/components/SettingsPage.js b/components/SettingsPage.js index b82ebf4..0ca3f23 100644 --- a/components/SettingsPage.js +++ b/components/SettingsPage.js @@ -4,18 +4,20 @@ // - 三个面板纵向排列在滚动容器里,scroll-snap 每次滑动对齐一个面板 // - 点侧边栏导航 → 平滑滚动到对应面板;滚动结束 → 自动更新导航高亮 import { useState, useRef, useCallback } from 'react'; +import { useTranslation } from 'react-i18next'; import { Icon } from './Icons'; import SettingsProfile from './SettingsProfile'; import AccountSecurity from './AccountSecurity'; import RecoveryCodes from './RecoveryCodes'; const NAV = [ - { key: 'profile', label: '个人资料', icon: 'user' }, - { key: 'security', label: '安全设置', icon: 'shieldAlert' }, - { key: 'recovery', label: '恢复码', icon: 'lock' }, + { key: 'profile', labelKey: 'settings.profile', icon: 'user' }, + { key: 'security', labelKey: 'settings.security', icon: 'shieldAlert' }, + { key: 'recovery', labelKey: 'settings.recovery', icon: 'lock' }, ]; export default function SettingsPage() { + const { t } = useTranslation(); const [tab, setTab] = useState('profile'); const scrollRef = useRef(null); const scrollTicking = useRef(false); @@ -46,7 +48,7 @@ export default function SettingsPage() { return ( <div className="page-slide active"> <div className="page-header" style={{ maxWidth: 1200, margin: '0 auto', width: '100%' }}> - <h2><Icon name="settings" size={20} /> 设置</h2> + <h2><Icon name="settings" size={20} /> {t('settings.title')}</h2> </div> <div className="settings-layout" style={{ maxWidth: 1200, margin: '0 auto', width: '100%', display: 'flex', gap: 28, alignItems: 'flex-start' }}> <aside className="settings-sidebar" style={{ width: 200, flexShrink: 0 }}> @@ -60,7 +62,7 @@ export default function SettingsPage() { onClick={(e) => goTo(n.key, e)} > <span className="nav-icon"><Icon name={n.icon} size={18} /></span> - {n.label} + {t(n.labelKey)} </a> ))} </nav> diff --git a/components/SettingsProfile.js b/components/SettingsProfile.js index 6316671..4c239ed 100644 --- a/components/SettingsProfile.js +++ b/components/SettingsProfile.js @@ -1,12 +1,15 @@ 'use client'; -// 设置 - 个人资料(头像 + 用户名/简介/签名) +// 设置 - 个人资料(头像 + 用户名/简介/签名 + 语言) import { useState, useRef } from 'react'; +import { useTranslation } from 'react-i18next'; import { API, uploadImage } from '@/lib/api'; import { useApp } from './AppProvider'; +import { setAppLanguage } from '@/lib/i18n'; export default function SettingsProfile() { const { currentUser, setCurrentUser } = useApp(); + const { t, i18n } = useTranslation(); const [username, setUsername] = useState(currentUser?.username || ''); const [bio, setBio] = useState(currentUser?.bio || ''); const [signature, setSignature] = useState(currentUser?.signature || ''); @@ -82,6 +85,27 @@ export default function SettingsProfile() { </div> <button className="btn-primary" style={{ width: '100%', padding: 10 }} onClick={handleSave}>保存设置</button> </div> + + {/* 语言设置 */} + <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20, marginTop: 16 }}> + <label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 8 }}>{t('settings.language')}</label> + <div style={{ display: 'flex', gap: 10 }}> + <button + className={'btn' + (i18n.language === 'zh' ? ' btn-primary' : '')} + style={{ padding: '8px 20px', borderRadius: 6, cursor: 'pointer', border: '1px solid var(--border)', background: i18n.language === 'zh' ? 'var(--primary)' : 'transparent', color: i18n.language === 'zh' ? '#fff' : 'var(--text)' }} + onClick={() => setAppLanguage('zh')} + > + {t('settings.languageZh')} + </button> + <button + className={'btn' + (i18n.language === 'en' ? ' btn-primary' : '')} + style={{ padding: '8px 20px', borderRadius: 6, cursor: 'pointer', border: '1px solid var(--border)', background: i18n.language === 'en' ? 'var(--primary)' : 'transparent', color: i18n.language === 'en' ? '#fff' : 'var(--text)' }} + onClick={() => setAppLanguage('en')} + > + {t('settings.languageEn')} + </button> + </div> + </div> </div> ); } diff --git a/components/chat/ConversationList.js b/components/chat/ConversationList.js index 1bb97ec..2541244 100644 --- a/components/chat/ConversationList.js +++ b/components/chat/ConversationList.js @@ -3,6 +3,7 @@ // 私信 - 会话列表 import { useEffect, useState } from 'react'; import { API } from '@/lib/api'; +import { Icon } from '../Icons'; function avatar(username) { return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') + @@ -24,7 +25,7 @@ export default function ConversationList({ onOpenChat, onClose }) { <div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}> <div className="modal-content" style={{ display: 'flex', flexDirection: 'column', height: '70vh', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}> - <h2 style={{ fontSize: 18, margin: 0 }}>✉️ 私信</h2> + <h2 style={{ fontSize: 18, margin: 0 }}><Icon name="message" size={18} style={{ verticalAlign: -3, marginRight: 6 }} /> 私信</h2> <span className="close" onClick={onClose} style={{ fontSize: 24, cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}>×</span> </div> <div id="messageListContent" style={{ flex: 1, overflowY: 'auto', padding: 0 }}> diff --git a/lib/i18n.js b/lib/i18n.js new file mode 100644 index 0000000..c07b627 --- /dev/null +++ b/lib/i18n.js @@ -0,0 +1,41 @@ +'use client'; + +// i18n 配置:i18next + react-i18next +// - 模块顶层无条件 init(SSR Node 与客户端都执行):SSR 输出用默认 zh, +// 与客户端初始语言一致 → 无 hydration mismatch +// - initI18n() 在客户端按 localStorage/浏览器语言切换;SSR 时 no-op +import i18n from 'i18next'; +import { initReactI18next } from 'react-i18next'; +import zh from '@/locales/zh.json'; +import en from '@/locales/en.json'; + +i18n.use(initReactI18next).init({ + resources: { + zh: { translation: zh }, + en: { translation: en }, + }, + lng: 'zh', + fallbackLng: 'zh', + interpolation: { escapeValue: false }, + react: { useSuspense: false }, + // 同步初始化:SSR 渲染时 t() 立即返回翻译(否则返回 key → hydration mismatch) + initImmediate: false, +}); + +// 客户端初始化:按 localStorage / 浏览器语言切换(SSR 阶段 no-op) +export function initI18n() { + if (typeof window === 'undefined') return i18n; + try { + const saved = localStorage.getItem('forumlify-lang'); + const nav = (navigator.language || 'zh').toLowerCase(); + const lng = saved || (nav.startsWith('en') ? 'en' : 'zh'); + if (i18n.language !== lng) i18n.changeLanguage(lng); + } catch (e) {} + return i18n; +} + +// 切换语言(保存到 localStorage) +export function setAppLanguage(lng) { + if (typeof window !== 'undefined') localStorage.setItem('forumlify-lang', lng); + return i18n.changeLanguage(lng); +} diff --git a/locales/en.json b/locales/en.json new file mode 100644 index 0000000..a3ecc07 --- /dev/null +++ b/locales/en.json @@ -0,0 +1,154 @@ +{ + "appName": "Forumlify", + "nav": { + "home": "Home", + "messages": "Messages", + "settings": "Settings", + "admin": "Admin", + "login": "Login", + "register": "Register", + "logout": "Logout", + "darkMode": "Dark mode", + "lightMode": "Light mode", + "logoutConfirm": "Are you sure you want to log out?" + }, + "feed": { + "latest": "Latest posts", + "hot": "Latest replies", + "newPost": "New post", + "loading": "Loading...", + "empty": "✨ No posts yet — be the first to publish!", + "pinned": "📌 Pinned", + "deleted": "(edited)", + "report": "Report", + "delete": "Delete", + "confirmDelete": "Are you sure you want to delete this post?", + "deleteFailed": "Delete failed: {{msg}}", + "noTitle": "Untitled", + "anonymous": "Anonymous" + }, + "post": { + "title": "Post detail", + "back": "← Back", + "edit": "Edit", + "save": "Save", + "cancel": "Cancel", + "editFailed": "Load failed: {{msg}}", + "contentRequired": "Please fill in the content", + "reply": "Reply", + "replyCount": "{{count}} replies", + "reportReason": "Report reason", + "confirmDelete": "Are you sure you want to delete this post?", + "reportTitle": "Report post", + "submitReport": "Submit report" + }, + "newPost": { + "title": "Title", + "content": "Say something...", + "publish": "Publish post", + "uploading": "Uploading...", + "pleaseLogin": "Please log in first", + "captchaError": "Wrong captcha, please try again", + "publishSuccess": "Post published", + "publishFailed": "Publish failed: {{msg}}", + "answer": "Answer", + "captchaLoading": "Loading captcha...", + "drop": "Release to upload", + "dropHint": "Click or drag to upload image" + }, + "reply": { + "submit": "Submit reply", + "placeholder": "Write your reply...", + "empty": "No replies yet — be the first to comment 🛋️", + "replyFailed": "Reply failed: {{msg}}", + "delete": "Delete", + "confirmDelete": "Are you sure you want to delete this reply?", + "deleteFailed": "Delete failed: {{msg}}" + }, + "auth": { + "email": "Email", + "password": "Password", + "username": "Username", + "passwordHint": "Password (min 6 chars)", + "forgotPassword": "Forgot password?", + "captchaError": "Wrong captcha, please try again", + "registerSuccess": "🎉 Registration successful", + "loginSuccess": "Logged in", + "logoutSuccess": "Logged out", + "login": "Login", + "register": "Register" + }, + "settings": { + "title": "Settings", + "profile": "Profile", + "security": "Security", + "recovery": "Recovery codes", + "language": "Language", + "languageZh": "中文", + "languageEn": "English", + "username": "Username", + "bio": "Bio", + "signature": "Signature", + "save": "Save settings", + "saved": "Saved!", + "saveFailed": "Save failed: {{msg}}", + "usernameRequired": "Username cannot be empty", + "pleaseLogin": "Please log in first" + }, + "user": { + "title": "User profile", + "bioEmpty": "This user hasn't written a bio yet", + "sendMessage": "Send message", + "joined": "📅 Joined {{date}}", + "posts": "📝 {{count}} posts", + "admin": "🛡️ Admin", + "noPosts": "No posts yet", + "notFound": "User not found", + "loading": "Loading..." + }, + "stats": { + "topics": "Topics", + "posts": "Posts", + "users": "Users", + "links": "Links" + }, + "loading": "Loading...", + "common": { + "confirm": "Confirm", + "cancel": "Cancel", + "close": "Close" + }, + "report": { + "spam": "Spam", + "abuse": "Harassment", + "illegal": "Illegal content", + "nsfw": "Inappropriate content", + "other": "Other" + }, + "security": { + "title": "Account security", + "currentPw": "Current password", + "newPw": "New password", + "changePw": "Change password", + "currentPwVerify": "Current password (verify identity)", + "newEmail": "New email", + "changeEmail": "Change email", + "fillAll": "Please fill in all fields", + "pwMin": "New password must be at least 6 characters", + "pwChanged": "✅ Password changed", + "emailChanged": "✅ Email changed" + }, + "recovery": { + "title": "Recovery codes", + "desc": "Use these to reset your account if you forget your password. Each code works once.", + "view": "View recovery codes", + "regenerate": "Regenerate", + "remaining": "{{count}} recovery codes remaining", + "confirmRegenerate": "Regenerating will invalidate all old codes. Continue?", + "genFailed": "Generation failed: {{msg}}", + "fetchFailed": "Fetch failed: {{msg}}", + "newCodes": "🆕 New recovery codes", + "saveWarning": "⚠️ Save these codes now — they cannot be viewed again after closing.", + "saved": "I have saved them" + } +} \ No newline at end of file diff --git a/locales/zh.json b/locales/zh.json new file mode 100644 index 0000000..d7c8911 --- /dev/null +++ b/locales/zh.json @@ -0,0 +1,151 @@ +{ + "appName": "Forumlify", + "nav": { + "home": "首页", + "messages": "消息", + "settings": "设置", + "admin": "管理后台", + "login": "登录", + "register": "注册", + "logout": "退出", + "darkMode": "暗色模式", + "lightMode": "亮色模式", + "logoutConfirm": "确定要退出吗?" + }, + "feed": { + "latest": "最新发布", + "hot": "最新回复", + "newPost": "发布新帖", + "loading": "加载中...", + "empty": "✨ 还没有帖子,快来发布第一条吧!", + "pinned": "📌 置顶", + "deleted": "(已编辑)", + "report": "举报", + "delete": "删除", + "confirmDelete": "确定要删除这条帖子吗?", + "deleteFailed": "删除失败:{{msg}}", + "noTitle": "无标题", + "anonymous": "匿名用户" + }, + "post": { + "title": "帖子详情", + "back": "← 返回", + "edit": "编辑", + "save": "保存", + "cancel": "取消", + "editFailed": "加载失败:{{msg}}", + "contentRequired": "请填写内容", + "reply": "回复", + "replyCount": "{{count}} 条回复", + "reportReason": "举报原因", + "confirmDelete": "确定要删除这条帖子吗?", + "reportTitle": "举报帖子", + "submitReport": "提交举报" + }, + "newPost": { + "title": "标题", + "content": "说点什么...", + "publish": "发布帖子", + "uploading": "上传中...", + "pleaseLogin": "请先登录", + "captchaError": "验证码错误,请重新计算", + "publishSuccess": "发布成功", + "publishFailed": "发布失败:{{msg}}", + "answer": "答案", + "captchaLoading": "验证码加载中...", + "drop": "松开上传", + "dropHint": "点击或拖拽上传图片" + }, + "reply": { + "submit": "提交回复", + "placeholder": "写下你的回复...", + "empty": "还没有回复,快来抢沙发吧 🛋️", + "replyFailed": "回复失败:{{msg}}", + "delete": "删除", + "confirmDelete": "确定要删除这条回复吗?", + "deleteFailed": "删除失败:{{msg}}" + }, + "auth": { + "email": "邮箱", + "password": "密码", + "username": "用户名", + "passwordHint": "密码(至少6位)", + "forgotPassword": "忘记密码?", + "captchaError": "验证码错误,请重新计算", + "registerSuccess": "🎉 注册成功", + "loginSuccess": "登录成功", + "logoutSuccess": "已退出登录", + "login": "登录", + "register": "注册" + }, + "settings": { + "title": "设置", + "profile": "个人资料", + "security": "安全设置", + "recovery": "恢复码", + "username": "用户名", + "bio": "个人简介", + "signature": "个性签名", + "save": "保存设置", + "saved": "保存成功!", + "saveFailed": "保存失败:{{msg}}", + "usernameRequired": "用户名不能为空", + "pleaseLogin": "请先登录" + }, + "user": { + "title": "用户主页", + "bioEmpty": "这个人很懒,什么都没写", + "sendMessage": "发私信", + "joined": "📅 加入于 {{date}}", + "posts": "📝 发了 {{count}} 个帖子", + "admin": "🛡️ 管理员", + "noPosts": "还没有发帖", + "notFound": "用户不存在", + "loading": "加载中..." + }, + "stats": { + "topics": "主题", + "posts": "帖子", + "users": "用户", + "links": "友情链接" + }, + "loading": "加载中...", + "common": { + "confirm": "确定", + "cancel": "取消", + "close": "关闭" + }, + "report": { + "spam": "垃圾广告", + "abuse": "人身攻击", + "illegal": "违法内容", + "nsfw": "不适当内容", + "other": "其他" + }, + "security": { + "title": "账户安全", + "currentPw": "当前密码", + "newPw": "新密码", + "changePw": "修改密码", + "currentPwVerify": "当前密码(验证身份)", + "newEmail": "新邮箱", + "changeEmail": "修改邮箱", + "fillAll": "请填写完整信息", + "pwMin": "新密码至少6位", + "pwChanged": "✅ 密码修改成功", + "emailChanged": "✅ 邮箱修改成功" + }, + "recovery": { + "title": "恢复码", + "desc": "用于忘记密码时重置账户。每个恢复码只能使用一次。", + "view": "查看恢复码", + "regenerate": "重新生成", + "remaining": "剩余 {{count}} 个可用恢复码", + "confirmRegenerate": "重新生成将使所有旧恢复码失效,确定继续吗?", + "genFailed": "生成失败:{{msg}}", + "fetchFailed": "获取失败:{{msg}}", + "newCodes": "🆕 新恢复码", + "saveWarning": "⚠️ 请妥善保存这些恢复码,关闭窗口后无法再次查看。", + "saved": "我已保存" + } +} \ No newline at end of file diff --git a/package.json b/package.json index e29128d..915f6e0 100644 --- a/package.json +++ b/package.json @@ -16,12 +16,14 @@ "dependencies": { "aws4fetch": "^1.0.20", "bcryptjs": "^3.0.3", + "i18next": "^26.3.6", "jsonwebtoken": "^9.0.2", "marked": "^18.0.9", "next": "16", "pg": "^8.11.3", "react": "19", - "react-dom": "19" + "react-dom": "19", + "react-i18next": "^17.0.11" }, "devDependencies": { "@opennextjs/cloudflare": "^1.20.2",