fix: polish forum navigation and interface states

This commit is contained in:
lezi-fun committed 2026-08-11 15:25:05 +08:00
1 parent 0933220c70
commit 6947cdaf36
33 files changed
+1615 -360

No files matched your search

+3 -3
View File
@@ -18,7 +18,7 @@ import Modals from '@/components/Modals';
import LoadingScreen from '@/components/LoadingScreen';
function HomeInner() {
const { view, currentPostId, currentUsername, currentPageName, ready, forumName, forumNameLoaded } = useApp();
const { view, currentPostId, currentPostPreview, currentUsername, currentPageName, ready, forumName, forumNameLoaded } = useApp();
const [modal, setModal] = useState(null); // null | login | register | report
const [reportPostId, setReportPostId] = useState(null);
@@ -34,14 +34,14 @@ function HomeInner() {
<div className="app-fade-in">
<Navbar onOpenModal={openModal} />
<ChatManager />
<div id="app">
<div id="app" style={{ display: view === 'feed' ? 'flex' : 'none' }}>
<Sidebar />
<Feed onOpenModal={openModal} onReport={openReport} />
</div>
{/* 独立页面 */}
<div style={{ display: view !== 'feed' ? 'block' : 'none' }}>
{view === 'post' && currentPostId && <PostDetail postId={currentPostId} />}
{view === 'post' && currentPostId && <PostDetail postId={currentPostId} initialPost={currentPostPreview} />}
{view === 'user' && currentUsername && <UserProfile username={currentUsername} />}
{view === 'custom' && currentPageName && <CustomPage pageName={currentPageName} />}
{view === 'new' && <NewPost />}
+1 -1
View File
@@ -27,7 +27,7 @@ export async function POST(req) {
return Response.json({
user: r.rows[0],
message: isFirstUser ? '🎉 你是第一个用户,已自动设为管理员!' : '注册成功',
message: isFirstUser ? '你是第一个用户,已自动设为管理员!' : '注册成功',
});
} catch (err) {
if (err.code === '23505') {
+522 -28
View File
@@ -1,5 +1,5 @@
/* ============================================================
🧊 Forumlify —— 液态/磨砂玻璃风格(冰川蓝主题)
Forumlify —— 液态/磨砂玻璃风格(冰川蓝主题)
支持亮色/暗色模式 + 管理后台侧边栏 + 滑动Tab
============================================================ */
@@ -32,7 +32,7 @@
/* ===== 兼容旧变量(React 组件内联样式使用)===== */
--bg: #dfe6e9;
--modal-bg: rgba(255, 255, 255, 0.85); /* 弹窗背景:半透明玻璃感但保证可读性 */
--modal-bg: rgba(255, 255, 255, 0.85);
--surface: rgba(255, 255, 255, 0.18);
--border: rgba(255, 255, 255, 0.30);
--border-light: rgba(255, 255, 255, 0.12);
@@ -73,7 +73,7 @@
/* ===== 兼容旧变量(React 组件内联样式使用)===== */
--bg: #0f0f1a;
--modal-bg: rgba(24, 24, 38, 0.88); /* 弹窗背景:半透明玻璃感但保证可读性 */
--modal-bg: rgba(24, 24, 38, 0.88);
--surface: rgba(30, 30, 50, 0.35);
--border: rgba(255, 255, 255, 0.10);
--border-light: rgba(255, 255, 255, 0.06);
@@ -153,6 +153,16 @@ svg {
color: var(--glass-text);
}
[data-theme="light"] #authButtons .btn-ghost {
background: rgba(74, 74, 106, 0.1);
border-color: transparent;
color: #30304a;
}
[data-theme="light"] #authButtons .btn-ghost:hover {
background: rgba(91, 155, 213, 0.2);
color: #202038;
}
.btn-sm {
padding: 4px 12px;
border-radius: var(--radius-sm);
@@ -338,7 +348,7 @@ svg {
}
/* ===== 侧边栏 ===== */
#sidebar {
.sidebar {
width: 240px;
flex-shrink: 0;
}
@@ -433,6 +443,8 @@ svg {
border-radius: var(--radius-sm);
border: 1px solid var(--glass-border);
position: relative;
width: 280px;
max-width: 100%;
}
/* 滑块 */
@@ -470,8 +482,10 @@ svg {
cursor: pointer;
border-radius: calc(var(--radius-sm) - 2px);
transition: color 0.3s ease;
flex: 1;
flex: 1 1 0;
min-width: 0;
text-align: center;
white-space: nowrap;
}
.tab:hover {
color: var(--glass-text);
@@ -491,6 +505,36 @@ svg {
margin-right: 6px;
}
.feed-posts-drawer {
display: grid;
grid-template-rows: 1fr;
opacity: 1;
transform-origin: top;
transition:
grid-template-rows 0.34s cubic-bezier(0.22, 1, 0.36, 1),
opacity 0.2s ease,
transform 0.34s cubic-bezier(0.22, 1, 0.36, 1);
}
.feed-posts-drawer-inner {
min-height: 0;
overflow: hidden;
}
.feed-posts-drawer.closing,
.feed-posts-drawer.closed {
grid-template-rows: 0fr;
opacity: 0;
transform: scaleY(0.985);
}
.feed-posts-drawer.opening,
.feed-posts-drawer.idle {
grid-template-rows: 1fr;
opacity: 1;
transform: scaleY(1);
}
/* ===== 帖子卡片 ===== */
.post-card {
background: var(--glass-bg);
@@ -611,17 +655,11 @@ svg {
}
.modal.active {
display: flex;
animation: modalFade 0.2s ease-out;
animation: modalFade 0.28s ease-out;
}
@keyframes modalFade {
from {
opacity: 0;
transform: scale(0.96);
}
to {
opacity: 1;
transform: scale(1);
}
from { opacity: 0; }
to { opacity: 1; }
}
.modal-content {
background: var(--modal-bg, var(--glass-bg));
@@ -637,6 +675,13 @@ svg {
position: relative;
box-shadow: 0 24px 80px rgba(0, 0, 0, 0.2);
}
.modal.active .modal-content {
animation: modalContentIn 0.28s cubic-bezier(0.22, 1, 0.36, 1);
}
@keyframes modalContentIn {
from { transform: translateY(12px) scale(0.9); opacity: 0; }
to { transform: translateY(0) scale(1); opacity: 1; }
}
.modal-content .close {
position: absolute;
top: 14px;
@@ -843,6 +888,226 @@ svg {
display: block;
animation: slideIn 0.35s cubic-bezier(0.22, 1, 0.36, 1);
}
#pagePost.page-slide.active {
animation: none;
}
html.post-view-transition #pagePost .post-detail-card,
html.home-view-transition.returning-home #pagePost .post-detail-card {
view-transition-name: post-expand;
}
html.post-view-transition #navbar,
html.home-view-transition #navbar {
view-transition-name: persistent-navbar;
}
html.post-view-transition #sidebar,
html.post-view-transition #postSidebar,
html.home-view-transition.returning-home #sidebar,
html.home-view-transition.returning-home #postSidebar {
view-transition-name: post-sidebar;
}
html.post-view-transition #pagePost .post-detail-card .post-time,
html.home-view-transition.returning-home #pagePost .post-detail-card .post-time {
view-transition-name: post-time;
}
html.post-view-transition #pagePost .post-page-header h2,
html.home-view-transition.returning-home #pagePost .post-page-header h2 {
view-transition-name: post-heading;
}
html.post-view-transition::view-transition,
html.home-view-transition::view-transition {
background: linear-gradient(145deg, var(--bg-start) 0%, var(--bg-end) 100%);
}
html.post-view-transition::view-transition-group(post-expand) {
animation-duration: 0.96s;
animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
}
html.post-view-transition::view-transition-group(post-sidebar),
html.post-view-transition::view-transition-group(post-heading) {
animation-duration: 0.72s;
animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
}
html.post-view-transition::view-transition-group(post-time) {
animation-duration: 1.05s;
animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
}
html.post-view-transition::view-transition-group(persistent-navbar),
html.home-view-transition::view-transition-group(persistent-navbar),
html.post-view-transition::view-transition-old(persistent-navbar),
html.post-view-transition::view-transition-new(persistent-navbar),
html.home-view-transition::view-transition-old(persistent-navbar),
html.home-view-transition::view-transition-new(persistent-navbar) {
animation: none;
mix-blend-mode: normal;
}
html.post-view-transition::view-transition-old(root) {
animation: feedViewFadeOut 0.28s 0.34s ease-out both;
}
html.post-view-transition::view-transition-new(root) {
animation: postSurroundingsReveal 0.24s 0.56s ease-out both;
}
html.post-view-transition::view-transition-old(post-expand) {
animation: postCardFadeOut 0.2s 0.5s ease-out both;
}
html.post-view-transition::view-transition-new(post-expand) {
animation: postCardReveal 0.22s 0.56s ease-out both;
}
html.post-view-transition::view-transition-old(post-heading) {
animation: sharedTitleOut 0.14s 0.48s ease-out both;
}
html.post-view-transition::view-transition-new(post-heading) {
animation: sharedTitleIn 0.14s 0.82s ease-out both;
}
html.post-view-transition::view-transition-old(post-time) {
animation: sharedTimeOut 0.2s 0.32s ease-out both;
}
html.post-view-transition::view-transition-new(post-time) {
animation: sharedTimeIn 0.2s 0.38s ease-out both;
}
html.post-view-transition::view-transition-old(post-sidebar) {
animation: sharedSidebarOut 0.2s 0.42s ease-out both;
}
html.post-view-transition::view-transition-new(post-sidebar) {
animation: sharedSidebarIn 0.2s 0.42s ease-out both;
}
html.home-view-transition::view-transition-old(root) {
animation: homeSourceFadeOut 0.4s ease-in both;
}
html.home-view-transition::view-transition-new(root) {
animation: homeFeedFadeIn 0.5s ease-out both;
}
html.home-view-transition.returning-home::view-transition-old(root) {
animation: homeSourceFadeOut 0.24s ease-out both;
}
html.home-view-transition.returning-home::view-transition-new(root) {
animation: homeFeedFadeIn 0.32s ease-out both;
}
html.home-view-transition.returning-home::view-transition-group(post-expand) {
animation-duration: 0.48s;
animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
}
html.home-view-transition.returning-home::view-transition-group(post-sidebar),
html.home-view-transition.returning-home::view-transition-group(post-heading),
html.home-view-transition.returning-home::view-transition-group(post-time) {
animation-duration: 0.48s;
animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
}
html.home-view-transition.returning-home::view-transition-old(post-expand) {
animation: postDetailCollapse 0.24s 0.12s ease-out both;
}
html.home-view-transition.returning-home::view-transition-new(post-expand) {
animation: postCardFadeIn 0.24s 0.18s ease-out both;
}
html.home-view-transition.returning-home::view-transition-old(post-heading) {
animation: sharedTitleOut 0.12s 0.22s ease-out both;
}
html.home-view-transition.returning-home::view-transition-new(post-heading) {
animation: sharedTitleIn 0.12s 0.36s ease-out both;
}
html.home-view-transition.returning-home::view-transition-old(post-time),
html.home-view-transition.returning-home::view-transition-old(post-sidebar) {
animation: sharedTimeOut 0.14s 0.24s ease-out both;
}
html.home-view-transition.returning-home::view-transition-new(post-time),
html.home-view-transition.returning-home::view-transition-new(post-sidebar) {
animation: sharedTimeIn 0.14s 0.26s ease-out both;
}
@keyframes feedViewFadeOut {
to { opacity: 0; }
}
@keyframes postSurroundingsReveal {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes postCardFadeOut {
0%, 72% { opacity: 1; }
100% { opacity: 0; }
}
@keyframes postCardReveal {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes homeSourceFadeOut {
to { opacity: 0; }
}
@keyframes homeFeedFadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes postDetailCollapse {
to { opacity: 0; }
}
@keyframes postCardFadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes sharedTitleOut {
to { opacity: 0; }
}
@keyframes sharedTitleIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes sharedTimeOut {
to { opacity: 0.2; }
}
@keyframes sharedTimeIn {
from { opacity: 0.2; }
to { opacity: 1; }
}
@keyframes sharedSidebarOut {
to { opacity: 0.72; }
}
@keyframes sharedSidebarIn {
from { opacity: 0.72; }
to { opacity: 1; }
}
@keyframes slideIn {
from {
transform: translateX(40px);
@@ -906,6 +1171,34 @@ svg {
}
/* ===== 帖子详情页 ===== */
.post-page-layout {
display: flex;
gap: 28px;
max-width: 1200px;
margin: 0 auto;
width: 100%;
align-items: flex-start;
}
.post-page-main {
flex: 1;
min-width: 0;
padding-top: 0;
}
#postSidebar {
width: 240px;
flex-shrink: 0;
align-self: start;
}
.post-page-header {
max-width: 1200px;
margin-left: auto;
margin-right: auto;
width: 100%;
}
#pagePost .post-detail-card {
background: var(--glass-bg);
backdrop-filter: blur(16px);
@@ -923,6 +1216,10 @@ svg {
font-size: 22px;
}
#pagePost .post-detail-actions {
margin-top: 8px;
}
#repliesList {
margin-top: 4px;
}
@@ -1292,7 +1589,7 @@ svg {
/* ===== 响应式(保持原有) ===== */
@media (max-width: 768px) {
#sidebar {
.sidebar {
display: none;
}
#app {
@@ -1311,6 +1608,7 @@ svg {
.feed-header-left {
display: flex;
gap: 4px;
width: 100%;
}
.tab {
flex: 1;
@@ -1325,6 +1623,12 @@ svg {
.post-card {
padding: 14px 16px;
}
.post-page-layout {
display: block;
}
.post-page-main {
padding-top: 0;
}
.post-image {
max-width: 120px;
max-height: 100px;
@@ -1488,7 +1792,7 @@ svg {
}
[data-theme="dark"] .admin-sidebar {
background: var(--glass-bg);
background: #181826;
border-color: var(--glass-border);
}
[data-theme="dark"] .admin-nav-item:hover {
@@ -1505,7 +1809,7 @@ svg {
stroke: var(--primary);
}
[data-theme="dark"] .admin-content {
background: var(--glass-bg);
background: #181826;
border-color: var(--glass-border);
}
[data-theme="dark"] .admin-sidebar {
@@ -1541,7 +1845,7 @@ svg {
}
/* ============================================================
💬 私信模态框 —— 亮色模式修复
私信模态框 —— 亮色模式修复
============================================================ */
/* 亮色模式下私信列表模态框 + 聊天模态框 */
@@ -1602,7 +1906,7 @@ svg {
/* 暗色模式保持原样(不覆盖) */
/* ============================================================
⚠️ 自定义 CSS 警告模态框 —— 亮色模式文字修复
自定义 CSS 警告模态框 —— 亮色模式文字修复
============================================================ */
/* 亮色模式下警告模态框文字变深 */
@@ -1617,7 +1921,7 @@ svg {
}
/* ============================================================
🎨 自定义 CSS 按钮 —— 亮色模式修复
自定义 CSS 按钮 —— 亮色模式修复
============================================================ */
/* 亮色模式:删除自定义 CSS 按钮 */
@@ -1717,7 +2021,7 @@ svg {
color: #fff !important;
}
/* ============================================================
👤 用户个人主页 —— 卡片样式覆盖
用户个人主页 —— 卡片样式覆盖
============================================================ */
/* 用户主页的主卡片 */
@@ -2101,24 +2405,51 @@ a.btn-secondary {
border-radius: 10px;
font-size: 14px;
font-weight: 500;
color: #fff;
color: var(--glass-text);
border: 1px solid var(--glass-border);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
cursor: pointer;
animation: toastIn 0.25s cubic-bezier(0.22, 1, 0.36, 1);
display: flex;
align-items: center;
gap: 8px;
}
.toast-success {
background: rgba(34, 197, 94, 0.92);
background: rgba(255, 255, 255, 0.85);
border-color: #22c55e;
}
.toast-error {
background: rgba(239, 68, 68, 0.92);
background: rgba(255, 255, 255, 0.85);
border-color: #ef4444;
}
.toast-info {
background: rgba(91, 155, 213, 0.92);
.toast-warning {
background: rgba(255, 255, 255, 0.85);
border-color: #f59e0b;
}
.toast-success svg {
color: #22c55e;
}
.toast-error svg {
color: #ef4444;
}
.toast-warning svg {
color: #f59e0b;
}
[data-theme="dark"] .toast {
background: rgba(30, 30, 50, 0.85);
}
.toast.closing {
animation: toastOut 0.22s ease-in forwards;
}
@keyframes toastIn {
@@ -2126,6 +2457,65 @@ a.btn-secondary {
to { opacity: 1; transform: translateX(0); }
}
@keyframes toastOut {
from { opacity: 1; transform: translateX(0); }
to { opacity: 0; transform: translateX(24px); }
}
.modal.closing {
display: flex;
animation: modalFadeOut 0.32s ease-in forwards;
pointer-events: none;
}
@keyframes modalFadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
.modal.closing .modal-content {
animation: modalContentOut 0.32s cubic-bezier(0.4, 0, 1, 1) forwards;
}
@keyframes modalContentOut {
from { transform: translateY(0) scale(1); opacity: 1; }
to { transform: translateY(12px) scale(0.9); opacity: 0; }
}
.feedback-confirm {
z-index: 100001;
}
.feedback-confirm .modal-content {
max-width: 440px;
background: var(--modal-bg);
}
.feedback-confirm .modal-content p {
color: var(--glass-text-secondary);
line-height: 1.6;
overflow-wrap: anywhere;
}
.feedback-confirm-actions {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 24px;
}
.feedback-confirm-actions button {
border-radius: var(--radius-sm);
padding: 9px 18px;
cursor: pointer;
}
.feedback-confirm-actions .btn-danger {
border: 1px solid rgba(239, 68, 68, 0.5);
background: #dc2626;
color: #fff;
}
/* 设置页面侧边栏导航项 */
.settings-nav-item {
display: flex;
@@ -2163,6 +2553,12 @@ a.btn-secondary {
}
/* 设置页面侧边栏容器 */
.settings-layout {
max-width: none !important;
margin-left: 0 !important;
margin-right: 0 !important;
}
.settings-sidebar {
background: var(--glass-bg) !important;
backdrop-filter: blur(16px) !important;
@@ -2177,6 +2573,11 @@ a.btn-secondary {
/* 设置页面内容区 */
.settings-content {
flex: 1 1 0;
width: calc(100% - 228px) !important;
max-width: none !important;
min-width: 0;
overflow-wrap: anywhere;
background: var(--glass-bg) !important;
backdrop-filter: blur(16px) !important;
-webkit-backdrop-filter: blur(16px) !important;
@@ -2186,6 +2587,59 @@ a.btn-secondary {
box-shadow: var(--glass-shadow) !important;
}
.settings-content > *,
.settings-content [data-panel] {
max-width: 100%;
min-width: 0;
}
.language-toggle {
width: 220px;
max-width: 100%;
}
.language-toggle .tab {
min-width: 0;
white-space: nowrap;
}
@media (max-width: 768px) {
.settings-layout {
flex-direction: column;
gap: 12px !important;
}
.settings-sidebar {
position: static;
width: 100% !important;
}
.settings-nav {
display: flex;
width: 100%;
}
.settings-nav-item {
flex: 1 1 0;
min-width: 0;
justify-content: center;
padding: 8px 6px;
border-left: 0;
border-bottom: 3px solid transparent;
text-align: center;
white-space: normal;
}
.settings-nav-item.active {
border-left-color: transparent;
border-bottom-color: var(--primary);
}
.settings-content {
width: 100% !important;
}
}
/* 设置页面内部卡片 */
.settings-content [style*="background:var(--surface)"] {
background: rgba(255, 255, 255, 0.08) !important;
@@ -2255,7 +2709,7 @@ a.btn-secondary {
/* 暗色模式适配 */
[data-theme="dark"] .settings-sidebar {
background: var(--glass-bg) !important;
background: #181826 !important;
border-color: var(--glass-border) !important;
}
[data-theme="dark"] .settings-nav-item:hover {
@@ -2272,7 +2726,7 @@ a.btn-secondary {
stroke: var(--primary);
}
[data-theme="dark"] .settings-content {
background: var(--glass-bg) !important;
background: #181826 !important;
border-color: var(--glass-border) !important;
}
[data-theme="dark"] .settings-content input,
@@ -2283,6 +2737,46 @@ a.btn-secondary {
border-color: var(--glass-border) !important;
}
/* 详情页两列布局需要压过页面尾部的通用卡片与响应式覆盖。 */
#pagePost .post-page-layout {
display: flex !important;
gap: 28px !important;
width: 100% !important;
max-width: 1200px !important;
margin: 0 auto !important;
align-items: start !important;
}
#pagePost #postSidebar {
display: block !important;
width: 240px !important;
min-width: 240px !important;
flex: 0 0 240px !important;
align-self: start !important;
}
#pagePost .post-page-main {
display: block !important;
flex: 1 1 0 !important;
width: 100% !important;
min-width: 0 !important;
}
@media (max-width: 768px) {
#pagePost .post-page-layout {
display: block !important;
max-width: none !important;
}
#pagePost #postSidebar {
display: none !important;
}
#pagePost .post-page-main {
width: 100% !important;
}
}
/* ===== 小转圈(列表/局部加载) ===== */
.spinner-sm {
display: inline-block;
+11 -8
View File
@@ -5,10 +5,13 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { useToast } from './Toast';
export default function AccountSecurity() {
const { currentUser } = useApp();
const { t } = useTranslation();
const { toast } = useToast();
const [oldPassword, setOldPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [pwStatus, setPwStatus] = useState(null);
@@ -17,33 +20,33 @@ export default function AccountSecurity() {
const [emailStatus, setEmailStatus] = useState(null);
const changePassword = async () => {
if (!oldPassword || !newPassword) { alert(t('security.fillAll')); return; }
if (newPassword.length < 6) { alert(t('security.pwMin')); return; }
if (!oldPassword || !newPassword) { toast(t('security.fillAll'), 'warning'); return; }
if (newPassword.length < 6) { toast(t('security.pwMin'), 'warning'); return; }
try {
await API.updatePassword(currentUser.id, oldPassword, newPassword);
setPwStatus({ ok: true, msg: t('security.pwChanged') });
setOldPassword('');
setNewPassword('');
} catch (err) {
setPwStatus({ ok: false, msg: '❌ ' + err.message });
setPwStatus({ ok: false, msg: err.message });
}
};
const changeEmail = async () => {
if (!emailPassword || !newEmail) { alert(t('security.fillAll')); return; }
if (!emailPassword || !newEmail) { toast(t('security.fillAll'), 'warning'); return; }
try {
await API.updateEmail(currentUser.id, emailPassword, newEmail);
setEmailStatus({ ok: true, msg: t('security.emailChanged') });
setEmailPassword('');
setNewEmail('');
} catch (err) {
setEmailStatus({ ok: false, msg: '❌ ' + err.message });
setEmailStatus({ ok: false, 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: 12 }}>🔒 {t('security.title')}</h3>
<h3 style={{ fontSize: 16, marginBottom: 12 }}><Icon name="lock" size={16} /> {t('security.title')}</h3>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>{t('security.currentPw')}</label>
@@ -54,7 +57,7 @@ export default function AccountSecurity() {
<input type="password" value={newPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewPassword(e.target.value)} />
</div>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changePassword}>{t('security.changePw')}</button>
{pwStatus && <div style={{ fontSize: 13, marginTop: 6, color: pwStatus.ok ? '#22c55e' : '#ef4444' }}>{pwStatus.msg}</div>}
{pwStatus && <div style={{ fontSize: 13, marginTop: 6, color: pwStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={pwStatus.ok ? 'success' : 'error'} size={14} /> {pwStatus.msg}</div>}
<div style={{ borderTop: '1px solid var(--border)', margin: '16px 0' }}></div>
@@ -67,7 +70,7 @@ export default function AccountSecurity() {
<input type="email" value={newEmail} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewEmail(e.target.value)} />
</div>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changeEmail}>{t('security.changeEmail')}</button>
{emailStatus && <div style={{ fontSize: 13, marginTop: 6, color: emailStatus.ok ? '#22c55e' : '#ef4444' }}>{emailStatus.msg}</div>}
{emailStatus && <div style={{ fontSize: 13, marginTop: 6, color: emailStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={emailStatus.ok ? 'success' : 'error'} size={14} /> {emailStatus.msg}</div>}
</div>
);
}
+131 -10
View File
@@ -2,10 +2,47 @@
// 全局状态 Provider:用户、主题、论坛名、当前视图(feed/post/new/admin/...)
import { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react';
import { flushSync } from 'react-dom';
import { API, getTheme, setToken, getToken } from '@/lib/api';
const AppContext = createContext(null);
function stageSharedGeometry(transition, { name, duration, moveOffset, preserveSizeUntilMove = false }) {
transition.ready.then(() => {
const groupAnimation = document.getAnimations().find(
(animation) => animation.effect?.pseudoElement === `::view-transition-group(${name})`
);
const frames = groupAnimation?.effect?.getKeyframes();
if (!groupAnimation || !frames || frames.length < 2) return;
const start = frames[0];
const end = frames[frames.length - 1];
groupAnimation.effect.setKeyframes([
{
offset: 0,
width: start.width,
height: start.height,
transform: start.transform,
easing: 'cubic-bezier(0.16, 1, 0.3, 1)',
},
{
offset: moveOffset,
width: preserveSizeUntilMove ? start.width : end.width,
height: start.height,
transform: end.transform,
easing: 'cubic-bezier(0.4, 0, 0.2, 1)',
},
{
offset: 1,
width: end.width,
height: end.height,
transform: end.transform,
},
]);
groupAnimation.effect.updateTiming({ duration, easing: 'linear', fill: 'both' });
}).catch(() => {});
}
export function useApp() {
return useContext(AppContext);
}
@@ -17,6 +54,7 @@ export default function AppProvider({ children, cachedName = '' }) {
const [theme, setThemeState] = useState('light');
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom
const [currentPostId, setCurrentPostId] = useState(null);
const [currentPostPreview, setCurrentPostPreview] = useState(null);
const [currentUsername, setCurrentUsername] = useState(null);
const [currentPageName, setCurrentPageName] = useState(null);
const [sort, setSort] = useState('latest');
@@ -166,20 +204,101 @@ export default function AppProvider({ children, cachedName = '' }) {
url.searchParams.set('page', page);
url.searchParams.delete('post');
}
window.history.pushState({ page }, '', url);
setView(page);
setCurrentPostId(null);
refresh();
}, [refresh]);
const commitNavigation = (refreshFeed = true) => {
window.history.pushState({ page }, '', url);
setView(page);
setCurrentPostId(null);
setCurrentPostPreview(null);
if (refreshFeed) refresh();
};
const openPost = useCallback((postId) => {
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
if (page !== 'feed' || view === 'feed' || !document.startViewTransition || reduceMotion) {
commitNavigation();
return;
}
let targetCard = currentPostId
? Array.from(document.querySelectorAll('[data-post-id]')).find((element) => element.dataset.postId === String(currentPostId))
: null;
let targetTitle = null;
let targetTime = null;
document.documentElement.classList.add('home-view-transition');
if (targetCard) document.documentElement.classList.add('returning-home');
const transition = document.startViewTransition(() => {
flushSync(() => commitNavigation(false));
targetCard = currentPostId
? Array.from(document.querySelectorAll('[data-post-id]')).find((element) => element.dataset.postId === String(currentPostId))
: null;
targetTitle = targetCard?.querySelector('.post-title');
targetTime = targetCard?.querySelector('.post-time');
if (targetCard) targetCard.style.viewTransitionName = 'post-expand';
if (targetTitle) targetTitle.style.viewTransitionName = 'post-heading';
if (targetTime) targetTime.style.viewTransitionName = 'post-time';
});
stageSharedGeometry(transition, { name: 'post-expand', duration: 480, moveOffset: 0.72 });
stageSharedGeometry(transition, {
name: 'post-heading',
duration: 480,
moveOffset: 0.72,
preserveSizeUntilMove: true,
});
const clearTargetNames = () => {
if (targetCard) targetCard.style.viewTransitionName = '';
if (targetTitle) targetTitle.style.viewTransitionName = '';
if (targetTime) targetTime.style.viewTransitionName = '';
};
transition.ready.then(clearTargetNames, clearTargetNames);
transition.finished.finally(() => {
document.documentElement.classList.remove('home-view-transition', 'returning-home');
refresh();
});
}, [currentPostId, refresh, view]);
const openPost = useCallback((postId, sourceElement = null, preview = null) => {
const url = new URL(window.location);
url.searchParams.set('post', postId);
url.searchParams.delete('page');
url.searchParams.delete('user');
window.history.pushState({ page: 'post', postId }, '', url);
setView('post');
setCurrentPostId(postId);
const commitNavigation = () => {
window.history.pushState({ page: 'post', postId }, '', url);
setView('post');
setCurrentPostId(postId);
setCurrentPostPreview(preview);
};
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
if (!sourceElement || !document.startViewTransition || reduceMotion) {
commitNavigation();
return;
}
const sourceTitle = sourceElement.querySelector('.post-title');
const sourceTime = sourceElement.querySelector('.post-time');
sourceElement.style.viewTransitionName = 'post-expand';
if (sourceTitle) sourceTitle.style.viewTransitionName = 'post-heading';
if (sourceTime) sourceTime.style.viewTransitionName = 'post-time';
document.documentElement.classList.add('post-view-transition');
const transition = document.startViewTransition(() => {
flushSync(commitNavigation);
});
stageSharedGeometry(transition, { name: 'post-expand', duration: 960, moveOffset: 0.62 });
stageSharedGeometry(transition, {
name: 'post-heading',
duration: 960,
moveOffset: 0.62,
preserveSizeUntilMove: true,
});
const clearSourceNames = () => {
sourceElement.style.viewTransitionName = '';
if (sourceTitle) sourceTitle.style.viewTransitionName = '';
if (sourceTime) sourceTime.style.viewTransitionName = '';
};
transition.ready.then(clearSourceNames, clearSourceNames);
transition.finished.finally(() => {
document.documentElement.classList.remove('post-view-transition');
});
}, []);
const openUser = useCallback((username) => {
@@ -209,6 +328,7 @@ export default function AppProvider({ children, cachedName = '' }) {
if (state.postId) {
setView('post');
setCurrentPostId(state.postId);
setCurrentPostPreview(null);
} else if (state.username) {
setView('user');
setCurrentUsername(state.username);
@@ -218,6 +338,7 @@ export default function AppProvider({ children, cachedName = '' }) {
} else {
setView(state.page || 'feed');
setCurrentPostId(null);
setCurrentPostPreview(null);
setCurrentUsername(null);
setCurrentPageName(null);
}
@@ -262,7 +383,7 @@ export default function AppProvider({ children, cachedName = '' }) {
forumName, forumNameLoaded, updateForumName,
theme, toggleTheme,
view, navigate,
currentPostId, openPost,
currentPostId, currentPostPreview, openPost,
currentUsername, openUser,
currentPageName, openCustomPage,
sort, setSort,
+68 -25
View File
@@ -8,6 +8,7 @@ import { useApp } from './AppProvider';
import { Icon } from './Icons';
import ImageViewer from './ImageViewer';
import { renderMarkdown } from '@/lib/markdown';
import { useToast } from './Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
@@ -17,17 +18,21 @@ function avatar(username) {
export default function Feed({ onOpenModal, onReport }) {
const { currentUser, sort, setSort, openPost, openUser, navigate, refreshKey } = useApp();
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [posts, setPosts] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [viewerSrc, setViewerSrc] = useState(null);
const [selectedSort, setSelectedSort] = useState(sort);
const [drawerPhase, setDrawerPhase] = useState('idle');
const postListRef = useRef(null);
const sortTimerRef = useRef(null);
const pendingSortRef = useRef(null);
const PAGE_SIZE = 20;
const load = useCallback(async (targetPage) => {
setPosts(null);
setError(null);
try {
const result = await API.getPosts(sort, null, targetPage, PAGE_SIZE);
@@ -37,6 +42,16 @@ export default function Feed({ onOpenModal, onReport }) {
} catch (err) {
setError(err.message);
setPosts([]);
} finally {
if (pendingSortRef.current === sort) {
requestAnimationFrame(() => {
setDrawerPhase('opening');
sortTimerRef.current = setTimeout(() => {
pendingSortRef.current = null;
setDrawerPhase('idle');
}, 360);
});
}
}
}, [sort, refreshKey]);
@@ -58,13 +73,37 @@ export default function Feed({ onOpenModal, onReport }) {
// 排序切换时回第一页
useEffect(() => { setPage(1); }, [sort]);
useEffect(() => () => clearTimeout(sortTimerRef.current), []);
const handleSortChange = (nextSort) => {
if (nextSort === selectedSort) return;
setSelectedSort(nextSort);
clearTimeout(sortTimerRef.current);
// 快速切回当前排序时,直接重新展开尚未替换的列表。
if (nextSort === sort) {
pendingSortRef.current = null;
setDrawerPhase('opening');
sortTimerRef.current = setTimeout(() => setDrawerPhase('idle'), 360);
return;
}
setDrawerPhase('closing');
sortTimerRef.current = setTimeout(() => {
pendingSortRef.current = nextSort;
setDrawerPhase('closed');
setSort(nextSort);
}, 220);
};
const handleDelete = async (postId) => {
if (!confirm(t('feed.confirmDelete'))) return;
if (!await confirmAction(t('feed.confirmDelete'))) return;
try {
await API.deletePost(postId);
load(page);
} catch (err) {
alert(t('feed.deleteFailed', { msg: err.message }));
toast(t('feed.deleteFailed', { msg: err.message }), 'error');
}
};
@@ -72,34 +111,36 @@ 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')}>{t('feed.latest')}</button>
<button className={'tab' + (sort === 'hot' ? ' active' : '')} onClick={() => setSort('hot')}>{t('feed.hot')}</button>
<button className={'tab' + (selectedSort === 'latest' ? ' active' : '')} onClick={() => handleSortChange('latest')}>{t('feed.latest')}</button>
<button className={'tab' + (selectedSort === 'hot' ? ' active' : '')} onClick={() => handleSortChange('hot')}>{t('feed.hot')}</button>
</div>
<button
className="btn-primary fab-btn"
onClick={() => {
if (!currentUser) { alert(t('newPost.pleaseLogin')); return; }
if (!currentUser) { toast(t('newPost.pleaseLogin'), 'warning'); return; }
navigate('new');
}}
>
<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" />{t('feed.loading')}</div>
) : error ? (
<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' }}>{t('feed.empty')}</div>
) : (
posts.map((p) => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
return (
<div key={p.id} className="post-card" style={{ cursor: 'pointer' }}
onClick={() => openPost(p.id)}>
<div className={'feed-posts-drawer ' + drawerPhase}>
<div className="feed-posts-drawer-inner">
<div id="postList" ref={postListRef}>
{posts === null ? (
<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' }}>{t('feed.loadFailed', { msg: error })}</div>
) : posts.length === 0 ? (
<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') : '';
return (
<div key={p.id} className="post-card" data-post-id={p.id} style={{ cursor: 'pointer' }}
onClick={(e) => openPost(p.id, e.currentTarget, p)}>
{p.is_pinned && (
<div style={{ fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}>{t('feed.pinned')}</div>
<div style={{ fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}><Icon name="pin" size={12} /> {t('feed.pinned')}</div>
)}
<div className="post-header">
<img src={p.avatar_url || avatar(p.username)} className="post-avatar" alt="" />
@@ -130,7 +171,7 @@ export default function Feed({ onOpenModal, onReport }) {
</span>
<button className="action-report" onClick={(e) => {
e.stopPropagation();
if (!currentUser) { alert(t('newPost.pleaseLogin')); return; }
if (!currentUser) { toast(t('newPost.pleaseLogin'), 'warning'); return; }
onReport(p.id);
}}>
<Icon name="flag" size={14} /> {t('feed.report')}
@@ -144,10 +185,12 @@ export default function Feed({ onOpenModal, onReport }) {
</button>
)}
</div>
</div>
);
})
)}
</div>
);
})
)}
</div>
</div>
</div>
{totalPages > 1 && posts && posts.length > 0 && (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 6, padding: '16px 0', marginTop: 8, borderTop: '1px solid var(--border)', flexWrap: 'wrap' }}>
+90
View File
@@ -87,6 +87,11 @@ const PATHS = {
<path d="M12 5v14"/><path d="M5 12h14"/>
</>
),
back: (
<>
<polyline points="15 18 9 12 15 6"/>
</>
),
close: (
<>
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
@@ -97,4 +102,89 @@ const PATHS = {
<polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
</>
),
success: (
<>
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>
</>
),
error: (
<>
<circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>
</>
),
warning: (
<>
<path d="M12 9v4"/><path d="M12 17h.01"/><circle cx="12" cy="12" r="10"/>
</>
),
pending: (
<>
<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
</>
),
edit: (
<>
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
</>
),
pin: (
<>
<path d="M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8.5"/><polyline points="16 2 22 8 16 8"/><line x1="10" y1="14" x2="18" y2="14"/><line x1="10" y1="18" x2="14" y2="18"/>
</>
),
camera: (
<>
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/>
</>
),
image: (
<>
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>
</>
),
key: (
<>
<path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>
</>
),
calendar: (
<>
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
</>
),
refresh: (
<>
<polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
</>
),
list: (
<>
<line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/>
</>
),
megaphone: (
<>
<path d="M17 18.5c0 1.5-1.5 3-3.5 3s-3.5-1.5-3.5-3c0-.5.5-1 1-1h5c.5 0 1 .5 1 1z"/><path d="M4 11h16v6H4z"/><path d="M8 17v3"/><path d="M16 17v3"/><path d="M9 11V7a3 3 0 0 1 6 0v4"/>
</>
),
code: (
<>
<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>
</>
),
upload: (
<>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>
</>
),
save: (
<>
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/>
</>
),
flag: (
<>
<path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/>
</>
),
};
+3 -3
View File
@@ -6,7 +6,7 @@ import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
const TYPE_MAP = { reply: '💬', post_deleted: '🗑️', report_handled: '🛡️', system: '📢' };
const TYPE_MAP = { reply: 'message', post_deleted: 'trash', report_handled: 'shield', system: 'megaphone' };
export default function MessagesPage() {
const { currentUser } = useApp();
@@ -46,11 +46,11 @@ export default function MessagesPage() {
</div>
) : (
notifications.map((n) => {
const icon = TYPE_MAP[n.type] || '📌';
const icon = TYPE_MAP[n.type] || 'pin';
const time = n.created_at ? new Date(n.created_at).toLocaleString('zh-CN') : '';
return (
<div key={n.id} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px', borderBottom: '1px solid var(--border-light)', background: 'var(--surface)', borderRadius: 6, marginBottom: 6 }}>
<span style={{ fontSize: 20 }}>{icon}</span>
<span style={{ color: 'var(--text-secondary)', paddingTop: 2 }}><Icon name={icon} size={20} /></span>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 14 }}>{n.title}</div>
<div style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 2 }}>{n.content}</div>
+11 -9
View File
@@ -7,10 +7,12 @@ import { API, generateCaptcha } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import CaptchaImage from './CaptchaImage';
import { useToast } from './Toast';
export default function Modals({ modal, onClose, reportPostId }) {
const { login, register, currentUser, refresh } = useApp();
const { t } = useTranslation();
const { toast } = useToast();
// 登录表单
const [loginEmail, setLoginEmail] = useState('');
@@ -38,7 +40,7 @@ export default function Modals({ modal, onClose, reportPostId }) {
};
const handleLogin = async () => {
if (!loginEmail.trim() || !loginPassword) { alert('请填写完整信息'); return; }
if (!loginEmail.trim() || !loginPassword) { toast('请填写完整信息', 'warning'); return; }
try {
const result = await login(loginEmail.trim(), loginPassword);
if (result.user) {
@@ -48,15 +50,15 @@ export default function Modals({ modal, onClose, reportPostId }) {
refresh();
}
} catch (err) {
alert('登录失败:' + err.message);
toast('登录失败:' + err.message, 'error');
}
};
const handleRegister = async () => {
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { alert('请填写完整信息'); return; }
if (regPassword.length < 6) { alert('密码至少6位'); return; }
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { toast('请填写完整信息', 'warning'); return; }
if (regPassword.length < 6) { toast('密码至少6位', 'warning'); return; }
if (!regCaptcha || parseInt(regCaptchaInput) !== regCaptcha.answer) {
alert('验证码错误,请重新计算');
toast('验证码错误,请重新计算', 'warning');
setRegCaptcha(generateCaptcha());
setRegCaptchaInput('');
return;
@@ -68,10 +70,10 @@ export default function Modals({ modal, onClose, reportPostId }) {
setRegEmail('');
setRegPassword('');
setRegCaptchaInput('');
alert('注册成功!');
toast('注册成功!', 'success');
refresh();
} catch (err) {
alert('注册失败:' + err.message);
toast('注册失败:' + err.message, 'error');
}
};
@@ -80,9 +82,9 @@ export default function Modals({ modal, onClose, reportPostId }) {
try {
await API.createReport(reportPostId, reportReason);
onClose();
alert('举报已提交,管理员将尽快处理');
toast('举报已提交,管理员将尽快处理', 'success');
} catch (err) {
alert('举报失败:' + err.message);
toast('举报失败:' + err.message, 'error');
}
};
+6 -4
View File
@@ -7,10 +7,12 @@ import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { API } from '@/lib/api';
import { DMButton } from './chat/ChatManager';
import { useToast } from './Toast';
export default function Navbar({ onOpenModal }) {
const { currentUser, forumName, theme, toggleTheme, navigate, openCustomPage, logout } = useApp();
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [menuOpen, setMenuOpen] = useState(false);
const [customPages, setCustomPages] = useState([]);
@@ -37,7 +39,7 @@ export default function Navbar({ onOpenModal }) {
const goPage = (page) => {
if (page === 'admin' && currentUser?.role !== 'admin') {
alert('无权限访问');
toast('无权限访问', 'warning');
return;
}
setMenuOpen(false);
@@ -47,7 +49,7 @@ export default function Navbar({ onOpenModal }) {
const openMessages = (e) => {
e.preventDefault();
setMenuOpen(false);
// 消息页 = 通知列表(与原版一致),私信走导航栏 ✉️ 按钮
// 消息页展示通知列表,私信使用导航栏按钮。
navigate('messages');
};
@@ -117,9 +119,9 @@ export default function Navbar({ onOpenModal }) {
<hr />
<a
href="#"
onClick={(e) => {
onClick={async (e) => {
e.preventDefault();
if (confirm(t('nav.logoutConfirm'))) {
if (await confirmAction(t('nav.logoutConfirm'))) {
setMenuOpen(false);
logout();
}
+4 -3
View File
@@ -30,7 +30,7 @@ export default function NewPost() {
for (const file of files) {
if (!file.type.startsWith('image/')) continue;
if (file.size > 5 * 1024 * 1024) {
alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传');
toast('图片 ' + file.name + ' 超过 5MB,请压缩后上传', 'warning');
continue;
}
const dataUrl = await new Promise((resolve) => {
@@ -44,7 +44,7 @@ export default function NewPost() {
}
setPreviews((prev) => [...prev, ...newPreviews]);
} catch (err) {
alert('上传失败:' + err.message);
toast('上传失败:' + err.message, 'error');
} finally {
setUploading(false);
}
@@ -117,8 +117,9 @@ export default function NewPost() {
onDragLeave={(e) => { e.preventDefault(); setDragOver(false); }}
onDrop={(e) => { e.preventDefault(); setDragOver(false); if (e.dataTransfer.files) handleFiles(Array.from(e.dataTransfer.files)); }}
>
{!uploading && !dragOver && <Icon name="image" size={32} style={{ display: 'block', margin: '0 auto 8px', color: 'var(--text-secondary)' }} />}
<div style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
{uploading ? t('newPost.uploading') : (dragOver ? t('newPost.drop') : '📷 ' + t('newPost.dropHint'))}
{uploading ? t('newPost.uploading') : (dragOver ? t('newPost.drop') : t('newPost.dropHint'))}
</div>
</div>
<input
+73 -64
View File
@@ -5,18 +5,21 @@ import { useEffect, useState, useCallback, useRef } from 'react';
import { API, uploadImage } from '@/lib/api';
import { useApp } from './AppProvider';
import ReplyList from './ReplyList';
import Sidebar from './Sidebar';
import { Icon } from './Icons';
import ImageViewer from './ImageViewer';
import { renderMarkdown } from '@/lib/markdown';
import { useToast } from './Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
'&background=6366f1&color=fff&size=64';
}
export default function PostDetail({ postId }) {
export default function PostDetail({ postId, initialPost = null }) {
const { currentUser, navigate, openUser, refreshKey } = useApp();
const [post, setPost] = useState(null);
const { toast, confirmAction } = useToast();
const [post, setPost] = useState(initialPost);
const [error, setError] = useState(null);
const [viewerSrc, setViewerSrc] = useState(null);
const [editing, setEditing] = useState(false);
@@ -46,7 +49,7 @@ export default function PostDetail({ postId }) {
);
}
if (!post) {
return <div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>;
return <div id="pagePost" className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8' }}><span className="spinner-sm" />加载中...</div>;
}
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
@@ -55,23 +58,23 @@ export default function PostDetail({ postId }) {
const canEdit = currentUser && currentUser.id === post.user_id;
const handleDelete = async () => {
if (!confirm('确定要删除这条帖子吗?')) return;
if (!await confirmAction('确定要删除这条帖子吗?')) return;
try {
await API.deletePost(postId);
alert('删除成功');
toast('删除成功', 'success');
navigate('feed');
} catch (err) {
alert('删除失败:' + err.message);
toast('删除失败:' + err.message, 'error');
}
};
const handleTogglePin = async () => {
if (!confirm('确定要' + (post.is_pinned ? '取消' : '') + '置顶吗?')) return;
if (!await confirmAction('确定要' + (post.is_pinned ? '取消' : '') + '置顶吗?', { danger: false })) return;
try {
await API.togglePinPost(postId);
load();
} catch (err) {
alert('操作失败:' + err.message);
toast('操作失败:' + err.message, 'error');
}
};
@@ -83,27 +86,27 @@ export default function PostDetail({ postId }) {
};
const handleSaveEdit = async () => {
if (!editContent.trim()) { alert('请填写内容'); return; }
if (!editContent.trim()) { toast('请填写内容', 'warning'); return; }
try {
await API.updatePost(postId, editTitle.trim() || '无标题', editContent.trim(), editImages);
setEditing(false);
load();
} catch (err) {
alert('编辑失败:' + err.message);
toast('编辑失败:' + err.message, 'error');
}
};
// 编辑时上传新图片
const handleEditUpload = async (file) => {
if (!file) return;
if (!file.type.startsWith('image/')) { alert('请选择图片文件'); return; }
if (file.size > 5 * 1024 * 1024) { alert('图片不能超过 5MB'); return; }
if (!file.type.startsWith('image/')) { toast('请选择图片文件', 'warning'); return; }
if (file.size > 5 * 1024 * 1024) { toast('图片不能超过 5MB', 'warning'); return; }
setEditUploading(true);
try {
const url = await uploadImage(file);
setEditImages((prev) => [...prev, url]);
} catch (err) {
alert('上传失败:' + err.message);
toast('上传失败:' + err.message, 'error');
} finally {
setEditUploading(false);
}
@@ -116,68 +119,74 @@ export default function PostDetail({ postId }) {
return (
<div id="pagePost" className="page-slide active">
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<div className="page-header post-page-header">
<button className="back-btn" onClick={() => navigate('feed')}>
<Icon name="back" size={16} /> 返回
</button>
<h2>{post.title || '帖子详情'}</h2>
</div>
<div id="postDetailContent" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<div className="post-detail-card">
<div className="post-header">
<img src={post.avatar_url || avatar(post.username)} className="post-avatar" alt="" />
<span
className="post-username"
style={{ cursor: 'pointer', color: 'var(--primary)' }}
onClick={() => openUser(post.username)}
>
{post.username || '匿名用户'}
</span>
<span className="post-time">{time}</span>
{post.edited_at && (
<span style={{ fontSize: 12, color: 'var(--text-light)', marginLeft: 8 }}>
(已编辑 {new Date(post.edited_at).toLocaleString('zh-CN')})
<div className="post-page-layout">
<Sidebar id="postSidebar" />
<div id="postDetailContent" className="post-page-main">
<div className="post-detail-card">
<div className="post-header">
<img src={post.avatar_url || avatar(post.username)} className="post-avatar" alt="" />
<span
className="post-username"
style={{ cursor: 'pointer', color: 'var(--primary)' }}
onClick={() => openUser(post.username)}
>
{post.username || '匿名用户'}
</span>
)}
{post.is_pinned && (
<span style={{ fontSize: 12, color: 'var(--primary)', marginLeft: 8 }}>📌 置顶</span>
)}
<div style={{ display: 'flex', gap: 4, marginLeft: 'auto' }}>
{currentUser && currentUser.role === 'admin' && (
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleTogglePin}>
{post.is_pinned ? '📌 取消置顶' : '📌 置顶'}
</button>
<span className="post-time">{time}</span>
{post.edited_at && (
<span style={{ fontSize: 12, color: 'var(--text-light)', marginLeft: 8 }}>
(已编辑 {new Date(post.edited_at).toLocaleString('zh-CN')})
</span>
)}
{canDelete && (
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleEdit}>
✏️ 编辑
</button>
)}
{canDelete && (
<button className="btn-sm btn-danger" style={{ padding: '4px 10px' }} onClick={handleDelete}>
<Icon name="trash" size={14} /> 删除
</button>
{post.is_pinned && (
<span style={{ fontSize: 12, color: 'var(--primary)', marginLeft: 8, display: 'inline-flex', alignItems: 'center', gap: 3 }}><Icon name="pin" size={12} /> 置顶</span>
)}
<div style={{ display: 'flex', gap: 4, marginLeft: 'auto' }}>
{currentUser && currentUser.role === 'admin' && (
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleTogglePin}>
<Icon name="pin" size={12} /> {post.is_pinned ? '取消置顶' : '置顶'}
</button>
)}
{canEdit && (
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleEdit}>
<Icon name="edit" size={12} /> 编辑
</button>
)}
{canDelete && (
<button className="btn-sm btn-danger" style={{ padding: '4px 10px' }} onClick={handleDelete}>
<Icon name="trash" size={14} /> 删除
</button>
)}
</div>
</div>
<div className="post-content" style={{ fontSize: 16, lineHeight: 1.8 }} dangerouslySetInnerHTML={{ __html: renderMarkdown(post.content) }} />
{post.images && post.images.length > 0 && (
<div className="post-images">
{post.images.map((img, i) => (
<img key={i} src={img} className="post-image" alt="" style={{ cursor: 'pointer' }} onClick={() => setViewerSrc(img)} />
))}
</div>
)}
{post.signature && (
<div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border-light)', fontSize: 12, color: 'var(--text-secondary)' }} dangerouslySetInnerHTML={{ __html: renderMarkdown(post.signature) }} />
)}
</div>
<div className="post-content" style={{ fontSize: 16, lineHeight: 1.8 }} dangerouslySetInnerHTML={{ __html: renderMarkdown(post.content) }} />
{post.images && post.images.length > 0 && (
<div className="post-images">
{post.images.map((img, i) => (
<img key={i} src={img} className="post-image" alt="" style={{ cursor: 'pointer' }} onClick={() => setViewerSrc(img)} />
))}
</div>
)}
{post.signature && (
<div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border-light)', fontSize: 12, color: 'var(--text-secondary)' }} dangerouslySetInnerHTML={{ __html: renderMarkdown(post.signature) }} />
)}
<ReplyList postId={postId} onRefresh={load} />
</div>
<ReplyList postId={postId} onRefresh={load} />
</div>
{/* 编辑帖子 modal */}
{editing && (
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) setEditing(false); }}>
<div className="modal-content" style={{ maxWidth: 600, position: 'relative' }}>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, fontSize: 24, cursor: 'pointer', color: 'var(--text-light)' }} onClick={() => setEditing(false)}>&times;</span>
<h2 style={{ marginBottom: 16 }}>✏️ 编辑帖子</h2>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={() => setEditing(false)}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}><Icon name="edit" size={20} /> 编辑帖子</h2>
<input
type="text"
placeholder="标题"
@@ -202,15 +211,15 @@ export default function PostDetail({ postId }) {
type="button"
title="删除图片"
onClick={() => handleEditRemoveImage(img)}
style={{ position: 'absolute', top: -6, right: -6, width: 20, height: 20, borderRadius: '50%', background: '#ef4444', color: '#fff', border: 'none', cursor: 'pointer', fontSize: 12, lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
>&times;</button>
style={{ position: 'absolute', top: -6, right: -6, width: 20, height: 20, borderRadius: '50%', background: '#ef4444', color: '#fff', border: 'none', cursor: 'pointer', lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
><Icon name="close" size={12} /></button>
</div>
))}
</div>
)}
<div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
<button type="button" className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={() => editImageInputRef.current?.click()}>
{editUploading ? '上传中...' : '📷 上传图片'}
{editUploading ? '上传中...' : <><Icon name="camera" size={14} /> 上传图片</>}
</button>
<input type="file" ref={editImageInputRef} accept="image/*" multiple style={{ display: 'none' }} onChange={(e) => { const files = e.target.files; if (files && files.length > 0) { [...files].forEach((f) => handleEditUpload(f)); e.target.value = ''; } }} />
</div>
+22 -10
View File
@@ -4,11 +4,23 @@
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from './Icons';
import { useToast } from './Toast';
export default function RecoveryCodes() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [count, setCount] = useState(0);
const [modal, setModal] = useState(null); // null | {codes, isNew}
const [modalClosing, setModalClosing] = useState(false);
const closeModal = () => {
setModalClosing(true);
setTimeout(() => {
setModal(null);
setModalClosing(false);
}, 340);
};
const loadCount = () => {
API.getRecoveryCodeCount().then((d) => setCount(d.count || 0)).catch(() => {});
@@ -16,13 +28,13 @@ export default function RecoveryCodes() {
useEffect(loadCount, []);
const regenerate = async () => {
if (!confirm(t('recovery.confirmRegenerate'))) return;
if (!await confirmAction(t('recovery.confirmRegenerate'))) return;
try {
const d = await API.generateRecoveryCodes();
setModal({ codes: d.codes || [], isNew: true });
loadCount();
} catch (err) {
alert(t('recovery.genFailed', { msg: err.message }));
toast(t('recovery.genFailed', { msg: err.message }), 'error');
}
};
@@ -33,32 +45,32 @@ export default function RecoveryCodes() {
setModal({ codes: d.codes || [], isNew: false });
loadCount();
} catch (err) {
alert(t('recovery.fetchFailed', { msg: err.message }));
toast(t('recovery.fetchFailed', { msg: err.message }), 'error');
}
};
return (
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<h3 style={{ fontSize: 16, marginBottom: 8 }}>🔑 {t('recovery.title')}</h3>
<h3 style={{ fontSize: 16, marginBottom: 8 }}><Icon name="key" size={16} /> {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}>📋 {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>
<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}><Icon name="list" size={14} /> {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}><Icon name="refresh" size={14} /> {t('recovery.regenerate')}</button>
</div>
<div id="recoveryCodesStatus" style={{ fontSize: 13, color: 'var(--text-light)', marginTop: 8 }}>{t('recovery.remaining', { count })}</div>
{modal && (
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) setModal(null); }}>
<div className={'modal active' + (modalClosing ? ' closing' : '')} style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) closeModal(); }}>
<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)}>&times;</span>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={closeModal}><Icon name="close" size={20} /></span>
<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>
<p style={{ fontSize: 13, color: '#ef4444', marginBottom: 12, display: 'flex', alignItems: 'flex-start', gap: 6 }}><Icon name="warning" size={14} /> {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)}>{t('recovery.saved')}</button>
<button className="btn-primary" style={{ width: '100%', padding: 10, marginTop: 16 }} onClick={closeModal}>{t('recovery.saved')}</button>
</div>
</div>
)}
+9 -7
View File
@@ -7,6 +7,7 @@ import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { renderMarkdown } from '@/lib/markdown';
import CaptchaImage from './CaptchaImage';
import { useToast } from './Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
@@ -15,6 +16,7 @@ function avatar(username) {
export default function ReplyList({ postId, onRefresh }) {
const { currentUser, openUser } = useApp();
const { toast, confirmAction } = useToast();
const [replies, setReplies] = useState([]);
const [content, setContent] = useState('');
const [captcha, setCaptcha] = useState(null);
@@ -31,10 +33,10 @@ export default function ReplyList({ postId, onRefresh }) {
useEffect(() => { setCaptcha(generateCaptcha()); }, [postId]);
const handleSubmit = async () => {
if (!currentUser) { alert('请先登录'); return; }
if (!content.trim()) { alert('请填写回复内容'); return; }
if (!currentUser) { toast('请先登录', 'warning'); return; }
if (!content.trim()) { toast('请填写回复内容', 'warning'); return; }
if (!captcha || parseInt(captchaInput) !== captcha.answer) {
alert('验证码错误,请重新计算');
toast('验证码错误,请重新计算', 'warning');
setCaptcha(generateCaptcha());
setCaptchaInput('');
return;
@@ -48,17 +50,17 @@ export default function ReplyList({ postId, onRefresh }) {
load();
onRefresh();
} catch (err) {
alert('回复失败:' + err.message);
toast('回复失败:' + err.message, 'error');
}
};
const handleDelete = async (replyId) => {
if (!confirm('确定要删除这条回复吗?')) return;
if (!await confirmAction('确定要删除这条回复吗?')) return;
try {
await API.deleteReply(replyId);
load();
} catch (err) {
alert('删除失败:' + err.message);
toast('删除失败:' + err.message, 'error');
}
};
@@ -69,7 +71,7 @@ export default function ReplyList({ postId, onRefresh }) {
</div>
<div style={{ marginTop: 12 }}>
{replies.length === 0 ? (
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有回复,快来抢沙发吧 🛋️</div>
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}><Icon name="message" size={16} /> 还没有回复,快来发表第一条回复吧</div>
) : (
replies.map((r) => {
const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '';
+2 -2
View File
@@ -47,10 +47,10 @@ export default function SettingsPage() {
return (
<div className="page-slide active">
<div className="page-header" style={{ maxWidth: 1200, margin: '0 auto', width: '100%' }}>
<div className="page-header" style={{ width: '100%' }}>
<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' }}>
<div className="settings-layout" style={{ width: '100%', display: 'flex', gap: 28, alignItems: 'flex-start' }}>
<aside className="settings-sidebar" style={{ width: 200, flexShrink: 0 }}>
<nav className="settings-nav">
{NAV.map((n) => (
+26 -21
View File
@@ -6,10 +6,13 @@ import { useTranslation } from 'react-i18next';
import { API, uploadImage } from '@/lib/api';
import { useApp } from './AppProvider';
import { setAppLanguage } from '@/lib/i18n';
import { Icon } from './Icons';
import { useToast } from './Toast';
export default function SettingsProfile() {
const { currentUser, setCurrentUser } = useApp();
const { t, i18n } = useTranslation();
const { toast } = useToast();
const [username, setUsername] = useState(currentUser?.username || '');
const [bio, setBio] = useState(currentUser?.bio || '');
const [signature, setSignature] = useState(currentUser?.signature || '');
@@ -19,29 +22,29 @@ export default function SettingsProfile() {
const handleAvatar = async (file) => {
if (!file) return;
if (!file.type.startsWith('image/')) { setAvatarStatus({ ok: false, msg: '❌ 请选择图片文件' }); return; }
if (file.size > 5 * 1024 * 1024) { setAvatarStatus({ ok: false, msg: '❌ 图片不能超过 5MB' }); return; }
if (!file.type.startsWith('image/')) { setAvatarStatus({ ok: false, msg: t('settings.avatarFileRequired') }); return; }
if (file.size > 5 * 1024 * 1024) { setAvatarStatus({ ok: false, msg: t('settings.avatarTooLarge') }); return; }
try {
const url = await uploadImage(file);
await API.updateAvatar(currentUser.id, url);
setAvatarUrl(url);
setCurrentUser({ ...currentUser, avatar_url: url });
setAvatarStatus({ ok: true, msg: '✅ 头像已更新' });
setAvatarStatus({ ok: true, msg: t('settings.avatarUpdated') });
} catch (err) {
setAvatarStatus({ ok: false, msg: '❌ ' + err.message });
setAvatarStatus({ ok: false, msg: err.message });
}
};
const handleSave = async () => {
if (!currentUser) { alert('请先登录'); return; }
if (!username.trim()) { alert('用户名不能为空'); return; }
if (!currentUser) { toast(t('settings.pleaseLogin'), 'warning'); return; }
if (!username.trim()) { toast(t('settings.usernameRequired'), 'warning'); return; }
try {
const data = await API.updateProfile(currentUser.id, username.trim(), bio.trim(), signature.trim());
if (data.error) throw new Error(data.error);
setCurrentUser({ ...currentUser, username: username.trim(), bio: bio.trim(), signature: signature.trim() });
alert('保存成功!');
toast(t('settings.saved'), 'success');
} catch (err) {
alert('保存失败:' + err.message);
toast(t('settings.saveFailed', { msg: err.message }), 'error');
}
};
@@ -57,49 +60,51 @@ export default function SettingsProfile() {
<button
style={{ position: 'absolute', bottom: 0, right: 0, background: 'var(--primary)', color: '#fff', border: 'none', borderRadius: '50%', width: 32, height: 32, cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 2px 8px rgba(99,102,241,0.4)' }}
onClick={() => avatarInputRef.current?.click()}
aria-label={t('settings.changeAvatar')}
title={t('settings.changeAvatar')}
>
📷
<Icon name="camera" size={16} />
</button>
</div>
<input type="file" ref={avatarInputRef} accept="image/*" style={{ display: 'none' }} onChange={(e) => { if (e.target.files?.[0]) handleAvatar(e.target.files[0]); }} />
<h2 style={{ margin: '12px 0 4px' }}>{currentUser?.username}</h2>
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{bio || '这个人很懒,什么都没写'}</p>
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{bio || t('user.bioEmpty')}</p>
{avatarStatus && (
<div style={{ fontSize: 13, marginTop: 8, color: avatarStatus.ok ? '#22c55e' : '#ef4444' }}>{avatarStatus.msg}</div>
<div style={{ fontSize: 13, marginTop: 8, color: avatarStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5 }}><Icon name={avatarStatus.ok ? 'success' : 'error'} size={14} /> {avatarStatus.msg}</div>
)}
</div>
{/* 基本资料 */}
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<div style={{ marginBottom: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>用户名</label>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.username')}</label>
<input type="text" value={username} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setUsername(e.target.value)} />
</div>
<div style={{ marginBottom: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>个人简介</label>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.bio')}</label>
<textarea rows={3} value={bio} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }} onChange={(e) => setBio(e.target.value)} />
</div>
<div style={{ marginBottom: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>个性签名 <span style={{ color: 'var(--text-light)', fontWeight: 400 }}>(显示在每篇帖子底部,支持 Markdown)</span></label>
<textarea rows={2} value={signature} placeholder="签名..." style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical', fontFamily: 'inherit' }} onChange={(e) => setSignature(e.target.value)} />
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.signature')} <span style={{ color: 'var(--text-light)', fontWeight: 400 }}>({t('settings.signatureHint')})</span></label>
<textarea rows={2} value={signature} placeholder={t('settings.signaturePlaceholder')} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical', fontFamily: 'inherit' }} onChange={(e) => setSignature(e.target.value)} />
</div>
<button className="btn-primary" style={{ width: '100%', padding: 10 }} onClick={handleSave}>保存设置</button>
<button className="btn-primary" style={{ width: '100%', padding: 10 }} onClick={handleSave}>{t('settings.save')}</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 }}>
<div className="feed-header-left language-toggle" style={{ display: 'inline-flex' }}>
<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)' }}
className={'tab' + (i18n.language.startsWith('zh') ? ' active' : '')}
aria-pressed={i18n.language.startsWith('zh')}
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)' }}
className={'tab' + (i18n.language.startsWith('en') ? ' active' : '')}
aria-pressed={i18n.language.startsWith('en')}
onClick={() => setAppLanguage('en')}
>
{t('settings.languageEn')}
+21 -7
View File
@@ -5,17 +5,31 @@ import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import { Icon } from './Icons';
export default function Sidebar() {
const [stats, setStats] = useState({ posts: 0, users: 0, topics: 0, online: 0 });
const [links, setLinks] = useState([]);
const emptyStats = { posts: 0, users: 0, topics: 0, online: 0 };
let cachedStats = null;
let cachedLinks = null;
export default function Sidebar({ id = 'sidebar' }) {
const [stats, setStats] = useState(() => cachedStats || emptyStats);
const [links, setLinks] = useState(() => cachedLinks || []);
useEffect(() => {
API.getStats().then(setStats).catch(() => {});
API.getLinks().then(setLinks).catch(() => {});
if (!cachedStats) {
API.getStats().then((nextStats) => {
cachedStats = nextStats;
setStats(nextStats);
}).catch(() => {});
}
if (!cachedLinks) {
API.getLinks().then((nextLinks) => {
cachedLinks = nextLinks;
setLinks(nextLinks);
}).catch(() => {});
}
}, []);
return (
<aside id="sidebar">
<aside id={id} className="sidebar">
<div className="stats-box">
<h4>
<Icon name="book" size={14} /> 社区统计
@@ -29,7 +43,7 @@ export default function Sidebar() {
<h4>
<Icon name="link" size={14} /> 友情链接
</h4>
<ul id="friendlyLinks">
<ul id={id === 'sidebar' ? 'friendlyLinks' : undefined} className="friendly-links">
{links.length === 0 ? (
<li style={{ color: '#94a3b8', fontSize: 13 }}>暂无链接</li>
) : (
+67 -14
View File
@@ -4,7 +4,8 @@
// 用法:const { toast } = useToast(); toast('发布成功', 'success');
// 注意:不用 createPortal(SSR 时 document 不存在会造成 hydration mismatch,
// 导致整树重建)。toast-container 是 position:fixed,渲染位置不影响视觉。
import { createContext, useContext, useState, useCallback, useRef } from 'react';
import { createContext, useContext, useState, useCallback, useRef, useEffect } from 'react';
import { Icon } from './Icons';
const ToastContext = createContext(null);
@@ -16,33 +17,85 @@ let idCounter = 0;
export function ToastProvider({ children }) {
const [toasts, setToasts] = useState([]);
const [dialog, setDialog] = useState(null);
const timersRef = useRef({});
const dialogTimerRef = useRef(null);
const dialogResolverRef = useRef(null);
const toast = useCallback((message, type = 'success', duration = 3000) => {
const id = ++idCounter;
setToasts((prev) => [...prev, { id, message, type }]);
if (timersRef.current[id]) clearTimeout(timersRef.current[id]);
timersRef.current[id] = setTimeout(() => {
setToasts((prev) => prev.filter((t) => t.id !== id));
delete timersRef.current[id];
}, duration);
const removeToast = useCallback((id) => {
setToasts((prev) => prev.filter((item) => item.id !== id));
delete timersRef.current[id];
}, []);
const dismiss = useCallback((id) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
if (timersRef.current[id]) { clearTimeout(timersRef.current[id]); delete timersRef.current[id]; }
if (timersRef.current[id]) clearTimeout(timersRef.current[id]);
setToasts((prev) => prev.map((item) => item.id === id ? { ...item, closing: true } : item));
timersRef.current[id] = setTimeout(() => removeToast(id), 220);
}, [removeToast]);
const toast = useCallback((message, type = 'success', duration = 3000) => {
const id = ++idCounter;
setToasts((prev) => [...prev, { id, message, type, closing: false }]);
if (timersRef.current[id]) clearTimeout(timersRef.current[id]);
timersRef.current[id] = setTimeout(() => dismiss(id), duration);
}, [dismiss]);
const confirmAction = useCallback((message, options = {}) => {
if (dialogResolverRef.current) dialogResolverRef.current(false);
const isEnglish = localStorage.getItem('forumlify-lang') === 'en';
setDialog({
message,
title: options.title || (isEnglish ? 'Confirm action' : '确认操作'),
confirmLabel: options.confirmLabel || (isEnglish ? 'Confirm' : '确定'),
cancelLabel: options.cancelLabel || (isEnglish ? 'Cancel' : '取消'),
danger: options.danger !== false,
closing: false,
});
return new Promise((resolve) => {
dialogResolverRef.current = resolve;
});
}, []);
const closeDialog = useCallback((result) => {
setDialog((current) => current ? { ...current, closing: true } : current);
if (dialogTimerRef.current) clearTimeout(dialogTimerRef.current);
dialogTimerRef.current = setTimeout(() => {
setDialog(null);
const resolve = dialogResolverRef.current;
dialogResolverRef.current = null;
if (resolve) resolve(result);
}, 340);
}, []);
useEffect(() => () => {
Object.values(timersRef.current).forEach(clearTimeout);
if (dialogTimerRef.current) clearTimeout(dialogTimerRef.current);
if (dialogResolverRef.current) dialogResolverRef.current(false);
}, []);
return (
<ToastContext.Provider value={{ toast }}>
<ToastContext.Provider value={{ toast, confirmAction }}>
{children}
<div className="toast-container">
{toasts.map((t) => (
<div key={t.id} className={'toast toast-' + t.type} onClick={() => dismiss(t.id)}>
{t.message}
<div key={t.id} className={'toast toast-' + t.type + (t.closing ? ' closing' : '')} onClick={() => dismiss(t.id)} role="status">
<Icon name={t.type === 'error' ? 'error' : t.type === 'warning' ? 'warning' : 'success'} size={16} />
<span>{t.message}</span>
</div>
))}
</div>
{dialog && (
<div className={'modal active feedback-confirm' + (dialog.closing ? ' closing' : '')} onClick={(e) => { if (e.target === e.currentTarget) closeDialog(false); }}>
<div className="modal-content" role="alertdialog" aria-modal="true" aria-labelledby="feedbackConfirmTitle" aria-describedby="feedbackConfirmMessage">
<h2 id="feedbackConfirmTitle"><Icon name="warning" size={20} /> {dialog.title}</h2>
<p id="feedbackConfirmMessage">{dialog.message}</p>
<div className="feedback-confirm-actions">
<button className={dialog.danger ? 'btn-danger' : 'btn-primary'} onClick={() => closeDialog(true)}>{dialog.confirmLabel}</button>
<button className="btn-secondary" onClick={() => closeDialog(false)}>{dialog.cancelLabel}</button>
</div>
</div>
</div>
)}
</ToastContext.Provider>
);
}
+5 -5
View File
@@ -68,19 +68,19 @@ export default function UserProfile({ username }) {
</button>
)}
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
<span>📅 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span>📝 发了 {posts.length} 个帖子</span>
{user.role === 'admin' && <span style={{ color: 'var(--primary)', fontWeight: 600 }}>🛡️ 管理员</span>}
<span><Icon name="calendar" size={14} /> 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span><Icon name="file" size={14} /> 发了 {posts.length} 个帖子</span>
{user.role === 'admin' && <span style={{ color: 'var(--primary)', fontWeight: 600 }}><Icon name="shield" size={14} /> 管理员</span>}
</div>
</div>
<h3 style={{ margin: '24px 0 16px', fontSize: 18 }}>📝 发布的帖子</h3>
<h3 style={{ margin: '24px 0 16px', fontSize: 18 }}><Icon name="file" size={18} /> 发布的帖子</h3>
{posts.length === 0 ? (
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有发帖</div>
) : (
posts.map((p) => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
return (
<div key={p.id} className="post-card" style={{ cursor: 'pointer' }} onClick={() => openPost(p.id)}>
<div key={p.id} className="post-card" style={{ cursor: 'pointer' }} onClick={(e) => openPost(p.id, e.currentTarget, p)}>
<div className="post-title" style={{ fontSize: 16, fontWeight: 600 }}>{p.title || '无标题'}</div>
<div className="post-content" style={{ fontSize: 14, color: 'var(--text-secondary)' }}>
{(p.content || '').substring(0, 100)}{(p.content || '').length > 100 ? '...' : ''}
+23 -18
View File
@@ -2,9 +2,14 @@
// 管理后台 - 自定义 CSS(上传 style.css 覆盖默认样式)
import { useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function AdminCustomCss() {
const { t } = useTranslation();
const { confirmAction } = useToast();
const [status, setStatus] = useState(null);
const [dragOver, setDragOver] = useState(false);
const [pendingFile, setPendingFile] = useState(null); // 待确认的 CSS 文件
@@ -13,11 +18,11 @@ export default function AdminCustomCss() {
const handleFile = async (file) => {
if (!file) return;
if (file.name !== 'style.css') {
setStatus({ ok: false, msg: '❌ 文件名必须是 style.css' });
setStatus({ ok: false, msg: t('admin.css.filenameInvalid') });
return;
}
if (file.size > 1024 * 1024) {
setStatus({ ok: false, msg: '❌ CSS 文件不能超过 1MB' });
setStatus({ ok: false, msg: t('admin.css.sizeInvalid') });
return;
}
// 上传前警告确认(与原版一致)
@@ -27,33 +32,33 @@ export default function AdminCustomCss() {
const doUpload = async () => {
try {
await API.uploadCustomCss(pendingFile);
setStatus({ ok: true, msg: '✅ 自定义 CSS 已生效(刷新页面后应用)' });
setStatus({ ok: true, msg: t('admin.css.active') });
const link = document.getElementById('custom-css-link');
if (link) link.href = '/api/custom-css?t=' + Date.now();
} catch (err) {
setStatus({ ok: false, msg: '❌ ' + err.message });
setStatus({ ok: false, msg: err.message });
} finally {
setPendingFile(null);
}
};
const handleDelete = async () => {
if (!confirm('确定要删除自定义 CSS 吗?')) return;
if (!await confirmAction(t('admin.css.confirmDelete'))) return;
try {
await API.deleteCustomCss();
setStatus({ ok: true, msg: '✅ 已删除自定义 CSS' });
setStatus({ ok: true, msg: t('admin.css.deleted') });
const link = document.getElementById('custom-css-link');
if (link) link.remove();
} catch (err) {
setStatus({ ok: false, msg: '❌ ' + err.message });
setStatus({ ok: false, msg: err.message });
}
};
return (
<>
<h3 style={{ marginBottom: 16 }}>🎨 自定义 CSS</h3>
<h3 style={{ marginBottom: 16 }}><Icon name="code" size={16} /> {t('admin.css.title')}</h3>
<p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>
上传一个 <code>style.css</code> 文件覆盖默认样式(支持 CSS 变量、暗色模式等)。
{t('admin.css.description')}
</p>
<div
style={{
@@ -67,7 +72,7 @@ export default function AdminCustomCss() {
onDrop={(e) => { e.preventDefault(); setDragOver(false); if (e.dataTransfer.files?.[0]) handleFile(e.dataTransfer.files[0]); }}
>
<span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
{dragOver ? '松开上传' : '📄 点击或拖拽上传 style.css'}
<Icon name="upload" size={14} /> {dragOver ? t('admin.css.releaseUpload') : t('admin.css.uploadHint')}
</span>
</div>
<input
@@ -78,27 +83,27 @@ export default function AdminCustomCss() {
onChange={(e) => { if (e.target.files?.[0]) handleFile(e.target.files[0]); }}
/>
{status && (
<div style={{ fontSize: 13, marginTop: 8, color: status.ok ? '#22c55e' : '#ef4444' }}>{status.msg}</div>
<div style={{ fontSize: 13, marginTop: 8, color: status.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={status.ok ? 'success' : 'error'} size={14} /> {status.msg}</div>
)}
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
<button className="btn-primary" style={{ padding: '8px 20px' }} onClick={() => fileInputRef.current?.click()}>💾 保存 CSS</button>
<button className="btn-secondary" style={{ padding: '8px 20px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={handleDelete}>🗑️ 删除自定义 CSS</button>
<button className="btn-primary" style={{ padding: '8px 20px' }} onClick={() => fileInputRef.current?.click()}><Icon name="save" size={14} /> {t('admin.css.save')}</button>
<button className="btn-secondary" style={{ padding: '8px 20px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={handleDelete}><Icon name="trash" size={14} /> {t('admin.css.delete')}</button>
</div>
{/* 上传前警告确认 */}
{pendingFile && (
<div className="modal active" style={{ display: 'flex' }} onClick={() => setPendingFile(null)}>
<div className="modal-content" style={{ maxWidth: 420 }} onClick={(e) => e.stopPropagation()}>
<h2 style={{ marginBottom: 12 }}>⚠️ 警告</h2>
<h2 style={{ marginBottom: 12 }}><Icon name="warning" size={20} /> {t('admin.css.warningTitle')}</h2>
<p style={{ fontSize: 14, color: 'var(--text-secondary)', marginBottom: 16 }}>
若上传的 <strong>style.css</strong> 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。
{t('admin.css.warningBody')}
</p>
<p style={{ fontSize: 13, color: 'var(--text-light)', marginBottom: 20 }}>
请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。
{t('admin.css.warningHelp')}
</p>
<div style={{ display: 'flex', gap: 8 }}>
<button className="btn-primary" style={{ padding: '8px 24px' }} onClick={doUpload}>我了解,继续上传</button>
<button className="btn-secondary" style={{ padding: '8px 24px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={() => setPendingFile(null)}>取消</button>
<button className="btn-primary" style={{ padding: '8px 24px' }} onClick={doUpload}><Icon name="upload" size={14} /> {t('admin.css.continueUpload')}</button>
<button className="btn-secondary" style={{ padding: '8px 24px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={() => setPendingFile(null)}>{t('admin.common.cancel')}</button>
</div>
</div>
</div>
+20 -15
View File
@@ -2,10 +2,15 @@
// 管理后台 - 自定义页面管理(列表)
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import CustomPageEditor from './CustomPageEditor';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function AdminCustomPages() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [pages, setPages] = useState(null);
const [error, setError] = useState(null);
const [editing, setEditing] = useState(null); // null | 'new' | page对象
@@ -19,38 +24,38 @@ export default function AdminCustomPages() {
useEffect(load, []);
const handleDelete = async (p) => {
if (!confirm('确定要删除这个页面吗?')) return;
if (!await confirmAction(t('admin.page.confirmDelete'))) return;
try {
await API.adminDeleteCustomPage(p.id);
load();
} catch (err) {
alert('删除失败:' + err.message);
toast(t('admin.common.deleteFailed', { msg: err.message }), 'error');
}
};
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
return (
<>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
<h3 style={{ margin: 0 }}>📄 自定义页面</h3>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={() => setEditing('new')}>➕ 添加页面</button>
<h3 style={{ margin: 0 }}><Icon name="file" size={16} /> {t('admin.page.title')}</h3>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={() => setEditing('new')}><Icon name="plus" size={14} /> {t('admin.page.add')}</button>
</div>
<div id="customPageList">
{pages === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />加载中...</div>
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>
) : pages.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>暂无自定义页面</div>
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>{t('admin.page.empty')}</div>
) : (
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
<thead>
<tr style={{ textAlign: 'left', borderBottom: '2px solid var(--border)' }}>
<th style={{ padding: '8px 12px' }}>名称</th>
<th style={{ padding: '8px 12px' }}>标题</th>
<th style={{ padding: '8px 12px' }}>URL</th>
<th style={{ padding: '8px 12px' }}>状态</th>
<th style={{ padding: '8px 12px', textAlign: 'center' }}>操作</th>
<th style={{ padding: '8px 12px' }}>{t('admin.page.name')}</th>
<th style={{ padding: '8px 12px' }}>{t('admin.page.columnTitle')}</th>
<th style={{ padding: '8px 12px' }}>{t('admin.page.url')}</th>
<th style={{ padding: '8px 12px' }}>{t('admin.common.status')}</th>
<th style={{ padding: '8px 12px', textAlign: 'center' }}>{t('admin.common.actions')}</th>
</tr>
</thead>
<tbody>
@@ -60,11 +65,11 @@ export default function AdminCustomPages() {
<td style={{ padding: '8px 12px' }}>{p.title}</td>
<td style={{ padding: '8px 12px' }}><code style={{ background: 'var(--bg)', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>?custom={p.name}</code></td>
<td style={{ padding: '8px 12px' }}>
<span style={{ color: p.enabled ? '#22c55e' : '#ef4444' }}>{p.enabled ? '✅ 启用' : '❌ 禁用'}</span>
<span style={{ color: p.enabled ? '#22c55e' : '#ef4444', display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name={p.enabled ? 'success' : 'error'} size={13} /> {p.enabled ? t('admin.common.enabled') : t('admin.common.disabled')}</span>
</td>
<td style={{ padding: '8px 12px', textAlign: 'center', display: 'flex', gap: 6, justifyContent: 'center' }}>
<button className="btn-sm btn-secondary" onClick={() => setEditing(p)}>✏️</button>
<button className="btn-sm btn-danger" onClick={() => handleDelete(p)}>🗑️</button>
<button className="btn-sm btn-secondary" title={t('admin.page.edit')} aria-label={t('admin.page.edit')} onClick={() => setEditing(p)}><Icon name="edit" size={13} /></button>
<button className="btn-sm btn-danger" title={t('admin.page.delete')} aria-label={t('admin.page.delete')} onClick={() => handleDelete(p)}><Icon name="trash" size={13} /></button>
</td>
</tr>
))}
+11 -7
View File
@@ -5,9 +5,13 @@ import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import { useApp } from '../AppProvider';
import { Icon } from '../Icons';
import { useTranslation } from 'react-i18next';
import { useToast } from '../Toast';
export default function AdminForumSettings() {
const { updateForumName } = useApp();
const { t } = useTranslation();
const { toast } = useToast();
// 初始为空:收到服务器返回的论坛名后才显示,避免默认名一闪而过
const [name, setName] = useState('');
const [result, setResult] = useState(null); // {ok, msg}
@@ -19,30 +23,30 @@ export default function AdminForumSettings() {
}, []);
const handleSave = async () => {
if (!name.trim()) { alert('请输入论坛名称'); return; }
if (!name.trim()) { toast(t('admin.forum.nameRequired'), 'warning'); return; }
try {
await API.updateSettings(name.trim());
updateForumName(name.trim());
setResult({ ok: true, msg: '✅ 保存成功!' });
setResult({ ok: true, msg: t('admin.forum.saved') });
} catch {
setResult({ ok: false, msg: '❌ 保存失败' });
setResult({ ok: false, msg: t('admin.forum.saveFailed') });
}
};
return (
<>
<h3 style={{ marginBottom: 16 }}><Icon name="settings" size={16} /> 论坛设置</h3>
<h3 style={{ marginBottom: 16 }}><Icon name="settings" size={16} /> {t('admin.forum.title')}</h3>
<div style={{ maxWidth: 400 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 6 }}>论坛名称</label>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 6 }}>{t('admin.forum.nameLabel')}</label>
<input
type="text"
style={{ width: '100%', padding: '10px 14px', border: '1.5px solid var(--border)', borderRadius: 6, fontSize: 15, marginBottom: 12, fontFamily: 'inherit', background: 'var(--bg)', color: 'var(--text)' }}
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button className="btn-primary" style={{ padding: '10px 24px' }} onClick={handleSave}>保存</button>
<button className="btn-primary" style={{ padding: '10px 24px' }} onClick={handleSave}><Icon name="save" size={14} /> {t('admin.forum.save')}</button>
{result && (
<span style={{ marginLeft: 12, fontSize: 14, color: result.ok ? '#22c55e' : '#ef4444' }}>{result.msg}</span>
<span style={{ marginLeft: 12, fontSize: 14, color: result.ok ? '#22c55e' : '#ef4444' }}><Icon name={result.ok ? 'success' : 'error'} size={14} /> {result.msg}</span>
)}
</div>
</>
+13 -9
View File
@@ -2,10 +2,14 @@
// 管理后台 - 友情链接管理
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function AdminLinks() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [links, setLinks] = useState([]);
const [title, setTitle] = useState('');
const [url, setUrl] = useState('');
@@ -14,24 +18,24 @@ export default function AdminLinks() {
useEffect(load, []);
const handleAdd = async () => {
if (!title.trim() || !url.trim()) { alert('请填写完整信息'); return; }
if (!title.trim() || !url.trim()) { toast(t('admin.link.incomplete'), 'warning'); return; }
try {
await API.addLink(title.trim(), url.trim());
setTitle('');
setUrl('');
load();
} catch (err) {
alert('添加失败:' + err.message);
toast(t('admin.link.addFailed', { msg: err.message }), 'error');
}
};
const handleDelete = async (id) => {
if (!confirm('确定删除该链接吗?')) return;
if (!await confirmAction(t('admin.link.confirmDelete'))) return;
try {
await API.deleteLink(id);
load();
} catch (err) {
alert('删除失败:' + err.message);
toast(t('admin.common.deleteFailed', { msg: err.message }), 'error');
}
};
@@ -39,26 +43,26 @@ export default function AdminLinks() {
<>
<div style={{ marginBottom: 16, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<input
type="text" placeholder="链接名称"
type="text" placeholder={t('admin.link.namePlaceholder')}
style={{ flex: 1, minWidth: 120, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)' }}
value={title} onChange={(e) => setTitle(e.target.value)}
/>
<input
type="url" placeholder="链接地址"
type="url" placeholder={t('admin.link.urlPlaceholder')}
style={{ flex: 2, minWidth: 160, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)' }}
value={url} onChange={(e) => setUrl(e.target.value)}
/>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={handleAdd}>添加</button>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={handleAdd}>{t('admin.link.add')}</button>
</div>
<div id="linkList">
{links.length === 0 ? (
<div style={{ color: '#94a3b8', fontSize: 13 }}>暂无友情链接</div>
<div style={{ color: '#94a3b8', fontSize: 13 }}>{t('admin.link.empty')}</div>
) : (
links.map((l) => (
<div key={l.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: '1px solid #f1f5f9' }}>
<span><a href={l.url} target="_blank" rel="noreferrer" style={{ color: '#6366f1', textDecoration: 'none' }}>{l.title}</a></span>
<button className="btn-sm btn-danger" onClick={() => handleDelete(l.id)}>
<Icon name="trash" size={12} /> 删除
<Icon name="trash" size={12} /> {t('admin.common.delete')}
</button>
</div>
))
+10 -6
View File
@@ -2,9 +2,11 @@
// 管理后台 - 事件日志
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
export default function AdminLogs() {
const { t, i18n } = useTranslation();
const [logs, setLogs] = useState(null);
const [error, setError] = useState(null);
@@ -16,22 +18,24 @@ export default function AdminLogs() {
useEffect(load, []);
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
if (!logs) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />加载中...</div>;
if (logs.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>暂无日志</div>;
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
if (!logs) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
if (logs.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>{t('admin.log.empty')}</div>;
const dateLocale = i18n.resolvedLanguage === 'en' ? 'en-US' : 'zh-CN';
return (
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
<thead>
<tr style={{ textAlign: 'left', borderBottom: '1px solid var(--border)' }}>
<th>时间</th><th>用户</th><th>操作</th>
<th>{t('admin.log.time')}</th><th>{t('admin.log.user')}</th><th>{t('admin.log.action')}</th>
</tr>
</thead>
<tbody>
{logs.map((l) => (
<tr key={l.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
<td style={{ padding: '6px 0' }}>{new Date(l.created_at).toLocaleString('zh-CN')}</td>
<td style={{ padding: '6px 0' }}>{l.username || '系统'}</td>
<td style={{ padding: '6px 0' }}>{new Date(l.created_at).toLocaleString(dateLocale)}</td>
<td style={{ padding: '6px 0' }}>{l.username || t('admin.log.system')}</td>
<td style={{ padding: '6px 0' }}>{l.action}</td>
</tr>
))}
+29 -16
View File
@@ -2,12 +2,14 @@
// 管理后台 - 举报处理
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
const STATUS = { pending: '⏳ 待处理', approved: '✅ 已删除', rejected: '❌ 已驳回' };
import { useToast } from '../Toast';
export default function AdminReports() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [reports, setReports] = useState(null);
const [error, setError] = useState(null);
@@ -21,8 +23,8 @@ export default function AdminReports() {
const handleAction = async (r, action) => {
const status = action === 'approve' ? 'approved' : 'rejected';
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
const note = action === 'approve' ? t('admin.report.approvedNote') : t('admin.report.rejectedNote');
if (action === 'approve' && !await confirmAction(t('admin.report.confirmApprove'))) return;
try {
await API.updateReport(r.id, status, note);
if (action === 'approve' && r.post_id) {
@@ -30,35 +32,46 @@ export default function AdminReports() {
}
load();
} catch (err) {
alert('操作失败:' + err.message);
toast(t('admin.common.operationFailed', { msg: err.message }), 'error');
}
};
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
if (!reports) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />加载中...</div>;
if (reports.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>✅ 暂无举报</div>;
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
if (!reports) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
if (reports.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}><Icon name="success" size={16} /> {t('admin.report.empty')}</div>;
const statusLabels = {
pending: t('admin.report.statusPending'),
approved: t('admin.report.statusApproved'),
rejected: t('admin.report.statusRejected'),
};
const statusIcons = { pending: 'pending', approved: 'success', rejected: 'error' };
return reports.map((r) => (
<div key={r.id} className="report-item">
<div><strong>{r.reporter_name || '匿名'}</strong> 举报了帖子</div>
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>原因:{r.reason}</div>
<div>{t('admin.report.reportedPost', { name: r.reporter_name || t('admin.report.anonymous') })}</div>
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>{t('admin.report.reason', { reason: r.reason })}</div>
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>
帖子:{r.post_title || '无标题'} — {(r.post_content || '').substring(0, 30)}
{(r.post_content || '').length > 30 ? '...' : ''}
{t('admin.report.post', {
title: r.post_title || t('admin.report.untitled'),
content: (r.post_content || '').substring(0, 30) + ((r.post_content || '').length > 30 ? '...' : ''),
})}
</div>
<div style={{ fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
{statusIcons[r.status] && <Icon name={statusIcons[r.status]} size={13} />} {t('admin.common.status')}: {statusLabels[r.status] || r.status}
</div>
<div style={{ fontSize: 13, fontWeight: 600 }}>状态:{STATUS[r.status] || r.status}</div>
{r.handler_name && (
<div style={{ fontSize: 12, color: '#94a3b8' }}>
处理人:{r.handler_name}{r.handler_note ? ' (' + r.handler_note + ')' : ''}
{t('admin.report.handler', { name: r.handler_name })}{r.handler_note ? ' (' + r.handler_note + ')' : ''}
</div>
)}
{r.status === 'pending' && (
<div className="report-actions">
<button className="btn-sm btn-danger" onClick={() => handleAction(r, 'approve')}>
<Icon name="trash" size={12} /> 删除帖子
<Icon name="trash" size={12} /> {t('admin.report.deletePost')}
</button>
<button className="btn-sm btn-secondary" onClick={() => handleAction(r, 'reject')}>
<Icon name="close" size={12} /> 驳回举报
<Icon name="close" size={12} /> {t('admin.report.reject')}
</button>
</div>
)}
+22 -16
View File
@@ -2,11 +2,15 @@
// 管理后台 - 用户管理
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { useApp } from '../AppProvider';
import { useToast } from '../Toast';
export default function AdminUsers() {
const { currentUser } = useApp();
const { t, i18n } = useTranslation();
const { toast, confirmAction } = useToast();
const [users, setUsers] = useState(null);
const [error, setError] = useState(null);
@@ -19,30 +23,32 @@ export default function AdminUsers() {
useEffect(load, []);
const handleRole = async (u, role) => {
const roleName = role === 'admin' ? '管理员' : '普通用户';
if (!confirm(`确定要将该用户设为「${roleName}」吗?`)) return;
const roleName = role === 'admin' ? t('admin.user.roleAdmin') : t('admin.user.roleUser');
if (!await confirmAction(t('admin.user.confirmRole', { role: roleName }), { danger: false })) return;
try {
await API.updateUserRole(u.id, role);
load();
} catch (err) {
alert('操作失败:' + err.message);
toast(t('admin.common.operationFailed', { msg: err.message }), 'error');
}
};
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
if (!users) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />加载中...</div>;
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
if (!users) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
const dateLocale = i18n.resolvedLanguage === 'en' ? 'en-US' : 'zh-CN';
return (
<>
<div style={{ marginBottom: 12, fontSize: 13, color: '#94a3b8' }}>共 <strong>{users.length}</strong> 位用户</div>
<div style={{ marginBottom: 12, fontSize: 13, color: '#94a3b8' }}>{t('admin.user.count', { count: users.length })}</div>
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
<thead>
<tr style={{ textAlign: 'left', borderBottom: '2px solid var(--border)' }}>
<th style={{ padding: '10px 12px' }}>用户</th>
<th style={{ padding: '10px 12px' }}>角色</th>
<th style={{ padding: '10px 12px' }}>注册时间</th>
<th style={{ padding: '10px 12px', textAlign: 'center' }}>操作</th>
<th style={{ padding: '10px 12px' }}>{t('admin.user.user')}</th>
<th style={{ padding: '10px 12px' }}>{t('admin.user.role')}</th>
<th style={{ padding: '10px 12px' }}>{t('admin.user.registeredAt')}</th>
<th style={{ padding: '10px 12px', textAlign: 'center' }}>{t('admin.common.actions')}</th>
</tr>
</thead>
<tbody>
@@ -59,7 +65,7 @@ export default function AdminUsers() {
alt=""
/>
<span style={{ fontWeight: 500 }}>{u.username}</span>
{isCurrent && <span style={{ fontSize: 11, color: '#94a3b8', background: '#eef2ff', padding: '1px 8px', borderRadius: 4 }}>你</span>}
{isCurrent && <span style={{ fontSize: 11, color: '#94a3b8', background: '#eef2ff', padding: '1px 8px', borderRadius: 4 }}>{t('admin.user.you')}</span>}
</div>
</td>
<td style={{ padding: '10px 12px' }}>
@@ -67,19 +73,19 @@ export default function AdminUsers() {
display: 'inline-block', padding: '2px 10px', borderRadius: 4, fontSize: 12, fontWeight: 500,
...(isAdmin ? { background: '#6366f1', color: '#fff' } : { background: 'var(--border)', color: 'var(--text-secondary)' }),
}}>
{isAdmin ? '管理员' : '普通用户'}
{isAdmin ? t('admin.user.roleAdmin') : t('admin.user.roleUser')}
</span>
</td>
<td style={{ padding: '10px 12px', color: '#94a3b8', fontSize: 13 }}>
{u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '—'}
{u.created_at ? new Date(u.created_at).toLocaleDateString(dateLocale) : '—'}
</td>
<td style={{ padding: '10px 12px', textAlign: 'center' }}>
{isCurrent ? (
<span style={{ fontSize: 12, color: '#94a3b8' }}>不可操作自己</span>
<span style={{ fontSize: 12, color: '#94a3b8' }}>{t('admin.user.cannotSelf')}</span>
) : isAdmin ? (
<button className="btn-sm btn-secondary" style={{ padding: '4px 12px' }} onClick={() => handleRole(u, 'user')}>设为普通用户</button>
<button className="btn-sm btn-secondary" style={{ padding: '4px 12px' }} onClick={() => handleRole(u, 'user')}>{t('admin.user.makeUser')}</button>
) : (
<button className="btn-sm btn-primary" style={{ padding: '4px 12px', background: '#6366f1', color: '#fff', border: 'none', borderRadius: 4, cursor: 'pointer' }} onClick={() => handleRole(u, 'admin')}>设为管理员</button>
<button className="btn-sm btn-primary" style={{ padding: '4px 12px', background: '#6366f1', color: '#fff', border: 'none', borderRadius: 4, cursor: 'pointer' }} onClick={() => handleRole(u, 'admin')}>{t('admin.user.makeAdmin')}</button>
)}
</td>
</tr>
+24 -19
View File
@@ -2,9 +2,14 @@
// 管理后台 - 自定义页面编辑器(modal)
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function CustomPageEditor({ page, onClose, onSaved }) {
const { t } = useTranslation();
const { toast } = useToast();
const isEdit = !!page;
const [name, setName] = useState(page?.name || '');
const [title, setTitle] = useState(page?.title || '');
@@ -12,11 +17,11 @@ export default function CustomPageEditor({ page, onClose, onSaved }) {
const [enabled, setEnabled] = useState(page?.enabled !== false);
const handleSave = async () => {
if (!name.trim()) { alert('请输入页面名称'); return; }
if (!title.trim()) { alert('请输入导航栏显示名称'); return; }
if (!content.trim()) { alert('请输入页面内容'); return; }
if (!name.trim()) { toast(t('admin.page.nameRequired'), 'warning'); return; }
if (!title.trim()) { toast(t('admin.page.titleRequired'), 'warning'); return; }
if (!content.trim()) { toast(t('admin.page.contentRequired'), 'warning'); return; }
if (!/^[a-zA-Z0-9\-_]+$/.test(name.trim())) {
alert('页面名称只允许字母、数字、短横线和下划线');
toast(t('admin.page.nameInvalid'), 'warning');
return;
}
try {
@@ -27,61 +32,61 @@ export default function CustomPageEditor({ page, onClose, onSaved }) {
}
onSaved();
} catch (err) {
alert('保存失败:' + err.message);
toast(t('admin.common.saveFailed', { msg: err.message }), 'error');
}
};
return (
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
<div className="modal-content" style={{ maxWidth: 600, maxHeight: '90vh', overflowY: 'auto', position: 'relative' }}>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, fontSize: 24, cursor: 'pointer', color: 'var(--text-light)' }} onClick={onClose}>&times;</span>
<h2 style={{ marginBottom: 16 }}>{isEdit ? '✏️ 编辑页面' : '📄 添加页面'}</h2>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={onClose}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}><Icon name={isEdit ? 'edit' : 'file'} size={20} /> {isEdit ? t('admin.page.editTitle') : t('admin.page.addTitle')}</h2>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>页面名称</label>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.nameLabel')}</label>
<input
type="text"
value={name}
readOnly={isEdit}
placeholder="about (用于 URL: ?custom=about)"
placeholder={t('admin.page.namePlaceholder')}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: isEdit ? 'var(--border-light)' : 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setName(e.target.value)}
/>
{isEdit
? <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>⚠️ 名称不可修改</div>
: <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>只允许字母、数字、短横线和下划线</div>}
? <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}><Icon name="warning" size={12} /> {t('admin.page.nameLocked')}</div>
: <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>{t('admin.page.nameHint')}</div>}
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>导航栏显示名称</label>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.navTitleLabel')}</label>
<input
type="text"
value={title}
placeholder="关于我们"
placeholder={t('admin.page.navTitlePlaceholder')}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>状态</label>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.common.status')}</label>
<select
value={String(enabled)}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setEnabled(e.target.value === 'true')}
>
<option value="true">启用</option>
<option value="false">禁用</option>
<option value="true">{t('admin.common.enabled')}</option>
<option value="false">{t('admin.common.disabled')}</option>
</select>
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>页面内容(HTML + CSS + JS)</label>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.contentLabel')}</label>
<textarea
rows={12}
value={content}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 13, fontFamily: 'monospace', background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }}
onChange={(e) => setContent(e.target.value)}
/>
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>支持 HTML、CSS(&lt;style&gt;)、JS(&lt;script&gt;),内容会在独立的沙盒中渲染</div>
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>{t('admin.page.contentHelp')}</div>
</div>
<button className="btn-primary" style={{ padding: '10px 24px', width: '100%' }} onClick={handleSave}>保存</button>
<button className="btn-primary" style={{ padding: '10px 24px', width: '100%' }} onClick={handleSave}>{t('admin.common.save')}</button>
</div>
</div>
);
+4 -2
View File
@@ -7,6 +7,7 @@ import { useApp } from '../AppProvider';
import { Icon } from '../Icons';
import ConversationList from './ConversationList';
import ChatWindow from './ChatWindow';
import { useToast } from '../Toast';
// 私信按钮(含未读 badge),渲染在导航栏内
export function DMButton() {
@@ -101,15 +102,16 @@ export default function ChatManager() {
// 供其他组件调用的打开私信(通过自定义事件桥接)
export function useOpenPrivateChat() {
const { currentUser } = useApp();
const { toast } = useToast();
const open = async (otherUserId, otherUsername) => {
if (!currentUser) { alert('请先登录'); return; }
if (!currentUser) { toast('请先登录', 'warning'); return; }
try {
const result = await API.getOrCreateConversation(otherUserId);
window.dispatchEvent(new CustomEvent('forumlify-open-chat', {
detail: { conversationId: result.id, otherUserId, otherUsername },
}));
} catch (err) {
alert('打开私信失败:' + err.message);
toast('打开私信失败:' + err.message, 'error');
}
};
return open;
+6 -3
View File
@@ -4,6 +4,8 @@
import { useEffect, useState, useRef, useCallback } from 'react';
import { API } from '@/lib/api';
import { useApp } from '../AppProvider';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
@@ -12,6 +14,7 @@ function avatar(username) {
export default function ChatWindow({ conversationId, otherUserId, otherUsername, onClose, onRefreshList }) {
const { currentUser } = useApp();
const { toast } = useToast();
const [messages, setMessages] = useState(null);
const [content, setContent] = useState('');
const containerRef = useRef(null);
@@ -47,7 +50,7 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
load();
onRefreshList();
} catch (err) {
alert('发送失败:' + err.message);
toast('发送失败:' + err.message, 'error');
}
};
@@ -56,7 +59,7 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
<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)' }}>
<span id="chatTitle" style={{ fontWeight: 600, fontSize: 16 }}>{otherUsername}</span>
<span className="close" onClick={onClose} style={{ fontSize: 24, cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}>&times;</span>
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
</div>
<div id="chatMessages" ref={containerRef} style={{ flex: 1, overflowY: 'auto', padding: 16, minHeight: 0 }}>
{messages === null ? (
@@ -83,7 +86,7 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
{m.content}
</div>
<div style={{ fontSize: 11, color: 'var(--text-light)', marginTop: 4, textAlign: isMine ? 'right' : 'left' }}>
{time} {isMine ? (m.is_read ? '✓✓' : '✓') : ''}
{time} {isMine && <Icon name="success" size={10} aria-label={m.is_read ? '已读' : '已发送'} />}
</div>
</div>
</div>
+1 -1
View File
@@ -26,7 +26,7 @@ export default function ConversationList({ onOpenChat, 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 }}><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 }}>&times;</span>
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
</div>
<div id="messageListContent" style={{ flex: 1, overflowY: 'auto', padding: 0 }}>
{conversations === null ? (
+138 -12
View File
@@ -17,8 +17,8 @@
"hot": "Latest replies",
"newPost": "New post",
"loading": "Loading...",
"empty": "✨ No posts yet — be the first to publish!",
"pinned": "📌 Pinned",
"empty": "No posts yet — be the first to publish!",
"pinned": "Pinned",
"deleted": "(edited)",
"report": "Report",
"delete": "Delete",
@@ -59,7 +59,7 @@
"reply": {
"submit": "Submit reply",
"placeholder": "Write your reply...",
"empty": "No replies yet — be the first to comment 🛋️",
"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?",
@@ -72,7 +72,7 @@
"passwordHint": "Password (min 6 chars)",
"forgotPassword": "Forgot password?",
"captchaError": "Wrong captcha, please try again",
"registerSuccess": "🎉 Registration successful",
"registerSuccess": "Registration successful",
"loginSuccess": "Logged in",
"logoutSuccess": "Logged out",
"login": "Login",
@@ -89,6 +89,12 @@
"username": "Username",
"bio": "Bio",
"signature": "Signature",
"signatureHint": "Shown below every post; Markdown is supported",
"signaturePlaceholder": "Signature...",
"avatarFileRequired": "Please select an image file",
"avatarTooLarge": "Image must be smaller than 5MB",
"avatarUpdated": "Avatar updated",
"changeAvatar": "Change avatar",
"save": "Save settings",
"saved": "Saved!",
"saveFailed": "Save failed: {{msg}}",
@@ -99,9 +105,9 @@
"title": "User profile",
"bioEmpty": "This user hasn't written a bio yet",
"sendMessage": "Send message",
"joined": "📅 Joined {{date}}",
"posts": "📝 {{count}} posts",
"admin": "🛡️ Admin",
"joined": "Joined {{date}}",
"posts": "{{count}} posts",
"admin": "Admin",
"noPosts": "No posts yet",
"notFound": "User not found",
"loading": "Loading..."
@@ -135,8 +141,8 @@
"changeEmail": "Change email",
"fillAll": "Please fill in all fields",
"pwMin": "New password must be at least 6 characters",
"pwChanged": "✅ Password changed",
"emailChanged": "✅ Email changed"
"pwChanged": "Password changed",
"emailChanged": "Email changed"
},
"recovery": {
"title": "Recovery codes",
@@ -147,8 +153,128 @@
"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.",
"newCodes": "New recovery codes",
"saveWarning": "Save these codes now — they cannot be viewed again after closing.",
"saved": "I have saved them"
},
"admin": {
"title": "Admin",
"reports": "Reports",
"users": "Users",
"logs": "Event logs",
"links": "Links",
"forumSettings": "Forum settings",
"customPages": "Custom pages",
"customCss": "Custom CSS",
"common": {
"loading": "Loading...",
"loadFailed": "Load failed: {{msg}}",
"operationFailed": "Operation failed: {{msg}}",
"deleteFailed": "Delete failed: {{msg}}",
"saveFailed": "Save failed: {{msg}}",
"delete": "Delete",
"save": "Save",
"cancel": "Cancel",
"actions": "Actions",
"status": "Status",
"enabled": "Enabled",
"disabled": "Disabled"
},
"report": {
"statusPending": "Pending",
"statusApproved": "Deleted",
"statusRejected": "Rejected",
"approvedNote": "Removed the reported post",
"rejectedNote": "Report dismissed",
"confirmApprove": "Delete this post and mark the report as resolved?",
"empty": "No reports",
"anonymous": "Anonymous",
"reportedPost": "{{name}} reported a post",
"reason": "Reason: {{reason}}",
"post": "Post: {{title}} — {{content}}",
"untitled": "Untitled",
"handler": "Handled by: {{name}}",
"deletePost": "Delete post",
"reject": "Reject report"
},
"user": {
"roleAdmin": "Admin",
"roleUser": "User",
"confirmRole": "Set this user's role to {{role}}?",
"count": "{{count}} users",
"user": "User",
"role": "Role",
"registeredAt": "Registered",
"you": "You",
"cannotSelf": "You cannot edit yourself",
"makeUser": "Make user",
"makeAdmin": "Make admin"
},
"log": {
"empty": "No logs",
"time": "Time",
"user": "User",
"action": "Action",
"system": "System"
},
"link": {
"incomplete": "Please complete all fields",
"addFailed": "Add failed: {{msg}}",
"confirmDelete": "Delete this link?",
"namePlaceholder": "Link name",
"urlPlaceholder": "Link URL",
"add": "Add",
"empty": "No links"
},
"page": {
"confirmDelete": "Delete this page?",
"title": "Custom pages",
"add": "Add page",
"empty": "No custom pages",
"name": "Name",
"columnTitle": "Title",
"url": "URL",
"edit": "Edit page",
"delete": "Delete page",
"editTitle": "Edit page",
"addTitle": "Add page",
"nameRequired": "Enter a page name",
"titleRequired": "Enter a navigation label",
"contentRequired": "Enter page content",
"nameInvalid": "Page names may only contain letters, numbers, hyphens, and underscores",
"nameLabel": "Page name",
"namePlaceholder": "about (used in URL: ?custom=about)",
"nameLocked": "The name cannot be changed",
"nameHint": "Letters, numbers, hyphens, and underscores only",
"navTitleLabel": "Navigation label",
"navTitlePlaceholder": "About us",
"contentLabel": "Page content (HTML + CSS + JS)",
"contentHelp": "HTML, CSS (<style>), and JS (<script>) are supported and rendered in an isolated sandbox"
},
"css": {
"filenameInvalid": "The file must be named style.css",
"sizeInvalid": "The CSS file must be smaller than 1MB",
"active": "Custom CSS is active (refresh to apply it)",
"confirmDelete": "Delete the custom CSS?",
"deleted": "Custom CSS deleted",
"title": "Custom CSS",
"description": "Upload a style.css file to override the default styles, including CSS variables and dark mode.",
"releaseUpload": "Release to upload",
"uploadHint": "Click or drag to upload style.css",
"save": "Save CSS",
"delete": "Delete custom CSS",
"warningTitle": "Warning",
"warningBody": "Invalid style.css rules can break the forum layout or make the site unusable.",
"warningHelp": "Upload a complete, tested file. If something goes wrong, delete the custom CSS to restore the default styles.",
"continueUpload": "I understand, upload"
},
"forum": {
"nameRequired": "Enter a forum name",
"saved": "Saved!",
"saveFailed": "Save failed",
"title": "Forum settings",
"nameLabel": "Forum name",
"save": "Save"
}
}
}
}
+141 -12
View File
@@ -17,8 +17,8 @@
"hot": "最新回复",
"newPost": "发布新帖",
"loading": "加载中...",
"empty": "✨ 还没有帖子,快来发布第一条吧!",
"pinned": "📌 置顶",
"empty": "还没有帖子,快来发布第一条吧!",
"pinned": "置顶",
"deleted": "(已编辑)",
"report": "举报",
"delete": "删除",
@@ -59,7 +59,7 @@
"reply": {
"submit": "提交回复",
"placeholder": "写下你的回复...",
"empty": "还没有回复,快来抢沙发吧 🛋️",
"empty": "还没有回复,快来发表第一条回复吧",
"replyFailed": "回复失败:{{msg}}",
"delete": "删除",
"confirmDelete": "确定要删除这条回复吗?",
@@ -72,7 +72,7 @@
"passwordHint": "密码(至少6位)",
"forgotPassword": "忘记密码?",
"captchaError": "验证码错误,请重新计算",
"registerSuccess": "🎉 注册成功",
"registerSuccess": "注册成功",
"loginSuccess": "登录成功",
"logoutSuccess": "已退出登录",
"login": "登录",
@@ -83,9 +83,18 @@
"profile": "个人资料",
"security": "安全设置",
"recovery": "恢复码",
"language": "语言",
"languageZh": "中文",
"languageEn": "English",
"username": "用户名",
"bio": "个人简介",
"signature": "个性签名",
"signatureHint": "显示在每篇帖子底部,支持 Markdown",
"signaturePlaceholder": "签名...",
"avatarFileRequired": "请选择图片文件",
"avatarTooLarge": "图片不能超过 5MB",
"avatarUpdated": "头像已更新",
"changeAvatar": "更换头像",
"save": "保存设置",
"saved": "保存成功!",
"saveFailed": "保存失败:{{msg}}",
@@ -96,9 +105,9 @@
"title": "用户主页",
"bioEmpty": "这个人很懒,什么都没写",
"sendMessage": "发私信",
"joined": "📅 加入于 {{date}}",
"posts": "📝 发了 {{count}} 个帖子",
"admin": "🛡️ 管理员",
"joined": "加入于 {{date}}",
"posts": "发了 {{count}} 个帖子",
"admin": "管理员",
"noPosts": "还没有发帖",
"notFound": "用户不存在",
"loading": "加载中..."
@@ -132,8 +141,8 @@
"changeEmail": "修改邮箱",
"fillAll": "请填写完整信息",
"pwMin": "新密码至少6位",
"pwChanged": "✅ 密码修改成功",
"emailChanged": "✅ 邮箱修改成功"
"pwChanged": "密码修改成功",
"emailChanged": "邮箱修改成功"
},
"recovery": {
"title": "恢复码",
@@ -144,8 +153,128 @@
"confirmRegenerate": "重新生成将使所有旧恢复码失效,确定继续吗?",
"genFailed": "生成失败:{{msg}}",
"fetchFailed": "获取失败:{{msg}}",
"newCodes": "🆕 新恢复码",
"saveWarning": "⚠️ 请妥善保存这些恢复码,关闭窗口后无法再次查看。",
"newCodes": "新恢复码",
"saveWarning": "请妥善保存这些恢复码,关闭窗口后无法再次查看。",
"saved": "我已保存"
},
"admin": {
"title": "管理后台",
"reports": "举报处理",
"users": "用户管理",
"logs": "事件日志",
"links": "友情链接",
"forumSettings": "论坛设置",
"customPages": "自定义页面",
"customCss": "自定义 CSS",
"common": {
"loading": "加载中...",
"loadFailed": "加载失败:{{msg}}",
"operationFailed": "操作失败:{{msg}}",
"deleteFailed": "删除失败:{{msg}}",
"saveFailed": "保存失败:{{msg}}",
"delete": "删除",
"save": "保存",
"cancel": "取消",
"actions": "操作",
"status": "状态",
"enabled": "启用",
"disabled": "禁用"
},
"report": {
"statusPending": "待处理",
"statusApproved": "已删除",
"statusRejected": "已驳回",
"approvedNote": "已删除违规帖子",
"rejectedNote": "举报不成立",
"confirmApprove": "确定要删除该帖子并标记举报为已处理吗?",
"empty": "暂无举报",
"anonymous": "匿名",
"reportedPost": "{{name}} 举报了帖子",
"reason": "原因:{{reason}}",
"post": "帖子:{{title}} — {{content}}",
"untitled": "无标题",
"handler": "处理人:{{name}}",
"deletePost": "删除帖子",
"reject": "驳回举报"
},
"user": {
"roleAdmin": "管理员",
"roleUser": "普通用户",
"confirmRole": "确定要将该用户设为「{{role}}」吗?",
"count": "共 {{count}} 位用户",
"user": "用户",
"role": "角色",
"registeredAt": "注册时间",
"you": "你",
"cannotSelf": "不可操作自己",
"makeUser": "设为普通用户",
"makeAdmin": "设为管理员"
},
"log": {
"empty": "暂无日志",
"time": "时间",
"user": "用户",
"action": "操作",
"system": "系统"
},
"link": {
"incomplete": "请填写完整信息",
"addFailed": "添加失败:{{msg}}",
"confirmDelete": "确定删除该链接吗?",
"namePlaceholder": "链接名称",
"urlPlaceholder": "链接地址",
"add": "添加",
"empty": "暂无友情链接"
},
"page": {
"confirmDelete": "确定要删除这个页面吗?",
"title": "自定义页面",
"add": "添加页面",
"empty": "暂无自定义页面",
"name": "名称",
"columnTitle": "标题",
"url": "URL",
"edit": "编辑页面",
"delete": "删除页面",
"editTitle": "编辑页面",
"addTitle": "添加页面",
"nameRequired": "请输入页面名称",
"titleRequired": "请输入导航栏显示名称",
"contentRequired": "请输入页面内容",
"nameInvalid": "页面名称只允许字母、数字、短横线和下划线",
"nameLabel": "页面名称",
"namePlaceholder": "about(用于 URL:?custom=about)",
"nameLocked": "名称不可修改",
"nameHint": "只允许字母、数字、短横线和下划线",
"navTitleLabel": "导航栏显示名称",
"navTitlePlaceholder": "关于我们",
"contentLabel": "页面内容(HTML + CSS + JS)",
"contentHelp": "支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染"
},
"css": {
"filenameInvalid": "文件名必须是 style.css",
"sizeInvalid": "CSS 文件不能超过 1MB",
"active": "自定义 CSS 已生效(刷新页面后应用)",
"confirmDelete": "确定要删除自定义 CSS 吗?",
"deleted": "已删除自定义 CSS",
"title": "自定义 CSS",
"description": "上传一个 style.css 文件覆盖默认样式(支持 CSS 变量、暗色模式等)。",
"releaseUpload": "松开上传",
"uploadHint": "点击或拖拽上传 style.css",
"save": "保存 CSS",
"delete": "删除自定义 CSS",
"warningTitle": "警告",
"warningBody": "若上传的 style.css 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。",
"warningHelp": "请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。",
"continueUpload": "我了解,继续上传"
},
"forum": {
"nameRequired": "请输入论坛名称",
"saved": "保存成功!",
"saveFailed": "保存失败",
"title": "论坛设置",
"nameLabel": "论坛名称",
"save": "保存"
}
}
}
}
+98
View File
@@ -0,0 +1,98 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFile, readdir } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
function flatten(value, prefix = '', result = new Map()) {
for (const [key, child] of Object.entries(value)) {
const fullKey = prefix ? `${prefix}.${key}` : key;
if (child && typeof child === 'object' && !Array.isArray(child)) {
flatten(child, fullKey, result);
} else {
result.set(fullKey, child);
}
}
return result;
}
async function readLocale(name) {
const source = await readFile(path.join(projectRoot, 'locales', `${name}.json`), 'utf8');
return flatten(JSON.parse(source));
}
async function sourceFiles(directory) {
const entries = await readdir(directory, { withFileTypes: true });
const nested = await Promise.all(entries.map(async (entry) => {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) return sourceFiles(target);
return /\.(?:css|js|jsx|json|ts|tsx)$/.test(entry.name) ? [target] : [];
}));
return nested.flat();
}
test('Chinese and English locales expose the same non-empty keys', async () => {
const [zh, en] = await Promise.all([readLocale('zh'), readLocale('en')]);
assert.deepEqual([...zh.keys()].sort(), [...en.keys()].sort());
for (const [locale, values] of [['zh', zh], ['en', en]]) {
for (const [key, value] of values) {
assert.equal(typeof value, 'string', `${locale}.${key} must be a string`);
assert.notEqual(value.trim(), '', `${locale}.${key} must not be empty`);
}
}
});
test('runtime UI contains no emoji except the approved chat greeting', async () => {
const roots = ['app', 'components', 'locales'].map((name) => path.join(projectRoot, name));
const files = (await Promise.all(roots.map(sourceFiles))).flat();
const occurrences = [];
for (const file of files) {
const source = await readFile(file, 'utf8');
for (const match of source.matchAll(/\p{Extended_Pictographic}/gu)) {
occurrences.push({
file: path.relative(projectRoot, file),
emoji: match[0],
});
}
}
assert.deepEqual(occurrences, [
{ file: 'components/chat/ChatWindow.js', emoji: '👋' },
]);
});
test('runtime UI does not call native alert or confirm dialogs', async () => {
const roots = ['app', 'components', 'lib'].map((name) => path.join(projectRoot, name));
const files = (await Promise.all(roots.map(sourceFiles))).flat();
const calls = [];
for (const file of files) {
const source = await readFile(file, 'utf8');
if (/\b(?:window\.)?(?:alert|confirm)\s*\(/.test(source)) {
calls.push(path.relative(projectRoot, file));
}
}
assert.deepEqual(calls, []);
});
test('every statically named Icon has an SVG path', async () => {
const componentsRoot = path.join(projectRoot, 'components');
const files = await sourceFiles(componentsRoot);
const iconSource = await readFile(path.join(componentsRoot, 'Icons.js'), 'utf8');
const definitions = new Set([...iconSource.matchAll(/^\s{2}(\w+): \(/gm)].map((match) => match[1]));
const usages = new Set();
for (const file of files) {
const source = await readFile(file, 'utf8');
for (const match of source.matchAll(/<Icon\s+[^>]*name="([A-Za-z0-9]+)"/g)) {
usages.add(match[1]);
}
}
assert.deepEqual([...usages].filter((name) => !definitions.has(name)).sort(), []);
});