feat: 增加友链申请、独立页面、投票/悬赏/抽奖帖与侧栏签到,并统一开发数据目录
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
56
frontend/package-lock.json
generated
56
frontend/package-lock.json
generated
@@ -8,6 +8,9 @@
|
||||
"name": "jiang13-forum-web",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@hookform/resolvers": "^5.4.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.16",
|
||||
"@radix-ui/react-dialog": "^1.1.16",
|
||||
@@ -352,6 +355,59 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/accessibility": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
||||
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/core": {
|
||||
"version": "6.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/sortable": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
|
||||
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@dnd-kit/core": "^6.3.0",
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/utilities": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
|
||||
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.21.5",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@hookform/resolvers": "^5.4.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.16",
|
||||
"@radix-ui/react-dialog": "^1.1.16",
|
||||
|
||||
@@ -31,6 +31,7 @@ const UserProfilePage = lazyWithRetry(() => import('./pages/UserProfilePage'));
|
||||
const FavoritesPage = lazyWithRetry(() => import('./pages/FavoritesPage'));
|
||||
const MessagesPage = lazyWithRetry(() => import('./pages/MessagesPage'));
|
||||
const ProjectsPage = lazyWithRetry(() => import('./pages/ProjectsPage'));
|
||||
const LinksPage = lazyWithRetry(() => import('./pages/LinksPage'));
|
||||
const AdminDashboardPage = lazyWithRetry(() => import('./pages/admin/AdminDashboardPage'));
|
||||
const AdminPostsPage = lazyWithRetry(() => import('./pages/admin/AdminPostsPage'));
|
||||
const AdminCommentsPage = lazyWithRetry(() => import('./pages/admin/AdminCommentsPage'));
|
||||
@@ -38,6 +39,9 @@ const AdminReportsPage = lazyWithRetry(() => import('./pages/admin/AdminReportsP
|
||||
const AdminUsersPage = lazyWithRetry(() => import('./pages/admin/AdminUsersPage'));
|
||||
const AdminBadgesPage = lazyWithRetry(() => import('./pages/admin/AdminBadgesPage'));
|
||||
const AdminMediaPage = lazyWithRetry(() => import('./pages/admin/AdminMediaPage'));
|
||||
const AdminPagesPage = lazyWithRetry(() => import('./pages/admin/AdminPagesPage'));
|
||||
const AdminLinksPage = lazyWithRetry(() => import('./pages/admin/AdminLinksPage'));
|
||||
const SitePageView = lazyWithRetry(() => import('./pages/SitePageView'));
|
||||
const AdminSettingsPage = lazyWithRetry(() => import('./pages/admin/AdminSettingsPage'));
|
||||
const NotFoundPage = lazyWithRetry(() => import('./pages/NotFoundPage'));
|
||||
|
||||
@@ -52,6 +56,8 @@ const router = createBrowserRouter(
|
||||
<Route index element={<Navigate to="/admin/dashboard" replace />} />
|
||||
<Route path="dashboard" element={<Suspense fallback={<PageLoader />}><AdminDashboardPage /></Suspense>} />
|
||||
<Route path="boards" element={<Suspense fallback={<PageLoader />}><BoardsManagePage /></Suspense>} />
|
||||
<Route path="pages" element={<Suspense fallback={<PageLoader />}><AdminPagesPage /></Suspense>} />
|
||||
<Route path="links" element={<Suspense fallback={<PageLoader />}><AdminLinksPage /></Suspense>} />
|
||||
<Route path="posts" element={<Suspense fallback={<PageLoader />}><AdminPostsPage /></Suspense>} />
|
||||
<Route path="comments" element={<Suspense fallback={<PageLoader />}><AdminCommentsPage /></Suspense>} />
|
||||
<Route path="reports" element={<Suspense fallback={<PageLoader />}><AdminReportsPage /></Suspense>} />
|
||||
@@ -63,6 +69,7 @@ const router = createBrowserRouter(
|
||||
</Route>
|
||||
<Route element={<MainLayout />}>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/board/:id" element={<HomePage />} />
|
||||
{/* :id 可为 123 或 123.html(伪静态后缀由后台配置) */}
|
||||
<Route path="/post/:id" element={<PostDetailPage />} />
|
||||
<Route path="/compose" element={<ComposePage />} />
|
||||
@@ -71,7 +78,9 @@ const router = createBrowserRouter(
|
||||
<Route path="/user/:id" element={<UserProfilePage />} />
|
||||
<Route path="/favorites" element={<FavoritesPage />} />
|
||||
<Route path="/projects" element={<ProjectsPage />} />
|
||||
<Route path="/links" element={<LinksPage />} />
|
||||
<Route path="/messages" element={<MessagesPage />} />
|
||||
<Route path="/page/:slug" element={<Suspense fallback={<PageLoader />}><SitePageView /></Suspense>} />
|
||||
<Route path="*" element={<Suspense fallback={<PageLoader />}><NotFoundPage /></Suspense>} />
|
||||
</Route>
|
||||
<Route path="*" element={<Suspense fallback={<PageLoader fullScreen />}><NotFoundPage standalone /></Suspense>} />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { User, UserPublic, UserActivityStats, Board, PostItem, Comment, RecentComment, ForumStats, TagCount, AdminDashboard, AdminSettings, ForumLimits, ForumLimitsPublic, PostDetailResponse, PostRevision, CommentRevision, MailConfig, OIDCConfig, OAuthClient, OAuthClientInput, GiteaProject, GiteaSyncConfig, StorageConfig, MediaListResult, SiteBranding, RegisterConfig, PrivateMessage, MessageConversation, PostReport, ReportReason, ReportStatus, BadgeDef, PointLedger, CheckInStatus, LotteryStatus } from './types';
|
||||
import type { User, UserPublic, UserActivityStats, Board, PostItem, Comment, RecentComment, ForumStats, TagCount, AdminDashboard, AdminSettings, ForumLimits, ForumLimitsPublic, PostDetailResponse, PostRevision, CommentRevision, MailConfig, OIDCConfig, OAuthClient, OAuthClientInput, GiteaProject, GiteaSyncConfig, StorageConfig, MediaListResult, SiteBranding, RegisterConfig, PrivateMessage, MessageConversation, PostReport, ReportReason, ReportStatus, BadgeDef, PointLedger, CheckInStatus, LotteryStatus, SitePage, SitePageSummary, PollView, PostLotteryView, FriendLinkApply } from './types';
|
||||
|
||||
const BASE = '';
|
||||
|
||||
@@ -26,6 +26,8 @@ export const api = {
|
||||
stats: () => request<ForumStats>('/api/stats'),
|
||||
forumLimits: () => request<ForumLimitsPublic>('/api/forum-limits'),
|
||||
siteBranding: () => request<SiteBranding>('/api/site-branding'),
|
||||
pages: () => request<{ pages: SitePageSummary[] }>('/api/pages'),
|
||||
page: (slug: string) => request<{ page: SitePage }>(`/api/pages/${encodeURIComponent(slug)}`),
|
||||
boards: () => request<{ boards: Board[] }>('/api/boards'),
|
||||
projects: (params?: { page?: number; limit?: number }) => {
|
||||
const q = new URLSearchParams();
|
||||
@@ -40,7 +42,6 @@ export const api = {
|
||||
const q = new URLSearchParams(params as Record<string, string>).toString();
|
||||
return request<{ posts: PostItem[]; total: number; page: number; has_more: boolean }>(`/api/posts?${q}`);
|
||||
},
|
||||
hotPosts: () => request<{ posts: PostItem[] }>('/api/posts/hot'),
|
||||
tags: (limit = 40) => request<{ tags: TagCount[] }>(`/api/tags?limit=${limit}`),
|
||||
post: (id: number, opts?: { skipView?: boolean }) => {
|
||||
const q = opts?.skipView ? '?skip_view=1' : '';
|
||||
@@ -285,6 +286,7 @@ export const api = {
|
||||
check_in: CheckInStatus;
|
||||
lottery: LotteryStatus;
|
||||
}>(`/api/me/points?page=${page}`),
|
||||
checkInStatus: () => request<{ check_in: CheckInStatus }>('/api/me/check-in'),
|
||||
checkIn: () =>
|
||||
request<{ message: string; check_in: CheckInStatus; points: number }>('/api/me/check-in', { method: 'POST' }),
|
||||
lotteryStatus: () => request<{ lottery: LotteryStatus }>('/api/me/lottery'),
|
||||
@@ -341,13 +343,19 @@ export const api = {
|
||||
fd.append('image', file);
|
||||
return request<{ url: string }>('/api/uploads/image', { method: 'POST', body: fd, headers: {} });
|
||||
},
|
||||
createPost: (data: { board_id: string; title: string; content: string; tags?: string; post_type?: string }) => {
|
||||
createPost: (data: {
|
||||
board_id: string; title: string; content: string; tags?: string; post_type?: string;
|
||||
poll_options?: string; bounty_points?: number; lottery_winner_count?: number;
|
||||
}) => {
|
||||
const fd = new FormData();
|
||||
fd.append('board_id', data.board_id);
|
||||
fd.append('title', data.title);
|
||||
fd.append('content', data.content);
|
||||
fd.append('tags', data.tags || '');
|
||||
fd.append('post_type', data.post_type || 'normal');
|
||||
if (data.poll_options) fd.append('poll_options', data.poll_options);
|
||||
if (data.bounty_points != null) fd.append('bounty_points', String(data.bounty_points));
|
||||
if (data.lottery_winner_count != null) fd.append('lottery_winner_count', String(data.lottery_winner_count));
|
||||
return request<{ post_id: number; message?: string; status?: string }>('/api/posts', { method: 'POST', body: fd, headers: {} });
|
||||
},
|
||||
updatePost: (id: number, data: { title: string; content: string; tags?: string; board_id?: string | number; post_type?: string }) => {
|
||||
@@ -372,6 +380,59 @@ export const api = {
|
||||
headers: {},
|
||||
});
|
||||
},
|
||||
pollVote: (id: number, optionIds: number[]) =>
|
||||
request<{ message: string; poll: PollView }>(`/api/posts/${id}/poll/vote`, {
|
||||
method: 'POST', body: JSON.stringify({ option_ids: optionIds }),
|
||||
}),
|
||||
pollClose: (id: number) =>
|
||||
request<{ message: string; poll: PollView }>(`/api/posts/${id}/poll/close`, { method: 'POST', body: '{}' }),
|
||||
bountyAward: (id: number, commentId: number) => {
|
||||
const fd = new FormData();
|
||||
fd.append('comment_id', String(commentId));
|
||||
return request<{ message: string }>(`/api/posts/${id}/bounty/award`, { method: 'POST', body: fd, headers: {} });
|
||||
},
|
||||
bountyRefund: (id: number) =>
|
||||
request<{ message: string }>(`/api/posts/${id}/bounty/refund`, { method: 'POST', body: '{}' }),
|
||||
postLotteryDraw: (id: number) =>
|
||||
request<{ message: string; lottery: PostLotteryView }>(`/api/posts/${id}/lottery/draw`, { method: 'POST', body: '{}' }),
|
||||
adminPages: () => request<{ pages: SitePage[] }>('/api/admin/pages'),
|
||||
adminCreatePage: (data: Partial<SitePage>) =>
|
||||
request<{ message: string; page: SitePage }>('/api/admin/pages', { method: 'POST', body: JSON.stringify(data) }),
|
||||
adminUpdatePage: (id: number, data: Partial<SitePage>) =>
|
||||
request<{ message: string }>(`/api/admin/pages/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
adminDeletePage: (id: number) =>
|
||||
request<{ message: string }>(`/api/admin/pages/${id}`, { method: 'DELETE' }),
|
||||
adminFriendLinkApplies: (params?: { page?: number; size?: number; status?: string }) => {
|
||||
const q = new URLSearchParams();
|
||||
if (params?.page) q.set('page', String(params.page));
|
||||
if (params?.size) q.set('size', String(params.size));
|
||||
if (params?.status) q.set('status', params.status);
|
||||
const qs = q.toString();
|
||||
return request<{
|
||||
applies: FriendLinkApply[];
|
||||
total: number;
|
||||
page: number;
|
||||
pending_count: number;
|
||||
reciprocal_check_enabled?: boolean;
|
||||
}>(`/api/admin/friend-link-applies${qs ? `?${qs}` : ''}`);
|
||||
},
|
||||
adminUpdateFriendLinkSettings: (body: { reciprocal_check_enabled: boolean }) =>
|
||||
request<{ message: string; reciprocal_check_enabled: boolean }>('/api/admin/friend-link-settings', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
adminApproveFriendLinkApply: (id: number) =>
|
||||
request<{ message: string; apply: FriendLinkApply }>(`/api/admin/friend-link-applies/${id}/approve`, {
|
||||
method: 'POST', body: '{}',
|
||||
}),
|
||||
adminRejectFriendLinkApply: (id: number, body?: { note?: string }) =>
|
||||
request<{ message: string; apply: FriendLinkApply }>(`/api/admin/friend-link-applies/${id}/reject`, {
|
||||
method: 'POST', body: JSON.stringify(body ?? {}),
|
||||
}),
|
||||
adminRecheckFriendLinkApply: (id: number) =>
|
||||
request<{ message: string; apply: FriendLinkApply }>(`/api/admin/friend-link-applies/${id}/recheck`, {
|
||||
method: 'POST',
|
||||
}),
|
||||
deletePost: (id: number) => request<{ message: string }>(`/api/posts/${id}`, { method: 'DELETE' }),
|
||||
login: (username: string, password: string) => {
|
||||
const fd = new FormData();
|
||||
@@ -425,6 +486,37 @@ export const api = {
|
||||
like: (id: number) => request<{ liked: boolean; like_count: number }>(`/api/posts/${id}/like`, { method: 'POST' }),
|
||||
likeComment: (id: number) => request<{ liked: boolean; like_count: number }>(`/api/comments/${id}/like`, { method: 'POST' }),
|
||||
favorite: (id: number) => request<{ favorited: boolean }>(`/api/posts/${id}/favorite`, { method: 'POST' }),
|
||||
applyFriendLink: (body: {
|
||||
name: string;
|
||||
url: string;
|
||||
logo: string;
|
||||
link_on_homepage: boolean;
|
||||
reciprocal_page_url?: string;
|
||||
}) =>
|
||||
request<{ message: string; apply: FriendLinkApply; warning?: string }>('/api/friend-links/apply', {
|
||||
method: 'POST', body: JSON.stringify(body),
|
||||
}),
|
||||
uploadFriendLinkLogo: (file: File) => {
|
||||
const fd = new FormData();
|
||||
fd.append('logo', file);
|
||||
return request<{ message: string; url: string }>('/api/friend-links/logo', {
|
||||
method: 'POST', body: fd, headers: {},
|
||||
});
|
||||
},
|
||||
myFriendLinkApplies: () =>
|
||||
request<{ applies: FriendLinkApply[] }>('/api/friend-links/my-applies'),
|
||||
updateFriendLinkApply: (id: number, body: {
|
||||
name: string;
|
||||
url: string;
|
||||
logo: string;
|
||||
link_on_homepage: boolean;
|
||||
reciprocal_page_url?: string;
|
||||
}) =>
|
||||
request<{ message: string; apply: FriendLinkApply; warning?: string }>(`/api/friend-links/applies/${id}`, {
|
||||
method: 'PUT', body: JSON.stringify(body),
|
||||
}),
|
||||
cancelFriendLinkApply: (id: number) =>
|
||||
request<{ message: string }>(`/api/friend-links/applies/${id}`, { method: 'DELETE' }),
|
||||
reportPost: (id: number, body: { reason: ReportReason; detail?: string }) =>
|
||||
request<{ message: string; report: PostReport }>(`/api/posts/${id}/report`, {
|
||||
method: 'POST', body: JSON.stringify(body),
|
||||
|
||||
@@ -69,6 +69,7 @@ export interface ForumStats {
|
||||
users: number;
|
||||
posts: number;
|
||||
boards: number;
|
||||
comments: number;
|
||||
}
|
||||
|
||||
/** 标签云单项 */
|
||||
@@ -84,10 +85,15 @@ export interface PostItem {
|
||||
title: string;
|
||||
content?: string;
|
||||
tags: string;
|
||||
/** normal=讨论 | question=问答 */
|
||||
post_type?: 'normal' | 'question' | string;
|
||||
/** normal=讨论 | question=问答 | poll=投票 | bounty=悬赏 | lottery=抽奖 */
|
||||
post_type?: 'normal' | 'question' | 'poll' | 'bounty' | 'lottery' | string;
|
||||
/** 仅问答帖有意义 */
|
||||
question_resolved?: boolean;
|
||||
bounty_points?: number;
|
||||
bounty_status?: 'open' | 'awarded' | 'refunded' | string;
|
||||
bounty_comment_id?: number;
|
||||
lottery_winner_count?: number;
|
||||
lottery_status?: 'open' | 'drawn' | string;
|
||||
pinned: boolean;
|
||||
/** 板块内置顶(仅板块列表抬升,首页不抬升) */
|
||||
board_pinned?: boolean;
|
||||
@@ -131,12 +137,18 @@ export interface PostDetailResponse {
|
||||
comment_count: number;
|
||||
liked: boolean;
|
||||
favorited: boolean;
|
||||
/** 当前用户是否已在本帖发表过评论(含审核中) */
|
||||
has_replied?: boolean;
|
||||
can_edit?: boolean;
|
||||
edit_block_reason?: string;
|
||||
is_edited?: boolean;
|
||||
post_edit_window_hours?: number;
|
||||
poll?: PollView;
|
||||
lottery?: PostLotteryView;
|
||||
/** 悬赏进行中:当前用户是否可取消悬赏 */
|
||||
bounty_can_refund?: boolean;
|
||||
bounty_refund_block_reason?: string;
|
||||
/** 他人已发布有效回复数 */
|
||||
bounty_eligible_reply_count?: number;
|
||||
}
|
||||
|
||||
export interface Comment {
|
||||
@@ -171,9 +183,23 @@ export interface AdminDashboard {
|
||||
pending_posts?: number;
|
||||
pending_comments?: number;
|
||||
pending_reports?: number;
|
||||
pending_friend_links?: number;
|
||||
recent_posts: PostItem[];
|
||||
}
|
||||
|
||||
export type AsideWidgetId = 'tag_cloud' | 'recent_comments' | 'friend_links';
|
||||
|
||||
export interface AsideWidget {
|
||||
id: AsideWidgetId;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_ASIDE_WIDGETS: AsideWidget[] = [
|
||||
{ id: 'tag_cloud', enabled: false },
|
||||
{ id: 'recent_comments', enabled: false },
|
||||
{ id: 'friend_links', enabled: true },
|
||||
];
|
||||
|
||||
export interface ForumLimits {
|
||||
post_edit_window_hours: number;
|
||||
comment_edit_window_minutes: number;
|
||||
@@ -194,6 +220,16 @@ export interface ForumLimits {
|
||||
signature_max: number;
|
||||
open_posts_in_new_tab: boolean;
|
||||
open_content_links_in_new_tab: boolean;
|
||||
/** 右侧栏标签云 */
|
||||
aside_show_tag_cloud: boolean;
|
||||
/** 右侧栏最新评论 */
|
||||
aside_show_recent_comments: boolean;
|
||||
/** 右侧栏友情链接 */
|
||||
aside_show_friend_links: boolean;
|
||||
/** 右侧栏可选组件顺序与开关 */
|
||||
aside_widgets: AsideWidget[];
|
||||
/** 首页列表样式:title 仅标题 / thumbnail 缩略图 */
|
||||
feed_list_style: 'title' | 'excerpt' | 'thumbnail';
|
||||
/** 伪静态(固定链接)开关 */
|
||||
permalink_enabled: boolean;
|
||||
/** 伪静态后缀,不含点,如 html / htm */
|
||||
@@ -214,6 +250,11 @@ export interface ForumLimitsPublic {
|
||||
signature_max: number;
|
||||
open_posts_in_new_tab: boolean;
|
||||
open_content_links_in_new_tab: boolean;
|
||||
aside_show_tag_cloud: boolean;
|
||||
aside_show_recent_comments: boolean;
|
||||
aside_show_friend_links: boolean;
|
||||
aside_widgets: AsideWidget[];
|
||||
feed_list_style: 'title' | 'excerpt' | 'thumbnail';
|
||||
permalink_enabled: boolean;
|
||||
permalink_ext: string;
|
||||
}
|
||||
@@ -221,12 +262,77 @@ export interface ForumLimitsPublic {
|
||||
export interface FriendLink {
|
||||
name: string;
|
||||
url: string;
|
||||
logo?: string;
|
||||
}
|
||||
|
||||
export interface FriendLinkApply {
|
||||
id: number;
|
||||
user_id: number;
|
||||
name: string;
|
||||
url: string;
|
||||
description?: string;
|
||||
logo?: string;
|
||||
reciprocal_page_url?: string;
|
||||
link_on_homepage?: boolean;
|
||||
reciprocal_verified?: boolean;
|
||||
reciprocal_check_note?: string;
|
||||
reciprocal_checked_at?: string;
|
||||
status: 'pending' | 'approved' | 'rejected';
|
||||
review_note?: string;
|
||||
reviewed_at?: string;
|
||||
created_at: string;
|
||||
user?: User;
|
||||
}
|
||||
|
||||
export interface SitePageSummary {
|
||||
id: number;
|
||||
title: string;
|
||||
slug: string;
|
||||
show_in_footer?: boolean;
|
||||
show_in_nav?: boolean;
|
||||
sort_order?: number;
|
||||
}
|
||||
|
||||
export interface SitePage extends SitePageSummary {
|
||||
content: string;
|
||||
published: boolean;
|
||||
}
|
||||
|
||||
export interface PollOptionView {
|
||||
id: number;
|
||||
text: string;
|
||||
vote_count: number;
|
||||
percent?: number;
|
||||
}
|
||||
|
||||
export interface PollView {
|
||||
multi: boolean;
|
||||
max_choices: number;
|
||||
closed: boolean;
|
||||
ends_at?: string;
|
||||
options: PollOptionView[];
|
||||
my_option_ids?: number[];
|
||||
total_votes: number;
|
||||
}
|
||||
|
||||
export interface PostLotteryWinnerView {
|
||||
user_id: number;
|
||||
username: string;
|
||||
nickname: string;
|
||||
comment_id: number;
|
||||
}
|
||||
|
||||
export interface PostLotteryView {
|
||||
winner_count: number;
|
||||
status: string;
|
||||
participant_count: number;
|
||||
winners?: PostLotteryWinnerView[];
|
||||
}
|
||||
|
||||
export interface SiteBranding {
|
||||
name: string;
|
||||
slogan: string;
|
||||
/** 站点简介(首页可见 + SEO description) */
|
||||
/** 站点简介(右侧栏顶部 + SEO description) */
|
||||
description?: string;
|
||||
/** SEO keywords,逗号分隔 */
|
||||
keywords?: string;
|
||||
@@ -241,6 +347,8 @@ export interface SiteBranding {
|
||||
icp_beian_url?: string;
|
||||
/** 页脚友情链接 */
|
||||
friend_links?: FriendLink[];
|
||||
/** 公开站点根 URL(API 动态填充) */
|
||||
site_url?: string;
|
||||
}
|
||||
|
||||
export interface AdminSettings {
|
||||
|
||||
104
frontend/src/components/AsideCheckInStrip.tsx
Normal file
104
frontend/src/components/AsideCheckInStrip.tsx
Normal file
@@ -0,0 +1,104 @@
|
||||
import { CalendarCheck, Check, Gift, Loader2 } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { useCheckIn } from '../hooks/useCheckIn';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { loginPath } from '../utils/authRedirect';
|
||||
|
||||
/** 右侧栏首块底部:每日签到 */
|
||||
export default function AsideCheckInStrip() {
|
||||
const nav = useNavigate();
|
||||
const { user } = useAuth();
|
||||
const { status, loading, busy, doCheckIn } = useCheckIn();
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<div className="widget-checkin">
|
||||
<div className="widget-checkin-panel widget-checkin-panel--guest">
|
||||
<div className="widget-checkin-main">
|
||||
<div className="widget-checkin-icon" aria-hidden>
|
||||
<CalendarCheck size={18} strokeWidth={2.25} />
|
||||
</div>
|
||||
<div className="widget-checkin-info">
|
||||
<span className="widget-checkin-title">每日签到</span>
|
||||
<span className="widget-checkin-meta">登录后每日可得 5–15 积分</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="widget-checkin-action"
|
||||
onClick={() => nav(loginPath())}
|
||||
>
|
||||
<Gift size={15} aria-hidden />
|
||||
登录签到
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (loading && !status) {
|
||||
return (
|
||||
<div className="widget-checkin" aria-busy="true" aria-label="签到加载中">
|
||||
<Skeleton className="widget-checkin-skeleton" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const checkedIn = !!status?.checked_in;
|
||||
const streak = status?.streak ?? 0;
|
||||
const todayPoints = status?.today_points ?? 5;
|
||||
|
||||
const meta = checkedIn
|
||||
? (streak > 0 ? `连续 ${streak} 天 · 今日已获得 ${todayPoints} 积分` : `今日已获得 ${todayPoints} 积分`)
|
||||
: (streak > 0 ? `连续 ${streak} 天 · 今日可得 ${todayPoints} 积分` : `今日签到可得 ${todayPoints} 积分`);
|
||||
|
||||
return (
|
||||
<div className="widget-checkin">
|
||||
<div
|
||||
className={`widget-checkin-panel${checkedIn ? ' widget-checkin-panel--done' : ''}`}
|
||||
>
|
||||
<div className="widget-checkin-main">
|
||||
<div className="widget-checkin-icon" aria-hidden>
|
||||
{checkedIn ? (
|
||||
<Check size={18} strokeWidth={2.5} />
|
||||
) : (
|
||||
<CalendarCheck size={18} strokeWidth={2.25} />
|
||||
)}
|
||||
</div>
|
||||
<div className="widget-checkin-info">
|
||||
<span className="widget-checkin-title">
|
||||
{checkedIn ? '今日已签到' : '每日签到'}
|
||||
</span>
|
||||
<span className="widget-checkin-meta">{meta}</span>
|
||||
</div>
|
||||
{!checkedIn && (
|
||||
<span className="widget-checkin-reward" aria-hidden>
|
||||
{todayPoints}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{!checkedIn && (
|
||||
<button
|
||||
type="button"
|
||||
className="widget-checkin-action"
|
||||
disabled={busy}
|
||||
onClick={doCheckIn}
|
||||
>
|
||||
{busy ? (
|
||||
<>
|
||||
<Loader2 size={15} className="widget-checkin-action-spinner animate-spin" aria-hidden />
|
||||
签到中…
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Gift size={15} aria-hidden />
|
||||
立即签到
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Check, Clock, History, MessageSquare, X, Pencil, Trash2,
|
||||
Check, Award, Clock, History, MessageSquare, X, Pencil, Trash2,
|
||||
ThumbsUp, MoreHorizontal, Flag,
|
||||
} from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
@@ -51,6 +51,7 @@ import { isHtmlEmpty } from '../utils/postContent';
|
||||
import { Tooltip } from './ui/Tooltip';
|
||||
import UserLink from './UserLink';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { pinAwardedCommentTree } from '../utils/bounty';
|
||||
|
||||
function isCommentAuthor(c: Comment, user?: User | null): boolean {
|
||||
return !!user && c.user_id > 0 && c.user_id === user.id;
|
||||
@@ -83,6 +84,13 @@ interface ItemProps {
|
||||
onRequireLogin?: (actionLabel: string) => void;
|
||||
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
|
||||
renderReplyBox?: (comment: Comment) => ReactNode;
|
||||
bountyAward?: {
|
||||
open: boolean;
|
||||
awardedCommentId?: number;
|
||||
postAuthorId: number;
|
||||
canAward: boolean;
|
||||
onAward: (commentId: number) => void;
|
||||
};
|
||||
}
|
||||
|
||||
/** 单条评论(支持嵌套子回复 + 内联回复框 + 编辑/删除) */
|
||||
@@ -103,12 +111,14 @@ function CommentItem({
|
||||
onRequireLogin,
|
||||
onLikeUpdate,
|
||||
renderReplyBox,
|
||||
bountyAward,
|
||||
}: ItemProps) {
|
||||
const { limits } = useForumLimits();
|
||||
const c = node.comment;
|
||||
const nick = commentNick(c);
|
||||
const guest = isGuestComment(c);
|
||||
const isHighlighted = highlightFloor === c.floor;
|
||||
const isBountyAwarded = bountyAward?.awardedCommentId === c.id;
|
||||
const hidden = !!c.content_hidden;
|
||||
const isReplying = replyToId === c.id;
|
||||
const isEditing = editingId === c.id;
|
||||
@@ -215,7 +225,12 @@ function CommentItem({
|
||||
return (
|
||||
<div
|
||||
id={`floor-${c.floor}`}
|
||||
className={`waline-comment ${nested ? 'nested' : ''} ${isHighlighted ? 'highlight' : ''}`}
|
||||
className={cn(
|
||||
'waline-comment',
|
||||
nested && 'nested',
|
||||
isHighlighted && 'highlight',
|
||||
isBountyAwarded && 'waline-comment--bounty-awarded',
|
||||
)}
|
||||
>
|
||||
{!guest && c.user_id ? (
|
||||
<UserLink
|
||||
@@ -255,6 +270,12 @@ function CommentItem({
|
||||
) : (
|
||||
<span className="waline-comment-author">{nick}</span>
|
||||
)}
|
||||
{isBountyAwarded && (
|
||||
<span className="waline-comment-bounty-badge" title="悬赏已采纳">
|
||||
<Check size={12} aria-hidden />
|
||||
已采纳
|
||||
</span>
|
||||
)}
|
||||
{!hidden && (
|
||||
<button
|
||||
type="button"
|
||||
@@ -351,6 +372,17 @@ function CommentItem({
|
||||
编辑
|
||||
</button>
|
||||
)}
|
||||
{bountyAward?.open && bountyAward.canAward && c.user_id !== bountyAward.postAuthorId
|
||||
&& c.status === 'published' && !hidden && (
|
||||
<button
|
||||
type="button"
|
||||
className="bounty-award-btn"
|
||||
onClick={() => bountyAward.onAward(c.id)}
|
||||
>
|
||||
<Award size={14} aria-hidden />
|
||||
采纳
|
||||
</button>
|
||||
)}
|
||||
{!hidden && !isEditing && isAdmin && showEdited && (
|
||||
<button type="button" className="waline-comment-reply-btn" onClick={() => setRevOpen(true)}>
|
||||
<History size={14} />
|
||||
@@ -481,6 +513,7 @@ function CommentItem({
|
||||
onRequireLogin={onRequireLogin}
|
||||
onLikeUpdate={onLikeUpdate}
|
||||
renderReplyBox={renderReplyBox}
|
||||
bountyAward={bountyAward}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -506,6 +539,7 @@ interface Props {
|
||||
onRequireLogin?: (actionLabel: string) => void;
|
||||
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
|
||||
renderReplyBox?: (comment: Comment) => ReactNode;
|
||||
bountyAward?: ItemProps['bountyAward'];
|
||||
}
|
||||
|
||||
/** Waline 嵌套楼层评论列表 */
|
||||
@@ -525,8 +559,12 @@ export default function CommentThreadList({
|
||||
onRequireLogin,
|
||||
onLikeUpdate,
|
||||
renderReplyBox,
|
||||
bountyAward,
|
||||
}: Props) {
|
||||
const tree = buildCommentTree(comments);
|
||||
const tree = pinAwardedCommentTree(
|
||||
buildCommentTree(comments),
|
||||
bountyAward?.awardedCommentId,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="comment-thread-list">
|
||||
@@ -548,6 +586,7 @@ export default function CommentThreadList({
|
||||
onRequireLogin={onRequireLogin}
|
||||
onLikeUpdate={onLikeUpdate}
|
||||
renderReplyBox={renderReplyBox}
|
||||
bountyAward={bountyAward}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Users, FileText, LayoutGrid } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import type { Board, ForumStats } from '../api/types';
|
||||
import { navigateFeed } from '../utils/feedCache';
|
||||
|
||||
interface Props {
|
||||
boardId: number;
|
||||
@@ -81,7 +82,7 @@ export default function FeedHeader({
|
||||
<button
|
||||
type="button"
|
||||
className="feed-head__clear"
|
||||
onClick={() => nav('/')}
|
||||
onClick={() => navigateFeed(nav, '/')}
|
||||
>
|
||||
{tag ? '清除标签' : '清除搜索'}
|
||||
</button>
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import PostListSkeleton from './PostListSkeleton';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
|
||||
/** 首页 Feed 初始骨架(标题区 + 排序栏 + 列表) */
|
||||
export default function FeedPageSkeleton() {
|
||||
const { limits } = useForumLimits();
|
||||
|
||||
return (
|
||||
<div className="page-wrap page-wrap--feed" aria-busy="true" aria-label="内容加载中">
|
||||
<div className="feed-panel">
|
||||
@@ -27,7 +30,7 @@ export default function FeedPageSkeleton() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="post-list-scroll">
|
||||
<PostListSkeleton />
|
||||
<PostListSkeleton listStyle={limits.feed_list_style ?? 'title'} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useRef } from 'react';
|
||||
import { boardPath, type PermalinkOpts } from '../utils/permalink';
|
||||
import { getCachedForumLimits } from '../hooks/useForumLimits';
|
||||
import { Clock, MessageCircle, Flame } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { moveTabIndex } from '../hooks/useOverlayA11y';
|
||||
@@ -30,10 +32,9 @@ export function parseFeedSort(raw: string | null): FeedSort {
|
||||
export function buildHomeUrl(
|
||||
boardId: number,
|
||||
sort: FeedSort = 'latest',
|
||||
opts?: { keyword?: string; tag?: string; author?: string; titleOnly?: boolean },
|
||||
opts?: { keyword?: string; tag?: string; author?: string; titleOnly?: boolean; permalink?: PermalinkOpts },
|
||||
) {
|
||||
const p = new URLSearchParams();
|
||||
if (boardId) p.set('board', String(boardId));
|
||||
const tag = opts?.tag?.trim();
|
||||
const keyword = opts?.keyword?.trim();
|
||||
const author = opts?.author?.trim();
|
||||
@@ -48,6 +49,11 @@ export function buildHomeUrl(
|
||||
}
|
||||
if (sort !== 'latest') p.set('sort', sort);
|
||||
const qs = p.toString();
|
||||
|
||||
if (boardId) {
|
||||
const base = boardPath(boardId, opts?.permalink ?? getCachedForumLimits());
|
||||
return qs ? `${base}?${qs}` : base;
|
||||
}
|
||||
return qs ? `/?${qs}` : '/';
|
||||
}
|
||||
|
||||
|
||||
276
frontend/src/components/FriendLinkApplyDialog.tsx
Normal file
276
frontend/src/components/FriendLinkApplyDialog.tsx
Normal file
@@ -0,0 +1,276 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link2, Upload } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { api } from '../api/client';
|
||||
import type { FriendLinkApply } from '../api/types';
|
||||
import { getCachedSiteBranding } from '../hooks/useSiteBranding';
|
||||
import { resolveFriendLinkLogo } from '../utils/friendLink';
|
||||
import FriendLinkSiteInfo from './FriendLinkSiteInfo';
|
||||
|
||||
type LinkPlacement = 'homepage' | 'custom';
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
editApply?: FriendLinkApply | null;
|
||||
onSubmitted?: () => void;
|
||||
}
|
||||
|
||||
/** 友链申请 / 修改弹窗 */
|
||||
export default function FriendLinkApplyDialog({ open, onOpenChange, editApply, onSubmitted }: Props) {
|
||||
const [name, setName] = useState('');
|
||||
const [url, setUrl] = useState('');
|
||||
const [logo, setLogo] = useState('');
|
||||
const [linkPlacement, setLinkPlacement] = useState<LinkPlacement>('homepage');
|
||||
const [reciprocalPageURL, setReciprocalPageURL] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [uploadingLogo, setUploadingLogo] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const isEdit = !!editApply?.id;
|
||||
|
||||
const reset = () => {
|
||||
setName('');
|
||||
setUrl('');
|
||||
setLogo('');
|
||||
setLinkPlacement('homepage');
|
||||
setReciprocalPageURL('');
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (editApply) {
|
||||
setName(editApply.name ?? '');
|
||||
setUrl(editApply.url ?? '');
|
||||
setLogo(editApply.logo ?? '');
|
||||
const onHomepage = editApply.link_on_homepage !== false;
|
||||
setLinkPlacement(onHomepage ? 'homepage' : 'custom');
|
||||
setReciprocalPageURL(onHomepage ? '' : (editApply.reciprocal_page_url ?? ''));
|
||||
} else {
|
||||
reset();
|
||||
}
|
||||
}, [open, editApply]);
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next) reset();
|
||||
onOpenChange(next);
|
||||
};
|
||||
|
||||
const uploadLogo = async (file: File | undefined) => {
|
||||
if (!file) return;
|
||||
setUploadingLogo(true);
|
||||
try {
|
||||
const r = await api.uploadFriendLinkLogo(file);
|
||||
setLogo(r.url);
|
||||
notify.success('LOGO 已上传');
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '上传失败');
|
||||
} finally {
|
||||
setUploadingLogo(false);
|
||||
if (fileRef.current) fileRef.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const submit = async () => {
|
||||
const trimmedName = name.trim();
|
||||
const trimmedURL = url.trim();
|
||||
const trimmedLogo = logo.trim();
|
||||
const trimmedReciprocal = reciprocalPageURL.trim();
|
||||
if (!trimmedName || !trimmedURL) {
|
||||
notify.warning('请填写网站名称与网站链接');
|
||||
return;
|
||||
}
|
||||
if (!/^https?:\/\//i.test(trimmedURL)) {
|
||||
notify.warning('网站链接需以 http:// 或 https:// 开头');
|
||||
return;
|
||||
}
|
||||
if (!trimmedLogo) {
|
||||
notify.warning('请填写或上传网站 LOGO');
|
||||
return;
|
||||
}
|
||||
if (linkPlacement === 'custom') {
|
||||
if (!trimmedReciprocal) {
|
||||
notify.warning('请填写添加本站链接的页面地址');
|
||||
return;
|
||||
}
|
||||
if (!/^https?:\/\//i.test(trimmedReciprocal)) {
|
||||
notify.warning('回链页地址需以 http:// 或 https:// 开头');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const linkOnHomepage = linkPlacement === 'homepage';
|
||||
const body = {
|
||||
name: trimmedName,
|
||||
url: trimmedURL,
|
||||
logo: trimmedLogo,
|
||||
link_on_homepage: linkOnHomepage,
|
||||
reciprocal_page_url: linkOnHomepage ? trimmedURL : trimmedReciprocal,
|
||||
};
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
if (isEdit) {
|
||||
const r = await api.updateFriendLinkApply(editApply!.id, body);
|
||||
notify.success(
|
||||
editApply?.status === 'approved'
|
||||
? `已更新并重新提交审核,友链已暂时从列表移除${r.message.includes('回链检测') ? ',回链检测将在后台进行' : ''}`
|
||||
: r.message,
|
||||
);
|
||||
} else {
|
||||
const r = await api.applyFriendLink(body);
|
||||
notify.success(r.message);
|
||||
}
|
||||
onSubmitted?.();
|
||||
handleOpenChange(false);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '提交失败');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const logoPreview = resolveFriendLinkLogo(logo.trim(), getCachedSiteBranding().site_url);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="friend-link-apply-dialog sm:max-w-[560px]">
|
||||
<DialogHeader className="friend-link-apply-dialog__header">
|
||||
<DialogTitle>{isEdit ? '修改友链申请' : '申请本页友情链接'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<FriendLinkSiteInfo />
|
||||
|
||||
<div className="friend-link-apply-form">
|
||||
<div className="friend-link-apply-field">
|
||||
<Label htmlFor="friend-link-name">网站名称</Label>
|
||||
<Input
|
||||
id="friend-link-name"
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
placeholder="请输入您的网站名称"
|
||||
maxLength={32}
|
||||
/>
|
||||
</div>
|
||||
<div className="friend-link-apply-field">
|
||||
<Label htmlFor="friend-link-url">网站链接</Label>
|
||||
<Input
|
||||
id="friend-link-url"
|
||||
value={url}
|
||||
onChange={e => setUrl(e.target.value)}
|
||||
placeholder="请输入您的网站地址(以 http 开头)"
|
||||
maxLength={512}
|
||||
/>
|
||||
</div>
|
||||
<div className="friend-link-apply-field">
|
||||
<Label>本站链接放置位置</Label>
|
||||
<div className="friend-link-apply-placement" role="radiogroup" aria-label="本站链接放置位置">
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={linkPlacement === 'homepage'}
|
||||
className={cn(
|
||||
'friend-link-apply-placement__option',
|
||||
linkPlacement === 'homepage' && 'friend-link-apply-placement__option--active',
|
||||
)}
|
||||
onClick={() => setLinkPlacement('homepage')}
|
||||
>
|
||||
友链在我的网站首页
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={linkPlacement === 'custom'}
|
||||
className={cn(
|
||||
'friend-link-apply-placement__option',
|
||||
linkPlacement === 'custom' && 'friend-link-apply-placement__option--active',
|
||||
)}
|
||||
onClick={() => setLinkPlacement('custom')}
|
||||
>
|
||||
友链在其它页面
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{linkPlacement === 'custom' && (
|
||||
<div className="friend-link-apply-field">
|
||||
<Label htmlFor="friend-link-reciprocal">添加我方链接的页面地址</Label>
|
||||
<Input
|
||||
id="friend-link-reciprocal"
|
||||
value={reciprocalPageURL}
|
||||
onChange={e => setReciprocalPageURL(e.target.value)}
|
||||
placeholder="如:https://您的域名/link.htm"
|
||||
maxLength={512}
|
||||
/>
|
||||
<p className="friend-link-apply-field__hint">
|
||||
请填写实际放置本站友链的页面,提交后将在后台检测该页面
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="friend-link-apply-field">
|
||||
<Label htmlFor="friend-link-logo">填写或上传网站 LOGO</Label>
|
||||
<div className="friend-link-apply-logo-row">
|
||||
<div className="friend-link-apply-logo-preview" aria-label="LOGO 预览">
|
||||
{logoPreview ? (
|
||||
<img src={logoPreview} alt="" loading="lazy" decoding="async" />
|
||||
) : (
|
||||
<span>预览</span>
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
id="friend-link-logo"
|
||||
className="friend-link-apply-logo-input"
|
||||
value={logo}
|
||||
onChange={e => setLogo(e.target.value)}
|
||||
placeholder="LOGO 图片地址"
|
||||
maxLength={512}
|
||||
/>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/gif,image/webp"
|
||||
className="sr-only"
|
||||
onChange={e => uploadLogo(e.target.files?.[0])}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="friend-link-apply-logo-upload"
|
||||
disabled={uploadingLogo}
|
||||
onClick={() => fileRef.current?.click()}
|
||||
>
|
||||
{uploadingLogo ? <Spinner size="sm" /> : <Upload size={15} aria-hidden />}
|
||||
上传
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="friend-link-apply-dialog__footer">
|
||||
<p className="friend-link-apply-dialog__note">
|
||||
<Link2 size={14} aria-hidden />
|
||||
提交后立即返回,回链检测在后台进行,结果供管理员参考
|
||||
</p>
|
||||
<div className="friend-link-apply-dialog__actions">
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)}>
|
||||
取消
|
||||
</Button>
|
||||
<Button type="button" disabled={submitting || uploadingLogo} onClick={submit}>
|
||||
{submitting ? '提交中…' : isEdit ? '保存并提交' : '提交申请'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
56
frontend/src/components/FriendLinkSiteInfo.tsx
Normal file
56
frontend/src/components/FriendLinkSiteInfo.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
import { useSiteBranding } from '../hooks/useSiteBranding';
|
||||
|
||||
function resolveSiteURL(siteURL?: string): string {
|
||||
const fromApi = siteURL?.trim();
|
||||
if (fromApi) return fromApi;
|
||||
if (typeof window !== 'undefined') return window.location.origin;
|
||||
return '';
|
||||
}
|
||||
|
||||
function resolveSiteLogoURL(logo?: string, favicon?: string, siteURL?: string): string {
|
||||
const raw = logo?.trim() || favicon?.trim() || '';
|
||||
if (!raw) return '';
|
||||
if (/^https?:\/\//i.test(raw)) return raw;
|
||||
const base = resolveSiteURL(siteURL);
|
||||
if (!base) return raw;
|
||||
return raw.startsWith('/') ? `${base}${raw}` : `${base}/${raw}`;
|
||||
}
|
||||
|
||||
/** 申请弹窗内:本站友链信息(名称 / 地址 / LOGO 链接) */
|
||||
export default function FriendLinkSiteInfo() {
|
||||
const { branding } = useSiteBranding();
|
||||
const siteURL = resolveSiteURL(branding.site_url);
|
||||
const siteLogoURL = resolveSiteLogoURL(branding.logo, branding.favicon, branding.site_url);
|
||||
|
||||
return (
|
||||
<section className="friend-link-site-info" aria-label="本站友链信息">
|
||||
<h3 className="friend-link-site-info__title">本站信息(请添加本站链接后再申请)</h3>
|
||||
<dl className="friend-link-site-info__list">
|
||||
<div className="friend-link-site-info__item">
|
||||
<dt>名称</dt>
|
||||
<dd>{branding.name}</dd>
|
||||
</div>
|
||||
<div className="friend-link-site-info__item">
|
||||
<dt>地址</dt>
|
||||
<dd>
|
||||
{siteURL ? (
|
||||
<a href={siteURL} target="_blank" rel="noopener noreferrer">{siteURL}</a>
|
||||
) : (
|
||||
'—'
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div className="friend-link-site-info__item">
|
||||
<dt>LOGO</dt>
|
||||
<dd>
|
||||
{siteLogoURL ? (
|
||||
<a href={siteLogoURL} target="_blank" rel="noopener noreferrer">{siteLogoURL}</a>
|
||||
) : (
|
||||
'—'
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
182
frontend/src/components/PostBountyBanner.tsx
Normal file
182
frontend/src/components/PostBountyBanner.tsx
Normal file
@@ -0,0 +1,182 @@
|
||||
import { useState } from 'react';
|
||||
import { CheckCircle2, Coins } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '../api/client';
|
||||
import type { PostItem } from '../api/types';
|
||||
|
||||
interface Props {
|
||||
post: PostItem;
|
||||
isOwnerOrAdmin: boolean;
|
||||
isAdmin?: boolean;
|
||||
/** 是否可取消悬赏(楼主有他人回复时为 false;管理员为 true) */
|
||||
canRefund?: boolean;
|
||||
refundBlockReason?: string;
|
||||
eligibleReplyCount?: number;
|
||||
onUpdate?: () => void;
|
||||
/** 跳转到被采纳的评论楼层 */
|
||||
onJumpToAwarded?: () => void;
|
||||
/** 被采纳评论是否仍在当前评论列表中 */
|
||||
canJumpToAwarded?: boolean;
|
||||
}
|
||||
|
||||
/** 悬赏帖状态卡 */
|
||||
export default function PostBountyBanner({
|
||||
post,
|
||||
isOwnerOrAdmin,
|
||||
isAdmin = false,
|
||||
canRefund = true,
|
||||
refundBlockReason,
|
||||
eligibleReplyCount = 0,
|
||||
onUpdate,
|
||||
onJumpToAwarded,
|
||||
canJumpToAwarded,
|
||||
}: Props) {
|
||||
const [refundOpen, setRefundOpen] = useState(false);
|
||||
const [refunding, setRefunding] = useState(false);
|
||||
|
||||
if (post.post_type !== 'bounty') return null;
|
||||
|
||||
const points = post.bounty_points ?? 0;
|
||||
const open = post.bounty_status === 'open' && points > 0;
|
||||
const awarded = post.bounty_status === 'awarded';
|
||||
const refunded = post.bounty_status === 'refunded';
|
||||
|
||||
if (refunded && !isOwnerOrAdmin) return null;
|
||||
|
||||
const showRefundButton = isOwnerOrAdmin && canRefund;
|
||||
const ownerRefundBlocked = isOwnerOrAdmin && !isAdmin && !canRefund;
|
||||
|
||||
const confirmRefund = async () => {
|
||||
setRefunding(true);
|
||||
try {
|
||||
await api.bountyRefund(post.id);
|
||||
notify.success('悬赏已退回');
|
||||
setRefundOpen(false);
|
||||
onUpdate?.();
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '操作失败');
|
||||
} finally {
|
||||
setRefunding(false);
|
||||
}
|
||||
};
|
||||
|
||||
const refundDialogDescription = isAdmin && eligibleReplyCount > 0
|
||||
? `将强制取消悬赏并把 ${points} 积分退回楼主账户。当前已有 ${eligibleReplyCount} 条他人回复,请确认已审慎处理。`
|
||||
: `确定取消悬赏并将 ${points} 积分退回你的账户?取消后他人将无法再参与本帖悬赏。`;
|
||||
|
||||
if (open) {
|
||||
let ownerHint = '在评论上点击「采纳」发放积分';
|
||||
if (ownerRefundBlocked) {
|
||||
ownerHint = refundBlockReason || '已有用户回复,请从评论中采纳发放积分';
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="post-bounty post-bounty--open" aria-label="悬赏">
|
||||
<div className="post-bounty__head">
|
||||
<div className="post-bounty__lead">
|
||||
<Coins size={18} className="post-bounty__icon" aria-hidden />
|
||||
<div className="post-bounty__titles">
|
||||
<strong className="post-bounty__title">悬赏进行中</strong>
|
||||
<span className="post-bounty__points">{points} 积分</span>
|
||||
</div>
|
||||
</div>
|
||||
{showRefundButton && (
|
||||
<div className="post-bounty__actions">
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setRefundOpen(true)}>
|
||||
取消悬赏
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p className="post-bounty__hint">
|
||||
{isOwnerOrAdmin
|
||||
? ownerHint
|
||||
: `回复本帖,优质回答可获得这 ${points} 积分`}
|
||||
</p>
|
||||
</section>
|
||||
{showRefundButton && (
|
||||
<AlertDialog
|
||||
open={refundOpen}
|
||||
onOpenChange={(next) => { if (!next && !refunding) setRefundOpen(false); }}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{isAdmin && eligibleReplyCount > 0 ? '强制取消悬赏?' : '取消悬赏?'}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{refundDialogDescription}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={refunding}>返回</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
disabled={refunding}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
void confirmRefund();
|
||||
}}
|
||||
>
|
||||
{refunding ? '退回中…' : '确认取消'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (awarded) {
|
||||
return (
|
||||
<section className="post-bounty post-bounty--awarded" aria-label="悬赏已采纳">
|
||||
<div className="post-bounty__head">
|
||||
<div className="post-bounty__lead">
|
||||
<CheckCircle2 size={18} className="post-bounty__icon" aria-hidden />
|
||||
<div className="post-bounty__titles">
|
||||
<strong className="post-bounty__title">已采纳</strong>
|
||||
<span className="post-bounty__subtitle">
|
||||
{points} 积分已发放给被采纳的回复
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{canJumpToAwarded && onJumpToAwarded && (
|
||||
<div className="post-bounty__actions post-bounty__actions--inline">
|
||||
<button type="button" className="post-bounty__jump" onClick={onJumpToAwarded}>
|
||||
查看被采纳的回复
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
if (refunded) {
|
||||
return (
|
||||
<section className="post-bounty post-bounty--refunded" aria-label="悬赏已退回">
|
||||
<div className="post-bounty__head">
|
||||
<div className="post-bounty__lead">
|
||||
<Coins size={18} className="post-bounty__icon" aria-hidden />
|
||||
<div className="post-bounty__titles">
|
||||
<strong className="post-bounty__title">悬赏已取消</strong>
|
||||
<span className="post-bounty__subtitle">积分已退回</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import { memo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Eye, Image as ImageIcon, MessageCircle, ThumbsUp } from 'lucide-react';
|
||||
import BoardBadge from '@/components/BoardBadge';
|
||||
import FeaturedIcon from '@/components/FeaturedIcon';
|
||||
import UserLink from '@/components/UserLink';
|
||||
import type { PostItem } from '../api/types';
|
||||
import type { FeedSort } from './FeedSortBar';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import { formatTime } from '../utils/content';
|
||||
import { postPath } from '../utils/permalink';
|
||||
import { toPostImageThumbSrc } from '../utils/postContent';
|
||||
import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText';
|
||||
import { parseTags } from './TagInput';
|
||||
|
||||
@@ -19,6 +20,11 @@ interface Props {
|
||||
|
||||
function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
||||
const nav = useNavigate();
|
||||
const { limits } = useForumLimits();
|
||||
const feedStyle = limits.feed_list_style ?? 'title';
|
||||
const showExcerpt = feedStyle === 'excerpt' || feedStyle === 'thumbnail';
|
||||
const showThumb = feedStyle === 'thumbnail';
|
||||
|
||||
const initial = post.user?.nickname?.[0] || '?';
|
||||
const timeLabel = sort === 'reply'
|
||||
? (post.last_reply_at
|
||||
@@ -29,8 +35,10 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
||||
const likeCount = post.like_count ?? 0;
|
||||
const viewCount = post.view_count ?? 0;
|
||||
const href = postPath(post.id);
|
||||
const excerpt = excerptFromHTML(post.content || '', 72);
|
||||
const hasImage = !!firstImageFromHTML(post.content || '');
|
||||
const firstImage = firstImageFromHTML(post.content || '');
|
||||
const thumbSrc = showThumb && firstImage ? toPostImageThumbSrc(firstImage) : null;
|
||||
const excerpt = showExcerpt ? excerptFromHTML(post.content || '', 60) : '';
|
||||
const showImageIcon = !!firstImage && !thumbSrc;
|
||||
const tagList = parseTags(post.tags || '').slice(0, 3);
|
||||
|
||||
const openPost = () => onSelect(post.id);
|
||||
@@ -41,7 +49,6 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
||||
}
|
||||
};
|
||||
const onTitleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
|
||||
// 修饰键 / 非左键:交给浏览器(新标签等)
|
||||
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
|
||||
e.stopPropagation();
|
||||
return;
|
||||
@@ -51,9 +58,107 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
||||
openPost();
|
||||
};
|
||||
|
||||
const titleRow = (
|
||||
<div className="post-title-row">
|
||||
{post.pinned && (
|
||||
<span className="post-pin-badge" title="全局置顶">全局置顶</span>
|
||||
)}
|
||||
{post.board_pinned && (
|
||||
<span className="post-pin-badge post-pin-badge--board" title="板块置顶">板块置顶</span>
|
||||
)}
|
||||
{post.featured && (
|
||||
<span className="post-feature-badge" title="精华">
|
||||
<FeaturedIcon size={12} />
|
||||
精华
|
||||
</span>
|
||||
)}
|
||||
{post.status === 'pending' && (
|
||||
<span className="post-status-badge post-status-badge--pending" title="审核中">审核中</span>
|
||||
)}
|
||||
{post.status === 'rejected' && (
|
||||
<span className="post-status-badge post-status-badge--rejected" title="未通过">未通过</span>
|
||||
)}
|
||||
{post.post_type === 'question' && (
|
||||
<span
|
||||
className={`post-qa-badge${post.question_resolved ? ' post-qa-badge--resolved' : ' post-qa-badge--open'}`}
|
||||
title={post.question_resolved ? '已解决' : '未解决'}
|
||||
>
|
||||
{post.question_resolved ? '已解决' : '未解决'}
|
||||
</span>
|
||||
)}
|
||||
{post.post_type === 'poll' && (
|
||||
<span className="post-type-badge post-type-badge--poll" title="投票">投票</span>
|
||||
)}
|
||||
{post.post_type === 'bounty' && post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0 && (
|
||||
<span className="post-bounty-badge post-bounty-badge--open" title="悬赏">悬赏 {post.bounty_points}</span>
|
||||
)}
|
||||
{post.post_type === 'bounty' && post.bounty_status === 'awarded' && (
|
||||
<span className="post-bounty-badge post-bounty-badge--awarded" title="已采纳">已采纳</span>
|
||||
)}
|
||||
{post.post_type === 'lottery' && (
|
||||
<span className="post-type-badge post-type-badge--lottery" title="抽奖">
|
||||
{post.lottery_status === 'drawn' ? '已开奖' : '抽奖'}
|
||||
</span>
|
||||
)}
|
||||
<a href={href} className="post-title" onClick={onTitleClick}>
|
||||
{post.title}
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
|
||||
const metaLeft = (
|
||||
<div className="post-meta-left">
|
||||
<UserLink user={post.user} stopPropagation className="post-meta-author" showBadges={false} />
|
||||
<span className="post-meta-sep" aria-hidden>·</span>
|
||||
<span className="post-meta-time">{timeLabel}</span>
|
||||
{post.board && (
|
||||
<>
|
||||
<span className="post-meta-sep" aria-hidden>·</span>
|
||||
<span className="post-meta-board">{post.board.name}</span>
|
||||
</>
|
||||
)}
|
||||
{tagList.map(t => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
className="post-list-tag"
|
||||
title={`筛选标签:${t}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
nav(`/?tag=${encodeURIComponent(t)}`);
|
||||
}}
|
||||
>
|
||||
#{t}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
const stats = (
|
||||
<div className="post-stats">
|
||||
{showImageIcon && (
|
||||
<span className="post-stat post-stat--media" title="含图片">
|
||||
<ImageIcon aria-hidden />
|
||||
</span>
|
||||
)}
|
||||
<span className={`post-stat${commentCount === 0 ? ' post-stat--zero' : ''}`} title="评论">
|
||||
<MessageCircle aria-hidden />
|
||||
{commentCount}
|
||||
</span>
|
||||
<span className={`post-stat${likeCount === 0 ? ' post-stat--zero' : ''}`} title="点赞">
|
||||
<ThumbsUp aria-hidden />
|
||||
{likeCount}
|
||||
</span>
|
||||
<span className={`post-stat${viewCount === 0 ? ' post-stat--zero' : ''}`} title="浏览">
|
||||
<Eye aria-hidden />
|
||||
{viewCount}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="post-row"
|
||||
className={`post-row post-row--v2${thumbSrc ? ' post-row--has-thumb' : ''}`}
|
||||
role="link"
|
||||
tabIndex={0}
|
||||
onClick={openPost}
|
||||
@@ -71,88 +176,32 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
||||
: initial}
|
||||
</UserLink>
|
||||
|
||||
<div className="post-body">
|
||||
<div className="post-head">
|
||||
<div className="post-head-meta">
|
||||
<UserLink user={post.user} stopPropagation className="post-author" showBadges />
|
||||
<span className="post-head-dot" aria-hidden>·</span>
|
||||
<span className="post-time">{timeLabel}</span>
|
||||
{thumbSrc ? (
|
||||
<div className="post-main post-main--with-thumb">
|
||||
<div className="post-content">
|
||||
{titleRow}
|
||||
{excerpt && <p className="post-excerpt">{excerpt}</p>}
|
||||
<div className="post-meta post-meta--inline">{metaLeft}</div>
|
||||
</div>
|
||||
<div className="post-aside">
|
||||
<div className="post-thumb" aria-hidden>
|
||||
<img src={thumbSrc} alt="" loading="lazy" decoding="async" />
|
||||
</div>
|
||||
{stats}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="post-title-row">
|
||||
{post.pinned && (
|
||||
<span className="post-pin-badge" title="全局置顶">全局置顶</span>
|
||||
)}
|
||||
{post.board_pinned && (
|
||||
<span className="post-pin-badge post-pin-badge--board" title="板块置顶">板块置顶</span>
|
||||
)}
|
||||
{post.featured && (
|
||||
<span className="post-feature-badge" title="精华">
|
||||
<FeaturedIcon size={12} />
|
||||
精华
|
||||
</span>
|
||||
)}
|
||||
{post.status === 'pending' && (
|
||||
<span className="post-status-badge post-status-badge--pending" title="审核中">审核中</span>
|
||||
)}
|
||||
{post.status === 'rejected' && (
|
||||
<span className="post-status-badge post-status-badge--rejected" title="未通过">未通过</span>
|
||||
)}
|
||||
{post.post_type === 'question' && (
|
||||
<span
|
||||
className={`post-qa-badge${post.question_resolved ? ' post-qa-badge--resolved' : ' post-qa-badge--open'}`}
|
||||
title={post.question_resolved ? '已解决' : '未解决'}
|
||||
>
|
||||
{post.question_resolved ? '已解决' : '未解决'}
|
||||
</span>
|
||||
)}
|
||||
<a href={href} className="post-title" onClick={onTitleClick}>
|
||||
{post.title}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{excerpt && <p className="post-excerpt">{excerpt}</p>}
|
||||
|
||||
<div className="post-foot">
|
||||
<div className="post-foot-left">
|
||||
{post.board && <BoardBadge board={post.board} />}
|
||||
{tagList.map(t => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
className="post-list-tag"
|
||||
title={`筛选标签:${t}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
nav(`/?tag=${encodeURIComponent(t)}`);
|
||||
}}
|
||||
>
|
||||
{t}
|
||||
</button>
|
||||
))}
|
||||
) : (
|
||||
<div className="post-main">
|
||||
<div className="post-text">
|
||||
{titleRow}
|
||||
{excerpt && <p className="post-excerpt">{excerpt}</p>}
|
||||
</div>
|
||||
<div className="post-stats">
|
||||
{hasImage && (
|
||||
<span className="post-stat post-stat--media" title="含图片">
|
||||
<ImageIcon aria-hidden />
|
||||
</span>
|
||||
)}
|
||||
<span className={`post-stat${commentCount === 0 ? ' post-stat--zero' : ''}`} title="评论">
|
||||
<MessageCircle aria-hidden />
|
||||
{commentCount}
|
||||
</span>
|
||||
<span className={`post-stat${likeCount === 0 ? ' post-stat--zero' : ''}`} title="点赞">
|
||||
<ThumbsUp aria-hidden />
|
||||
{likeCount}
|
||||
</span>
|
||||
<span className={`post-stat${viewCount === 0 ? ' post-stat--zero' : ''}`} title="浏览">
|
||||
<Eye aria-hidden />
|
||||
{viewCount}
|
||||
</span>
|
||||
<div className="post-meta">
|
||||
{metaLeft}
|
||||
{stats}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,37 +1,73 @@
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import type { ForumLimitsPublic } from '../api/types';
|
||||
|
||||
export type FeedListStyle = ForumLimitsPublic['feed_list_style'];
|
||||
|
||||
/** 虚拟列表行高预估值 */
|
||||
export function feedListRowEstimate(style: FeedListStyle): number {
|
||||
switch (style) {
|
||||
case 'excerpt': return 68;
|
||||
case 'thumbnail': return 72;
|
||||
default: return 52;
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
count?: number;
|
||||
listStyle?: FeedListStyle;
|
||||
}
|
||||
|
||||
/** 帖子列表加载骨架屏(对齐卡片式列表) */
|
||||
export default function PostListSkeleton({ count = 8 }: Props) {
|
||||
/** 帖子列表加载骨架屏(对齐 v2 紧凑列表) */
|
||||
export default function PostListSkeleton({ count = 8, listStyle = 'title' }: Props) {
|
||||
const showExcerpt = listStyle === 'excerpt' || listStyle === 'thumbnail';
|
||||
const showThumb = listStyle === 'thumbnail';
|
||||
|
||||
return (
|
||||
<div className="post-list-skeleton" aria-busy="true" aria-label="加载中">
|
||||
{Array.from({ length: count }, (_, i) => (
|
||||
<div key={i} className="post-row post-row--skeleton">
|
||||
<Skeleton className="skeleton--avatar" />
|
||||
<div className="post-body">
|
||||
<div className="post-head">
|
||||
<div className="skeleton-meta-row">
|
||||
<Skeleton className="skeleton--meta" />
|
||||
<Skeleton className="skeleton--meta skeleton--meta-short" />
|
||||
{Array.from({ length: count }, (_, i) => {
|
||||
const hasThumb = showThumb && i % 3 === 0;
|
||||
return (
|
||||
<div key={i} className={`post-row post-row--v2 post-row--skeleton${hasThumb ? ' post-row--has-thumb' : ''}`}>
|
||||
<Skeleton className="skeleton--avatar skeleton--avatar-v2" />
|
||||
{hasThumb ? (
|
||||
<div className="post-main post-main--with-thumb">
|
||||
<div className="post-content">
|
||||
<Skeleton className="skeleton--title skeleton--title-v2" style={{ width: `${58 + (i % 4) * 9}%` }} />
|
||||
{showExcerpt && (
|
||||
<Skeleton className="skeleton--excerpt skeleton--excerpt-v2" style={{ width: `${72 + (i % 3) * 8}%` }} />
|
||||
)}
|
||||
<Skeleton className="skeleton--meta-line" style={{ width: `${45 + (i % 3) * 10}%` }} />
|
||||
</div>
|
||||
<div className="post-aside">
|
||||
<Skeleton className="skeleton--thumb skeleton--thumb-tall" />
|
||||
<div className="post-stats">
|
||||
<Skeleton className="skeleton--stat" />
|
||||
<Skeleton className="skeleton--stat" />
|
||||
<Skeleton className="skeleton--stat" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{i % 4 === 0 && <Skeleton className="skeleton--badge" />}
|
||||
</div>
|
||||
<Skeleton className="skeleton--title" style={{ width: `${58 + (i % 4) * 9}%` }} />
|
||||
<Skeleton className="skeleton--excerpt" style={{ width: `${72 + (i % 3) * 8}%` }} />
|
||||
<div className="post-foot">
|
||||
<Skeleton className="skeleton--badge" />
|
||||
<div className="post-stats">
|
||||
<Skeleton className="skeleton--stat" />
|
||||
<Skeleton className="skeleton--stat" />
|
||||
<Skeleton className="skeleton--stat" />
|
||||
) : (
|
||||
<div className="post-main">
|
||||
<div className="post-text">
|
||||
<Skeleton className="skeleton--title skeleton--title-v2" style={{ width: `${58 + (i % 4) * 9}%` }} />
|
||||
{showExcerpt && (
|
||||
<Skeleton className="skeleton--excerpt skeleton--excerpt-v2" style={{ width: `${72 + (i % 3) * 8}%` }} />
|
||||
)}
|
||||
</div>
|
||||
<div className="post-meta">
|
||||
<Skeleton className="skeleton--meta-line" style={{ width: `${45 + (i % 3) * 10}%` }} />
|
||||
<div className="post-stats">
|
||||
<Skeleton className="skeleton--stat" />
|
||||
<Skeleton className="skeleton--stat" />
|
||||
<Skeleton className="skeleton--stat" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
98
frontend/src/components/PostLotteryCard.tsx
Normal file
98
frontend/src/components/PostLotteryCard.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
import { useState } from 'react';
|
||||
import { Gift } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '../api/client';
|
||||
import type { PostLotteryView } from '../api/types';
|
||||
import { userPath } from '../utils/userPath';
|
||||
|
||||
interface Props {
|
||||
postId: number;
|
||||
lottery: PostLotteryView;
|
||||
isOwnerOrAdmin: boolean;
|
||||
onUpdate: (lottery: PostLotteryView) => void;
|
||||
}
|
||||
|
||||
/** 抽奖帖信息卡 */
|
||||
export default function PostLotteryCard({ postId, lottery, isOwnerOrAdmin, onUpdate }: Props) {
|
||||
const [drawOpen, setDrawOpen] = useState(false);
|
||||
const [drawing, setDrawing] = useState(false);
|
||||
const drawn = lottery.status === 'drawn';
|
||||
const canDraw = !drawn && isOwnerOrAdmin && lottery.participant_count >= lottery.winner_count;
|
||||
|
||||
const confirmDraw = async () => {
|
||||
setDrawing(true);
|
||||
try {
|
||||
const r = await api.postLotteryDraw(postId);
|
||||
onUpdate(r.lottery);
|
||||
notify.success('开奖完成');
|
||||
setDrawOpen(false);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '开奖失败');
|
||||
} finally {
|
||||
setDrawing(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="post-lottery" aria-label="抽奖">
|
||||
<div className="post-lottery__head">
|
||||
<Gift size={18} aria-hidden />
|
||||
<strong>{drawn ? '已开奖' : '抽奖进行中'}</strong>
|
||||
<span>抽取 {lottery.winner_count} 人 · 当前 {lottery.participant_count} 人参与</span>
|
||||
</div>
|
||||
{!drawn && (
|
||||
<p className="post-lottery__hint">回帖即可参与(楼主除外),由作者或管理员手动开奖</p>
|
||||
)}
|
||||
{drawn && lottery.winners && lottery.winners.length > 0 && (
|
||||
<ul className="post-lottery__winners">
|
||||
{lottery.winners.map(w => (
|
||||
<li key={`${w.user_id}-${w.comment_id}`}>
|
||||
<a href={userPath(w.user_id)}>{w.nickname || w.username}</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{canDraw && (
|
||||
<Button type="button" size="sm" onClick={() => setDrawOpen(true)}>立即开奖</Button>
|
||||
)}
|
||||
</section>
|
||||
<AlertDialog
|
||||
open={drawOpen}
|
||||
onOpenChange={(next) => { if (!next && !drawing) setDrawOpen(false); }}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>立即开奖?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
将从 {lottery.participant_count} 位参与者中抽取 {lottery.winner_count} 名中奖者。此操作不可撤销。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={drawing}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
disabled={drawing}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
void confirmDraw();
|
||||
}}
|
||||
>
|
||||
{drawing ? '开奖中…' : '确认开奖'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
175
frontend/src/components/PostPollCard.tsx
Normal file
175
frontend/src/components/PostPollCard.tsx
Normal file
@@ -0,0 +1,175 @@
|
||||
import { useState } from 'react';
|
||||
import { BarChart3 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '../api/client';
|
||||
import type { PollView } from '../api/types';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { formatDateTime } from '../utils/content';
|
||||
|
||||
interface Props {
|
||||
postId: number;
|
||||
poll: PollView;
|
||||
isOwnerOrAdmin: boolean;
|
||||
onUpdate: (poll: PollView) => void;
|
||||
}
|
||||
|
||||
/** 投票帖投票卡 */
|
||||
export default function PostPollCard({ postId, poll, isOwnerOrAdmin, onUpdate }: Props) {
|
||||
const { user } = useAuth();
|
||||
const [selected, setSelected] = useState<number[]>(poll.my_option_ids ?? []);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const voted = (poll.my_option_ids?.length ?? 0) > 0;
|
||||
const showResults = poll.closed || voted;
|
||||
const canVote = !voted && !poll.closed;
|
||||
|
||||
const headTitle = poll.closed
|
||||
? '投票已结束'
|
||||
: poll.multi
|
||||
? `多选(最多 ${poll.max_choices} 项)`
|
||||
: '单选投票';
|
||||
|
||||
const endsAtMs = poll.ends_at ? new Date(poll.ends_at).getTime() : NaN;
|
||||
const expiredByDeadline = poll.closed && poll.ends_at && !Number.isNaN(endsAtMs) && endsAtMs <= Date.now();
|
||||
|
||||
const deadlineHint = poll.ends_at && !Number.isNaN(endsAtMs)
|
||||
? poll.closed
|
||||
? (expiredByDeadline ? `已于 ${formatDateTime(poll.ends_at)} 截止` : undefined)
|
||||
: `截止于 ${formatDateTime(poll.ends_at)}`
|
||||
: undefined;
|
||||
|
||||
const toggle = (id: number) => {
|
||||
if (!canVote) return;
|
||||
if (!user) {
|
||||
notify.warning('请先登录');
|
||||
return;
|
||||
}
|
||||
if (poll.multi) {
|
||||
setSelected(prev => (
|
||||
prev.includes(id)
|
||||
? prev.filter(x => x !== id)
|
||||
: [...prev, id].slice(0, poll.max_choices)
|
||||
));
|
||||
} else {
|
||||
setSelected([id]);
|
||||
}
|
||||
};
|
||||
|
||||
const submit = async () => {
|
||||
if (!user) {
|
||||
notify.warning('请先登录');
|
||||
return;
|
||||
}
|
||||
if (selected.length === 0) {
|
||||
notify.warning('请选择选项');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await api.pollVote(postId, selected);
|
||||
onUpdate(r.poll);
|
||||
notify.success('投票成功');
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '投票失败');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const closePoll = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await api.pollClose(postId);
|
||||
onUpdate(r.poll);
|
||||
notify.success('投票已结束');
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '操作失败');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="post-poll" aria-label="投票">
|
||||
<div className="post-poll__head">
|
||||
<BarChart3 size={18} aria-hidden />
|
||||
<strong>{headTitle}</strong>
|
||||
{deadlineHint && (
|
||||
<span className="post-poll__deadline">{deadlineHint}</span>
|
||||
)}
|
||||
<span className="post-poll__meta">{poll.total_votes} 票</span>
|
||||
</div>
|
||||
<ul
|
||||
className="post-poll__options"
|
||||
role={poll.multi ? 'group' : 'radiogroup'}
|
||||
aria-label="投票选项"
|
||||
>
|
||||
{poll.options.map(opt => {
|
||||
const isActive = selected.includes(opt.id);
|
||||
const isMine = poll.my_option_ids?.includes(opt.id);
|
||||
return (
|
||||
<li key={opt.id}>
|
||||
<button
|
||||
type="button"
|
||||
className={[
|
||||
'post-poll__option',
|
||||
poll.multi ? 'post-poll__option--multi' : 'post-poll__option--single',
|
||||
isActive ? 'active' : '',
|
||||
showResults ? 'results' : '',
|
||||
isMine ? 'mine' : '',
|
||||
].filter(Boolean).join(' ')}
|
||||
disabled={!canVote}
|
||||
onClick={() => toggle(opt.id)}
|
||||
role={poll.multi ? 'checkbox' : 'radio'}
|
||||
aria-checked={isActive}
|
||||
>
|
||||
<span className="post-poll__option-main">
|
||||
<span className="post-poll__option-indicator" aria-hidden />
|
||||
<span className="post-poll__option-text">{opt.text}</span>
|
||||
{showResults && (
|
||||
<span className="post-poll__option-stat">
|
||||
{opt.percent ?? 0}% · {opt.vote_count} 票
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{showResults && (
|
||||
<span className="post-poll__option-bar" aria-hidden>
|
||||
<span
|
||||
className="post-poll__option-fill"
|
||||
style={{ width: `${opt.percent ?? 0}%` }}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<div className="post-poll__actions">
|
||||
{canVote && user && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
disabled={busy || selected.length === 0}
|
||||
onClick={submit}
|
||||
>
|
||||
提交投票
|
||||
</Button>
|
||||
)}
|
||||
{canVote && user && selected.length === 0 && (
|
||||
<p className="post-poll__select-hint">
|
||||
{poll.multi ? '请选择后提交' : '请选择一项后提交'}
|
||||
</p>
|
||||
)}
|
||||
{!user && canVote && (
|
||||
<p className="post-poll__login-hint">登录后可参与投票</p>
|
||||
)}
|
||||
{isOwnerOrAdmin && !poll.closed && (
|
||||
<Button type="button" variant="outline" size="sm" disabled={busy} onClick={closePoll}>
|
||||
结束投票
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
import { ListTree, MessageCircle, MessagesSquare, Tags, Sparkles } from 'lucide-react';
|
||||
import { useLocation, useSearchParams } from 'react-router-dom';
|
||||
import { useMemo } from 'react';
|
||||
import { ListTree, MessageCircle, Tags, Link2 } from 'lucide-react';
|
||||
import { useLocation, useSearchParams, useNavigate } from 'react-router-dom';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import type { PostItem, RecentComment, TagCount, User } from '../api/types';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { AsideWidget, RecentComment, TagCount, User, ForumStats, FriendLink } from '../api/types';
|
||||
import type { PostHeading } from '../utils/postHeadings';
|
||||
import { useSiteBranding } from '../hooks/useSiteBranding';
|
||||
import { formatShortDateTime, formatTime } from '../utils/content';
|
||||
import { resolveAsideWidgets } from '../utils/asideWidgets';
|
||||
import TagCloud from './TagCloud';
|
||||
import UserLink from './UserLink';
|
||||
import ArticleOutline from './ArticleOutline';
|
||||
import PostAuthorCard from './PostAuthorCard';
|
||||
import AsideCheckInStrip from './AsideCheckInStrip';
|
||||
|
||||
export type PostDetailAside = {
|
||||
author?: User | null;
|
||||
@@ -20,38 +24,29 @@ export type PostDetailAside = {
|
||||
};
|
||||
|
||||
interface Props {
|
||||
hot: PostItem[];
|
||||
recentComments: RecentComment[];
|
||||
tags?: TagCount[];
|
||||
tagsLoading?: boolean;
|
||||
stats?: ForumStats | null;
|
||||
onPostClick: (id: number, opts?: { floor?: number }) => void;
|
||||
/** 首次拉取中,显示骨架避免空态闪烁 */
|
||||
loading?: boolean;
|
||||
/** 右侧栏可选组件顺序与开关 */
|
||||
asideWidgets: AsideWidget[];
|
||||
/** 帖子详情:右侧顶部展示作者与目录 */
|
||||
postDetail?: PostDetailAside | null;
|
||||
}
|
||||
|
||||
function ActiveSkeleton() {
|
||||
return (
|
||||
<div className="widget-skeleton" aria-busy="true" aria-label="正在聊加载中">
|
||||
{Array.from({ length: 6 }, (_, i) => (
|
||||
<div key={i} className="widget-item widget-item--active widget-item--skeleton">
|
||||
<Skeleton className="skeleton--widget-title" style={{ width: `${62 + (i % 4) * 8}%` }} />
|
||||
<Skeleton className="skeleton--widget-time" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CommentSkeleton() {
|
||||
return (
|
||||
<div className="widget-skeleton" aria-busy="true" aria-label="评论加载中">
|
||||
{Array.from({ length: 5 }, (_, i) => (
|
||||
<div key={i} className="widget-item widget-item--comment widget-item--skeleton">
|
||||
<Skeleton className="skeleton--widget-avatar" />
|
||||
<Skeleton className="skeleton--widget-title" style={{ width: `${55 + (i % 3) * 12}%` }} />
|
||||
<Skeleton className="skeleton--widget-time" />
|
||||
<div className="widget-item-comment-main">
|
||||
<Skeleton className="skeleton--widget-title" style={{ width: `${72 + (i % 3) * 8}%` }} />
|
||||
<Skeleton className="skeleton--widget-meta" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -59,21 +54,24 @@ function CommentSkeleton() {
|
||||
}
|
||||
|
||||
export default function RightPanel({
|
||||
hot,
|
||||
recentComments,
|
||||
tags = [],
|
||||
tagsLoading = false,
|
||||
stats = null,
|
||||
onPostClick,
|
||||
loading = false,
|
||||
asideWidgets,
|
||||
postDetail = null,
|
||||
}: Props) {
|
||||
const { branding } = useSiteBranding();
|
||||
const nav = useNavigate();
|
||||
const loc = useLocation();
|
||||
const [params] = useSearchParams();
|
||||
const activeTag = params.get('tag') || '';
|
||||
const hotList = hot?.slice(0, 8) ?? [];
|
||||
const commentList = recentComments?.slice(0, 6) ?? [];
|
||||
// 站点首页:右侧品牌块承担唯一 h1;板块/搜索等页面由 Feed 标题作 h1
|
||||
const friendLinks = (branding.friend_links ?? []).filter(
|
||||
(l: FriendLink) => l.name?.trim() && l.url?.trim(),
|
||||
);
|
||||
const isSiteHome = loc.pathname === '/'
|
||||
&& !params.get('board')
|
||||
&& !params.get('keyword')
|
||||
@@ -81,13 +79,144 @@ export default function RightPanel({
|
||||
&& !params.get('author');
|
||||
const description = branding.description?.trim() || '';
|
||||
const slogan = branding.slogan?.trim() || '';
|
||||
// 有独立简介时展示简介;否则用欢迎语,避免与页脚 slogan 三连重复
|
||||
const aboutText = description || '欢迎参与讨论,发帖、评论,一起把小圈子聊热。';
|
||||
// 有近期讨论则展示「正在聊」;否则显示欢迎引导
|
||||
const showActive = loading || hotList.length > 0;
|
||||
const showWelcome = !loading && hotList.length === 0;
|
||||
const introText = description || slogan;
|
||||
const isPostDetail = !!postDetail;
|
||||
|
||||
const enabledWidgets = useMemo(
|
||||
() => resolveAsideWidgets({
|
||||
aside_widgets: asideWidgets,
|
||||
aside_show_tag_cloud: false,
|
||||
aside_show_recent_comments: false,
|
||||
aside_show_friend_links: false,
|
||||
}).filter(w => w.enabled),
|
||||
[asideWidgets],
|
||||
);
|
||||
|
||||
const handleApplyClick = () => {
|
||||
nav('/links?apply=1');
|
||||
};
|
||||
|
||||
const renderWidget = (widget: AsideWidget) => {
|
||||
switch (widget.id) {
|
||||
case 'friend_links':
|
||||
return (
|
||||
<div key="friend_links" className="widget-card widget-card--friend-links">
|
||||
<div className="widget-card-head widget-card-head--split">
|
||||
<span className="widget-card-head-main">
|
||||
<Link2 className="widget-card-icon widget-card-icon--links" aria-hidden />
|
||||
<button type="button" className="widget-friend-links-title" onClick={() => nav('/links')}>
|
||||
友情链接
|
||||
</button>
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="widget-friend-links-apply"
|
||||
onClick={handleApplyClick}
|
||||
>
|
||||
申请
|
||||
</Button>
|
||||
</div>
|
||||
<div className="widget-card-body">
|
||||
{friendLinks.length === 0 ? (
|
||||
<div className="widget-empty">暂无友情链接</div>
|
||||
) : (
|
||||
<>
|
||||
<ul className="widget-friend-links-list">
|
||||
{friendLinks.slice(0, 8).map((link: FriendLink) => (
|
||||
<li key={`${link.name}-${link.url}`}>
|
||||
<a href={link.url} target="_blank" rel="noopener noreferrer">{link.name}</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{friendLinks.length > 8 && (
|
||||
<button type="button" className="widget-friend-links-more" onClick={() => nav('/links')}>
|
||||
查看全部 {friendLinks.length} 个
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
case 'tag_cloud':
|
||||
return (
|
||||
<div key="tag_cloud" className="widget-card widget-card--tags">
|
||||
<div className="widget-card-head">
|
||||
<Tags className="widget-card-icon widget-card-icon--tags" aria-hidden />
|
||||
标签云
|
||||
</div>
|
||||
<div className="widget-card-body widget-card-body--tags">
|
||||
<TagCloud tags={tags} loading={tagsLoading} activeTag={activeTag} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
case 'recent_comments':
|
||||
return (
|
||||
<div key="recent_comments" className="widget-card">
|
||||
<div className="widget-card-head">
|
||||
<MessageCircle className="widget-card-icon widget-card-icon--notice" aria-hidden />
|
||||
最新评论
|
||||
</div>
|
||||
<div className="widget-card-body">
|
||||
{loading && commentList.length === 0 ? (
|
||||
<CommentSkeleton />
|
||||
) : commentList.length === 0 ? (
|
||||
<div className="widget-empty">暂无评论</div>
|
||||
) : commentList.map(item => (
|
||||
<div
|
||||
key={item.id}
|
||||
className="widget-item widget-item--comment"
|
||||
title={item.post_title ? `${item.author} · ${item.post_title}` : item.author}
|
||||
>
|
||||
{item.user_id ? (
|
||||
<UserLink
|
||||
user={{ id: item.user_id, nickname: item.author, avatar: item.avatar }}
|
||||
showAvatar={false}
|
||||
showName={false}
|
||||
stopPropagation
|
||||
className="widget-item-avatar user-link--avatar-only"
|
||||
>
|
||||
{item.avatar
|
||||
? <img src={item.avatar} alt="" loading="lazy" decoding="async" />
|
||||
: (item.author?.[0] || '?')}
|
||||
</UserLink>
|
||||
) : (
|
||||
<span className="widget-item-avatar" aria-hidden>
|
||||
{item.avatar
|
||||
? <img src={item.avatar} alt="" loading="lazy" decoding="async" />
|
||||
: (item.author?.[0] || '?')}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="widget-item-comment-main"
|
||||
onClick={() => onPostClick(item.post_id, item.floor > 0 ? { floor: item.floor } : undefined)}
|
||||
>
|
||||
<span className="widget-item-title">{item.excerpt}</span>
|
||||
<span className="widget-item-meta">
|
||||
<span
|
||||
className="widget-item-time"
|
||||
title={formatShortDateTime(item.created_at)}
|
||||
>
|
||||
{formatTime(item.created_at)}
|
||||
</span>
|
||||
{item.post_title && (
|
||||
<span className="widget-item-post-title">{item.post_title}</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
|
||||
{isPostDetail && (
|
||||
@@ -114,121 +243,6 @@ export default function RightPanel({
|
||||
</>
|
||||
)}
|
||||
|
||||
{!isPostDetail && showWelcome && (
|
||||
<div className="widget-card widget-card--welcome">
|
||||
<div className="widget-card-head">
|
||||
<Sparkles className="widget-card-icon widget-card-icon--welcome" aria-hidden />
|
||||
加入讨论
|
||||
</div>
|
||||
<div className="widget-card-body widget-welcome-body">
|
||||
<p>社区还在起步,每条回复都很珍贵。</p>
|
||||
<ul>
|
||||
<li>逛逛板块,找到感兴趣的话题</li>
|
||||
<li>游客也能评论,登录可点赞收藏</li>
|
||||
<li>发一篇帖,留下你的痕迹</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isPostDetail && showActive && (
|
||||
<div className="widget-card">
|
||||
<div className="widget-card-head">
|
||||
<MessagesSquare className="widget-card-icon widget-card-icon--hot" aria-hidden />
|
||||
正在聊
|
||||
</div>
|
||||
<div className="widget-card-body">
|
||||
{loading && hotList.length === 0 ? (
|
||||
<ActiveSkeleton />
|
||||
) : hotList.length === 0 ? (
|
||||
<div className="widget-empty">近 7 日暂无新回复</div>
|
||||
) : hotList.map((item) => {
|
||||
const replyLabel = item.last_reply_at
|
||||
? `${formatTime(item.last_reply_at)}有人回`
|
||||
: '近期有讨论';
|
||||
const count = item.comment_count ?? 0;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className="widget-item widget-item--active"
|
||||
onClick={() => onPostClick(item.id)}
|
||||
title={item.title}
|
||||
>
|
||||
<span className="widget-item-title">{item.title}</span>
|
||||
<span className="widget-item-meta">
|
||||
<span className="widget-item-time">{replyLabel}</span>
|
||||
{count > 0 && <span className="widget-item-count">{count} 评</span>}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isPostDetail && (
|
||||
<div className="widget-card widget-card--tags">
|
||||
<div className="widget-card-head">
|
||||
<Tags className="widget-card-icon widget-card-icon--tags" aria-hidden />
|
||||
标签云
|
||||
</div>
|
||||
<div className="widget-card-body widget-card-body--tags">
|
||||
<TagCloud tags={tags} loading={tagsLoading} activeTag={activeTag} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isPostDetail && (
|
||||
<div className="widget-card">
|
||||
<div className="widget-card-head">
|
||||
<MessageCircle className="widget-card-icon widget-card-icon--notice" aria-hidden />
|
||||
最新评论
|
||||
</div>
|
||||
<div className="widget-card-body">
|
||||
{loading && commentList.length === 0 ? (
|
||||
<CommentSkeleton />
|
||||
) : commentList.length === 0 ? (
|
||||
<div className="widget-empty">暂无评论</div>
|
||||
) : commentList.map(item => (
|
||||
<div
|
||||
key={item.id}
|
||||
className="widget-item widget-item--comment"
|
||||
title={item.post_title ? `${item.author} · ${item.post_title}` : item.author}
|
||||
>
|
||||
{item.user_id ? (
|
||||
<UserLink
|
||||
user={{ id: item.user_id, nickname: item.author, avatar: item.avatar }}
|
||||
showAvatar={false}
|
||||
showName={false}
|
||||
stopPropagation
|
||||
className="widget-item-avatar user-link--avatar-only"
|
||||
>
|
||||
{item.avatar
|
||||
? <img src={item.avatar} alt="" loading="lazy" decoding="async" />
|
||||
: (item.author?.[0] || '?')}
|
||||
</UserLink>
|
||||
) : (
|
||||
<span className="widget-item-avatar" aria-hidden>
|
||||
{item.avatar
|
||||
? <img src={item.avatar} alt="" loading="lazy" decoding="async" />
|
||||
: (item.author?.[0] || '?')}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="widget-item-comment-main"
|
||||
onClick={() => onPostClick(item.post_id, item.floor > 0 ? { floor: item.floor } : undefined)}
|
||||
>
|
||||
<span className="widget-item-title">{item.excerpt}</span>
|
||||
<span className="widget-item-time">{formatShortDateTime(item.created_at)}</span>
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isPostDetail && (
|
||||
<div className="widget-card widget-card--about">
|
||||
<div className="widget-card-body">
|
||||
@@ -238,14 +252,32 @@ export default function RightPanel({
|
||||
) : (
|
||||
<p className="widget-about-title">{branding.name}</p>
|
||||
)}
|
||||
<p className="widget-about-desc">{aboutText}</p>
|
||||
{description && slogan && slogan !== description && (
|
||||
<p className="widget-about-slogan">{slogan}</p>
|
||||
{introText && (
|
||||
<p className="widget-about-desc">{introText}</p>
|
||||
)}
|
||||
</div>
|
||||
{stats && (
|
||||
<div className="widget-stats" aria-label="论坛统计">
|
||||
<div className="widget-stat">
|
||||
<span className="widget-stat-value">{stats.posts}</span>
|
||||
<span className="widget-stat-label">帖子</span>
|
||||
</div>
|
||||
<div className="widget-stat">
|
||||
<span className="widget-stat-value">{stats.comments}</span>
|
||||
<span className="widget-stat-label">回复</span>
|
||||
</div>
|
||||
<div className="widget-stat">
|
||||
<span className="widget-stat-value">{stats.users}</span>
|
||||
<span className="widget-stat-label">用户</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<AsideCheckInStrip />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isPostDetail && enabledWidgets.map(renderWidget)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft,
|
||||
Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft, FileText, Link2,
|
||||
} from 'lucide-react';
|
||||
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom';
|
||||
import { useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom';
|
||||
import type { Board } from '../api/types';
|
||||
import type { PostHeading } from '../utils/postHeadings';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
@@ -12,9 +12,12 @@ import { navigateFeed } from '../utils/feedCache';
|
||||
import BoardIconDisplay from './BoardIconDisplay';
|
||||
import { getBoardThemeIndex } from '../utils/boardTheme';
|
||||
import ArticleOutline from './ArticleOutline';
|
||||
import { useSitePages } from '../hooks/useSitePages';
|
||||
import { pagePath } from '../utils/permalink';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
|
||||
// 内容页不参与左侧栏高亮(非 feed 浏览上下文)
|
||||
const NEUTRAL_SIDEBAR_PREFIXES = ['/post/', '/profile', '/user/'];
|
||||
const NEUTRAL_SIDEBAR_PREFIXES = ['/post/', '/profile', '/user/', '/page/'];
|
||||
|
||||
export function isNeutralSidebarRoute(pathname: string): boolean {
|
||||
return NEUTRAL_SIDEBAR_PREFIXES.some(prefix => pathname.startsWith(prefix));
|
||||
@@ -26,6 +29,8 @@ function resolveMenuKey(pathname: string, activeBoard: number, keyword = ''): st
|
||||
if (keyword.trim()) return null;
|
||||
if (pathname.startsWith('/favorites')) return 'favorites';
|
||||
if (pathname.startsWith('/projects')) return 'projects';
|
||||
if (pathname.startsWith('/links')) return 'links';
|
||||
if (pathname.startsWith('/page/')) return 'pages';
|
||||
if (pathname.startsWith('/admin')) return 'admin';
|
||||
return activeBoard === 0 ? 'all' : String(activeBoard);
|
||||
}
|
||||
@@ -59,9 +64,37 @@ export default function Sidebar({
|
||||
const sort = parseFeedSort(params.get('sort'));
|
||||
const { user } = useAuth();
|
||||
const isAdmin = user?.role === 'admin';
|
||||
const { navPages } = useSitePages();
|
||||
const { limits } = useForumLimits();
|
||||
|
||||
const keyword = params.get('keyword') || '';
|
||||
const menuKey = resolveMenuKey(loc.pathname, activeBoard, keyword);
|
||||
const permalinkOpts = { permalink: limits };
|
||||
|
||||
const feedNavLink = (
|
||||
key: string,
|
||||
to: string,
|
||||
label: React.ReactNode,
|
||||
icon: React.ReactNode,
|
||||
selectId: number,
|
||||
className?: string,
|
||||
trailing?: React.ReactNode,
|
||||
) => (
|
||||
<Link
|
||||
key={key}
|
||||
to={to}
|
||||
className={cn('sidebar-nav-item', className, menuKey != null && menuKey === key && 'active')}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
onSelectBoard(selectId);
|
||||
navigateFeed(nav, to);
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
<span className="flex-1 truncate">{label}</span>
|
||||
{trailing}
|
||||
</Link>
|
||||
);
|
||||
|
||||
const navItem = (key: string, label: React.ReactNode, icon?: React.ReactNode, onClick?: () => void) => (
|
||||
<button
|
||||
@@ -99,9 +132,10 @@ export default function Sidebar({
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-section">浏览</div>
|
||||
<nav className="sidebar-nav">
|
||||
{navItem('all', '全部帖子', <Home aria-hidden />, () => { onSelectBoard(0); navigateFeed(nav, buildHomeUrl(0, sort)); })}
|
||||
{feedNavLink('all', buildHomeUrl(0, sort, permalinkOpts), '全部帖子', <Home aria-hidden />, 0)}
|
||||
{user && navItem('favorites', '我的收藏', <Star aria-hidden />, () => nav('/favorites'))}
|
||||
{navItem('projects', '开源码桶', <FolderGit2 aria-hidden />, () => nav('/projects'))}
|
||||
{navItem('links', '友情链接', <Link2 aria-hidden />, () => nav('/links'))}
|
||||
</nav>
|
||||
|
||||
{(boardsLoading && boards.length === 0) ? (
|
||||
@@ -123,29 +157,27 @@ export default function Sidebar({
|
||||
{boards.map(b => {
|
||||
const isActive = menuKey != null && menuKey === String(b.id);
|
||||
const themeIdx = getBoardThemeIndex(b);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={b.id}
|
||||
className={cn(
|
||||
'sidebar-nav-item',
|
||||
'sidebar-nav-item--board',
|
||||
isActive && 'active',
|
||||
isActive && `sidebar-nav-item--board-${themeIdx}`,
|
||||
)}
|
||||
onClick={() => { onSelectBoard(b.id); navigateFeed(nav, buildHomeUrl(b.id, sort)); }}
|
||||
>
|
||||
<BoardIconDisplay
|
||||
board={b}
|
||||
className={cn('sidebar-board-icon', `sidebar-board-icon--${themeIdx}`)}
|
||||
/>
|
||||
<span className="flex-1 truncate">{b.name}</span>
|
||||
{(b.post_count ?? 0) > 0 && (
|
||||
<span className="sidebar-nav-item__meta" title={`${b.post_count} 篇帖子`}>
|
||||
{b.post_count} 帖
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
const boardUrl = buildHomeUrl(b.id, sort, permalinkOpts);
|
||||
const postMeta = (b.post_count ?? 0) > 0 ? (
|
||||
<span className="sidebar-nav-item__meta" title={`${b.post_count} 篇帖子`}>
|
||||
{b.post_count} 帖
|
||||
</span>
|
||||
) : null;
|
||||
return feedNavLink(
|
||||
String(b.id),
|
||||
boardUrl,
|
||||
b.name,
|
||||
<BoardIconDisplay
|
||||
board={b}
|
||||
className={cn('sidebar-board-icon', `sidebar-board-icon--${themeIdx}`)}
|
||||
/>,
|
||||
b.id,
|
||||
cn(
|
||||
'sidebar-nav-item--board',
|
||||
isActive && 'active',
|
||||
isActive && `sidebar-nav-item--board-${themeIdx}`,
|
||||
),
|
||||
postMeta,
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
@@ -159,6 +191,17 @@ export default function Sidebar({
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{(navPages.length > 0) && (
|
||||
<>
|
||||
<div className="sidebar-section sidebar-section--spaced">站点</div>
|
||||
<nav className="sidebar-nav">
|
||||
{navPages.map(p => (
|
||||
navItem(`page-${p.slug}`, p.title, <FileText aria-hidden />, () => nav(pagePath(p.slug, limits)))
|
||||
))}
|
||||
</nav>
|
||||
</>
|
||||
)}
|
||||
|
||||
{isAdmin && (
|
||||
<>
|
||||
<div className="sidebar-section sidebar-section--spaced">管理</div>
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
import { useSiteBranding } from '../hooks/useSiteBranding';
|
||||
import { useMediaQuery } from '../hooks/useTheme';
|
||||
import type { FriendLink } from '../api/types';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useSitePages } from '../hooks/useSitePages';
|
||||
import { pagePath } from '../utils/permalink';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
|
||||
function FooterSep() {
|
||||
return <span className="site-footer__sep" aria-hidden>·</span>;
|
||||
}
|
||||
|
||||
/** 站点页脚:版权、Sitemap、友链、备案号 */
|
||||
/** 站点页脚:版权、Sitemap、备案号 */
|
||||
export default function SiteFooter() {
|
||||
const { branding } = useSiteBranding();
|
||||
const { footerPages } = useSitePages();
|
||||
const { limits } = useForumLimits();
|
||||
const year = new Date().getFullYear();
|
||||
const links = Array.isArray(branding.friend_links) ? branding.friend_links : [];
|
||||
const icp = branding.icp_beian?.trim() || '';
|
||||
const icpURL = branding.icp_beian_url?.trim() || 'https://beian.miit.gov.cn/';
|
||||
|
||||
@@ -29,31 +33,30 @@ export default function SiteFooter() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(links.length > 0 || icp) && (
|
||||
<nav className="site-footer__nav" aria-label="站点链接">
|
||||
{links.map((link: FriendLink, i) => (
|
||||
<span key={`${link.name}-${link.url}`} className="site-footer__friend">
|
||||
{i > 0 && <FooterSep />}
|
||||
<a href={link.url} target="_blank" rel="noopener noreferrer">
|
||||
{link.name}
|
||||
</a>
|
||||
</span>
|
||||
))}
|
||||
{icp && (
|
||||
<>
|
||||
{links.length > 0 && <FooterSep />}
|
||||
<a
|
||||
href={icpURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="site-footer__icp"
|
||||
>
|
||||
{icp}
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
)}
|
||||
<nav className="site-footer__nav" aria-label="站点链接">
|
||||
<span className="site-footer__friend">
|
||||
<Link to="/links">友情链接</Link>
|
||||
</span>
|
||||
{footerPages.map(p => (
|
||||
<span key={p.slug} className="site-footer__friend">
|
||||
<FooterSep />
|
||||
<Link to={pagePath(p.slug, limits)}>{p.title}</Link>
|
||||
</span>
|
||||
))}
|
||||
{icp && (
|
||||
<>
|
||||
<FooterSep />
|
||||
<a
|
||||
href={icpURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="site-footer__icp"
|
||||
>
|
||||
{icp}
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
|
||||
@@ -4,10 +4,11 @@ import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { Inbox, SearchX } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import PostListItem from './PostListItem';
|
||||
import PostListSkeleton from './PostListSkeleton';
|
||||
import PostListSkeleton, { feedListRowEstimate } from './PostListSkeleton';
|
||||
import FeedPagination from './FeedPagination';
|
||||
import { InFlowSiteFooter } from './SiteFooter';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import { useMediaQuery } from '../hooks/useTheme';
|
||||
import { loginPath } from '../utils/authRedirect';
|
||||
import type { PostItem } from '../api/types';
|
||||
@@ -67,7 +68,10 @@ export default function VirtualPostList({
|
||||
}: Props) {
|
||||
const nav = useNavigate();
|
||||
const { user } = useAuth();
|
||||
const { limits } = useForumLimits();
|
||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||
const feedStyle = limits.feed_list_style ?? 'title';
|
||||
const rowEstimate = feedListRowEstimate(feedStyle);
|
||||
const parentRef = useRef<HTMLDivElement>(null);
|
||||
const restoredRef = useRef(false);
|
||||
const onScrollTopChangeRef = useRef(onScrollTopChange);
|
||||
@@ -116,7 +120,7 @@ export default function VirtualPostList({
|
||||
const virtualizer = useVirtualizer({
|
||||
count: posts.length,
|
||||
getScrollElement,
|
||||
estimateSize: () => 108,
|
||||
estimateSize: () => rowEstimate,
|
||||
overscan: 8,
|
||||
scrollMargin: isMobile ? scrollMargin : 0,
|
||||
measureElement:
|
||||
@@ -214,7 +218,7 @@ export default function VirtualPostList({
|
||||
return (
|
||||
<div className="post-list-scroll" ref={parentRef}>
|
||||
{isInitialLoad ? (
|
||||
<PostListSkeleton />
|
||||
<PostListSkeleton listStyle={feedStyle} />
|
||||
) : isEmpty ? (
|
||||
<div className="empty-feed" role="status">
|
||||
{isSearchEmpty
|
||||
|
||||
215
frontend/src/components/admin/AdminSortableList.tsx
Normal file
215
frontend/src/components/admin/AdminSortableList.tsx
Normal file
@@ -0,0 +1,215 @@
|
||||
import {
|
||||
type CSSProperties,
|
||||
type ElementType,
|
||||
type HTMLAttributes,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type DragEndEvent,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
SortableContext,
|
||||
rectSortingStrategy,
|
||||
sortableKeyboardCoordinates,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
type SortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { ArrowDown, ArrowUp, GripVertical } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { reorderItems, shouldShowSortableMoveButtons } from '../../utils/sortOrder';
|
||||
|
||||
export type SortableItemControls = {
|
||||
setNodeRef: (node: HTMLElement | null) => void;
|
||||
style: CSSProperties;
|
||||
isDragging: boolean;
|
||||
dragHandleProps: HTMLAttributes<HTMLButtonElement>;
|
||||
moveUp: () => void;
|
||||
moveDown: () => void;
|
||||
canMoveUp: boolean;
|
||||
canMoveDown: boolean;
|
||||
};
|
||||
|
||||
type AdminSortableListProps<T> = {
|
||||
items: T[];
|
||||
getId: (item: T) => string | number;
|
||||
onReorder: (items: T[]) => void;
|
||||
renderItem: (item: T, index: number, controls: SortableItemControls) => ReactNode;
|
||||
showMoveButtons?: boolean | 'auto';
|
||||
strategy?: 'vertical' | 'grid';
|
||||
as?: ElementType;
|
||||
className?: string;
|
||||
ariaLabel?: string;
|
||||
};
|
||||
|
||||
function resolveStrategy(mode: 'vertical' | 'grid'): SortingStrategy {
|
||||
return mode === 'grid' ? rectSortingStrategy : verticalListSortingStrategy;
|
||||
}
|
||||
|
||||
function SortableItem<T>({
|
||||
item,
|
||||
index,
|
||||
items,
|
||||
getId,
|
||||
onReorder,
|
||||
showMoveButtons,
|
||||
renderItem,
|
||||
}: {
|
||||
item: T;
|
||||
index: number;
|
||||
items: T[];
|
||||
getId: (item: T) => string | number;
|
||||
onReorder: (items: T[]) => void;
|
||||
showMoveButtons: boolean;
|
||||
renderItem: AdminSortableListProps<T>['renderItem'];
|
||||
}) {
|
||||
const id = getId(item);
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id });
|
||||
|
||||
const style: CSSProperties = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
};
|
||||
|
||||
const moveUp = () => {
|
||||
if (index > 0) onReorder(reorderItems(items, index, index - 1));
|
||||
};
|
||||
const moveDown = () => {
|
||||
if (index < items.length - 1) onReorder(reorderItems(items, index, index + 1));
|
||||
};
|
||||
|
||||
const controls: SortableItemControls = {
|
||||
setNodeRef,
|
||||
style,
|
||||
isDragging,
|
||||
dragHandleProps: { ...attributes, ...listeners },
|
||||
moveUp,
|
||||
moveDown,
|
||||
canMoveUp: index > 0,
|
||||
canMoveDown: index < items.length - 1,
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{renderItem(item, index, controls)}
|
||||
{showMoveButtons && (
|
||||
<span className="sr-only" aria-live="polite">
|
||||
{controls.canMoveUp ? '可上移' : ''}{controls.canMoveDown ? '可下移' : ''}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function SortableDragHandle({
|
||||
label = '拖拽调整顺序',
|
||||
className = 'admin-sortable-row__handle',
|
||||
...props
|
||||
}: HTMLAttributes<HTMLButtonElement> & { label?: string }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={className}
|
||||
aria-label={label}
|
||||
{...props}
|
||||
>
|
||||
<GripVertical size={16} aria-hidden />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function SortableMoveButtons({
|
||||
controls,
|
||||
className = 'admin-sortable-row__order',
|
||||
}: {
|
||||
controls: Pick<SortableItemControls, 'moveUp' | 'moveDown' | 'canMoveUp' | 'canMoveDown'>;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={className}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={!controls.canMoveUp}
|
||||
onClick={controls.moveUp}
|
||||
aria-label="上移"
|
||||
>
|
||||
<ArrowUp size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={!controls.canMoveDown}
|
||||
onClick={controls.moveDown}
|
||||
aria-label="下移"
|
||||
>
|
||||
<ArrowDown size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminSortableList<T>({
|
||||
items,
|
||||
getId,
|
||||
onReorder,
|
||||
renderItem,
|
||||
showMoveButtons = 'auto',
|
||||
strategy = 'vertical',
|
||||
as: Wrapper = 'div',
|
||||
className,
|
||||
ariaLabel,
|
||||
}: AdminSortableListProps<T>) {
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||
);
|
||||
|
||||
const moveButtons = shouldShowSortableMoveButtons(items.length, showMoveButtons);
|
||||
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id) return;
|
||||
const oldIndex = items.findIndex(item => getId(item) === active.id);
|
||||
const newIndex = items.findIndex(item => getId(item) === over.id);
|
||||
if (oldIndex < 0 || newIndex < 0) return;
|
||||
onReorder(reorderItems(items, oldIndex, newIndex));
|
||||
};
|
||||
|
||||
return (
|
||||
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
||||
<SortableContext items={items.map(getId)} strategy={resolveStrategy(strategy)}>
|
||||
<Wrapper className={className} role={ariaLabel ? 'group' : undefined} aria-label={ariaLabel}>
|
||||
{items.map((item, index) => (
|
||||
<SortableItem
|
||||
key={String(getId(item))}
|
||||
item={item}
|
||||
index={index}
|
||||
items={items}
|
||||
getId={getId}
|
||||
onReorder={onReorder}
|
||||
showMoveButtons={moveButtons}
|
||||
renderItem={renderItem}
|
||||
/>
|
||||
))}
|
||||
</Wrapper>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
);
|
||||
}
|
||||
71
frontend/src/components/admin/AsideWidgetList.tsx
Normal file
71
frontend/src/components/admin/AsideWidgetList.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
import AdminSortableList, { SortableDragHandle } from './AdminSortableList';
|
||||
import type { AsideWidget, AsideWidgetId } from '../../api/types';
|
||||
|
||||
const WIDGET_META: Record<AsideWidgetId, { label: string; hint: string }> = {
|
||||
tag_cloud: {
|
||||
label: '标签云',
|
||||
hint: '在右侧栏展示热门标签',
|
||||
},
|
||||
recent_comments: {
|
||||
label: '最新评论',
|
||||
hint: '在右侧栏展示最近回复',
|
||||
},
|
||||
friend_links: {
|
||||
label: '友情链接',
|
||||
hint: '关闭后不在右侧栏展示,友链仍可在「友情链接」页面查看与申请',
|
||||
},
|
||||
};
|
||||
|
||||
type Props = {
|
||||
widgets: AsideWidget[];
|
||||
onChange: (next: AsideWidget[]) => void;
|
||||
};
|
||||
|
||||
export default function AsideWidgetList({ widgets, onChange }: Props) {
|
||||
const handleToggle = (id: AsideWidgetId, enabled: boolean) => {
|
||||
onChange(widgets.map(w => (w.id === id ? { ...w, enabled } : w)));
|
||||
};
|
||||
|
||||
return (
|
||||
<AdminSortableList
|
||||
items={widgets}
|
||||
getId={widget => widget.id}
|
||||
onReorder={onChange}
|
||||
showMoveButtons={false}
|
||||
className="admin-sortable-list admin-sortable-list--boxed"
|
||||
ariaLabel="右侧栏组件"
|
||||
renderItem={(widget, _index, controls) => {
|
||||
const meta = WIDGET_META[widget.id];
|
||||
return (
|
||||
<div
|
||||
ref={controls.setNodeRef}
|
||||
style={controls.style}
|
||||
className={`admin-sortable-row admin-sortable-row--widget${controls.isDragging ? ' is-dragging' : ''}`}
|
||||
>
|
||||
<SortableDragHandle
|
||||
label={`拖拽调整「${meta.label}」顺序`}
|
||||
{...controls.dragHandleProps}
|
||||
/>
|
||||
<div className="admin-sortable-row__main">
|
||||
<span className="admin-sortable-row__label" id={`aside-widget-label-${widget.id}`}>
|
||||
{meta.label}
|
||||
</span>
|
||||
<span className="admin-sortable-row__hint">{meta.hint}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
id={`aside-widget-${widget.id}`}
|
||||
role="switch"
|
||||
aria-checked={widget.enabled}
|
||||
aria-labelledby={`aside-widget-label-${widget.id}`}
|
||||
className={`admin-settings-switch${widget.enabled ? ' is-on' : ''}`}
|
||||
onClick={() => handleToggle(widget.id, !widget.enabled)}
|
||||
>
|
||||
<span className="admin-settings-switch-ui" aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,13 @@ import BoardIconDisplay from '../BoardIconDisplay';
|
||||
import { getBoardThemeIndex } from '../../utils/boardTheme';
|
||||
import type { Board, ForumLimitsPublic } from '../../api/types';
|
||||
|
||||
export type PostType = 'normal' | 'question';
|
||||
export type PostType = 'normal' | 'question' | 'poll' | 'bounty' | 'lottery';
|
||||
|
||||
const SPECIAL_TYPE_LABELS: Record<'poll' | 'bounty' | 'lottery', string> = {
|
||||
poll: '投票',
|
||||
bounty: '悬赏',
|
||||
lottery: '抽奖',
|
||||
};
|
||||
|
||||
interface Props {
|
||||
isEdit: boolean;
|
||||
@@ -32,34 +38,93 @@ export default function ComposeContextBar({
|
||||
onTagsChange,
|
||||
limits,
|
||||
}: Props) {
|
||||
const isSpecialEdit = isEdit && (postType === 'poll' || postType === 'bounty' || postType === 'lottery');
|
||||
|
||||
return (
|
||||
<section className="compose-context" aria-label="发布设置">
|
||||
<div className="compose-context-row">
|
||||
<span className="compose-context-label">类型</span>
|
||||
<div className="compose-type-field">
|
||||
<div className="compose-type-pills" role="radiogroup" aria-label="帖子类型">
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={postType === 'normal'}
|
||||
className={`compose-type-pill${postType === 'normal' ? ' active' : ''}`}
|
||||
onClick={() => onPostTypeChange('normal')}
|
||||
>
|
||||
讨论
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={postType === 'question'}
|
||||
className={`compose-type-pill${postType === 'question' ? ' active' : ''}`}
|
||||
onClick={() => onPostTypeChange('question')}
|
||||
>
|
||||
问答
|
||||
</button>
|
||||
{isSpecialEdit ? (
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked
|
||||
className="compose-type-pill active"
|
||||
disabled
|
||||
>
|
||||
{SPECIAL_TYPE_LABELS[postType]}
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={postType === 'normal'}
|
||||
className={`compose-type-pill${postType === 'normal' ? ' active' : ''}`}
|
||||
onClick={() => onPostTypeChange('normal')}
|
||||
>
|
||||
讨论
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={postType === 'question'}
|
||||
className={`compose-type-pill${postType === 'question' ? ' active' : ''}`}
|
||||
onClick={() => onPostTypeChange('question')}
|
||||
disabled={isEdit}
|
||||
>
|
||||
问答
|
||||
</button>
|
||||
{!isEdit && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={postType === 'poll'}
|
||||
className={`compose-type-pill${postType === 'poll' ? ' active' : ''}`}
|
||||
onClick={() => onPostTypeChange('poll')}
|
||||
>
|
||||
投票
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={postType === 'bounty'}
|
||||
className={`compose-type-pill${postType === 'bounty' ? ' active' : ''}`}
|
||||
onClick={() => onPostTypeChange('bounty')}
|
||||
>
|
||||
悬赏
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={postType === 'lottery'}
|
||||
className={`compose-type-pill${postType === 'lottery' ? ' active' : ''}`}
|
||||
onClick={() => onPostTypeChange('lottery')}
|
||||
>
|
||||
抽奖
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{postType === 'question' && (
|
||||
<span className="compose-type-hint">问答可标记解决状态</span>
|
||||
)}
|
||||
{postType === 'poll' && (
|
||||
<span className="compose-type-hint">
|
||||
{isEdit ? '投票选项发布后不可修改' : '发布后选项不可修改'}
|
||||
</span>
|
||||
)}
|
||||
{postType === 'bounty' && (
|
||||
<span className="compose-type-hint">发布成功即扣除积分;有人回复后不可自行取消,需采纳或联系管理员</span>
|
||||
)}
|
||||
{postType === 'lottery' && (
|
||||
<span className="compose-type-hint">回帖参与,手动开奖</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="compose-context-row">
|
||||
|
||||
259
frontend/src/components/compose/ComposeSpecialFields.tsx
Normal file
259
frontend/src/components/compose/ComposeSpecialFields.tsx
Normal file
@@ -0,0 +1,259 @@
|
||||
import { Plus, Trash2 } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import type { PostType } from './ComposeContextBar';
|
||||
|
||||
interface Props {
|
||||
postType: PostType;
|
||||
pollOptions: string[];
|
||||
onPollOptionsChange: (opts: string[]) => void;
|
||||
pollMulti: boolean;
|
||||
onPollMultiChange: (v: boolean) => void;
|
||||
pollMaxChoices: number;
|
||||
onPollMaxChoicesChange: (v: number) => void;
|
||||
pollEndsAt: string;
|
||||
onPollEndsAtChange: (v: string) => void;
|
||||
pollNoEndTime: boolean;
|
||||
onPollNoEndTimeChange: (v: boolean) => void;
|
||||
bountyPoints: number;
|
||||
onBountyPointsChange: (v: number) => void;
|
||||
userPointsBalance?: number;
|
||||
lotteryWinners: number;
|
||||
onLotteryWinnersChange: (v: number) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
/** 默认截止时间:7 天后,分钟进位到下一整点 */
|
||||
export function defaultPollEndsAtLocal(): string {
|
||||
const d = new Date(Date.now() + 7 * 24 * 3600_000);
|
||||
d.setMinutes(0, 0, 0);
|
||||
if (d.getTime() <= Date.now()) {
|
||||
d.setHours(d.getHours() + 1);
|
||||
}
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
/** datetime-local → ISO8601(UTC) */
|
||||
export function pollEndsAtLocalToISO(local: string): string | undefined {
|
||||
const trimmed = local.trim();
|
||||
if (!trimmed) return undefined;
|
||||
const d = new Date(trimmed);
|
||||
if (Number.isNaN(d.getTime())) return undefined;
|
||||
return d.toISOString();
|
||||
}
|
||||
|
||||
/** ISO8601 → datetime-local */
|
||||
export function pollEndsAtISOToLocal(iso: string): string {
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
/** 特殊帖类型附加字段(投票/悬赏/抽奖) */
|
||||
export default function ComposeSpecialFields({
|
||||
postType,
|
||||
pollOptions,
|
||||
onPollOptionsChange,
|
||||
pollMulti,
|
||||
onPollMultiChange,
|
||||
pollMaxChoices,
|
||||
onPollMaxChoicesChange,
|
||||
pollEndsAt,
|
||||
onPollEndsAtChange,
|
||||
pollNoEndTime,
|
||||
onPollNoEndTimeChange,
|
||||
bountyPoints,
|
||||
onBountyPointsChange,
|
||||
userPointsBalance,
|
||||
lotteryWinners,
|
||||
onLotteryWinnersChange,
|
||||
disabled,
|
||||
}: Props) {
|
||||
if (postType === 'normal' || postType === 'question') return null;
|
||||
|
||||
if (postType === 'poll') {
|
||||
return (
|
||||
<section className="compose-special" aria-label="投票设置">
|
||||
<Label>投票选项(2-10 项)</Label>
|
||||
<div className="compose-special__poll-mode">
|
||||
<Switch checked={pollMulti} onCheckedChange={onPollMultiChange} disabled={disabled} id="poll-multi" />
|
||||
<label htmlFor="poll-multi">允许多选</label>
|
||||
{pollMulti && (
|
||||
<>
|
||||
<span className="compose-special__max-choices-label">最多可选</span>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={pollOptions.length || 10}
|
||||
value={pollMaxChoices}
|
||||
onChange={e => onPollMaxChoicesChange(Number(e.target.value) || 1)}
|
||||
disabled={disabled}
|
||||
className="compose-special__max-choices"
|
||||
aria-label="最多可选"
|
||||
/>
|
||||
<span className="compose-special__max-choices-suffix">项</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="compose-special__poll-deadline">
|
||||
<div className="compose-special__poll-deadline-toggle">
|
||||
<Switch
|
||||
checked={pollNoEndTime}
|
||||
onCheckedChange={onPollNoEndTimeChange}
|
||||
disabled={disabled}
|
||||
id="poll-no-end-time"
|
||||
/>
|
||||
<label htmlFor="poll-no-end-time">不限时</label>
|
||||
</div>
|
||||
{!pollNoEndTime && (
|
||||
<div className="compose-special__poll-deadline-field">
|
||||
<Label htmlFor="poll-ends-at" className="compose-special__poll-deadline-label">投票截止时间</Label>
|
||||
<Input
|
||||
id="poll-ends-at"
|
||||
type="datetime-local"
|
||||
value={pollEndsAt}
|
||||
onChange={e => onPollEndsAtChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
className="compose-special__poll-deadline-input w-auto"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="compose-special__options">
|
||||
{pollOptions.map((opt, i) => (
|
||||
<div key={i} className="compose-special__option-row">
|
||||
<Input
|
||||
value={opt}
|
||||
placeholder={`选项 ${i + 1}`}
|
||||
maxLength={64}
|
||||
disabled={disabled}
|
||||
onChange={e => {
|
||||
const next = [...pollOptions];
|
||||
next[i] = e.target.value;
|
||||
onPollOptionsChange(next);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={disabled || pollOptions.length <= 2}
|
||||
onClick={() => onPollOptionsChange(pollOptions.filter((_, j) => j !== i))}
|
||||
aria-label="删除选项"
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{pollOptions.length < 10 && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={disabled}
|
||||
onClick={() => onPollOptionsChange([...pollOptions, ''])}
|
||||
>
|
||||
<Plus size={14} /> 添加选项
|
||||
</Button>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
if (postType === 'bounty') {
|
||||
const showBalance = !disabled && typeof userPointsBalance === 'number';
|
||||
const balance = userPointsBalance ?? 0;
|
||||
const overBudget = showBalance && bountyPoints > balance;
|
||||
const remaining = showBalance && bountyPoints > 0 && !overBudget
|
||||
? balance - bountyPoints
|
||||
: null;
|
||||
|
||||
return (
|
||||
<section className="compose-special" aria-label="悬赏设置">
|
||||
<Label htmlFor="bounty-points">悬赏积分(发布即扣除)</Label>
|
||||
<div className="compose-special__bounty-row">
|
||||
<Input
|
||||
id="bounty-points"
|
||||
type="number"
|
||||
min={1}
|
||||
value={bountyPoints || ''}
|
||||
disabled={disabled}
|
||||
onChange={e => onBountyPointsChange(Math.max(0, Number(e.target.value) || 0))}
|
||||
/>
|
||||
{showBalance && (
|
||||
<p className={cn(
|
||||
'compose-special__balance',
|
||||
overBudget && 'compose-special__balance--over',
|
||||
)}
|
||||
>
|
||||
{overBudget
|
||||
? '积分不足'
|
||||
: remaining != null
|
||||
? `当前余额 ${balance} · 发布后剩余 ${remaining}`
|
||||
: `当前余额 ${balance}`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
if (postType === 'lottery') {
|
||||
return (
|
||||
<section className="compose-special" aria-label="抽奖设置">
|
||||
<Label htmlFor="lottery-winners">中奖人数(1-20)</Label>
|
||||
<Input
|
||||
id="lottery-winners"
|
||||
type="number"
|
||||
min={1}
|
||||
max={20}
|
||||
value={lotteryWinners || 1}
|
||||
disabled={disabled}
|
||||
onChange={e => onLotteryWinnersChange(Math.min(20, Math.max(1, Number(e.target.value) || 1)))}
|
||||
/>
|
||||
<p className="compose-special__hint">参与者为已回帖用户(不含楼主),由作者或管理员开奖</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function buildPollOptionsPayload(
|
||||
options: string[],
|
||||
multi: boolean,
|
||||
maxChoices: number,
|
||||
endsAtISO?: string | null,
|
||||
): string {
|
||||
const payload: Record<string, unknown> = {
|
||||
multi,
|
||||
max_choices: maxChoices,
|
||||
options: options.filter(o => o.trim()).map(text => ({ text: text.trim() })),
|
||||
};
|
||||
if (endsAtISO) payload.ends_at = endsAtISO;
|
||||
return JSON.stringify(payload);
|
||||
}
|
||||
|
||||
/** 统计有效(非空)投票选项数量 */
|
||||
export function countValidPollOptions(options: string[]): number {
|
||||
return options.filter(o => o.trim()).length;
|
||||
}
|
||||
|
||||
/** 前端校验投票截止时间(非不限时时) */
|
||||
export function validatePollEndsAtLocal(local: string): string | null {
|
||||
const iso = pollEndsAtLocalToISO(local);
|
||||
if (!iso) return '请选择有效的投票截止时间';
|
||||
if (new Date(iso).getTime() <= Date.now() + 5 * 60_000) {
|
||||
return '投票截止时间须晚于当前时间至少 5 分钟';
|
||||
}
|
||||
if (new Date(iso).getTime() > Date.now() + 365 * 24 * 3600_000) {
|
||||
return '投票截止时间不能超过 365 天';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
53
frontend/src/hooks/useCheckIn.ts
Normal file
53
frontend/src/hooks/useCheckIn.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '../api/client';
|
||||
import type { CheckInStatus } from '../api/types';
|
||||
import { useAuth } from './useAuth';
|
||||
|
||||
/** 每日签到状态与操作(侧栏、积分页等复用) */
|
||||
export function useCheckIn(enabled = true) {
|
||||
const { user, refresh } = useAuth();
|
||||
const [status, setStatus] = useState<CheckInStatus | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
if (!user || !enabled) {
|
||||
setStatus(null);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
api.checkInStatus()
|
||||
.then(d => setStatus(d.check_in))
|
||||
.catch(e => notify.error(e instanceof Error ? e.message : '加载签到状态失败'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [user, enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const doCheckIn = useCallback(async () => {
|
||||
if (!user) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await api.checkIn();
|
||||
notify.success(`签到成功,+${r.check_in.today_points} 积分`);
|
||||
setStatus(r.check_in);
|
||||
await refresh();
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '签到失败');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [user, refresh]);
|
||||
|
||||
return {
|
||||
status,
|
||||
loading,
|
||||
busy,
|
||||
doCheckIn,
|
||||
reload: load,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api } from '../api/client';
|
||||
import type { ForumLimitsPublic } from '../api/types';
|
||||
import { DEFAULT_ASIDE_WIDGETS } from '../api/types';
|
||||
|
||||
const DEFAULT_LIMITS: ForumLimitsPublic = {
|
||||
post_title_max: 128,
|
||||
@@ -16,6 +17,11 @@ const DEFAULT_LIMITS: ForumLimitsPublic = {
|
||||
signature_max: 200,
|
||||
open_posts_in_new_tab: true,
|
||||
open_content_links_in_new_tab: true,
|
||||
aside_show_tag_cloud: false,
|
||||
aside_show_recent_comments: false,
|
||||
aside_show_friend_links: true,
|
||||
aside_widgets: DEFAULT_ASIDE_WIDGETS,
|
||||
feed_list_style: 'title',
|
||||
permalink_enabled: false,
|
||||
permalink_ext: 'html',
|
||||
};
|
||||
|
||||
41
frontend/src/hooks/useSitePages.ts
Normal file
41
frontend/src/hooks/useSitePages.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api } from '../api/client';
|
||||
import type { SitePageSummary } from '../api/types';
|
||||
|
||||
let cache: SitePageSummary[] | null = null;
|
||||
let pending: Promise<SitePageSummary[]> | null = null;
|
||||
|
||||
/** 已发布单页摘要(页脚/侧栏导航) */
|
||||
export function useSitePages() {
|
||||
const [pages, setPages] = useState<SitePageSummary[]>(cache ?? []);
|
||||
|
||||
useEffect(() => {
|
||||
if (cache) {
|
||||
setPages(cache);
|
||||
return;
|
||||
}
|
||||
if (!pending) {
|
||||
pending = api.pages()
|
||||
.then(d => {
|
||||
cache = d.pages ?? [];
|
||||
return cache;
|
||||
})
|
||||
.catch(() => {
|
||||
cache = [];
|
||||
return cache;
|
||||
})
|
||||
.finally(() => { pending = null; });
|
||||
}
|
||||
pending.then(setPages);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
pages,
|
||||
footerPages: pages.filter(p => p.show_in_footer),
|
||||
navPages: pages.filter(p => p.show_in_nav),
|
||||
};
|
||||
}
|
||||
|
||||
export function invalidateSitePagesCache() {
|
||||
cache = null;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState, useCallback, useRef } from 'react';
|
||||
import { Outlet, NavLink, useNavigate, useLocation } from 'react-router-dom';
|
||||
import {
|
||||
LayoutDashboard, FolderKanban, FileText, MessageSquare, Flag, Users, Images, Settings, ArrowLeft, Moon, Sun, Menu, X, Award,
|
||||
LayoutDashboard, FolderKanban, FileText, MessageSquare, Flag, Users, Images, Settings, ArrowLeft, Moon, Sun, Menu, X, Award, Link2, BookOpen,
|
||||
} from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
@@ -16,7 +16,7 @@ import { useNoIndexSEO } from '../hooks/usePageSEO';
|
||||
import SiteBrandMark from '../components/SiteBrandMark';
|
||||
import { api } from '../api/client';
|
||||
|
||||
type BadgeKey = 'posts' | 'comments' | 'reports';
|
||||
type BadgeKey = 'posts' | 'comments' | 'reports' | 'links';
|
||||
|
||||
type NavItem = {
|
||||
to: string;
|
||||
@@ -50,8 +50,10 @@ const NAV_GROUPS: NavGroup[] = [
|
||||
label: '社区',
|
||||
items: [
|
||||
{ to: '/admin/boards', label: '板块管理', icon: FolderKanban },
|
||||
{ to: '/admin/pages', label: '单页管理', icon: BookOpen },
|
||||
{ to: '/admin/users', label: '用户管理', icon: Users },
|
||||
{ to: '/admin/badges', label: '徽章管理', icon: Award },
|
||||
{ to: '/admin/links', label: '友情链接', icon: Link2, badgeKey: 'links' },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -67,6 +69,7 @@ type PendingCounts = {
|
||||
posts: number;
|
||||
comments: number;
|
||||
reports: number;
|
||||
links: number;
|
||||
};
|
||||
|
||||
function formatNavBadge(n: number) {
|
||||
@@ -82,7 +85,7 @@ export default function AdminLayout() {
|
||||
useNoIndexSEO('管理后台');
|
||||
const isNarrow = useMediaQuery('(max-width: 768px)');
|
||||
const [navOpen, setNavOpen] = useState(false);
|
||||
const [pending, setPending] = useState<PendingCounts>({ posts: 0, comments: 0, reports: 0 });
|
||||
const [pending, setPending] = useState<PendingCounts>({ posts: 0, comments: 0, reports: 0, links: 0 });
|
||||
const nav = useNavigate();
|
||||
const location = useLocation();
|
||||
const drawerRef = useRef<HTMLElement>(null);
|
||||
@@ -99,10 +102,23 @@ export default function AdminLayout() {
|
||||
posts: d.pending_posts ?? 0,
|
||||
comments: d.pending_comments ?? 0,
|
||||
reports: d.pending_reports ?? 0,
|
||||
links: d.pending_friend_links ?? 0,
|
||||
}))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || !user || user.role !== 'admin') return;
|
||||
refreshPending();
|
||||
const onRefresh = () => refreshPending();
|
||||
window.addEventListener('admin-pending-refresh', onRefresh);
|
||||
const timer = window.setInterval(refreshPending, 60_000);
|
||||
return () => {
|
||||
window.removeEventListener('admin-pending-refresh', onRefresh);
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [loading, user, refreshPending]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
if (!user) {
|
||||
|
||||
@@ -14,13 +14,14 @@ import { useAuth } from '../hooks/useAuth';
|
||||
import { useTheme, useMediaQuery } from '../hooks/useTheme';
|
||||
import { useOverlayA11y, moveTabIndex } from '../hooks/useOverlayA11y';
|
||||
import { api } from '../api/client';
|
||||
import type { Board, PostItem, RecentComment, ForumStats, TagCount, User } from '../api/types';
|
||||
import type { Board, RecentComment, ForumStats, TagCount, User } from '../api/types';
|
||||
import type { PostHeading } from '../utils/postHeadings';
|
||||
import { getCachedBoards, getCachedStats, getCachedHot, getCachedRecentComments, getCachedTags, hasCachedAside, setCachedBoards, setCachedStats, setCachedHot, setCachedRecentComments, setCachedTags } from '../utils/layoutCache';
|
||||
import { getCachedBoards, getCachedStats, getCachedRecentComments, getCachedTags, hasCachedAside, setCachedBoards, setCachedStats, setCachedRecentComments, setCachedTags } from '../utils/layoutCache';
|
||||
import Sidebar, { isNeutralSidebarRoute } from '../components/Sidebar';
|
||||
import RightPanel from '../components/RightPanel';
|
||||
import BackToTop from '../components/BackToTop';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import { resolveAsideWidgets } from '../utils/asideWidgets';
|
||||
import { buildHomeUrl, parseFeedSort } from '../components/FeedSortBar';
|
||||
import { navigateFeed } from '../utils/feedCache';
|
||||
import { notify } from '@/lib/notify';
|
||||
@@ -32,6 +33,7 @@ import { useSiteBranding } from '../hooks/useSiteBranding';
|
||||
import SiteBrandMark from '../components/SiteBrandMark';
|
||||
import SiteFooter from '../components/SiteFooter';
|
||||
import { userPath } from '../utils/userPath';
|
||||
import { parsePermalinkID } from '../utils/permalink';
|
||||
|
||||
export default function MainLayout() {
|
||||
const { user, loading: authLoading, logout } = useAuth();
|
||||
@@ -46,7 +48,6 @@ export default function MainLayout() {
|
||||
|
||||
const [boards, setBoards] = useState<Board[]>(() => getCachedBoards());
|
||||
const [stats, setStats] = useState<ForumStats | null>(() => getCachedStats());
|
||||
const [hot, setHot] = useState<PostItem[]>(() => getCachedHot());
|
||||
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
|
||||
const [unreadMessages, setUnreadMessages] = useState(0);
|
||||
const [tags, setTags] = useState<TagCount[]>(() => getCachedTags());
|
||||
@@ -66,7 +67,11 @@ export default function MainLayout() {
|
||||
const [asideLoading, setAsideLoading] = useState(() => !hasCachedAside());
|
||||
const [boardsLoading, setBoardsLoading] = useState(() => getCachedBoards().length === 0);
|
||||
const asideEverLoaded = useRef(false);
|
||||
const [boardId, setBoardId] = useState(Number(params.get('board')) || 0);
|
||||
const [boardId, setBoardId] = useState(() => {
|
||||
const m = loc.pathname.match(/^\/board\/(\d+(?:\.[A-Za-z0-9]{1,16})?)$/);
|
||||
if (m) return parsePermalinkID(m[1]) || 0;
|
||||
return Number(params.get('board')) || 0;
|
||||
});
|
||||
const [keyword, setKeyword] = useState(params.get('keyword') || '');
|
||||
const [searchAuthor, setSearchAuthor] = useState(params.get('author') || '');
|
||||
const [searchTitleOnly, setSearchTitleOnly] = useState(params.get('title_only') === '1');
|
||||
@@ -74,6 +79,9 @@ export default function MainLayout() {
|
||||
const [searchAdvanced, setSearchAdvanced] = useState(false);
|
||||
const feedSort = parseFeedSort(params.get('sort'));
|
||||
const { limits: forumLimits } = useForumLimits();
|
||||
const asideWidgets = useMemo(() => resolveAsideWidgets(forumLimits), [forumLimits]);
|
||||
const showTagCloud = asideWidgets.some(w => w.id === 'tag_cloud' && w.enabled);
|
||||
const showRecentComments = asideWidgets.some(w => w.id === 'recent_comments' && w.enabled);
|
||||
|
||||
const asideDrawerRef = useRef<HTMLElement>(null);
|
||||
const asideCloseRef = useRef<HTMLButtonElement>(null);
|
||||
@@ -99,7 +107,14 @@ export default function MainLayout() {
|
||||
initialFocusRef: sidebarCloseRef,
|
||||
});
|
||||
|
||||
useEffect(() => { setBoardId(Number(params.get('board')) || 0); }, [params]);
|
||||
useEffect(() => {
|
||||
const m = loc.pathname.match(/^\/board\/(\d+(?:\.[A-Za-z0-9]{1,16})?)$/);
|
||||
if (m) {
|
||||
setBoardId(parsePermalinkID(m[1]) || 0);
|
||||
return;
|
||||
}
|
||||
setBoardId(Number(params.get('board')) || 0);
|
||||
}, [loc.pathname, params]);
|
||||
useEffect(() => {
|
||||
setKeyword(params.get('keyword') || '');
|
||||
setSearchAuthor(params.get('author') || '');
|
||||
@@ -183,7 +198,7 @@ export default function MainLayout() {
|
||||
|
||||
// 标签云:进页/离开发帖页时拉取;不跟 posts-refresh 联动(置顶/精华等不改标签)
|
||||
useEffect(() => {
|
||||
if (isCompose) return;
|
||||
if (isCompose || !showTagCloud) return;
|
||||
let cancelled = false;
|
||||
if (getCachedTags().length === 0) setTagsLoading(true);
|
||||
api.tags(40).then(d => {
|
||||
@@ -197,31 +212,24 @@ export default function MainLayout() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [isCompose]);
|
||||
}, [isCompose, showTagCloud]);
|
||||
|
||||
const needAsideData = !isCompose && (!hideAside || asideOpen);
|
||||
const needRecentComments = needAsideData && showRecentComments;
|
||||
useEffect(() => {
|
||||
if (!needAsideData) return;
|
||||
if (!needRecentComments) return;
|
||||
let cancelled = false;
|
||||
// 无缓存时才显示加载态,有缓存则静默刷新,避免抽屉高度跳动
|
||||
if (!asideEverLoaded.current && !hasCachedAside()) {
|
||||
setAsideLoading(true);
|
||||
}
|
||||
|
||||
Promise.all([
|
||||
api.hotPosts().then(d => {
|
||||
if (cancelled) return;
|
||||
const next = Array.isArray(d.posts) ? d.posts : [];
|
||||
setHot(next);
|
||||
setCachedHot(next);
|
||||
}).catch(() => {}),
|
||||
api.recentComments().then(d => {
|
||||
if (cancelled) return;
|
||||
const next = Array.isArray(d.comments) ? d.comments : [];
|
||||
setRecentComments(next);
|
||||
setCachedRecentComments(next);
|
||||
}).catch(() => {}),
|
||||
]).finally(() => {
|
||||
api.recentComments().then(d => {
|
||||
if (cancelled) return;
|
||||
const next = Array.isArray(d.comments) ? d.comments : [];
|
||||
setRecentComments(next);
|
||||
setCachedRecentComments(next);
|
||||
}).catch(() => {}).finally(() => {
|
||||
if (!cancelled) {
|
||||
asideEverLoaded.current = true;
|
||||
setAsideLoading(false);
|
||||
@@ -231,7 +239,7 @@ export default function MainLayout() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [needAsideData]);
|
||||
}, [needRecentComments]);
|
||||
|
||||
const doSearch = () => {
|
||||
const kw = keyword.trim();
|
||||
@@ -239,7 +247,7 @@ export default function MainLayout() {
|
||||
const activeKw = (params.get('keyword') || '').trim();
|
||||
const activeAuthor = (params.get('author') || '').trim();
|
||||
const activeTitleOnly = params.get('title_only') === '1';
|
||||
const activeBoard = Number(params.get('board')) || 0;
|
||||
const activeBoard = boardId;
|
||||
if (!kw && !author) {
|
||||
if (activeKw || activeAuthor) navigateFeed(nav, '/');
|
||||
return;
|
||||
@@ -260,9 +268,10 @@ export default function MainLayout() {
|
||||
keyword: kw,
|
||||
author,
|
||||
titleOnly: !!kw && searchTitleOnly,
|
||||
permalink: forumLimits,
|
||||
});
|
||||
const same =
|
||||
loc.pathname === '/'
|
||||
(loc.pathname === '/' || /^\/board\/\d+/.test(loc.pathname))
|
||||
&& activeKw === kw
|
||||
&& activeAuthor === author
|
||||
&& activeTitleOnly === (!!kw && searchTitleOnly)
|
||||
@@ -280,7 +289,7 @@ export default function MainLayout() {
|
||||
}, [nav, forumLimits.open_posts_in_new_tab]);
|
||||
|
||||
const userInitial = user?.nickname?.charAt(0) || '?';
|
||||
const isFeedHome = loc.pathname === '/';
|
||||
const isFeedHome = loc.pathname === '/' || /^\/board\/\d+/.test(loc.pathname);
|
||||
const outletKeyword = params.get('keyword') || '';
|
||||
const outletTag = params.get('tag') || '';
|
||||
const outletAuthor = params.get('author') || '';
|
||||
@@ -318,7 +327,7 @@ export default function MainLayout() {
|
||||
|
||||
const selectBoardChip = (id: number) => {
|
||||
setBoardId(id);
|
||||
navigateFeed(nav, buildHomeUrl(id, feedSort));
|
||||
navigateFeed(nav, buildHomeUrl(id, feedSort, { permalink: forumLimits }));
|
||||
};
|
||||
|
||||
const onBoardBarKeyDown = (e: React.KeyboardEvent) => {
|
||||
@@ -632,11 +641,12 @@ export default function MainLayout() {
|
||||
{!isCompose && (
|
||||
<aside className="aside-panel">
|
||||
<RightPanel
|
||||
hot={hot}
|
||||
recentComments={recentComments}
|
||||
tags={tags}
|
||||
tagsLoading={tagsLoading}
|
||||
stats={stats}
|
||||
loading={asideLoading}
|
||||
asideWidgets={asideWidgets}
|
||||
onPostClick={openPost}
|
||||
postDetail={isPostDetail ? {
|
||||
author: postOutline?.author ?? null,
|
||||
@@ -746,11 +756,12 @@ export default function MainLayout() {
|
||||
</div>
|
||||
<div className="aside-drawer-body">
|
||||
<RightPanel
|
||||
hot={hot}
|
||||
recentComments={recentComments}
|
||||
tags={tags}
|
||||
tagsLoading={tagsLoading}
|
||||
stats={stats}
|
||||
loading={asideLoading}
|
||||
asideWidgets={asideWidgets}
|
||||
onPostClick={openPost}
|
||||
postDetail={isPostDetail ? {
|
||||
author: postOutline?.author ?? null,
|
||||
|
||||
@@ -30,6 +30,8 @@ import type { Board } from '../api/types';
|
||||
import { BoardColorPicker, BoardIconPicker } from '../components/BoardAppearancePicker';
|
||||
import BoardIconDisplay from '../components/BoardIconDisplay';
|
||||
import { getBoardThemeIndex } from '../utils/boardTheme';
|
||||
import AdminSortableList, { SortableDragHandle, SortableMoveButtons } from '../components/admin/AdminSortableList';
|
||||
import { persistSortOrderChanges, shouldShowSortableMoveButtons } from '../utils/sortOrder';
|
||||
|
||||
const boardSchema = z.object({
|
||||
name: z.string().min(1, '请输入名称').max(64),
|
||||
@@ -48,6 +50,7 @@ export default function BoardsManagePage() {
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<Board | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [reordering, setReordering] = useState(false);
|
||||
|
||||
const form = useForm<BoardFormValues>({
|
||||
resolver: zodResolver(boardSchema),
|
||||
@@ -125,6 +128,32 @@ export default function BoardsManagePage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleBoardReorder = async (reordered: Board[]) => {
|
||||
const before = [...boards];
|
||||
setReordering(true);
|
||||
try {
|
||||
const after = await persistSortOrderChanges(before, reordered, board =>
|
||||
api.updateBoard(board.id, {
|
||||
name: board.name,
|
||||
description: board.description ?? '',
|
||||
sort_order: board.sort_order ?? 0,
|
||||
icon: board.icon ?? '',
|
||||
color_index: board.color_index ?? -1,
|
||||
}).then(() => undefined),
|
||||
);
|
||||
setBoards(after);
|
||||
notify.success('板块排序已更新');
|
||||
window.dispatchEvent(new Event('boards-refresh'));
|
||||
} catch (e: unknown) {
|
||||
setBoards(before);
|
||||
notify.error(e instanceof Error ? e.message : '排序保存失败');
|
||||
} finally {
|
||||
setReordering(false);
|
||||
}
|
||||
};
|
||||
|
||||
const showMoveButtons = shouldShowSortableMoveButtons(boards.length);
|
||||
|
||||
if (!ready) {
|
||||
return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
|
||||
}
|
||||
@@ -152,60 +181,76 @@ export default function BoardsManagePage() {
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[72px]">排序</TableHead>
|
||||
<TableHead className="w-[60px]">ID</TableHead>
|
||||
<TableHead className="w-[52px]">图标</TableHead>
|
||||
<TableHead>名称</TableHead>
|
||||
<TableHead>简介</TableHead>
|
||||
<TableHead className="w-[70px]">排序</TableHead>
|
||||
<TableHead className="w-[70px]">权重</TableHead>
|
||||
<TableHead className="w-[80px]">帖子数</TableHead>
|
||||
<TableHead className="w-[160px]">操作</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{boards.map(board => {
|
||||
<AdminSortableList
|
||||
as={TableBody}
|
||||
items={boards}
|
||||
getId={board => board.id}
|
||||
onReorder={handleBoardReorder}
|
||||
showMoveButtons="auto"
|
||||
renderItem={(board, _index, controls) => {
|
||||
const themeIdx = getBoardThemeIndex(board);
|
||||
return (
|
||||
<TableRow key={board.id}>
|
||||
<TableCell>{board.id}</TableCell>
|
||||
<TableCell>
|
||||
<span className={cn('board-table-icon', `sidebar-board-icon--${themeIdx}`)}>
|
||||
<BoardIconDisplay board={board} />
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell><strong>{board.name}</strong></TableCell>
|
||||
<TableCell className="max-w-[200px] truncate">{board.description}</TableCell>
|
||||
<TableCell>{board.sort_order}</TableCell>
|
||||
<TableCell><Badge variant="secondary">{board.post_count ?? 0}</Badge></TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button variant="ghost" size="sm" onClick={() => openEdit(board)}>编辑</Button>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive">
|
||||
删除
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确定删除该板块?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
删除后该板块下的帖子将无法通过板块筛选,此操作不可撤销。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => handleDelete(board.id)}>
|
||||
<TableRow
|
||||
ref={controls.setNodeRef}
|
||||
style={controls.style}
|
||||
className={cn('admin-sortable-table-row', controls.isDragging && 'is-dragging')}
|
||||
>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-0">
|
||||
<SortableDragHandle label={`拖拽调整「${board.name}」顺序`} {...controls.dragHandleProps} />
|
||||
{showMoveButtons && <SortableMoveButtons controls={controls} />}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>{board.id}</TableCell>
|
||||
<TableCell>
|
||||
<span className={cn('board-table-icon', `sidebar-board-icon--${themeIdx}`)}>
|
||||
<BoardIconDisplay board={board} />
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell><strong>{board.name}</strong></TableCell>
|
||||
<TableCell className="max-w-[200px] truncate">{board.description}</TableCell>
|
||||
<TableCell>{board.sort_order}</TableCell>
|
||||
<TableCell><Badge variant="secondary">{board.post_count ?? 0}</Badge></TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button variant="ghost" size="sm" onClick={() => openEdit(board)} disabled={reordering}>编辑</Button>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive" disabled={reordering}>
|
||||
删除
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确定删除该板块?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
删除后该板块下的帖子将无法通过板块筛选,此操作不可撤销。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => handleDelete(board.id)}>
|
||||
删除
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
}}
|
||||
/>
|
||||
</Table>
|
||||
{boards.length === 0 && (
|
||||
<div className="empty-state">
|
||||
|
||||
@@ -13,7 +13,16 @@ import { serializeTags, parseTags } from '../components/TagInput';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import ComposeHeader from '../components/compose/ComposeHeader';
|
||||
import ComposeContextBar, { type PostType } from '../components/compose/ComposeContextBar';
|
||||
import ComposeSpecialFields, {
|
||||
buildPollOptionsPayload,
|
||||
countValidPollOptions,
|
||||
defaultPollEndsAtLocal,
|
||||
pollEndsAtISOToLocal,
|
||||
pollEndsAtLocalToISO,
|
||||
validatePollEndsAtLocal,
|
||||
} from '../components/compose/ComposeSpecialFields';
|
||||
import ComposeDocument from '../components/compose/ComposeDocument';
|
||||
import { sortBoardsForCompose } from '../utils/board';
|
||||
import { getCachedBoards } from '../utils/layoutCache';
|
||||
import type { LayoutCtx } from '../layouts/MainLayout';
|
||||
import { loginPath } from '../utils/authRedirect';
|
||||
@@ -36,8 +45,8 @@ interface ComposeBaseline {
|
||||
}
|
||||
|
||||
function resolveBoards(ctxBoards?: Board[]): Board[] {
|
||||
if (ctxBoards && ctxBoards.length > 0) return ctxBoards;
|
||||
return getCachedBoards();
|
||||
const raw = ctxBoards && ctxBoards.length > 0 ? ctxBoards : getCachedBoards();
|
||||
return sortBoardsForCompose(raw);
|
||||
}
|
||||
|
||||
/** 格式化剩余可编辑时间 */
|
||||
@@ -74,6 +83,13 @@ export default function ComposePage() {
|
||||
const [tags, setTags] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
const [postType, setPostType] = useState<PostType>('normal');
|
||||
const [pollOptions, setPollOptions] = useState(['', '']);
|
||||
const [pollMulti, setPollMulti] = useState(false);
|
||||
const [pollMaxChoices, setPollMaxChoices] = useState(2);
|
||||
const [pollEndsAt, setPollEndsAt] = useState(defaultPollEndsAtLocal);
|
||||
const [pollNoEndTime, setPollNoEndTime] = useState(false);
|
||||
const [bountyPoints, setBountyPoints] = useState(0);
|
||||
const [lotteryWinners, setLotteryWinners] = useState(1);
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [loading, setLoading] = useState(isEdit);
|
||||
/** 新建帖:板块列表是否已就绪(避免请求中误显空态) */
|
||||
@@ -101,7 +117,7 @@ export default function ComposePage() {
|
||||
: api.boards();
|
||||
Promise.all([boardsPromise, api.post(editId!, { skipView: true })])
|
||||
.then(([boardsData, postData]) => {
|
||||
const list = boardsData.boards ?? [];
|
||||
const list = sortBoardsForCompose(boardsData.boards ?? []);
|
||||
setBoards(list);
|
||||
const post = postData.post;
|
||||
const isOwnerOrAdmin = user.role === 'admin' || post.user_id === user.id;
|
||||
@@ -116,7 +132,13 @@ export default function ComposePage() {
|
||||
return;
|
||||
}
|
||||
const loadedBoardId = String(post.board_id);
|
||||
const loadedType = post.post_type === 'question' ? 'question' : 'normal';
|
||||
const loadedType = (
|
||||
post.post_type === 'question' ? 'question'
|
||||
: post.post_type === 'poll' ? 'poll'
|
||||
: post.post_type === 'bounty' ? 'bounty'
|
||||
: post.post_type === 'lottery' ? 'lottery'
|
||||
: 'normal'
|
||||
) as PostType;
|
||||
const serverBaseline: ComposeBaseline = {
|
||||
title: post.title,
|
||||
tags: post.tags ?? '',
|
||||
@@ -130,6 +152,18 @@ export default function ComposePage() {
|
||||
setTags(serverBaseline.tags);
|
||||
setContent(serverBaseline.content);
|
||||
setPostType(loadedType);
|
||||
if (postData.poll) {
|
||||
setPollOptions(postData.poll.options.map(o => o.text));
|
||||
setPollMulti(postData.poll.multi);
|
||||
setPollMaxChoices(postData.poll.max_choices);
|
||||
if (postData.poll.ends_at) {
|
||||
setPollNoEndTime(false);
|
||||
setPollEndsAt(pollEndsAtISOToLocal(postData.poll.ends_at));
|
||||
} else {
|
||||
setPollNoEndTime(true);
|
||||
setPollEndsAt(defaultPollEndsAtLocal());
|
||||
}
|
||||
}
|
||||
|
||||
const windowHours = postData.post_edit_window_hours ?? 0;
|
||||
if (user.role !== 'admin' && windowHours > 0) {
|
||||
@@ -175,6 +209,13 @@ export default function ComposePage() {
|
||||
setTags(draft.tags);
|
||||
setContent(draft.content);
|
||||
setPostType(draft.postType);
|
||||
if (draft.postType === 'poll') {
|
||||
if (draft.pollOptions?.length) setPollOptions(draft.pollOptions);
|
||||
if (typeof draft.pollMulti === 'boolean') setPollMulti(draft.pollMulti);
|
||||
if (typeof draft.pollMaxChoices === 'number') setPollMaxChoices(draft.pollMaxChoices);
|
||||
if (typeof draft.pollNoEndTime === 'boolean') setPollNoEndTime(draft.pollNoEndTime);
|
||||
if (typeof draft.pollEndsAt === 'string' && draft.pollEndsAt) setPollEndsAt(draft.pollEndsAt);
|
||||
}
|
||||
setBaseline(emptyBaseline);
|
||||
setDraftHint('已恢复本地草稿,编辑中将自动保存');
|
||||
return;
|
||||
@@ -229,11 +270,18 @@ export default function ComposePage() {
|
||||
content,
|
||||
boardId,
|
||||
postType,
|
||||
...(postType === 'poll' ? {
|
||||
pollOptions,
|
||||
pollMulti,
|
||||
pollMaxChoices,
|
||||
pollEndsAt,
|
||||
pollNoEndTime,
|
||||
} : {}),
|
||||
});
|
||||
setDraftHint('草稿已自动保存到本机');
|
||||
}, 800);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [isEdit, baseline, isDirty, title, tags, content, boardId, postType]);
|
||||
}, [isEdit, baseline, isDirty, title, tags, content, boardId, postType, pollOptions, pollMulti, pollMaxChoices, pollEndsAt, pollNoEndTime]);
|
||||
|
||||
const {
|
||||
dialogOpen,
|
||||
@@ -307,15 +355,42 @@ export default function ComposePage() {
|
||||
if (!boardId) { notify.warning('请选择板块'); return; }
|
||||
if (!trimmedTitle) { notify.warning('请输入标题'); return; }
|
||||
if (isHtmlEmpty(content)) { notify.warning('请输入正文内容'); return; }
|
||||
if (postType === 'poll' && !isEdit && countValidPollOptions(pollOptions) < 2) {
|
||||
notify.warning('投票至少需要 2 个非空选项');
|
||||
return;
|
||||
}
|
||||
if (postType === 'poll' && !isEdit && !pollNoEndTime) {
|
||||
const err = validatePollEndsAtLocal(pollEndsAt);
|
||||
if (err) { notify.warning(err); return; }
|
||||
}
|
||||
if (postType === 'bounty' && !isEdit) {
|
||||
const balance = user?.points ?? 0;
|
||||
if (bountyPoints < 1) {
|
||||
notify.warning('请填写悬赏积分');
|
||||
return;
|
||||
}
|
||||
if (bountyPoints > balance) {
|
||||
notify.warning('积分不足');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setPublishing(true);
|
||||
try {
|
||||
const pollEndsAtISO = postType === 'poll' && !pollNoEndTime
|
||||
? pollEndsAtLocalToISO(pollEndsAt)
|
||||
: null;
|
||||
const payload = {
|
||||
title: trimmedTitle,
|
||||
content: content.trim(),
|
||||
tags: serializeTags(parseTags(tags)),
|
||||
board_id: boardId,
|
||||
post_type: postType,
|
||||
poll_options: postType === 'poll'
|
||||
? buildPollOptionsPayload(pollOptions, pollMulti, pollMaxChoices, pollEndsAtISO)
|
||||
: undefined,
|
||||
bounty_points: postType === 'bounty' ? bountyPoints : undefined,
|
||||
lottery_winner_count: postType === 'lottery' ? lotteryWinners : undefined,
|
||||
};
|
||||
if (isEdit) {
|
||||
await api.updatePost(editId!, payload);
|
||||
@@ -372,6 +447,25 @@ export default function ComposePage() {
|
||||
onTagsChange={setTags}
|
||||
limits={limits}
|
||||
/>
|
||||
<ComposeSpecialFields
|
||||
postType={postType}
|
||||
pollOptions={pollOptions}
|
||||
onPollOptionsChange={setPollOptions}
|
||||
pollMulti={pollMulti}
|
||||
onPollMultiChange={setPollMulti}
|
||||
pollMaxChoices={pollMaxChoices}
|
||||
onPollMaxChoicesChange={setPollMaxChoices}
|
||||
pollEndsAt={pollEndsAt}
|
||||
onPollEndsAtChange={setPollEndsAt}
|
||||
pollNoEndTime={pollNoEndTime}
|
||||
onPollNoEndTimeChange={setPollNoEndTime}
|
||||
bountyPoints={bountyPoints}
|
||||
onBountyPointsChange={setBountyPoints}
|
||||
userPointsBalance={!isEdit ? user?.points : undefined}
|
||||
lotteryWinners={lotteryWinners}
|
||||
onLotteryWinnersChange={setLotteryWinners}
|
||||
disabled={isEdit && postType !== 'normal' && postType !== 'question'}
|
||||
/>
|
||||
</ComposeDocument>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useNavigate, useOutletContext, useSearchParams, useLocation } from 'react-router-dom';
|
||||
import { useNavigate, useOutletContext, useSearchParams, useLocation, useParams } from 'react-router-dom';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '../api/client';
|
||||
import type { PostItem } from '../api/types';
|
||||
@@ -20,17 +20,35 @@ import {
|
||||
import { openForumPost } from '../utils/openPost';
|
||||
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
|
||||
import { siteMetaDescription, useSiteBranding } from '../hooks/useSiteBranding';
|
||||
import { boardPath, canonicalRedirectPath, parsePermalinkID } from '../utils/permalink';
|
||||
import NotFoundPage from './NotFoundPage';
|
||||
|
||||
/** 仅从 URL 解析板块 ID(不以 layout 状态回退,避免回首页误用上一板块) */
|
||||
function boardIdFromLocation(routeId: string | undefined, searchParams: URLSearchParams): number {
|
||||
if (routeId) {
|
||||
const id = parsePermalinkID(routeId);
|
||||
return Number.isFinite(id) && id > 0 ? id : 0;
|
||||
}
|
||||
const q = Number(searchParams.get('board')) || 0;
|
||||
return q > 0 ? q : 0;
|
||||
}
|
||||
|
||||
export default function HomePage() {
|
||||
const nav = useNavigate();
|
||||
const location = useLocation();
|
||||
const { id: boardRouteId } = useParams();
|
||||
const [params] = useSearchParams();
|
||||
const ctx = useOutletContext<LayoutCtx>();
|
||||
const { branding } = useSiteBranding();
|
||||
const { limits, loading: limitsLoading } = useForumLimits();
|
||||
const pageSize = Math.max(1, limits.page_size_default);
|
||||
|
||||
const boardId = Number(params.get('board')) || ctx?.boardId || 0;
|
||||
const boardId = boardIdFromLocation(boardRouteId, params);
|
||||
const queryBoardId = Number(params.get('board')) || 0;
|
||||
const isBoardRoute = !!boardRouteId;
|
||||
const isInvalidBoardRoute = isBoardRoute && boardId === 0;
|
||||
const boardsLoading = ctx?.boardsLoading ?? true;
|
||||
const isMissingBoard = isBoardRoute && boardId > 0 && !boardsLoading && !(ctx?.boards ?? []).some(b => b.id === boardId);
|
||||
const keyword = params.get('keyword') || '';
|
||||
const tag = params.get('tag') || '';
|
||||
const author = params.get('author') || '';
|
||||
@@ -51,11 +69,30 @@ export default function HomePage() {
|
||||
canonicalPath: tag
|
||||
? `/?tag=${encodeURIComponent(tag)}`
|
||||
: boardId
|
||||
? `/?board=${boardId}`
|
||||
? boardPath(boardId, limits)
|
||||
: '/',
|
||||
ogType: 'website',
|
||||
});
|
||||
|
||||
// 旧版 /?board=id 重定向到规范板块路径
|
||||
useEffect(() => {
|
||||
if (queryBoardId && !boardRouteId) {
|
||||
const p = new URLSearchParams(params);
|
||||
p.delete('board');
|
||||
const qs = p.toString();
|
||||
const target = boardPath(queryBoardId, limits) + (qs ? `?${qs}` : '');
|
||||
nav(target, { replace: true });
|
||||
return;
|
||||
}
|
||||
if (boardRouteId && boardId > 0) {
|
||||
const redirect = canonicalRedirectPath('board', boardId, location.pathname, limits);
|
||||
if (redirect) {
|
||||
const qs = location.search;
|
||||
nav(redirect + qs, { replace: true });
|
||||
}
|
||||
}
|
||||
}, [queryBoardId, boardId, boardRouteId, params, nav, limits, location.pathname, location.search]);
|
||||
|
||||
const [posts, setPosts] = useState<PostItem[]>([]);
|
||||
const [postTotal, setPostTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
@@ -137,7 +174,7 @@ export default function HomePage() {
|
||||
|
||||
// 等限制就绪后再拉列表;筛选变化时重载
|
||||
useEffect(() => {
|
||||
if (limitsLoading) return;
|
||||
if (limitsLoading || isInvalidBoardRoute || isMissingBoard) return;
|
||||
|
||||
const forceRefresh = (location.state as FeedNavState | null)?.refreshFeed;
|
||||
if (forceRefresh) {
|
||||
@@ -174,6 +211,8 @@ export default function HomePage() {
|
||||
location.state,
|
||||
loadFirst,
|
||||
beginFeedRefresh,
|
||||
isInvalidBoardRoute,
|
||||
isMissingBoard,
|
||||
]);
|
||||
|
||||
// 筛选未变时同步列表快照;变筛选的那一帧先保留旧快照供 cleanup 写入
|
||||
@@ -230,13 +269,22 @@ export default function HomePage() {
|
||||
loadFirst();
|
||||
return;
|
||||
}
|
||||
navigateFeed(nav, buildHomeUrl(boardId, next, { keyword, tag, author, titleOnly }));
|
||||
navigateFeed(nav, buildHomeUrl(boardId, next, { keyword, tag, author, titleOnly, permalink: limits }));
|
||||
};
|
||||
|
||||
const showSortBar = !keyword && !tag && !author;
|
||||
|
||||
if (isInvalidBoardRoute || isMissingBoard) {
|
||||
return (
|
||||
<NotFoundPage
|
||||
title="板块不存在"
|
||||
description="该板块不存在,或已被删除。"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// 首屏用同构骨架,避免标题/列表分区先后出现造成闪动
|
||||
if ((loading || limitsLoading) && posts.length === 0) {
|
||||
if ((loading || limitsLoading || (isBoardRoute && boardsLoading)) && posts.length === 0) {
|
||||
return <FeedPageSkeleton />;
|
||||
}
|
||||
|
||||
|
||||
300
frontend/src/pages/LinksPage.tsx
Normal file
300
frontend/src/pages/LinksPage.tsx
Normal file
@@ -0,0 +1,300 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { ArrowLeft, Link2, Pencil, Plus, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '../api/client';
|
||||
import type { FriendLink, FriendLinkApply } from '../api/types';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
|
||||
import { getCachedSiteBranding, invalidateSiteBrandingCache, useSiteBranding } from '../hooks/useSiteBranding';
|
||||
import { formatTime } from '../utils/content';
|
||||
import { loginPath } from '../utils/authRedirect';
|
||||
import { resolveFriendLinkLogo, isReciprocalChecking, reciprocalStatusLabel } from '../utils/friendLink';
|
||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||
import FriendLinkApplyDialog from '../components/FriendLinkApplyDialog';
|
||||
|
||||
function applyStatusBadge(status: FriendLinkApply['status']) {
|
||||
switch (status) {
|
||||
case 'pending':
|
||||
return <Badge variant="orange">待审核</Badge>;
|
||||
case 'approved':
|
||||
return <Badge variant="green">已通过</Badge>;
|
||||
case 'rejected':
|
||||
return <Badge variant="secondary">已拒绝</Badge>;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function linkInitial(name: string): string {
|
||||
const t = name.trim();
|
||||
return t ? t.charAt(0).toUpperCase() : '?';
|
||||
}
|
||||
|
||||
/** 友情链接独立页面:展示友链、申请与管理自己的申请 */
|
||||
export default function LinksPage() {
|
||||
const nav = useNavigate();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const { branding } = useSiteBranding();
|
||||
const { user } = useAuth();
|
||||
const [applyOpen, setApplyOpen] = useState(false);
|
||||
const [editApply, setEditApply] = useState<FriendLinkApply | null>(null);
|
||||
const [myApplies, setMyApplies] = useState<FriendLinkApply[]>([]);
|
||||
const [myLoading, setMyLoading] = useState(false);
|
||||
const [cancelingId, setCancelingId] = useState<number | null>(null);
|
||||
|
||||
usePageSEO({
|
||||
title: '友情链接',
|
||||
description: `${branding.name} 的友情链接与申请入口`,
|
||||
keywords: joinSEOKeywords('友情链接', getCachedSiteBranding().keywords),
|
||||
canonicalPath: '/links',
|
||||
});
|
||||
|
||||
const friendLinks = (branding.friend_links ?? []).filter(
|
||||
(l: FriendLink) => l.name?.trim() && l.url?.trim(),
|
||||
);
|
||||
|
||||
const loadMyApplies = useCallback(() => {
|
||||
if (!user) {
|
||||
setMyApplies([]);
|
||||
return;
|
||||
}
|
||||
setMyLoading(true);
|
||||
api.myFriendLinkApplies()
|
||||
.then(r => setMyApplies(r.applies ?? []))
|
||||
.catch(e => notify.error(e instanceof Error ? e.message : '加载失败'))
|
||||
.finally(() => setMyLoading(false));
|
||||
}, [user]);
|
||||
|
||||
useEffect(() => {
|
||||
loadMyApplies();
|
||||
}, [loadMyApplies]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user || !myApplies.some(isReciprocalChecking)) return;
|
||||
const timer = window.setInterval(loadMyApplies, 3000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [user, myApplies, loadMyApplies]);
|
||||
|
||||
useEffect(() => {
|
||||
if (params.get('apply') === '1') {
|
||||
if (!user) {
|
||||
nav(loginPath('/links?apply=1'));
|
||||
return;
|
||||
}
|
||||
setApplyOpen(true);
|
||||
const next = new URLSearchParams(params);
|
||||
next.delete('apply');
|
||||
setParams(next, { replace: true });
|
||||
}
|
||||
}, [params, setParams, user, nav]);
|
||||
|
||||
const openApply = () => {
|
||||
if (!user) {
|
||||
nav(loginPath('/links?apply=1'));
|
||||
return;
|
||||
}
|
||||
setEditApply(null);
|
||||
setApplyOpen(true);
|
||||
};
|
||||
|
||||
const openEditApply = (apply: FriendLinkApply) => {
|
||||
setEditApply(apply);
|
||||
setApplyOpen(true);
|
||||
};
|
||||
|
||||
const handleApplyOpenChange = (open: boolean) => {
|
||||
setApplyOpen(open);
|
||||
if (!open) setEditApply(null);
|
||||
};
|
||||
|
||||
const onApplySubmitted = useCallback(() => {
|
||||
loadMyApplies();
|
||||
invalidateSiteBrandingCache();
|
||||
}, [loadMyApplies]);
|
||||
|
||||
const cancelApply = async (apply: FriendLinkApply) => {
|
||||
if (apply.status !== 'pending') return;
|
||||
setCancelingId(apply.id);
|
||||
try {
|
||||
const r = await api.cancelFriendLinkApply(apply.id);
|
||||
notify.success(r.message);
|
||||
loadMyApplies();
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '撤销失败');
|
||||
} finally {
|
||||
setCancelingId(null);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="page-wrap">
|
||||
<div className="page-inner-wide">
|
||||
<Button variant="ghost" className="mb-3" onClick={() => nav('/')}>
|
||||
<ArrowLeft />
|
||||
返回
|
||||
</Button>
|
||||
|
||||
<div className="links-page-head">
|
||||
<div>
|
||||
<h1 className="page-title">友情链接</h1>
|
||||
<p className="page-desc">
|
||||
与本站互链的站点列表
|
||||
{friendLinks.length > 0 ? ` · 共 ${friendLinks.length} 个` : ''}
|
||||
</p>
|
||||
</div>
|
||||
<Button type="button" onClick={openApply}>
|
||||
<Plus size={16} aria-hidden />
|
||||
申请友链
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{friendLinks.length === 0 ? (
|
||||
<div className="empty-state links-page-empty">
|
||||
<Link2 className="empty-state-icon" aria-hidden size={36} strokeWidth={1.5} />
|
||||
<p>暂无友情链接</p>
|
||||
<p className="page-desc" style={{ marginTop: 8 }}>
|
||||
注册登录后可提交申请,审核通过后将展示在此页
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="links-page-board">
|
||||
<div className="links-page-grid">
|
||||
{friendLinks.map(link => {
|
||||
const logoURL = resolveFriendLinkLogo(link.logo, branding.site_url);
|
||||
return (
|
||||
<a
|
||||
key={`${link.name}-${link.url}`}
|
||||
href={link.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="links-page-card"
|
||||
title={link.name}
|
||||
>
|
||||
<div className="links-page-card__logo">
|
||||
{logoURL ? (
|
||||
<img src={logoURL} alt="" loading="lazy" decoding="async" />
|
||||
) : (
|
||||
<span>{linkInitial(link.name)}</span>
|
||||
)}
|
||||
</div>
|
||||
<strong className="links-page-card__name">{link.name}</strong>
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{user && (
|
||||
<section className="links-page-my" aria-label="我的友链申请">
|
||||
<h2 className="links-page-my__title">我的申请</h2>
|
||||
{myLoading ? (
|
||||
<div className="flex justify-center py-10"><Spinner /></div>
|
||||
) : myApplies.length === 0 ? (
|
||||
<p className="links-page-my__empty">你还没有提交过友链申请</p>
|
||||
) : (
|
||||
<div className="links-page-my-list">
|
||||
{myApplies.map(apply => (
|
||||
<div key={apply.id} className="links-page-my-row">
|
||||
{apply.logo?.trim() && (
|
||||
<div className="links-page-my-row__logo">
|
||||
<img src={resolveFriendLinkLogo(apply.logo, branding.site_url)} alt="" loading="lazy" decoding="async" />
|
||||
</div>
|
||||
)}
|
||||
<div className="links-page-my-row__main">
|
||||
<div className="links-page-my-row__title">
|
||||
<strong>{apply.name}</strong>
|
||||
{applyStatusBadge(apply.status)}
|
||||
</div>
|
||||
<a href={apply.url} target="_blank" rel="noopener noreferrer" className="links-page-my-row__url">
|
||||
{apply.url}
|
||||
</a>
|
||||
{apply.status === 'rejected' && apply.review_note?.trim() && (
|
||||
<p className="links-page-my-row__note">拒绝原因:{apply.review_note}</p>
|
||||
)}
|
||||
{apply.status === 'pending' && (
|
||||
<p className="links-page-my-row__note">
|
||||
回链检测:{reciprocalStatusLabel(apply).text}
|
||||
</p>
|
||||
)}
|
||||
{apply.status === 'approved' && (
|
||||
<p className="links-page-my-row__note">修改后将重新进入审核,友链会暂时从列表移除</p>
|
||||
)}
|
||||
<p className="links-page-my-row__meta">{formatTime(apply.created_at)}</p>
|
||||
</div>
|
||||
{apply.status === 'pending' && (
|
||||
<div className="links-page-my-row__actions">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => openEditApply(apply)}
|
||||
>
|
||||
<Pencil size={14} aria-hidden />
|
||||
修改
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={cancelingId === apply.id}
|
||||
onClick={() => cancelApply(apply)}
|
||||
>
|
||||
<Trash2 size={14} aria-hidden />
|
||||
撤销
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{apply.status === 'rejected' && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => openEditApply(apply)}
|
||||
>
|
||||
<Pencil size={14} aria-hidden />
|
||||
修改并重新提交
|
||||
</Button>
|
||||
)}
|
||||
{apply.status === 'approved' && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => openEditApply(apply)}
|
||||
>
|
||||
<Pencil size={14} aria-hidden />
|
||||
修改
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{!user && (
|
||||
<p className="links-page-login-hint">
|
||||
<Link to={loginPath('/links')}>登录</Link>
|
||||
或
|
||||
<Link to="/register">注册</Link>
|
||||
后可申请友链并管理自己的申请
|
||||
</p>
|
||||
)}
|
||||
|
||||
<InFlowSiteFooter />
|
||||
</div>
|
||||
|
||||
<FriendLinkApplyDialog
|
||||
open={applyOpen}
|
||||
onOpenChange={handleApplyOpenChange}
|
||||
editApply={editApply}
|
||||
onSubmitted={onApplySubmitted}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -34,11 +34,15 @@ import {
|
||||
} from '@/components/ui/dialog';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '../api/client';
|
||||
import type { PostItem, Comment, ReportReason } from '../api/types';
|
||||
import type { PostItem, Comment, ReportReason, PollView, PostLotteryView } from '../api/types';
|
||||
import { REPORT_REASON_OPTIONS } from '../utils/report';
|
||||
import CommentThreadList from '../components/CommentThreadList';
|
||||
import CommentBox, { type CommentSubmitData } from '../components/CommentBox';
|
||||
import PostContent from '../components/PostContent';
|
||||
import PostPollCard from '../components/PostPollCard';
|
||||
import PostBountyBanner from '../components/PostBountyBanner';
|
||||
import { findCommentFloor } from '../utils/bounty';
|
||||
import PostLotteryCard from '../components/PostLotteryCard';
|
||||
import PostRevisionPanel from '../components/PostRevisionPanel';
|
||||
import ArticleOutline from '../components/ArticleOutline';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
@@ -81,6 +85,8 @@ export default function PostDetailPage() {
|
||||
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
|
||||
|
||||
const [post, setPost] = useState<PostItem | null>(null);
|
||||
const [poll, setPoll] = useState<PollView | null>(null);
|
||||
const [lottery, setLottery] = useState<PostLotteryView | null>(null);
|
||||
const [comments, setComments] = useState<Comment[]>([]);
|
||||
const [liked, setLiked] = useState(false);
|
||||
const [favorited, setFavorited] = useState(false);
|
||||
@@ -104,6 +110,11 @@ export default function PostDetailPage() {
|
||||
const [rejectOpen, setRejectOpen] = useState(false);
|
||||
const [rejectReason, setRejectReason] = useState('');
|
||||
const [rejecting, setRejecting] = useState(false);
|
||||
const [bountyAwardTarget, setBountyAwardTarget] = useState<number | null>(null);
|
||||
const [bountyAwarding, setBountyAwarding] = useState(false);
|
||||
const [bountyCanRefund, setBountyCanRefund] = useState(true);
|
||||
const [bountyRefundBlockReason, setBountyRefundBlockReason] = useState('');
|
||||
const [bountyEligibleReplyCount, setBountyEligibleReplyCount] = useState(0);
|
||||
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
const commentSectionRef = useRef<HTMLDivElement>(null);
|
||||
@@ -189,12 +200,17 @@ export default function PostDetailPage() {
|
||||
]);
|
||||
if (seq !== loadSeq.current) return;
|
||||
setPost(detail.post);
|
||||
setPoll(detail.poll ?? null);
|
||||
setLottery(detail.lottery ?? null);
|
||||
setLiked(detail.liked);
|
||||
setFavorited(detail.favorited);
|
||||
setCanEdit(detail.can_edit ?? false);
|
||||
setIsEdited(detail.is_edited ?? isTimeDiffSignificant(detail.post.created_at, detail.post.updated_at ?? detail.post.created_at));
|
||||
setEditBlockReason(detail.edit_block_reason ?? '');
|
||||
setEditWindowHours(detail.post_edit_window_hours ?? 0);
|
||||
setBountyCanRefund(detail.bounty_can_refund ?? true);
|
||||
setBountyRefundBlockReason(detail.bounty_refund_block_reason ?? '');
|
||||
setBountyEligibleReplyCount(detail.bounty_eligible_reply_count ?? 0);
|
||||
setComments(Array.isArray(comm.comments) ? comm.comments : []);
|
||||
void refresh();
|
||||
} catch {
|
||||
@@ -218,6 +234,11 @@ export default function PostDetailPage() {
|
||||
try {
|
||||
const detail = await api.post(postId, { skipView: true });
|
||||
setPost(detail.post);
|
||||
setPoll(detail.poll ?? null);
|
||||
setLottery(detail.lottery ?? null);
|
||||
setBountyCanRefund(detail.bounty_can_refund ?? true);
|
||||
setBountyRefundBlockReason(detail.bounty_refund_block_reason ?? '');
|
||||
setBountyEligibleReplyCount(detail.bounty_eligible_reply_count ?? 0);
|
||||
} catch {
|
||||
// 评论已成功,正文刷新失败不阻断
|
||||
}
|
||||
@@ -547,6 +568,32 @@ export default function PostDetailPage() {
|
||||
? formatEditRemaining(post.created_at, editWindowHours)
|
||||
: '';
|
||||
|
||||
const handleBountyAward = (commentId: number) => {
|
||||
setBountyAwardTarget(commentId);
|
||||
};
|
||||
|
||||
const confirmBountyAward = async () => {
|
||||
if (bountyAwardTarget == null) return;
|
||||
setBountyAwarding(true);
|
||||
try {
|
||||
await api.bountyAward(post.id, bountyAwardTarget);
|
||||
notify.success('悬赏已发放');
|
||||
setBountyAwardTarget(null);
|
||||
await reloadPostContent();
|
||||
await reloadComments();
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '操作失败');
|
||||
} finally {
|
||||
setBountyAwarding(false);
|
||||
}
|
||||
};
|
||||
const awardedCommentFloor = findCommentFloor(comments, post.bounty_comment_id);
|
||||
const canJumpToAwarded = awardedCommentFloor != null;
|
||||
|
||||
const handleJumpToAwarded = () => {
|
||||
if (awardedCommentFloor != null) jumpToFloor(awardedCommentFloor);
|
||||
};
|
||||
|
||||
const handlePin = async () => {
|
||||
if (!post) return;
|
||||
try {
|
||||
@@ -729,6 +776,20 @@ export default function PostDetailPage() {
|
||||
{post.question_resolved ? '已解决' : '未解决'}
|
||||
</span>
|
||||
)}
|
||||
{post.post_type === 'poll' && (
|
||||
<span className="post-type-badge post-type-badge--poll">投票</span>
|
||||
)}
|
||||
{post.post_type === 'bounty' && post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0 && (
|
||||
<span className="post-bounty-badge post-bounty-badge--open post-bounty-badge--detail">悬赏 {post.bounty_points}</span>
|
||||
)}
|
||||
{post.post_type === 'bounty' && post.bounty_status === 'awarded' && (
|
||||
<span className="post-bounty-badge post-bounty-badge--awarded post-bounty-badge--detail">已采纳</span>
|
||||
)}
|
||||
{post.post_type === 'lottery' && (
|
||||
<span className="post-type-badge post-type-badge--lottery">
|
||||
{post.lottery_status === 'drawn' ? '已开奖' : '抽奖'}
|
||||
</span>
|
||||
)}
|
||||
{post.title}
|
||||
</h1>
|
||||
<div className="post-detail-author-row">
|
||||
@@ -791,6 +852,34 @@ export default function PostDetailPage() {
|
||||
</details>
|
||||
)}
|
||||
|
||||
{poll && (
|
||||
<PostPollCard
|
||||
postId={post.id}
|
||||
poll={poll}
|
||||
isOwnerOrAdmin={isOwnerOrAdmin}
|
||||
onUpdate={setPoll}
|
||||
/>
|
||||
)}
|
||||
<PostBountyBanner
|
||||
post={post}
|
||||
isOwnerOrAdmin={isOwnerOrAdmin}
|
||||
isAdmin={isAdmin}
|
||||
canRefund={bountyCanRefund}
|
||||
refundBlockReason={bountyRefundBlockReason}
|
||||
eligibleReplyCount={bountyEligibleReplyCount}
|
||||
onUpdate={reloadPostContent}
|
||||
onJumpToAwarded={handleJumpToAwarded}
|
||||
canJumpToAwarded={canJumpToAwarded}
|
||||
/>
|
||||
{lottery && (
|
||||
<PostLotteryCard
|
||||
postId={post.id}
|
||||
lottery={lottery}
|
||||
isOwnerOrAdmin={isOwnerOrAdmin}
|
||||
onUpdate={v => { setLottery(v); void reloadPostContent(); }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<PostContent
|
||||
html={post.content || ''}
|
||||
isLoggedIn={!!user}
|
||||
@@ -1078,10 +1167,42 @@ export default function PostDetailPage() {
|
||||
inline
|
||||
/>
|
||||
)}
|
||||
bountyAward={post.post_type === 'bounty' ? {
|
||||
open: post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0,
|
||||
awardedCommentId: post.bounty_comment_id,
|
||||
postAuthorId: post.user_id,
|
||||
canAward: isOwnerOrAdmin,
|
||||
onAward: handleBountyAward,
|
||||
} : undefined}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<AlertDialog
|
||||
open={bountyAwardTarget != null}
|
||||
onOpenChange={(open) => { if (!open && !bountyAwarding) setBountyAwardTarget(null); }}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>采纳该回复?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
确定采纳该回复并发放 {post.bounty_points ?? 0} 悬赏积分?此操作不可撤销。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={bountyAwarding}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
disabled={bountyAwarding}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
void confirmBountyAward();
|
||||
}}
|
||||
>
|
||||
{bountyAwarding ? '发放中…' : '确认采纳'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<InFlowSiteFooter />
|
||||
</article>
|
||||
);
|
||||
|
||||
55
frontend/src/pages/SitePageView.tsx
Normal file
55
frontend/src/pages/SitePageView.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import NotFoundPage from './NotFoundPage';
|
||||
import { api } from '../api/client';
|
||||
import type { SitePage } from '../api/types';
|
||||
import PostContent from '../components/PostContent';
|
||||
import PageLoader from '../components/PageLoader';
|
||||
import { usePageSEO } from '../hooks/usePageSEO';
|
||||
import { parsePermalinkSlug, pagePath } from '../utils/permalink';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
|
||||
/** 自定义单页(关于我们、版规等) */
|
||||
export default function SitePageView() {
|
||||
const { slug: rawSlug } = useParams();
|
||||
const slug = parsePermalinkSlug(rawSlug);
|
||||
const { limits } = useForumLimits();
|
||||
const [page, setPage] = useState<SitePage | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [notFound, setNotFound] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!slug) {
|
||||
setNotFound(true);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
api.page(slug)
|
||||
.then(d => setPage(d.page))
|
||||
.catch(() => setNotFound(true))
|
||||
.finally(() => setLoading(false));
|
||||
}, [slug]);
|
||||
|
||||
usePageSEO({
|
||||
title: page?.title,
|
||||
description: page?.title,
|
||||
canonicalPath: slug ? pagePath(slug, limits) : undefined,
|
||||
ogType: 'article',
|
||||
});
|
||||
|
||||
if (!slug) return <NotFoundPage title="页面不存在" />;
|
||||
if (loading) return <PageLoader />;
|
||||
if (notFound || !page) return <NotFoundPage title="页面不存在" description="该页面不存在或未发布" />;
|
||||
|
||||
return (
|
||||
<div className="page-wrap">
|
||||
<article className="site-page">
|
||||
<header className="site-page__head">
|
||||
<h1>{page.title}</h1>
|
||||
</header>
|
||||
<PostContent html={page.content} className="site-page__body post-body" />
|
||||
</article>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -27,6 +27,8 @@ import {
|
||||
badgeIcon,
|
||||
formatBadgeCondition,
|
||||
} from '../../utils/badgeIcons';
|
||||
import AdminSortableList, { SortableDragHandle, SortableMoveButtons } from '../../components/admin/AdminSortableList';
|
||||
import { mergeReorderedSubset, persistSortOrderChanges, shouldShowSortableMoveButtons } from '../../utils/sortOrder';
|
||||
|
||||
type KindTab = 'all' | 'auto' | 'limited';
|
||||
|
||||
@@ -62,6 +64,7 @@ export default function AdminBadgesPage() {
|
||||
const [form, setForm] = useState<Partial<BadgeDef>>({ ...EMPTY });
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [togglingId, setTogglingId] = useState<number | null>(null);
|
||||
const [reordering, setReordering] = useState(false);
|
||||
|
||||
const load = () => {
|
||||
setLoading(true);
|
||||
@@ -161,6 +164,27 @@ export default function AdminBadgesPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleBadgeReorder = async (reorderedFiltered: BadgeDef[]) => {
|
||||
const subsetBefore = [...filtered];
|
||||
const before = [...rows];
|
||||
setReordering(true);
|
||||
try {
|
||||
const merged = mergeReorderedSubset(before, subsetBefore, reorderedFiltered);
|
||||
const after = await persistSortOrderChanges(before, merged, badge =>
|
||||
api.adminUpsertBadge({ ...badge, sort_order: badge.sort_order }),
|
||||
);
|
||||
setRows(after);
|
||||
notify.success('徽章排序已更新');
|
||||
} catch (e: unknown) {
|
||||
setRows(before);
|
||||
notify.error(e instanceof Error ? e.message : '排序保存失败');
|
||||
} finally {
|
||||
setReordering(false);
|
||||
}
|
||||
};
|
||||
|
||||
const showMoveButtons = shouldShowSortableMoveButtons(filtered.length);
|
||||
|
||||
if (!ready) return null;
|
||||
|
||||
const PreviewIcon = badgeIcon(form.icon);
|
||||
@@ -249,14 +273,30 @@ export default function AdminBadgesPage() {
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="admin-badge-grid">
|
||||
{filtered.map(b => {
|
||||
<AdminSortableList
|
||||
strategy="grid"
|
||||
className="admin-badge-grid"
|
||||
items={filtered}
|
||||
getId={b => b.id}
|
||||
onReorder={handleBadgeReorder}
|
||||
showMoveButtons="auto"
|
||||
ariaLabel="徽章列表排序"
|
||||
renderItem={(b, _index, controls) => {
|
||||
const Icon = badgeIcon(b.icon);
|
||||
return (
|
||||
<article
|
||||
key={b.id}
|
||||
className={cn('admin-badge-card', !b.enabled && 'is-disabled')}
|
||||
ref={controls.setNodeRef}
|
||||
style={controls.style}
|
||||
className={cn(
|
||||
'admin-badge-card',
|
||||
'admin-sortable-grid-item',
|
||||
!b.enabled && 'is-disabled',
|
||||
controls.isDragging && 'is-dragging',
|
||||
)}
|
||||
>
|
||||
<div className="admin-sortable-grid-item__handle-wrap">
|
||||
<SortableDragHandle label={`拖拽调整「${b.name}」顺序`} {...controls.dragHandleProps} />
|
||||
</div>
|
||||
<div className="admin-badge-card-top">
|
||||
<div className={cn('admin-badge-preview', b.kind === 'limited' && 'is-limited')}>
|
||||
<Icon size={22} aria-hidden />
|
||||
@@ -283,15 +323,16 @@ export default function AdminBadgesPage() {
|
||||
{formatBadgeCondition(b)}
|
||||
</span>
|
||||
<div className="admin-badge-card-actions">
|
||||
{showMoveButtons && <SortableMoveButtons controls={controls} />}
|
||||
<label className="admin-badge-switch" title={b.enabled ? '点击停用' : '点击启用'}>
|
||||
<span className="sr-only">启用</span>
|
||||
<Switch
|
||||
checked={b.enabled}
|
||||
disabled={togglingId === b.id}
|
||||
disabled={togglingId === b.id || reordering}
|
||||
onCheckedChange={() => toggleEnabled(b)}
|
||||
/>
|
||||
</label>
|
||||
<Button size="sm" variant="outline" onClick={() => openEdit(b)}>
|
||||
<Button size="sm" variant="outline" onClick={() => openEdit(b)} disabled={reordering}>
|
||||
<Pencil size={13} />
|
||||
编辑
|
||||
</Button>
|
||||
@@ -299,8 +340,8 @@ export default function AdminBadgesPage() {
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={(open) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { FileText, Flag, MessageSquare } from 'lucide-react';
|
||||
import { FileText, Flag, MessageSquare, Link2 } from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { api } from '../../api/client';
|
||||
@@ -29,7 +29,8 @@ export default function AdminDashboardPage() {
|
||||
const pendingPosts = data.pending_posts ?? 0;
|
||||
const pendingComments = data.pending_comments ?? 0;
|
||||
const pendingReports = data.pending_reports ?? 0;
|
||||
const pendingTotal = pendingPosts + pendingComments + pendingReports;
|
||||
const pendingFriendLinks = data.pending_friend_links ?? 0;
|
||||
const pendingTotal = pendingPosts + pendingComments + pendingReports + pendingFriendLinks;
|
||||
|
||||
const stats = [
|
||||
{ label: '注册用户', value: data.users },
|
||||
@@ -63,6 +64,14 @@ export default function AdminDashboardPage() {
|
||||
to: '/admin/reports',
|
||||
icon: Flag,
|
||||
},
|
||||
{
|
||||
key: 'links',
|
||||
label: '待审友链',
|
||||
count: pendingFriendLinks,
|
||||
hint: '用户提交的友情链接申请',
|
||||
to: '/admin/links',
|
||||
icon: Link2,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
|
||||
712
frontend/src/pages/admin/AdminLinksPage.tsx
Normal file
712
frontend/src/pages/admin/AdminLinksPage.tsx
Normal file
@@ -0,0 +1,712 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Link2, Plus, Trash2, Check, X, ExternalLink, Eye, RotateCcw,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { api } from '../../api/client';
|
||||
import { useAdminGuard } from '../../layouts/AdminLayout';
|
||||
import type { FriendLink, FriendLinkApply, SiteBranding } from '../../api/types';
|
||||
import { useSiteBranding, seedSiteBrandingCache, invalidateSiteBrandingCache } from '../../hooks/useSiteBranding';
|
||||
import { formatTime } from '../../utils/content';
|
||||
import { resolveFriendLinkLogo, isReciprocalChecking, reciprocalStatusLabel } from '../../utils/friendLink';
|
||||
import AdminSortableList, { SortableDragHandle, SortableMoveButtons } from '../../components/admin/AdminSortableList';
|
||||
import { shouldShowSortableMoveButtons } from '../../utils/sortOrder';
|
||||
|
||||
type ApplyStatusTab = 'pending' | 'approved' | 'rejected' | 'all';
|
||||
|
||||
type LinkRow = FriendLink & { _key: string };
|
||||
|
||||
const APPLY_PAGE_SIZE = 20;
|
||||
|
||||
function applyStatusBadge(status: FriendLinkApply['status']) {
|
||||
switch (status) {
|
||||
case 'pending':
|
||||
return <Badge variant="orange">待审核</Badge>;
|
||||
case 'approved':
|
||||
return <Badge variant="green">已通过</Badge>;
|
||||
case 'rejected':
|
||||
return <Badge variant="secondary">已拒绝</Badge>;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function linkInitial(name: string): string {
|
||||
const t = name.trim();
|
||||
return t ? t.charAt(0).toUpperCase() : '?';
|
||||
}
|
||||
|
||||
function normalizeLinks(list: FriendLink[]): FriendLink[] {
|
||||
return list
|
||||
.map(l => ({
|
||||
name: l.name.trim(),
|
||||
url: l.url.trim(),
|
||||
logo: l.logo?.trim() || '',
|
||||
}))
|
||||
.filter(l => l.name && l.url);
|
||||
}
|
||||
|
||||
function linksEqual(a: FriendLink[], b: FriendLink[]): boolean {
|
||||
return JSON.stringify(normalizeLinks(a)) === JSON.stringify(normalizeLinks(b));
|
||||
}
|
||||
|
||||
function toLinkRows(list: FriendLink[]): LinkRow[] {
|
||||
return list.map((l, i) => ({
|
||||
...l,
|
||||
_key: `${l.url}-${l.name}-${i}`,
|
||||
}));
|
||||
}
|
||||
|
||||
function ApplyLogo({ apply, className, siteURL }: { apply: FriendLinkApply; className?: string; siteURL?: string }) {
|
||||
const logo = resolveFriendLinkLogo(apply.logo, siteURL);
|
||||
if (logo) {
|
||||
return (
|
||||
<div className={cn('admin-links-logo-thumb', className)}>
|
||||
<img src={logo} alt="" loading="lazy" decoding="async" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={cn('admin-links-logo-thumb admin-links-logo-thumb--placeholder', className)}>
|
||||
{linkInitial(apply.name)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ReciprocalAddress({ apply }: { apply: FriendLinkApply }) {
|
||||
const href = apply.reciprocal_page_url?.trim();
|
||||
if (!href) {
|
||||
return <span className="admin-links-reciprocal-empty">未填写</span>;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<a href={href} target="_blank" rel="noopener noreferrer">{href}</a>
|
||||
{apply.link_on_homepage ? '(首页)' : ''}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** 后台:友情链接独立管理 */
|
||||
export default function AdminLinksPage() {
|
||||
const nav = useNavigate();
|
||||
const { ready } = useAdminGuard();
|
||||
const { branding } = useSiteBranding();
|
||||
const rowKeyRef = useRef(0);
|
||||
|
||||
const [links, setLinks] = useState<LinkRow[]>([]);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const [applyStatus, setApplyStatus] = useState<ApplyStatusTab>('pending');
|
||||
const [applies, setApplies] = useState<FriendLinkApply[]>([]);
|
||||
const [applyPage, setApplyPage] = useState(1);
|
||||
const [applyTotal, setApplyTotal] = useState(0);
|
||||
const [pendingCount, setPendingCount] = useState(0);
|
||||
const [appliesLoading, setAppliesLoading] = useState(true);
|
||||
|
||||
const [detailApply, setDetailApply] = useState<FriendLinkApply | null>(null);
|
||||
const [rejectTarget, setRejectTarget] = useState<FriendLinkApply | null>(null);
|
||||
const [rejectNote, setRejectNote] = useState('');
|
||||
const [rejecting, setRejecting] = useState(false);
|
||||
const [handlingId, setHandlingId] = useState<number | null>(null);
|
||||
const [reciprocalCheckEnabled, setReciprocalCheckEnabled] = useState(false);
|
||||
const [reciprocalCheckSaving, setReciprocalCheckSaving] = useState(false);
|
||||
|
||||
const baselineLinks = branding.friend_links ?? [];
|
||||
const siteURL = branding.site_url;
|
||||
const isDirty = useMemo(
|
||||
() => !linksEqual(links, baselineLinks),
|
||||
[links, baselineLinks],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setLinks(toLinkRows(baselineLinks));
|
||||
}, [baselineLinks]);
|
||||
|
||||
const loadApplies = useCallback(async (status: ApplyStatusTab = applyStatus, page = 1) => {
|
||||
setAppliesLoading(true);
|
||||
try {
|
||||
const r = await api.adminFriendLinkApplies({ status, page, size: APPLY_PAGE_SIZE });
|
||||
setApplies(r.applies ?? []);
|
||||
setApplyTotal(r.total ?? 0);
|
||||
setApplyPage(r.page ?? page);
|
||||
setPendingCount(r.pending_count ?? 0);
|
||||
setReciprocalCheckEnabled(!!r.reciprocal_check_enabled);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '加载失败');
|
||||
} finally {
|
||||
setAppliesLoading(false);
|
||||
}
|
||||
}, [applyStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
if (ready) loadApplies(applyStatus, 1);
|
||||
}, [ready, applyStatus, loadApplies]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || !reciprocalCheckEnabled || !applies.some(isReciprocalChecking)) return;
|
||||
const timer = window.setInterval(() => loadApplies(applyStatus, applyPage), 3000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [ready, applies, applyStatus, applyPage, loadApplies, reciprocalCheckEnabled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!detailApply) return;
|
||||
const updated = applies.find(a => a.id === detailApply.id);
|
||||
if (updated) setDetailApply(updated);
|
||||
}, [applies, detailApply]);
|
||||
|
||||
const applyTabs: { key: ApplyStatusTab; label: string }[] = [
|
||||
{ key: 'pending', label: `待审${pendingCount ? ` (${pendingCount})` : ''}` },
|
||||
{ key: 'approved', label: '已通过' },
|
||||
{ key: 'rejected', label: '已拒绝' },
|
||||
{ key: 'all', label: '全部' },
|
||||
];
|
||||
|
||||
const applyTotalPages = Math.max(1, Math.ceil(applyTotal / APPLY_PAGE_SIZE));
|
||||
const showMoveButtons = shouldShowSortableMoveButtons(links.length);
|
||||
|
||||
const addLinkRow = () => {
|
||||
rowKeyRef.current += 1;
|
||||
setLinks(prev => [...prev, { name: '', url: '', logo: '', _key: `new-${rowKeyRef.current}` }]);
|
||||
};
|
||||
|
||||
const resetLinks = () => {
|
||||
setLinks(toLinkRows(baselineLinks));
|
||||
notify.success('已恢复为已保存的版本');
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
const cleaned = normalizeLinks(links);
|
||||
const urls = new Set<string>();
|
||||
for (const l of cleaned) {
|
||||
if (!/^https?:\/\//i.test(l.url)) {
|
||||
notify.warning('友情链接需完整 http/https URL');
|
||||
return;
|
||||
}
|
||||
const key = l.url.toLowerCase();
|
||||
if (urls.has(key)) {
|
||||
notify.warning(`存在重复 URL:${l.url}`);
|
||||
return;
|
||||
}
|
||||
urls.add(key);
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload: SiteBranding = { ...branding, friend_links: cleaned };
|
||||
const r = await api.adminUpdateBranding(payload);
|
||||
seedSiteBrandingCache({ ...branding, ...r.branding, friend_links: cleaned });
|
||||
setLinks(toLinkRows(cleaned));
|
||||
notify.success('友情链接已保存');
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const approveApply = async (apply: FriendLinkApply) => {
|
||||
setHandlingId(apply.id);
|
||||
try {
|
||||
const r = await api.adminApproveFriendLinkApply(apply.id);
|
||||
invalidateSiteBrandingCache();
|
||||
notify.success(r.message);
|
||||
setDetailApply(null);
|
||||
loadApplies(applyStatus, applyPage);
|
||||
window.dispatchEvent(new Event('admin-pending-refresh'));
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '操作失败');
|
||||
} finally {
|
||||
setHandlingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const openReject = (apply: FriendLinkApply) => {
|
||||
setDetailApply(null);
|
||||
setRejectTarget(apply);
|
||||
setRejectNote('');
|
||||
};
|
||||
|
||||
const recheckReciprocal = async (apply: FriendLinkApply) => {
|
||||
setHandlingId(apply.id);
|
||||
try {
|
||||
const r = await api.adminRecheckFriendLinkApply(apply.id);
|
||||
notify.success(r.message);
|
||||
setDetailApply(r.apply);
|
||||
loadApplies(applyStatus, applyPage);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '操作失败');
|
||||
} finally {
|
||||
setHandlingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleReciprocalCheck = async () => {
|
||||
if (reciprocalCheckSaving) return;
|
||||
const next = !reciprocalCheckEnabled;
|
||||
setReciprocalCheckEnabled(next);
|
||||
setReciprocalCheckSaving(true);
|
||||
try {
|
||||
const r = await api.adminUpdateFriendLinkSettings({ reciprocal_check_enabled: next });
|
||||
setReciprocalCheckEnabled(r.reciprocal_check_enabled);
|
||||
notify.success(r.message);
|
||||
} catch (e: unknown) {
|
||||
setReciprocalCheckEnabled(!next);
|
||||
notify.error(e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
setReciprocalCheckSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const submitReject = async () => {
|
||||
if (!rejectTarget) return;
|
||||
setRejecting(true);
|
||||
try {
|
||||
const r = await api.adminRejectFriendLinkApply(rejectTarget.id, { note: rejectNote.trim() });
|
||||
notify.success(r.message);
|
||||
setRejectTarget(null);
|
||||
setRejectNote('');
|
||||
loadApplies(applyStatus, applyPage);
|
||||
window.dispatchEvent(new Event('admin-pending-refresh'));
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '操作失败');
|
||||
} finally {
|
||||
setRejecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const renderApplicant = (apply: FriendLinkApply) => {
|
||||
const label = apply.user?.nickname || apply.user?.username || `用户 #${apply.user_id}`;
|
||||
if (apply.user_id) {
|
||||
return (
|
||||
<button type="button" className="admin-text-link" onClick={() => nav(`/user/${apply.user_id}`)}>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return label;
|
||||
};
|
||||
|
||||
const renderPendingCard = (apply: FriendLinkApply) => {
|
||||
const reciprocal = reciprocalStatusLabel(apply);
|
||||
return (
|
||||
<div
|
||||
key={apply.id}
|
||||
className={cn(
|
||||
'admin-links-pending-row',
|
||||
reciprocalCheckEnabled && !isReciprocalChecking(apply) && !apply.reciprocal_verified && 'admin-links-pending-row--warn',
|
||||
)}
|
||||
>
|
||||
<ApplyLogo apply={apply} className="admin-links-pending-logo" siteURL={siteURL} />
|
||||
<div className="admin-links-pending-main">
|
||||
<div className="admin-links-pending-title">
|
||||
<strong>{apply.name}</strong>
|
||||
<a href={apply.url} target="_blank" rel="noopener noreferrer">{apply.url}</a>
|
||||
</div>
|
||||
<p className="admin-links-pending-reciprocal">
|
||||
回链地址:
|
||||
<ReciprocalAddress apply={apply} />
|
||||
</p>
|
||||
<p className="admin-links-pending-meta">
|
||||
<Badge variant={reciprocal.variant}>{reciprocal.text}</Badge>
|
||||
{' · '}
|
||||
{renderApplicant(apply)}
|
||||
{' · '}
|
||||
{formatTime(apply.created_at)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="admin-links-pending-actions">
|
||||
<Button type="button" size="sm" variant="outline" onClick={() => setDetailApply(apply)}>
|
||||
<Eye size={14} aria-hidden /> 查看
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderApplyTable = () => (
|
||||
<div className="admin-table-scroll">
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>站点</th>
|
||||
<th>申请人</th>
|
||||
<th>回链地址</th>
|
||||
<th>回链检测</th>
|
||||
<th>状态</th>
|
||||
<th>时间</th>
|
||||
{applyStatus === 'rejected' || applyStatus === 'all' ? <th>备注</th> : null}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{applies.map(apply => {
|
||||
const reciprocal = reciprocalStatusLabel(apply);
|
||||
return (
|
||||
<tr key={apply.id}>
|
||||
<td>{apply.id}</td>
|
||||
<td className="admin-links-table-site">
|
||||
<div className="admin-links-table-site__head">
|
||||
<ApplyLogo apply={apply} siteURL={siteURL} />
|
||||
<div>
|
||||
<strong>{apply.name}</strong>
|
||||
<a href={apply.url} target="_blank" rel="noopener noreferrer">{apply.url}</a>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td>{renderApplicant(apply)}</td>
|
||||
<td className="admin-links-table-reciprocal"><ReciprocalAddress apply={apply} /></td>
|
||||
<td><Badge variant={reciprocal.variant}>{reciprocal.text}</Badge></td>
|
||||
<td>{applyStatusBadge(apply.status)}</td>
|
||||
<td className="text-sm whitespace-nowrap">{formatTime(apply.created_at)}</td>
|
||||
{(applyStatus === 'rejected' || applyStatus === 'all') && (
|
||||
<td className="text-sm text-muted-foreground max-w-[200px]">
|
||||
{apply.review_note?.trim() || '—'}
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!ready) return null;
|
||||
|
||||
return (
|
||||
<div className="admin-page admin-links-page">
|
||||
<header className="admin-page-head admin-links-page-head">
|
||||
<div>
|
||||
<h1><Link2 size={20} aria-hidden /> 友情链接</h1>
|
||||
<p>管理已发布友链(最多 20 条)并审核用户申请;通过后将展示在友情链接页面</p>
|
||||
</div>
|
||||
<div className="admin-links-page-head__actions">
|
||||
<Button type="button" variant="outline" asChild>
|
||||
<Link to="/links" target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink size={14} aria-hidden />
|
||||
预览友链页
|
||||
</Link>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={saving || !isDirty}
|
||||
onClick={save}
|
||||
>
|
||||
{saving ? '保存中…' : isDirty ? '保存友链' : '已是最新'}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="admin-links-columns">
|
||||
<div className="admin-card admin-links-apply-card">
|
||||
<div className="admin-card-head">
|
||||
<div className="admin-links-apply-head">
|
||||
<span>申请审核</span>
|
||||
{pendingCount > 0 && <Badge variant="orange">{pendingCount}</Badge>}
|
||||
</div>
|
||||
<div className="admin-links-reciprocal-toggle">
|
||||
<span id="admin-links-reciprocal-label">回链检测</span>
|
||||
<button
|
||||
type="button"
|
||||
id="admin-links-reciprocal-switch"
|
||||
role="switch"
|
||||
aria-checked={reciprocalCheckEnabled}
|
||||
aria-labelledby="admin-links-reciprocal-label"
|
||||
disabled={reciprocalCheckSaving}
|
||||
className={cn('admin-settings-switch', reciprocalCheckEnabled && 'is-on')}
|
||||
onClick={toggleReciprocalCheck}
|
||||
>
|
||||
<span className="admin-settings-switch-ui" aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="admin-card-desc">
|
||||
{reciprocalCheckEnabled
|
||||
? '回链检测结果仅供参考,未检测到回链仍可手动通过。'
|
||||
: '回链检测已关闭,申请仍可手动审核通过。'}
|
||||
</p>
|
||||
<div className="admin-card-body admin-links-apply-body">
|
||||
<div className="admin-tabs">
|
||||
{applyTabs.map(tab => (
|
||||
<button
|
||||
key={tab.key}
|
||||
type="button"
|
||||
className={cn('admin-tab', applyStatus === tab.key && 'active')}
|
||||
onClick={() => {
|
||||
setApplyStatus(tab.key);
|
||||
setApplyPage(1);
|
||||
}}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="admin-links-apply-scroll">
|
||||
{appliesLoading ? (
|
||||
<div className="flex justify-center py-12"><Spinner size="lg" /></div>
|
||||
) : applies.length === 0 ? (
|
||||
<p className="admin-table-empty">
|
||||
{applyStatus === 'pending' ? '暂无待审申请' : '暂无记录'}
|
||||
</p>
|
||||
) : applyStatus === 'pending' ? (
|
||||
<div className="admin-links-pending-list">
|
||||
{applies.map(renderPendingCard)}
|
||||
</div>
|
||||
) : (
|
||||
renderApplyTable()
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!appliesLoading && applyTotal > APPLY_PAGE_SIZE && (
|
||||
<div className="admin-pagination">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={applyPage <= 1}
|
||||
onClick={() => loadApplies(applyStatus, applyPage - 1)}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<span>{applyPage} / {applyTotalPages}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={applyPage >= applyTotalPages}
|
||||
onClick={() => loadApplies(applyStatus, applyPage + 1)}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-card admin-links-published-card">
|
||||
<div className="admin-card-head">
|
||||
<span>已发布友链</span>
|
||||
<Badge variant="secondary">{links.filter(l => l.name.trim() && l.url.trim()).length}/20</Badge>
|
||||
</div>
|
||||
<p className="admin-card-desc">
|
||||
保存后立即生效;右侧栏展示可在
|
||||
<Link to="/admin/settings" className="admin-inline-link">系统设置 → 右侧栏组件</Link>
|
||||
中配置。
|
||||
</p>
|
||||
<div className="admin-card-body admin-links-editor">
|
||||
<div className="admin-links-published-scroll">
|
||||
{links.length > 0 && (
|
||||
<div className="admin-links-table-head">
|
||||
<span>排序</span>
|
||||
<span>图标</span>
|
||||
<span>名称</span>
|
||||
<span>链接</span>
|
||||
<span>LOGO 地址</span>
|
||||
<span />
|
||||
</div>
|
||||
)}
|
||||
<AdminSortableList
|
||||
items={links}
|
||||
getId={link => link._key}
|
||||
onReorder={setLinks}
|
||||
showMoveButtons="auto"
|
||||
className="admin-sortable-list admin-links-table-body"
|
||||
ariaLabel="已发布友链"
|
||||
renderItem={(link, idx, controls) => (
|
||||
<div
|
||||
ref={controls.setNodeRef}
|
||||
style={controls.style}
|
||||
className={cn('admin-links-row', controls.isDragging && 'is-dragging')}
|
||||
>
|
||||
<div className="admin-links-row__order">
|
||||
<SortableDragHandle label={`拖拽调整「${link.name || '友链'}」顺序`} {...controls.dragHandleProps} />
|
||||
{showMoveButtons && (
|
||||
<SortableMoveButtons controls={controls} className="admin-links-row__move" />
|
||||
)}
|
||||
</div>
|
||||
<div className="admin-links-row__preview">
|
||||
{resolveFriendLinkLogo(link.logo, siteURL) ? (
|
||||
<img src={resolveFriendLinkLogo(link.logo, siteURL)} alt="" loading="lazy" decoding="async" />
|
||||
) : (
|
||||
<span>{linkInitial(link.name)}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="admin-links-field admin-links-field--name">
|
||||
<Label htmlFor={`link-name-${link._key}`} className="sr-only">名称</Label>
|
||||
<Input
|
||||
id={`link-name-${link._key}`}
|
||||
placeholder="站点名称"
|
||||
value={link.name}
|
||||
onChange={e => {
|
||||
const next = [...links];
|
||||
next[idx] = { ...next[idx], name: e.target.value };
|
||||
setLinks(next);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-links-field admin-links-field--url">
|
||||
<Label htmlFor={`link-url-${link._key}`} className="sr-only">链接</Label>
|
||||
<Input
|
||||
id={`link-url-${link._key}`}
|
||||
placeholder="https://..."
|
||||
value={link.url}
|
||||
onChange={e => {
|
||||
const next = [...links];
|
||||
next[idx] = { ...next[idx], url: e.target.value };
|
||||
setLinks(next);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-links-field admin-links-field--logo">
|
||||
<Label htmlFor={`link-logo-${link._key}`} className="sr-only">LOGO 地址</Label>
|
||||
<Input
|
||||
id={`link-logo-${link._key}`}
|
||||
placeholder="LOGO 地址(可选)"
|
||||
value={link.logo ?? ''}
|
||||
onChange={e => {
|
||||
const next = [...links];
|
||||
next[idx] = { ...next[idx], logo: e.target.value };
|
||||
setLinks(next);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-links-row__actions">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setLinks(links.filter((_, i) => i !== idx))}
|
||||
aria-label={`删除「${link.name || '友链'}」`}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
{links.length === 0 && <p className="admin-table-empty">暂无友情链接,可手动添加或审核通过用户申请</p>}
|
||||
</div>
|
||||
<div className="admin-links-editor__foot">
|
||||
<Button type="button" variant="outline" disabled={links.length >= 20} onClick={addLinkRow}>
|
||||
<Plus size={14} aria-hidden /> 添加链接
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" disabled={!isDirty} onClick={resetLinks}>
|
||||
<RotateCcw size={14} aria-hidden /> 放弃更改
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Dialog open={!!detailApply} onOpenChange={open => { if (!open) setDetailApply(null); }}>
|
||||
<DialogContent className="admin-links-apply-dialog sm:max-w-[520px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>友链申请详情</DialogTitle>
|
||||
<DialogDescription>
|
||||
确认信息无误后再通过;通过后将写入已发布友链列表。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{detailApply && (
|
||||
<div className="admin-links-apply-detail">
|
||||
<div className="admin-links-apply-detail__preview">
|
||||
<ApplyLogo apply={detailApply} siteURL={siteURL} />
|
||||
<div>
|
||||
<strong>{detailApply.name}</strong>
|
||||
<a href={detailApply.url} target="_blank" rel="noopener noreferrer">{detailApply.url}</a>
|
||||
</div>
|
||||
</div>
|
||||
<dl className="admin-links-apply-detail__grid">
|
||||
<div><dt>申请人</dt><dd>{renderApplicant(detailApply)}</dd></div>
|
||||
<div><dt>提交时间</dt><dd>{formatTime(detailApply.created_at)}</dd></div>
|
||||
<div><dt>回链地址</dt><dd>
|
||||
<ReciprocalAddress apply={detailApply} />
|
||||
</dd></div>
|
||||
<div><dt>回链检测</dt><dd>
|
||||
<Badge variant={reciprocalStatusLabel(detailApply).variant}>
|
||||
{reciprocalStatusLabel(detailApply).text}
|
||||
</Badge>
|
||||
</dd></div>
|
||||
{detailApply.logo?.trim() && (
|
||||
<div><dt>LOGO</dt><dd className="admin-links-apply-detail__logo-url">{detailApply.logo}</dd></div>
|
||||
)}
|
||||
</dl>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter className="admin-links-apply-dialog__footer">
|
||||
<Button type="button" variant="outline" onClick={() => setDetailApply(null)}>关闭</Button>
|
||||
{detailApply && (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={handlingId === detailApply.id || isReciprocalChecking(detailApply) || !reciprocalCheckEnabled}
|
||||
title={!reciprocalCheckEnabled ? '回链检测已关闭' : undefined}
|
||||
onClick={() => recheckReciprocal(detailApply)}
|
||||
>
|
||||
<RotateCcw size={14} aria-hidden />
|
||||
{handlingId === detailApply.id ? '处理中…' : '重新检测'}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={handlingId === detailApply.id}
|
||||
onClick={() => openReject(detailApply)}
|
||||
>
|
||||
<X size={14} aria-hidden /> 拒绝
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={handlingId === detailApply.id}
|
||||
onClick={() => approveApply(detailApply)}
|
||||
>
|
||||
<Check size={14} aria-hidden />
|
||||
{handlingId === detailApply.id ? '处理中…' : '确认通过'}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={!!rejectTarget} onOpenChange={open => { if (!open) setRejectTarget(null); }}>
|
||||
<DialogContent className="sm:max-w-[440px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>拒绝友链申请</DialogTitle>
|
||||
<DialogDescription>
|
||||
{rejectTarget ? `拒绝「${rejectTarget.name}」的申请,可选填原因通知申请人。` : ''}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Textarea
|
||||
value={rejectNote}
|
||||
onChange={e => setRejectNote(e.target.value)}
|
||||
placeholder="拒绝原因(可选)"
|
||||
maxLength={256}
|
||||
rows={4}
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setRejectTarget(null)}>取消</Button>
|
||||
<Button type="button" disabled={rejecting} onClick={submitReject}>
|
||||
{rejecting ? '提交中…' : '确认拒绝'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
251
frontend/src/pages/admin/AdminPagesPage.tsx
Normal file
251
frontend/src/pages/admin/AdminPagesPage.tsx
Normal file
@@ -0,0 +1,251 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { FileText, Plus, Pencil, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import {
|
||||
Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import ArticleEditor from '../../components/ArticleEditor';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '../../api/client';
|
||||
import { useAdminGuard } from '../../layouts/AdminLayout';
|
||||
import type { SitePage } from '../../api/types';
|
||||
import { invalidateSitePagesCache } from '../../hooks/useSitePages';
|
||||
import AdminSortableList, { SortableDragHandle, SortableMoveButtons } from '../../components/admin/AdminSortableList';
|
||||
import { persistSortOrderChanges, shouldShowSortableMoveButtons } from '../../utils/sortOrder';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const EMPTY: Partial<SitePage> = {
|
||||
title: '',
|
||||
slug: '',
|
||||
content: '',
|
||||
published: false,
|
||||
sort_order: 0,
|
||||
show_in_footer: true,
|
||||
show_in_nav: false,
|
||||
};
|
||||
|
||||
function slugify(title: string): string {
|
||||
const s = title.trim().toLowerCase()
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/[^a-z0-9-]/g, '')
|
||||
.replace(/-+/g, '-')
|
||||
.replace(/^-|-$/g, '');
|
||||
return s.slice(0, 64);
|
||||
}
|
||||
|
||||
/** 后台:自定义单页管理 */
|
||||
export default function AdminPagesPage() {
|
||||
const { ready } = useAdminGuard();
|
||||
const [rows, setRows] = useState<SitePage[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [form, setForm] = useState<Partial<SitePage>>({ ...EMPTY });
|
||||
const [editingId, setEditingId] = useState<number | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [reordering, setReordering] = useState(false);
|
||||
|
||||
const load = () => {
|
||||
setLoading(true);
|
||||
api.adminPages()
|
||||
.then(d => setRows(d.pages ?? []))
|
||||
.catch(e => notify.error(e.message))
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
useEffect(() => { if (ready) load(); }, [ready]);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditingId(null);
|
||||
setForm({ ...EMPTY });
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (p: SitePage) => {
|
||||
setEditingId(p.id);
|
||||
setForm({ ...p });
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
if (editingId) {
|
||||
await api.adminUpdatePage(editingId, form);
|
||||
notify.success('单页已更新');
|
||||
} else {
|
||||
await api.adminCreatePage(form);
|
||||
notify.success('单页已创建');
|
||||
}
|
||||
invalidateSitePagesCache();
|
||||
setDialogOpen(false);
|
||||
load();
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (id: number) => {
|
||||
if (!window.confirm('确定删除该单页?')) return;
|
||||
try {
|
||||
await api.adminDeletePage(id);
|
||||
invalidateSitePagesCache();
|
||||
notify.success('已删除');
|
||||
load();
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '删除失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handlePageReorder = async (reordered: SitePage[]) => {
|
||||
const before = [...rows];
|
||||
setReordering(true);
|
||||
try {
|
||||
const after = await persistSortOrderChanges(before, reordered, page =>
|
||||
api.adminUpdatePage(page.id, { sort_order: page.sort_order }),
|
||||
);
|
||||
setRows(after);
|
||||
invalidateSitePagesCache();
|
||||
notify.success('单页排序已更新');
|
||||
} catch (e: unknown) {
|
||||
setRows(before);
|
||||
notify.error(e instanceof Error ? e.message : '排序保存失败');
|
||||
} finally {
|
||||
setReordering(false);
|
||||
}
|
||||
};
|
||||
|
||||
const showMoveButtons = shouldShowSortableMoveButtons(rows.length);
|
||||
|
||||
if (!ready) return null;
|
||||
|
||||
return (
|
||||
<div className="admin-page">
|
||||
<header className="admin-page-head">
|
||||
<div>
|
||||
<h1><FileText size={20} aria-hidden /> 单页管理</h1>
|
||||
<p>创建「关于我们」「版规」等独立页面</p>
|
||||
</div>
|
||||
<Button onClick={openCreate}><Plus size={16} /> 新建单页</Button>
|
||||
</header>
|
||||
|
||||
{loading ? <Spinner /> : (
|
||||
<div className="admin-table-wrap">
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="w-[72px]">排序</th>
|
||||
<th>标题</th>
|
||||
<th>Slug</th>
|
||||
<th>权重</th>
|
||||
<th>发布</th>
|
||||
<th>展示</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
{rows.length === 0 ? (
|
||||
<tbody>
|
||||
<tr><td colSpan={7} className="admin-table-empty">暂无单页</td></tr>
|
||||
</tbody>
|
||||
) : (
|
||||
<AdminSortableList
|
||||
as="tbody"
|
||||
items={rows}
|
||||
getId={p => p.id}
|
||||
onReorder={handlePageReorder}
|
||||
showMoveButtons="auto"
|
||||
renderItem={(p, _index, controls) => (
|
||||
<tr
|
||||
ref={controls.setNodeRef}
|
||||
style={controls.style}
|
||||
className={cn('admin-sortable-table-row', controls.isDragging && 'is-dragging')}
|
||||
>
|
||||
<td>
|
||||
<div className="flex items-center gap-0">
|
||||
<SortableDragHandle label={`拖拽调整「${p.title}」顺序`} {...controls.dragHandleProps} />
|
||||
{showMoveButtons && <SortableMoveButtons controls={controls} />}
|
||||
</div>
|
||||
</td>
|
||||
<td>{p.title}</td>
|
||||
<td><code>/page/{p.slug}</code></td>
|
||||
<td>{p.sort_order}</td>
|
||||
<td>{p.published ? '是' : '否'}</td>
|
||||
<td>{[p.show_in_footer && '页脚', p.show_in_nav && '导航'].filter(Boolean).join('、') || '—'}</td>
|
||||
<td className="admin-table-actions">
|
||||
<Button variant="ghost" size="sm" onClick={() => openEdit(p)} disabled={reordering}><Pencil size={14} /></Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => remove(p.id)} disabled={reordering}><Trash2 size={14} /></Button>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent className="admin-page-dialog">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingId ? '编辑单页' : '新建单页'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="admin-form-grid">
|
||||
<div>
|
||||
<Label htmlFor="page-title">标题</Label>
|
||||
<Input
|
||||
id="page-title"
|
||||
value={form.title ?? ''}
|
||||
onChange={e => {
|
||||
const title = e.target.value;
|
||||
setForm(f => ({
|
||||
...f,
|
||||
title,
|
||||
slug: f.slug || slugify(title),
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="page-slug">Slug(URL 路径)</Label>
|
||||
<Input
|
||||
id="page-slug"
|
||||
value={form.slug ?? ''}
|
||||
onChange={e => setForm(f => ({ ...f, slug: e.target.value }))}
|
||||
placeholder="about-us"
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-row">
|
||||
<Label htmlFor="page-sort">排序</Label>
|
||||
<Input
|
||||
id="page-sort"
|
||||
type="number"
|
||||
value={form.sort_order ?? 0}
|
||||
onChange={e => setForm(f => ({ ...f, sort_order: Number(e.target.value) || 0 }))}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-switches">
|
||||
<label><Switch checked={!!form.published} onCheckedChange={v => setForm(f => ({ ...f, published: v }))} /> 发布</label>
|
||||
<label><Switch checked={!!form.show_in_footer} onCheckedChange={v => setForm(f => ({ ...f, show_in_footer: v }))} /> 页脚展示</label>
|
||||
<label><Switch checked={!!form.show_in_nav} onCheckedChange={v => setForm(f => ({ ...f, show_in_nav: v }))} /> 侧栏导航</label>
|
||||
</div>
|
||||
<div>
|
||||
<Label>正文</Label>
|
||||
<ArticleEditor
|
||||
value={form.content ?? ''}
|
||||
onChange={html => setForm(f => ({ ...f, content: html }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
|
||||
<Button disabled={saving} onClick={save}>{saving ? '保存中…' : '保存'}</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,10 @@ import { useAdminGuard } from '../../layouts/AdminLayout';
|
||||
import { invalidateForumLimitsCache } from '../../hooks/useForumLimits';
|
||||
import { DEFAULT_BRANDING, seedSiteBrandingCache } from '../../hooks/useSiteBranding';
|
||||
import { clearAllFeedCache } from '../../utils/feedCache';
|
||||
import type { AdminSettings, ForumLimits, MailConfig, OIDCConfig, OAuthClient, GiteaSyncConfig, StorageConfig, SiteBranding, FriendLink } from '../../api/types';
|
||||
import { normalizeAsideWidgets, resolveAsideWidgets, mergeForumLimitsWithAsideWidgets, resolveSavedAsideWidgets } from '../../utils/asideWidgets';
|
||||
import AsideWidgetList from '../../components/admin/AsideWidgetList';
|
||||
import type { AdminSettings, ForumLimits, MailConfig, OIDCConfig, OAuthClient, GiteaSyncConfig, StorageConfig, SiteBranding, AsideWidget } from '../../api/types';
|
||||
import { DEFAULT_ASIDE_WIDGETS } from '../../api/types';
|
||||
|
||||
type TabId = 'branding' | 'limits' | 'mail' | 'oidc' | 'gitea' | 'storage' | 'filter' | 'system';
|
||||
|
||||
@@ -88,7 +91,9 @@ const SETTING_SECTIONS: SettingSection[] = [
|
||||
},
|
||||
];
|
||||
|
||||
type BoolLimitKey = 'open_posts_in_new_tab' | 'open_content_links_in_new_tab';
|
||||
type BoolLimitKey =
|
||||
| 'open_posts_in_new_tab'
|
||||
| 'open_content_links_in_new_tab';
|
||||
|
||||
const NAV_TOGGLES: { key: BoolLimitKey; label: string; hint: string }[] = [
|
||||
{
|
||||
@@ -241,6 +246,7 @@ export default function AdminSettingsPage() {
|
||||
const { ready } = useAdminGuard();
|
||||
const [settings, setSettings] = useState<AdminSettings | null>(null);
|
||||
const [limits, setLimits] = useState<ForumLimits | null>(null);
|
||||
const [asideWidgets, setAsideWidgets] = useState<AsideWidget[]>(DEFAULT_ASIDE_WIDGETS);
|
||||
const [branding, setBranding] = useState<SiteBranding>(DEFAULT_BRANDING);
|
||||
const [mail, setMail] = useState<MailConfig>(EMPTY_MAIL);
|
||||
const [oidc, setOidc] = useState<OIDCConfig>(EMPTY_OIDC);
|
||||
@@ -277,13 +283,28 @@ export default function AdminSettingsPage() {
|
||||
api.adminSettings()
|
||||
.then(s => {
|
||||
setSettings(s);
|
||||
setLimits({
|
||||
const loadedAsideWidgets = normalizeAsideWidgets(
|
||||
resolveAsideWidgets({
|
||||
aside_widgets: s.limits?.aside_widgets,
|
||||
aside_show_tag_cloud: s.limits?.aside_show_tag_cloud ?? false,
|
||||
aside_show_recent_comments: s.limits?.aside_show_recent_comments ?? false,
|
||||
aside_show_friend_links: s.limits?.aside_show_friend_links ?? true,
|
||||
}),
|
||||
);
|
||||
setAsideWidgets(loadedAsideWidgets);
|
||||
const baseLimits: ForumLimits = {
|
||||
open_posts_in_new_tab: true,
|
||||
open_content_links_in_new_tab: true,
|
||||
aside_show_tag_cloud: false,
|
||||
aside_show_recent_comments: false,
|
||||
aside_show_friend_links: true,
|
||||
aside_widgets: loadedAsideWidgets,
|
||||
feed_list_style: 'title',
|
||||
permalink_enabled: false,
|
||||
permalink_ext: 'html',
|
||||
...s.limits,
|
||||
});
|
||||
};
|
||||
setLimits(mergeForumLimitsWithAsideWidgets(baseLimits, loadedAsideWidgets));
|
||||
setBranding({ ...DEFAULT_BRANDING, ...(s.branding ?? {}) });
|
||||
setMail({ ...EMPTY_MAIL, ...s.mail, password: '' });
|
||||
setOidc({ ...EMPTY_OIDC, ...(s.oidc ?? {}) });
|
||||
@@ -306,6 +327,20 @@ export default function AdminSettingsPage() {
|
||||
setLimits(prev => prev ? { ...prev, [key]: checked } : prev);
|
||||
};
|
||||
|
||||
const handleAsideWidgetsChange = (widgets: AsideWidget[]) => {
|
||||
const normalized = normalizeAsideWidgets(widgets);
|
||||
setAsideWidgets(normalized);
|
||||
setLimits(prev => prev ? mergeForumLimitsWithAsideWidgets(prev, normalized) : prev);
|
||||
};
|
||||
|
||||
const applySavedForumLimits = (savedWidgets: AsideWidget[], response: ForumLimits): ForumLimits => {
|
||||
const nextWidgets = resolveSavedAsideWidgets(savedWidgets, response.aside_widgets);
|
||||
const merged = mergeForumLimitsWithAsideWidgets(response, nextWidgets);
|
||||
setAsideWidgets(nextWidgets);
|
||||
setLimits(merged);
|
||||
return merged;
|
||||
};
|
||||
|
||||
const applyBranding = (next: SiteBranding) => {
|
||||
setBranding({ ...DEFAULT_BRANDING, ...next });
|
||||
setSettings(s => s ? { ...s, branding: next } : s);
|
||||
@@ -314,21 +349,15 @@ export default function AdminSettingsPage() {
|
||||
|
||||
const handleSaveBranding = async () => {
|
||||
if (!limits) return;
|
||||
const links = (branding.friend_links ?? [])
|
||||
.map(l => ({ name: l.name.trim(), url: l.url.trim() }))
|
||||
.filter(l => l.name || l.url);
|
||||
if (links.some(l => !l.name || !l.url)) {
|
||||
notify.warning('友情链接需同时填写名称与完整 URL');
|
||||
return;
|
||||
}
|
||||
setSavingBranding(true);
|
||||
try {
|
||||
const r = await api.adminUpdateBranding({ ...branding, friend_links: links });
|
||||
const r = await api.adminUpdateBranding(branding);
|
||||
applyBranding(r.branding);
|
||||
// 伪静态与品牌同属站点呈现,一并保存
|
||||
const forum = await api.adminUpdateForumSettings(limits);
|
||||
setLimits(forum.limits);
|
||||
invalidateForumLimitsCache();
|
||||
const forumPayload = mergeForumLimitsWithAsideWidgets(limits, asideWidgets);
|
||||
// 伪静态、右侧栏、浏览与链接、列表呈现同属站点呈现,一并保存
|
||||
const forum = await api.adminUpdateForumSettings(forumPayload);
|
||||
applySavedForumLimits(asideWidgets, forum.limits);
|
||||
clearAllFeedCache();
|
||||
notify.success('站点设置已保存');
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '保存失败');
|
||||
@@ -368,12 +397,13 @@ export default function AdminSettingsPage() {
|
||||
if (!limits) return;
|
||||
setSavingForum(true);
|
||||
try {
|
||||
const r = await api.adminUpdateForumSettings(limits);
|
||||
const forumPayload = mergeForumLimitsWithAsideWidgets(limits, asideWidgets);
|
||||
const r = await api.adminUpdateForumSettings(forumPayload);
|
||||
notify.success(r.message);
|
||||
invalidateForumLimitsCache();
|
||||
clearAllFeedCache();
|
||||
setLimits(r.limits);
|
||||
setSettings(s => s ? { ...s, limits: r.limits } : s);
|
||||
const merged = applySavedForumLimits(asideWidgets, r.limits);
|
||||
setSettings(s => s ? { ...s, limits: merged } : s);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
@@ -645,7 +675,7 @@ export default function AdminSettingsPage() {
|
||||
<section className="admin-settings-section" id="settings-brand-identity">
|
||||
<div className="admin-settings-section-head">
|
||||
<h3>品牌标识</h3>
|
||||
<p>名称、标语、简介与字标;简介用于首页展示与搜索引擎 description</p>
|
||||
<p>名称、标语、简介与字标;简介用于右侧栏顶部展示与搜索引擎 description</p>
|
||||
</div>
|
||||
<div className="admin-mail-grid">
|
||||
<div className="admin-mail-field">
|
||||
@@ -691,7 +721,7 @@ export default function AdminSettingsPage() {
|
||||
rows={3}
|
||||
/>
|
||||
<span className="admin-mail-field-hint">
|
||||
用于右侧栏介绍与 SEO description;未填写时回退到标语(建议 80–160 字)
|
||||
用于右侧栏顶部论坛简介与 SEO description;未填写时回退到标语(建议 80–160 字)
|
||||
</span>
|
||||
</div>
|
||||
<div className="admin-mail-field admin-mail-field--span2">
|
||||
@@ -810,7 +840,7 @@ export default function AdminSettingsPage() {
|
||||
<section className="admin-settings-section" id="settings-brand-footer">
|
||||
<div className="admin-settings-section-head">
|
||||
<h3>页脚信息</h3>
|
||||
<p>备案号与友情链接,显示在站点底部</p>
|
||||
<p>备案号显示在站点底部;友情链接请在「社区 → 友情链接」管理</p>
|
||||
</div>
|
||||
<div className="admin-mail-grid">
|
||||
<div className="admin-mail-field">
|
||||
@@ -835,69 +865,81 @@ export default function AdminSettingsPage() {
|
||||
<span className="admin-mail-field-hint">留空则用工信部默认页</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-friend-links" style={{ marginTop: 12 }}>
|
||||
<div className="admin-friend-links-list">
|
||||
{(branding.friend_links ?? []).map((link, idx) => (
|
||||
<div key={idx} className="admin-friend-links-row">
|
||||
<Input
|
||||
value={link.name}
|
||||
placeholder="友链名称"
|
||||
maxLength={32}
|
||||
onChange={e => {
|
||||
const name = e.target.value;
|
||||
setBranding(b => {
|
||||
const next = [...(b.friend_links ?? [])];
|
||||
next[idx] = { ...next[idx], name };
|
||||
return { ...b, friend_links: next };
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
value={link.url}
|
||||
placeholder="https://example.com"
|
||||
maxLength={512}
|
||||
onChange={e => {
|
||||
const url = e.target.value;
|
||||
setBranding(b => {
|
||||
const next = [...(b.friend_links ?? [])];
|
||||
next[idx] = { ...next[idx], url };
|
||||
return { ...b, friend_links: next };
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
</section>
|
||||
|
||||
<section className="admin-settings-section" id="settings-aside">
|
||||
<div className="admin-settings-section-head">
|
||||
<h3>右侧栏组件</h3>
|
||||
<p>「站点简介」固定在最上方;以下模块可拖拽排序,保存后同步影响桌面右侧栏与手机「社区动态」抽屉</p>
|
||||
</div>
|
||||
<AsideWidgetList
|
||||
widgets={asideWidgets}
|
||||
onChange={handleAsideWidgetsChange}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="admin-settings-section" id="settings-nav">
|
||||
<div className="admin-settings-section-head">
|
||||
<h3>浏览与链接</h3>
|
||||
<p>控制打开帖子与正文链接时是否新开浏览器标签页</p>
|
||||
</div>
|
||||
<div className="admin-settings-table" role="group" aria-label="浏览与链接">
|
||||
{NAV_TOGGLES.map(row => (
|
||||
<div key={row.key} className="admin-settings-row">
|
||||
<span className="admin-settings-row-label" id={`limit-label-${row.key}`}>
|
||||
{row.label}
|
||||
</span>
|
||||
<div className="admin-settings-row-input">
|
||||
<button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setBranding(b => ({
|
||||
...b,
|
||||
friend_links: (b.friend_links ?? []).filter((_, i) => i !== idx),
|
||||
}));
|
||||
}}
|
||||
id={`limit-${row.key}`}
|
||||
role="switch"
|
||||
aria-checked={!!limits[row.key]}
|
||||
aria-labelledby={`limit-label-${row.key}`}
|
||||
className={`admin-settings-switch${limits[row.key] ? ' is-on' : ''}`}
|
||||
onClick={() => handleBoolLimitChange(row.key, !limits[row.key])}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
<span className="admin-settings-switch-ui" aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<span className="admin-settings-row-hint">{row.hint}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="admin-settings-section" id="settings-feed-list">
|
||||
<div className="admin-settings-section-head">
|
||||
<h3>列表呈现</h3>
|
||||
<p>首页及帖子列表的信息密度与缩略图展示</p>
|
||||
</div>
|
||||
<div className="admin-settings-table" role="group" aria-label="列表呈现">
|
||||
<div className="admin-settings-row">
|
||||
<span className="admin-settings-row-label" id="limit-label-feed_list_style">
|
||||
帖子列表样式
|
||||
</span>
|
||||
<div className="admin-settings-row-input admin-settings-row-input--stack">
|
||||
<div className="admin-permalink-presets">
|
||||
{([
|
||||
{ value: 'title' as const, label: '仅标题' },
|
||||
{ value: 'excerpt' as const, label: '标题+摘要' },
|
||||
{ value: 'thumbnail' as const, label: '标题+摘要+缩略图' },
|
||||
]).map(opt => (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
className={`admin-permalink-chip${limits.feed_list_style === opt.value ? ' is-active' : ''}`}
|
||||
onClick={() => setLimits(prev => prev ? { ...prev, feed_list_style: opt.value } : prev)}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<span className="admin-settings-row-hint">
|
||||
仅标题最紧凑;摘要模式增加一行预览;缩略图模式在有站内配图时右侧显示封面
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={(branding.friend_links?.length ?? 0) >= 20}
|
||||
onClick={() => {
|
||||
setBranding(b => ({
|
||||
...b,
|
||||
friend_links: [...(b.friend_links ?? []), { name: '', url: '' } as FriendLink],
|
||||
}));
|
||||
}}
|
||||
>
|
||||
添加友链
|
||||
</Button>
|
||||
<span className="admin-mail-field-hint" style={{ display: 'block', marginTop: 8 }}>
|
||||
最多 20 条,需填写完整 http(s) 地址
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -968,7 +1010,7 @@ export default function AdminSettingsPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-settings-bar">
|
||||
<p>保存后立即影响顶栏、页脚、伪静态链接与浏览器标题</p>
|
||||
<p>保存后立即影响顶栏、页脚、列表样式、链接打开方式、伪静态链接与浏览器标题</p>
|
||||
<Button onClick={handleSaveBranding} loading={savingBranding}>
|
||||
保存站点设置
|
||||
</Button>
|
||||
@@ -981,39 +1023,10 @@ export default function AdminSettingsPage() {
|
||||
<div className="admin-card admin-settings-card">
|
||||
<div className="admin-card-head">
|
||||
<span>论坛限制</span>
|
||||
<span className="admin-settings-card-badge">共 {SETTING_SECTIONS.length + 1} 组</span>
|
||||
<span className="admin-settings-card-badge">共 {SETTING_SECTIONS.length} 组</span>
|
||||
</div>
|
||||
<div className="admin-card-body">
|
||||
<SettingTable sections={SETTING_SECTIONS} limits={limits} onChange={handleLimitChange} />
|
||||
<section className="admin-settings-section" id="settings-nav">
|
||||
<div className="admin-settings-section-head">
|
||||
<h3>浏览与链接</h3>
|
||||
<p>控制打开帖子与正文链接时是否新开浏览器标签页</p>
|
||||
</div>
|
||||
<div className="admin-settings-table" role="group" aria-label="浏览与链接">
|
||||
{NAV_TOGGLES.map(row => (
|
||||
<div key={row.key} className="admin-settings-row">
|
||||
<span className="admin-settings-row-label" id={`limit-label-${row.key}`}>
|
||||
{row.label}
|
||||
</span>
|
||||
<div className="admin-settings-row-input">
|
||||
<button
|
||||
type="button"
|
||||
id={`limit-${row.key}`}
|
||||
role="switch"
|
||||
aria-checked={!!limits[row.key]}
|
||||
aria-labelledby={`limit-label-${row.key}`}
|
||||
className={`admin-settings-switch${limits[row.key] ? ' is-on' : ''}`}
|
||||
onClick={() => handleBoolLimitChange(row.key, !limits[row.key])}
|
||||
>
|
||||
<span className="admin-settings-switch-ui" aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
<span className="admin-settings-row-hint">{row.hint}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-settings-bar">
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
70
frontend/src/utils/asideWidgets.ts
Normal file
70
frontend/src/utils/asideWidgets.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import type { AsideWidget, AsideWidgetId, ForumLimits, ForumLimitsPublic } from '../api/types';
|
||||
import { DEFAULT_ASIDE_WIDGETS } from '../api/types';
|
||||
|
||||
const ASIDE_WIDGET_IDS: AsideWidgetId[] = ['tag_cloud', 'recent_comments', 'friend_links'];
|
||||
|
||||
/** 从 limits 解析右侧栏组件列表(兼容仅有布尔开关的旧数据) */
|
||||
export function resolveAsideWidgets(
|
||||
limits: Pick<ForumLimitsPublic, 'aside_widgets' | 'aside_show_tag_cloud' | 'aside_show_recent_comments' | 'aside_show_friend_links'>,
|
||||
): AsideWidget[] {
|
||||
if (limits.aside_widgets?.length) {
|
||||
return normalizeAsideWidgets(limits.aside_widgets);
|
||||
}
|
||||
return [
|
||||
{ id: 'tag_cloud', enabled: limits.aside_show_tag_cloud },
|
||||
{ id: 'recent_comments', enabled: limits.aside_show_recent_comments },
|
||||
{ id: 'friend_links', enabled: limits.aside_show_friend_links },
|
||||
];
|
||||
}
|
||||
|
||||
/** 校验并补全右侧栏组件列表 */
|
||||
export function normalizeAsideWidgets(widgets: AsideWidget[]): AsideWidget[] {
|
||||
const seen = new Set<AsideWidgetId>();
|
||||
const out: AsideWidget[] = [];
|
||||
for (const w of widgets) {
|
||||
if (!ASIDE_WIDGET_IDS.includes(w.id) || seen.has(w.id)) continue;
|
||||
seen.add(w.id);
|
||||
out.push({ id: w.id, enabled: !!w.enabled });
|
||||
}
|
||||
for (const id of ASIDE_WIDGET_IDS) {
|
||||
if (!seen.has(id)) out.push({ id, enabled: false });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 将 aside_widgets 同步回 ForumLimits 布尔字段 */
|
||||
export function syncAsideBoolsFromWidgets(widgets: AsideWidget[]): Pick<ForumLimits, 'aside_show_tag_cloud' | 'aside_show_recent_comments' | 'aside_show_friend_links'> {
|
||||
const normalized = normalizeAsideWidgets(widgets);
|
||||
return {
|
||||
aside_show_tag_cloud: normalized.find(w => w.id === 'tag_cloud')?.enabled ?? false,
|
||||
aside_show_recent_comments: normalized.find(w => w.id === 'recent_comments')?.enabled ?? false,
|
||||
aside_show_friend_links: normalized.find(w => w.id === 'friend_links')?.enabled ?? true,
|
||||
};
|
||||
}
|
||||
|
||||
/** 合并右侧栏组件到论坛限制(保存 API 时使用) */
|
||||
export function mergeForumLimitsWithAsideWidgets(limits: ForumLimits, widgets: AsideWidget[]): ForumLimits {
|
||||
const normalized = normalizeAsideWidgets(widgets);
|
||||
return {
|
||||
...limits,
|
||||
aside_widgets: normalized,
|
||||
...syncAsideBoolsFromWidgets(normalized),
|
||||
};
|
||||
}
|
||||
|
||||
/** 保存后优先采用服务端返回的 aside_widgets,缺失时保留本次提交值 */
|
||||
export function resolveSavedAsideWidgets(saved: AsideWidget[], response?: AsideWidget[] | null): AsideWidget[] {
|
||||
if (response?.length) return normalizeAsideWidgets(response);
|
||||
return normalizeAsideWidgets(saved);
|
||||
}
|
||||
|
||||
export function isAsideWidgetEnabled(widgets: AsideWidget[], id: AsideWidgetId): boolean {
|
||||
return resolveAsideWidgets({
|
||||
aside_widgets: widgets,
|
||||
aside_show_tag_cloud: false,
|
||||
aside_show_recent_comments: false,
|
||||
aside_show_friend_links: false,
|
||||
}).find(w => w.id === id)?.enabled ?? false;
|
||||
}
|
||||
|
||||
export { DEFAULT_ASIDE_WIDGETS };
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { Board } from '../api/types';
|
||||
|
||||
/** 板块图标背景色 */
|
||||
const BOARD_COLORS = ['#2d8a55', '#3498db', '#9b59b6', '#e67e22', '#1abc9c', '#e74c3c', '#34495e'];
|
||||
|
||||
@@ -8,3 +10,30 @@ export function boardColor(id: number) {
|
||||
export function boardInitial(name: string) {
|
||||
return (name?.trim()?.[0] || '?').toUpperCase();
|
||||
}
|
||||
|
||||
/** 是否为公告类板块(名称含「公告」或 megaphone 图标) */
|
||||
function isAnnouncementBoard(board: Board): boolean {
|
||||
if (board.name.includes('公告')) return true;
|
||||
return (board.icon || '').trim() === 'megaphone';
|
||||
}
|
||||
|
||||
/** 是否为闲聊类板块(名称含「闲聊」) */
|
||||
function isCasualBoard(board: Board): boolean {
|
||||
return board.name.includes('闲聊');
|
||||
}
|
||||
|
||||
/**
|
||||
* 发帖页板块排序:闲聊置顶、公告置底,其余保持 API 原序。
|
||||
* 仅用于发帖选择器,不影响侧栏/导航排序。
|
||||
*/
|
||||
export function sortBoardsForCompose(boards: Board[]): Board[] {
|
||||
const casual: Board[] = [];
|
||||
const middle: Board[] = [];
|
||||
const announcement: Board[] = [];
|
||||
for (const b of boards) {
|
||||
if (isCasualBoard(b)) casual.push(b);
|
||||
else if (isAnnouncementBoard(b)) announcement.push(b);
|
||||
else middle.push(b);
|
||||
}
|
||||
return [...casual, ...middle, ...announcement];
|
||||
}
|
||||
|
||||
29
frontend/src/utils/bounty.ts
Normal file
29
frontend/src/utils/bounty.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { Comment } from '../api/types';
|
||||
import type { CommentNode } from '../utils/comment';
|
||||
|
||||
/** 评论树中是否包含指定评论 ID */
|
||||
export function commentTreeContains(node: CommentNode, commentId: number): boolean {
|
||||
if (node.comment.id === commentId) return true;
|
||||
return node.children.some(child => commentTreeContains(child, commentId));
|
||||
}
|
||||
|
||||
/** 将含被采纳评论的根楼层置顶 */
|
||||
export function pinAwardedCommentTree(
|
||||
tree: CommentNode[],
|
||||
awardedCommentId?: number,
|
||||
): CommentNode[] {
|
||||
if (!awardedCommentId) return tree;
|
||||
const idx = tree.findIndex(node => commentTreeContains(node, awardedCommentId));
|
||||
if (idx <= 0) return tree;
|
||||
const next = [...tree];
|
||||
const [node] = next.splice(idx, 1);
|
||||
next.unshift(node);
|
||||
return next;
|
||||
}
|
||||
|
||||
/** 根据评论 ID 查找楼层号 */
|
||||
export function findCommentFloor(comments: Comment[], commentId?: number): number | null {
|
||||
if (!commentId) return null;
|
||||
const hit = comments.find(c => c.id === commentId);
|
||||
return hit?.floor ?? null;
|
||||
}
|
||||
@@ -1,30 +1,59 @@
|
||||
/** 新建帖本地草稿(localStorage) */
|
||||
|
||||
const STORAGE_KEY = 'j13-compose-draft-v1';
|
||||
const STORAGE_KEY = 'j13-compose-draft-v2';
|
||||
|
||||
export type ComposeDraftPostType = 'normal' | 'question' | 'poll' | 'bounty' | 'lottery';
|
||||
|
||||
export type ComposeDraft = {
|
||||
title: string;
|
||||
tags: string;
|
||||
content: string;
|
||||
boardId: string;
|
||||
postType: 'normal' | 'question';
|
||||
postType: ComposeDraftPostType;
|
||||
pollOptions?: string[];
|
||||
pollMulti?: boolean;
|
||||
pollMaxChoices?: number;
|
||||
pollEndsAt?: string;
|
||||
pollNoEndTime?: boolean;
|
||||
savedAt: number;
|
||||
};
|
||||
|
||||
const VALID_POST_TYPES: ComposeDraftPostType[] = ['normal', 'question', 'poll', 'bounty', 'lottery'];
|
||||
|
||||
function normalizePostType(value: unknown): ComposeDraftPostType {
|
||||
if (typeof value === 'string' && VALID_POST_TYPES.includes(value as ComposeDraftPostType)) {
|
||||
return value as ComposeDraftPostType;
|
||||
}
|
||||
return 'normal';
|
||||
}
|
||||
|
||||
export function loadComposeDraft(): ComposeDraft | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
const data = JSON.parse(raw) as Partial<ComposeDraft>;
|
||||
if (!data || typeof data !== 'object') return null;
|
||||
return {
|
||||
const postType = normalizePostType(data.postType);
|
||||
const draft: ComposeDraft = {
|
||||
title: typeof data.title === 'string' ? data.title : '',
|
||||
tags: typeof data.tags === 'string' ? data.tags : '',
|
||||
content: typeof data.content === 'string' ? data.content : '',
|
||||
boardId: typeof data.boardId === 'string' ? data.boardId : '',
|
||||
postType: data.postType === 'question' ? 'question' : 'normal',
|
||||
postType,
|
||||
savedAt: typeof data.savedAt === 'number' ? data.savedAt : Date.now(),
|
||||
};
|
||||
if (postType === 'poll') {
|
||||
if (Array.isArray(data.pollOptions) && data.pollOptions.every(o => typeof o === 'string')) {
|
||||
draft.pollOptions = data.pollOptions.length >= 2 ? data.pollOptions : ['', ''];
|
||||
}
|
||||
if (typeof data.pollMulti === 'boolean') draft.pollMulti = data.pollMulti;
|
||||
if (typeof data.pollMaxChoices === 'number' && data.pollMaxChoices > 0) {
|
||||
draft.pollMaxChoices = data.pollMaxChoices;
|
||||
}
|
||||
if (typeof data.pollEndsAt === 'string') draft.pollEndsAt = data.pollEndsAt;
|
||||
if (typeof data.pollNoEndTime === 'boolean') draft.pollNoEndTime = data.pollNoEndTime;
|
||||
}
|
||||
return draft;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -42,6 +71,8 @@ export function saveComposeDraft(draft: Omit<ComposeDraft, 'savedAt'>): void {
|
||||
export function clearComposeDraft(): void {
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
// 清理旧版草稿键
|
||||
localStorage.removeItem('j13-compose-draft-v1');
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
@@ -50,10 +81,14 @@ export function clearComposeDraft(): void {
|
||||
/** 草稿是否有实质内容 */
|
||||
export function composeDraftHasContent(d: ComposeDraft | null | undefined): boolean {
|
||||
if (!d) return false;
|
||||
const hasPollOptions = d.postType === 'poll'
|
||||
&& Array.isArray(d.pollOptions)
|
||||
&& d.pollOptions.some(o => o.trim());
|
||||
return !!(
|
||||
d.title.trim()
|
||||
|| d.tags.trim()
|
||||
|| d.content.trim()
|
||||
|| (d.content && d.content.replace(/<[^>]*>/g, '').trim())
|
||||
|| hasPollOptions
|
||||
);
|
||||
}
|
||||
|
||||
38
frontend/src/utils/friendLink.ts
Normal file
38
frontend/src/utils/friendLink.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import type { FriendLinkApply } from '../api/types';
|
||||
|
||||
/** 解析友链 LOGO 为可加载的 URL(相对路径补全为当前站点 origin) */
|
||||
export function resolveFriendLinkLogo(logo?: string, siteURL?: string): string {
|
||||
const raw = logo?.trim() || '';
|
||||
if (!raw) return '';
|
||||
if (/^https?:\/\//i.test(raw)) return raw;
|
||||
if (raw.startsWith('/')) {
|
||||
const base = siteURL?.trim() || (typeof window !== 'undefined' ? window.location.origin : '');
|
||||
return base ? `${base.replace(/\/$/, '')}${raw}` : raw;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
/** 回链检测是否仍在后台进行中 */
|
||||
export function isReciprocalChecking(apply: FriendLinkApply): boolean {
|
||||
if (apply.status !== 'pending') return false;
|
||||
if (apply.reciprocal_checked_at) return false;
|
||||
if (apply.reciprocal_verified) return false;
|
||||
if (apply.reciprocal_check_note?.trim()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function reciprocalStatusLabel(apply: FriendLinkApply): {
|
||||
text: string;
|
||||
variant: 'green' | 'orange' | 'secondary';
|
||||
} {
|
||||
if (isReciprocalChecking(apply)) {
|
||||
return { text: '检测中…', variant: 'secondary' };
|
||||
}
|
||||
if (apply.reciprocal_verified) {
|
||||
return { text: '回链已检测到', variant: 'green' };
|
||||
}
|
||||
if (apply.reciprocal_check_note?.trim()) {
|
||||
return { text: apply.reciprocal_check_note, variant: 'orange' };
|
||||
}
|
||||
return { text: '未检测', variant: 'secondary' };
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import type { Board, ForumStats, RecentComment, PostItem, TagCount } from '../api/types';
|
||||
import type { Board, ForumStats, RecentComment, TagCount } from '../api/types';
|
||||
|
||||
const BOARDS_KEY = 'j13-cache-boards';
|
||||
const STATS_KEY = 'j13-cache-stats';
|
||||
const HOT_KEY = 'j13-cache-hot';
|
||||
const RECENT_COMMENTS_KEY = 'j13-cache-recent-comments';
|
||||
const TAGS_KEY = 'j13-cache-tags';
|
||||
|
||||
@@ -33,12 +32,6 @@ export function getCachedStats(): ForumStats | null {
|
||||
return readJson<ForumStats>(STATS_KEY);
|
||||
}
|
||||
|
||||
/** 读取缓存的热门帖子,避免右栏/抽屉首屏高度跳动 */
|
||||
export function getCachedHot(): PostItem[] {
|
||||
const list = readJson<PostItem[]>(HOT_KEY);
|
||||
return Array.isArray(list) ? list : [];
|
||||
}
|
||||
|
||||
/** 读取缓存的最新评论,避免右栏/抽屉首屏高度跳动 */
|
||||
export function getCachedRecentComments(): RecentComment[] {
|
||||
const list = readJson<RecentComment[]>(RECENT_COMMENTS_KEY);
|
||||
@@ -54,7 +47,7 @@ export function getCachedTags(): TagCount[] {
|
||||
/** 右栏是否已有可展示的 session 缓存(含空列表) */
|
||||
export function hasCachedAside(): boolean {
|
||||
try {
|
||||
return sessionStorage.getItem(HOT_KEY) != null || sessionStorage.getItem(RECENT_COMMENTS_KEY) != null;
|
||||
return sessionStorage.getItem(RECENT_COMMENTS_KEY) != null;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@@ -68,10 +61,6 @@ export function setCachedStats(stats: ForumStats) {
|
||||
writeJson(STATS_KEY, stats);
|
||||
}
|
||||
|
||||
export function setCachedHot(posts: PostItem[]) {
|
||||
writeJson(HOT_KEY, posts);
|
||||
}
|
||||
|
||||
export function setCachedRecentComments(list: RecentComment[]) {
|
||||
writeJson(RECENT_COMMENTS_KEY, list);
|
||||
}
|
||||
|
||||
@@ -30,6 +30,25 @@ export function userPath(id: number | string, opts?: PermalinkOpts): string {
|
||||
return `/user/${id}${suffix(opts)}`;
|
||||
}
|
||||
|
||||
/** 板块规范路径:/board/123 或 /board/123.html */
|
||||
export function boardPath(id: number | string, opts?: PermalinkOpts): string {
|
||||
return `/board/${id}${suffix(opts)}`;
|
||||
}
|
||||
|
||||
/** 自定义单页规范路径 */
|
||||
export function pagePath(slug: string, opts?: PermalinkOpts): string {
|
||||
const s = slug.trim().toLowerCase();
|
||||
if (!s) return '/';
|
||||
return `/page/${s}${suffix(opts)}`;
|
||||
}
|
||||
|
||||
/** 从 slug 路由参数解析(兼容 about / about.html) */
|
||||
export function parsePermalinkSlug(raw: string | undefined): string {
|
||||
if (!raw) return '';
|
||||
const m = String(raw).match(/^([a-z0-9][a-z0-9-]*[a-z0-9]|[a-z0-9])(?:\.[A-Za-z0-9]{1,16})?$/i);
|
||||
return m ? m[1].toLowerCase() : '';
|
||||
}
|
||||
|
||||
/** 从路由参数解析数字 ID(兼容 123 / 123.html) */
|
||||
export function parsePermalinkID(raw: string | undefined): number {
|
||||
if (!raw) return NaN;
|
||||
@@ -39,13 +58,17 @@ export function parsePermalinkID(raw: string | undefined): number {
|
||||
|
||||
/** 客户端:若当前 URL 非规范伪静态路径则返回应跳转的目标 */
|
||||
export function canonicalRedirectPath(
|
||||
kind: 'post' | 'user',
|
||||
kind: 'post' | 'user' | 'board',
|
||||
id: number,
|
||||
currentPathname: string,
|
||||
opts?: PermalinkOpts,
|
||||
): string | null {
|
||||
if (!id || Number.isNaN(id)) return null;
|
||||
const target = kind === 'post' ? postPath(id, opts) : userPath(id, opts);
|
||||
const target = kind === 'post'
|
||||
? postPath(id, opts)
|
||||
: kind === 'user'
|
||||
? userPath(id, opts)
|
||||
: boardPath(id, opts);
|
||||
const cur = currentPathname.replace(/\/$/, '') || '/';
|
||||
const want = target.replace(/\/$/, '') || '/';
|
||||
return cur === want ? null : target;
|
||||
|
||||
69
frontend/src/utils/sortOrder.ts
Normal file
69
frontend/src/utils/sortOrder.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { arrayMove } from '@dnd-kit/sortable';
|
||||
|
||||
export const ADMIN_SORTABLE_MOVE_BUTTONS_THRESHOLD = 8;
|
||||
|
||||
export function reorderItems<T>(items: T[], from: number, to: number): T[] {
|
||||
if (from < 0 || to < 0 || from >= items.length || to >= items.length || from === to) {
|
||||
return items;
|
||||
}
|
||||
return arrayMove(items, from, to);
|
||||
}
|
||||
|
||||
export function assignSortOrders<T extends { sort_order?: number }>(items: T[]): T[] {
|
||||
return items.map((item, index) => ({ ...item, sort_order: index + 1 }));
|
||||
}
|
||||
|
||||
export function diffSortOrderChanges<T extends { id: number; sort_order?: number }>(
|
||||
before: T[],
|
||||
after: T[],
|
||||
): Array<{ id: number; sort_order: number }> {
|
||||
const beforeMap = new Map(before.map(item => [item.id, item.sort_order ?? 0]));
|
||||
return after
|
||||
.filter(item => beforeMap.get(item.id) !== item.sort_order)
|
||||
.map(item => ({ id: item.id, sort_order: item.sort_order ?? 0 }));
|
||||
}
|
||||
|
||||
/** 将子集重排结果合并回完整列表,并重算 sort_order */
|
||||
export function mergeReorderedSubset<T extends { id: number; sort_order?: number }>(
|
||||
all: T[],
|
||||
subsetBefore: T[],
|
||||
subsetAfter: T[],
|
||||
): T[] {
|
||||
const sorted = [...all].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0) || a.id - b.id);
|
||||
const subsetIds = new Set(subsetBefore.map(item => item.id));
|
||||
const result: T[] = [];
|
||||
let subsetIdx = 0;
|
||||
for (const item of sorted) {
|
||||
if (subsetIds.has(item.id)) {
|
||||
if (subsetIdx < subsetAfter.length) {
|
||||
result.push(subsetAfter[subsetIdx++]);
|
||||
}
|
||||
} else {
|
||||
result.push(item);
|
||||
}
|
||||
}
|
||||
return assignSortOrders(result);
|
||||
}
|
||||
|
||||
export async function persistSortOrderChanges<T extends { id: number; sort_order?: number }>(
|
||||
before: T[],
|
||||
reordered: T[],
|
||||
updateItem: (item: T) => Promise<void>,
|
||||
): Promise<T[]> {
|
||||
const after = assignSortOrders(reordered);
|
||||
const changes = diffSortOrderChanges(before, after);
|
||||
for (const change of changes) {
|
||||
const item = after.find(row => row.id === change.id);
|
||||
if (item) await updateItem(item);
|
||||
}
|
||||
return after;
|
||||
}
|
||||
|
||||
export function shouldShowSortableMoveButtons(
|
||||
count: number,
|
||||
mode: boolean | 'auto' = 'auto',
|
||||
): boolean {
|
||||
if (mode === true) return true;
|
||||
if (mode === false) return false;
|
||||
return count > ADMIN_SORTABLE_MOVE_BUTTONS_THRESHOLD;
|
||||
}
|
||||
Reference in New Issue
Block a user