feat: 增加友链申请、独立页面、投票/悬赏/抽奖帖与侧栏签到,并统一开发数据目录
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
12
Makefile
12
Makefile
@@ -4,6 +4,7 @@
|
|||||||
APP_NAME := jiang13
|
APP_NAME := jiang13
|
||||||
MAIN_PKG := ./cmd/jiang13
|
MAIN_PKG := ./cmd/jiang13
|
||||||
BUILD_DIR := dist
|
BUILD_DIR := dist
|
||||||
|
DEV_DATA_DIR := dist/data
|
||||||
VERSION := 1.0.0
|
VERSION := 1.0.0
|
||||||
LDFLAGS := -s -w -X main.version=$(VERSION)
|
LDFLAGS := -s -w -X main.version=$(VERSION)
|
||||||
REGISTRY_IMAGE := hangzhang714128/jiang13-forum
|
REGISTRY_IMAGE := hangzhang714128/jiang13-forum
|
||||||
@@ -55,16 +56,19 @@ build-all: frontend-build
|
|||||||
tidy:
|
tidy:
|
||||||
$(GO) mod tidy
|
$(GO) mod tidy
|
||||||
|
|
||||||
## 本地运行(仅后端,使用已 embed 的前端)
|
## 本地运行(仅后端,使用已 embed 的前端;数据目录与 dist 二进制一致)
|
||||||
run:
|
run:
|
||||||
$(GO) run $(MAIN_PKG)
|
@mkdir -p $(DEV_DATA_DIR)
|
||||||
|
$(GO) run $(MAIN_PKG) --data $(DEV_DATA_DIR)
|
||||||
|
|
||||||
## 前端热更新开发(后端 :3000 + Vite :5173,Ctrl+C 同时退出)
|
## 前端热更新开发(后端 :3000 + Vite :5173,Ctrl+C 同时退出;数据目录与 dist 二进制一致)
|
||||||
dev:
|
dev:
|
||||||
@echo "前端热更新: http://localhost:5173"
|
@echo "前端热更新: http://localhost:5173"
|
||||||
@echo "后端 API : http://localhost:3000"
|
@echo "后端 API : http://localhost:3000"
|
||||||
|
@echo "数据目录 : $(DEV_DATA_DIR) (与 dist 二进制一致)"
|
||||||
|
@mkdir -p $(DEV_DATA_DIR)
|
||||||
@trap 'kill 0' INT; \
|
@trap 'kill 0' INT; \
|
||||||
$(GO) run $(MAIN_PKG) & \
|
$(GO) run $(MAIN_PKG) --dev --data $(DEV_DATA_DIR) & \
|
||||||
cd frontend && (test -d node_modules || npm install) && npm run dev
|
cd frontend && (test -d node_modules || npm install) && npm run dev
|
||||||
|
|
||||||
## 清理编译产物
|
## 清理编译产物
|
||||||
|
|||||||
@@ -346,6 +346,8 @@ make dev
|
|||||||
|
|
||||||
浏览器访问 `http://localhost:5173`,API 自动代理到 `http://localhost:3000`。
|
浏览器访问 `http://localhost:5173`,API 自动代理到 `http://localhost:3000`。
|
||||||
|
|
||||||
|
开发后端与 `dist/jiang13` 共用数据目录 `dist/data`(SQLite、上传、JWT 密钥等),避免 dev 与 dist 运行数据不一致。
|
||||||
|
|
||||||
**何时需要完整构建:**
|
**何时需要完整构建:**
|
||||||
|
|
||||||
- 修改 Go 代码或要发布单二进制 → `build.bat` / `make build`
|
- 修改 Go 代码或要发布单二进制 → `build.bat` / `make build`
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ $ErrorActionPreference = 'Stop'
|
|||||||
$AppName = 'jiang13'
|
$AppName = 'jiang13'
|
||||||
$MainPkg = './cmd/jiang13'
|
$MainPkg = './cmd/jiang13'
|
||||||
$BuildDir = 'dist'
|
$BuildDir = 'dist'
|
||||||
|
$DevDataDir = 'dist/data'
|
||||||
$Version = '1.0.0'
|
$Version = '1.0.0'
|
||||||
$RegistryImage = 'hangzhang714128/jiang13-forum'
|
$RegistryImage = 'hangzhang714128/jiang13-forum'
|
||||||
$Ldlags = "-s -w -X main.version=$Version"
|
$Ldlags = "-s -w -X main.version=$Version"
|
||||||
@@ -90,18 +91,21 @@ switch ($Target) {
|
|||||||
Write-Host '[ok] cleaned dist' -ForegroundColor Green
|
Write-Host '[ok] cleaned dist' -ForegroundColor Green
|
||||||
}
|
}
|
||||||
'run' {
|
'run' {
|
||||||
go run $MainPkg
|
Ensure-Dir $DevDataDir
|
||||||
|
go run $MainPkg --data $DevDataDir
|
||||||
}
|
}
|
||||||
'dev' {
|
'dev' {
|
||||||
$root = (Get-Location).Path
|
$root = (Get-Location).Path
|
||||||
|
Ensure-Dir $DevDataDir
|
||||||
Write-Host ''
|
Write-Host ''
|
||||||
Write-Host '[dev] 前端开发 : http://localhost:5173 (Vite HMR)' -ForegroundColor Green
|
Write-Host '[dev] 前端开发 : http://localhost:5173 (Vite HMR)' -ForegroundColor Green
|
||||||
Write-Host '[dev] 后端 API : http://localhost:3000 (Go)' -ForegroundColor Green
|
Write-Host '[dev] 后端 API : http://localhost:3000 (Go)' -ForegroundColor Green
|
||||||
|
Write-Host "[dev] 数据目录 : $DevDataDir (与 dist 二进制一致)" -ForegroundColor Green
|
||||||
Write-Host '[dev] 提示 : 请访问 5173 端口,Vite 会自动代理 API 到 3000' -ForegroundColor Yellow
|
Write-Host '[dev] 提示 : 请访问 5173 端口,Vite 会自动代理 API 到 3000' -ForegroundColor Yellow
|
||||||
Write-Host '[dev] 正在新窗口启动 Go 后端 (仅 API)...' -ForegroundColor Cyan
|
Write-Host '[dev] 正在新窗口启动 Go 后端 (仅 API)...' -ForegroundColor Cyan
|
||||||
Start-Process powershell -ArgumentList @(
|
Start-Process powershell -ArgumentList @(
|
||||||
'-NoExit', '-Command',
|
'-NoExit', '-Command',
|
||||||
"Set-Location '$root'; Write-Host '[backend] Go API on :3000' -ForegroundColor Cyan; go run $MainPkg --dev"
|
"Set-Location '$root'; Write-Host '[backend] Go API on :3000' -ForegroundColor Cyan; go run $MainPkg --dev --data '$DevDataDir'"
|
||||||
) | Out-Null
|
) | Out-Null
|
||||||
Start-Sleep -Seconds 2
|
Start-Sleep -Seconds 2
|
||||||
Push-Location frontend
|
Push-Location frontend
|
||||||
|
|||||||
56
frontend/package-lock.json
generated
56
frontend/package-lock.json
generated
@@ -8,6 +8,9 @@
|
|||||||
"name": "jiang13-forum-web",
|
"name": "jiang13-forum-web",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.1",
|
||||||
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@hookform/resolvers": "^5.4.0",
|
"@hookform/resolvers": "^5.4.0",
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.16",
|
"@radix-ui/react-alert-dialog": "^1.1.16",
|
||||||
"@radix-ui/react-dialog": "^1.1.16",
|
"@radix-ui/react-dialog": "^1.1.16",
|
||||||
@@ -352,6 +355,59 @@
|
|||||||
"node": ">=6.9.0"
|
"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": {
|
"node_modules/@esbuild/aix-ppc64": {
|
||||||
"version": "0.21.5",
|
"version": "0.21.5",
|
||||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
|
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
|
||||||
|
|||||||
@@ -9,6 +9,9 @@
|
|||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.1",
|
||||||
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@hookform/resolvers": "^5.4.0",
|
"@hookform/resolvers": "^5.4.0",
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.16",
|
"@radix-ui/react-alert-dialog": "^1.1.16",
|
||||||
"@radix-ui/react-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 FavoritesPage = lazyWithRetry(() => import('./pages/FavoritesPage'));
|
||||||
const MessagesPage = lazyWithRetry(() => import('./pages/MessagesPage'));
|
const MessagesPage = lazyWithRetry(() => import('./pages/MessagesPage'));
|
||||||
const ProjectsPage = lazyWithRetry(() => import('./pages/ProjectsPage'));
|
const ProjectsPage = lazyWithRetry(() => import('./pages/ProjectsPage'));
|
||||||
|
const LinksPage = lazyWithRetry(() => import('./pages/LinksPage'));
|
||||||
const AdminDashboardPage = lazyWithRetry(() => import('./pages/admin/AdminDashboardPage'));
|
const AdminDashboardPage = lazyWithRetry(() => import('./pages/admin/AdminDashboardPage'));
|
||||||
const AdminPostsPage = lazyWithRetry(() => import('./pages/admin/AdminPostsPage'));
|
const AdminPostsPage = lazyWithRetry(() => import('./pages/admin/AdminPostsPage'));
|
||||||
const AdminCommentsPage = lazyWithRetry(() => import('./pages/admin/AdminCommentsPage'));
|
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 AdminUsersPage = lazyWithRetry(() => import('./pages/admin/AdminUsersPage'));
|
||||||
const AdminBadgesPage = lazyWithRetry(() => import('./pages/admin/AdminBadgesPage'));
|
const AdminBadgesPage = lazyWithRetry(() => import('./pages/admin/AdminBadgesPage'));
|
||||||
const AdminMediaPage = lazyWithRetry(() => import('./pages/admin/AdminMediaPage'));
|
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 AdminSettingsPage = lazyWithRetry(() => import('./pages/admin/AdminSettingsPage'));
|
||||||
const NotFoundPage = lazyWithRetry(() => import('./pages/NotFoundPage'));
|
const NotFoundPage = lazyWithRetry(() => import('./pages/NotFoundPage'));
|
||||||
|
|
||||||
@@ -52,6 +56,8 @@ const router = createBrowserRouter(
|
|||||||
<Route index element={<Navigate to="/admin/dashboard" replace />} />
|
<Route index element={<Navigate to="/admin/dashboard" replace />} />
|
||||||
<Route path="dashboard" element={<Suspense fallback={<PageLoader />}><AdminDashboardPage /></Suspense>} />
|
<Route path="dashboard" element={<Suspense fallback={<PageLoader />}><AdminDashboardPage /></Suspense>} />
|
||||||
<Route path="boards" element={<Suspense fallback={<PageLoader />}><BoardsManagePage /></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="posts" element={<Suspense fallback={<PageLoader />}><AdminPostsPage /></Suspense>} />
|
||||||
<Route path="comments" element={<Suspense fallback={<PageLoader />}><AdminCommentsPage /></Suspense>} />
|
<Route path="comments" element={<Suspense fallback={<PageLoader />}><AdminCommentsPage /></Suspense>} />
|
||||||
<Route path="reports" element={<Suspense fallback={<PageLoader />}><AdminReportsPage /></Suspense>} />
|
<Route path="reports" element={<Suspense fallback={<PageLoader />}><AdminReportsPage /></Suspense>} />
|
||||||
@@ -63,6 +69,7 @@ const router = createBrowserRouter(
|
|||||||
</Route>
|
</Route>
|
||||||
<Route element={<MainLayout />}>
|
<Route element={<MainLayout />}>
|
||||||
<Route path="/" element={<HomePage />} />
|
<Route path="/" element={<HomePage />} />
|
||||||
|
<Route path="/board/:id" element={<HomePage />} />
|
||||||
{/* :id 可为 123 或 123.html(伪静态后缀由后台配置) */}
|
{/* :id 可为 123 或 123.html(伪静态后缀由后台配置) */}
|
||||||
<Route path="/post/:id" element={<PostDetailPage />} />
|
<Route path="/post/:id" element={<PostDetailPage />} />
|
||||||
<Route path="/compose" element={<ComposePage />} />
|
<Route path="/compose" element={<ComposePage />} />
|
||||||
@@ -71,7 +78,9 @@ const router = createBrowserRouter(
|
|||||||
<Route path="/user/:id" element={<UserProfilePage />} />
|
<Route path="/user/:id" element={<UserProfilePage />} />
|
||||||
<Route path="/favorites" element={<FavoritesPage />} />
|
<Route path="/favorites" element={<FavoritesPage />} />
|
||||||
<Route path="/projects" element={<ProjectsPage />} />
|
<Route path="/projects" element={<ProjectsPage />} />
|
||||||
|
<Route path="/links" element={<LinksPage />} />
|
||||||
<Route path="/messages" element={<MessagesPage />} />
|
<Route path="/messages" element={<MessagesPage />} />
|
||||||
|
<Route path="/page/:slug" element={<Suspense fallback={<PageLoader />}><SitePageView /></Suspense>} />
|
||||||
<Route path="*" element={<Suspense fallback={<PageLoader />}><NotFoundPage /></Suspense>} />
|
<Route path="*" element={<Suspense fallback={<PageLoader />}><NotFoundPage /></Suspense>} />
|
||||||
</Route>
|
</Route>
|
||||||
<Route path="*" element={<Suspense fallback={<PageLoader fullScreen />}><NotFoundPage standalone /></Suspense>} />
|
<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 = '';
|
const BASE = '';
|
||||||
|
|
||||||
@@ -26,6 +26,8 @@ export const api = {
|
|||||||
stats: () => request<ForumStats>('/api/stats'),
|
stats: () => request<ForumStats>('/api/stats'),
|
||||||
forumLimits: () => request<ForumLimitsPublic>('/api/forum-limits'),
|
forumLimits: () => request<ForumLimitsPublic>('/api/forum-limits'),
|
||||||
siteBranding: () => request<SiteBranding>('/api/site-branding'),
|
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'),
|
boards: () => request<{ boards: Board[] }>('/api/boards'),
|
||||||
projects: (params?: { page?: number; limit?: number }) => {
|
projects: (params?: { page?: number; limit?: number }) => {
|
||||||
const q = new URLSearchParams();
|
const q = new URLSearchParams();
|
||||||
@@ -40,7 +42,6 @@ export const api = {
|
|||||||
const q = new URLSearchParams(params as Record<string, string>).toString();
|
const q = new URLSearchParams(params as Record<string, string>).toString();
|
||||||
return request<{ posts: PostItem[]; total: number; page: number; has_more: boolean }>(`/api/posts?${q}`);
|
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}`),
|
tags: (limit = 40) => request<{ tags: TagCount[] }>(`/api/tags?limit=${limit}`),
|
||||||
post: (id: number, opts?: { skipView?: boolean }) => {
|
post: (id: number, opts?: { skipView?: boolean }) => {
|
||||||
const q = opts?.skipView ? '?skip_view=1' : '';
|
const q = opts?.skipView ? '?skip_view=1' : '';
|
||||||
@@ -285,6 +286,7 @@ export const api = {
|
|||||||
check_in: CheckInStatus;
|
check_in: CheckInStatus;
|
||||||
lottery: LotteryStatus;
|
lottery: LotteryStatus;
|
||||||
}>(`/api/me/points?page=${page}`),
|
}>(`/api/me/points?page=${page}`),
|
||||||
|
checkInStatus: () => request<{ check_in: CheckInStatus }>('/api/me/check-in'),
|
||||||
checkIn: () =>
|
checkIn: () =>
|
||||||
request<{ message: string; check_in: CheckInStatus; points: number }>('/api/me/check-in', { method: 'POST' }),
|
request<{ message: string; check_in: CheckInStatus; points: number }>('/api/me/check-in', { method: 'POST' }),
|
||||||
lotteryStatus: () => request<{ lottery: LotteryStatus }>('/api/me/lottery'),
|
lotteryStatus: () => request<{ lottery: LotteryStatus }>('/api/me/lottery'),
|
||||||
@@ -341,13 +343,19 @@ export const api = {
|
|||||||
fd.append('image', file);
|
fd.append('image', file);
|
||||||
return request<{ url: string }>('/api/uploads/image', { method: 'POST', body: fd, headers: {} });
|
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();
|
const fd = new FormData();
|
||||||
fd.append('board_id', data.board_id);
|
fd.append('board_id', data.board_id);
|
||||||
fd.append('title', data.title);
|
fd.append('title', data.title);
|
||||||
fd.append('content', data.content);
|
fd.append('content', data.content);
|
||||||
fd.append('tags', data.tags || '');
|
fd.append('tags', data.tags || '');
|
||||||
fd.append('post_type', data.post_type || 'normal');
|
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: {} });
|
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 }) => {
|
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: {},
|
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' }),
|
deletePost: (id: number) => request<{ message: string }>(`/api/posts/${id}`, { method: 'DELETE' }),
|
||||||
login: (username: string, password: string) => {
|
login: (username: string, password: string) => {
|
||||||
const fd = new FormData();
|
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' }),
|
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' }),
|
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' }),
|
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 }) =>
|
reportPost: (id: number, body: { reason: ReportReason; detail?: string }) =>
|
||||||
request<{ message: string; report: PostReport }>(`/api/posts/${id}/report`, {
|
request<{ message: string; report: PostReport }>(`/api/posts/${id}/report`, {
|
||||||
method: 'POST', body: JSON.stringify(body),
|
method: 'POST', body: JSON.stringify(body),
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ export interface ForumStats {
|
|||||||
users: number;
|
users: number;
|
||||||
posts: number;
|
posts: number;
|
||||||
boards: number;
|
boards: number;
|
||||||
|
comments: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 标签云单项 */
|
/** 标签云单项 */
|
||||||
@@ -84,10 +85,15 @@ export interface PostItem {
|
|||||||
title: string;
|
title: string;
|
||||||
content?: string;
|
content?: string;
|
||||||
tags: string;
|
tags: string;
|
||||||
/** normal=讨论 | question=问答 */
|
/** normal=讨论 | question=问答 | poll=投票 | bounty=悬赏 | lottery=抽奖 */
|
||||||
post_type?: 'normal' | 'question' | string;
|
post_type?: 'normal' | 'question' | 'poll' | 'bounty' | 'lottery' | string;
|
||||||
/** 仅问答帖有意义 */
|
/** 仅问答帖有意义 */
|
||||||
question_resolved?: boolean;
|
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;
|
pinned: boolean;
|
||||||
/** 板块内置顶(仅板块列表抬升,首页不抬升) */
|
/** 板块内置顶(仅板块列表抬升,首页不抬升) */
|
||||||
board_pinned?: boolean;
|
board_pinned?: boolean;
|
||||||
@@ -131,12 +137,18 @@ export interface PostDetailResponse {
|
|||||||
comment_count: number;
|
comment_count: number;
|
||||||
liked: boolean;
|
liked: boolean;
|
||||||
favorited: boolean;
|
favorited: boolean;
|
||||||
/** 当前用户是否已在本帖发表过评论(含审核中) */
|
|
||||||
has_replied?: boolean;
|
has_replied?: boolean;
|
||||||
can_edit?: boolean;
|
can_edit?: boolean;
|
||||||
edit_block_reason?: string;
|
edit_block_reason?: string;
|
||||||
is_edited?: boolean;
|
is_edited?: boolean;
|
||||||
post_edit_window_hours?: number;
|
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 {
|
export interface Comment {
|
||||||
@@ -171,9 +183,23 @@ export interface AdminDashboard {
|
|||||||
pending_posts?: number;
|
pending_posts?: number;
|
||||||
pending_comments?: number;
|
pending_comments?: number;
|
||||||
pending_reports?: number;
|
pending_reports?: number;
|
||||||
|
pending_friend_links?: number;
|
||||||
recent_posts: PostItem[];
|
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 {
|
export interface ForumLimits {
|
||||||
post_edit_window_hours: number;
|
post_edit_window_hours: number;
|
||||||
comment_edit_window_minutes: number;
|
comment_edit_window_minutes: number;
|
||||||
@@ -194,6 +220,16 @@ export interface ForumLimits {
|
|||||||
signature_max: number;
|
signature_max: number;
|
||||||
open_posts_in_new_tab: boolean;
|
open_posts_in_new_tab: boolean;
|
||||||
open_content_links_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;
|
permalink_enabled: boolean;
|
||||||
/** 伪静态后缀,不含点,如 html / htm */
|
/** 伪静态后缀,不含点,如 html / htm */
|
||||||
@@ -214,6 +250,11 @@ export interface ForumLimitsPublic {
|
|||||||
signature_max: number;
|
signature_max: number;
|
||||||
open_posts_in_new_tab: boolean;
|
open_posts_in_new_tab: boolean;
|
||||||
open_content_links_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_enabled: boolean;
|
||||||
permalink_ext: string;
|
permalink_ext: string;
|
||||||
}
|
}
|
||||||
@@ -221,12 +262,77 @@ export interface ForumLimitsPublic {
|
|||||||
export interface FriendLink {
|
export interface FriendLink {
|
||||||
name: string;
|
name: string;
|
||||||
url: 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 {
|
export interface SiteBranding {
|
||||||
name: string;
|
name: string;
|
||||||
slogan: string;
|
slogan: string;
|
||||||
/** 站点简介(首页可见 + SEO description) */
|
/** 站点简介(右侧栏顶部 + SEO description) */
|
||||||
description?: string;
|
description?: string;
|
||||||
/** SEO keywords,逗号分隔 */
|
/** SEO keywords,逗号分隔 */
|
||||||
keywords?: string;
|
keywords?: string;
|
||||||
@@ -241,6 +347,8 @@ export interface SiteBranding {
|
|||||||
icp_beian_url?: string;
|
icp_beian_url?: string;
|
||||||
/** 页脚友情链接 */
|
/** 页脚友情链接 */
|
||||||
friend_links?: FriendLink[];
|
friend_links?: FriendLink[];
|
||||||
|
/** 公开站点根 URL(API 动态填充) */
|
||||||
|
site_url?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AdminSettings {
|
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 { useState, useEffect } from 'react';
|
||||||
import {
|
import {
|
||||||
Check, Clock, History, MessageSquare, X, Pencil, Trash2,
|
Check, Award, Clock, History, MessageSquare, X, Pencil, Trash2,
|
||||||
ThumbsUp, MoreHorizontal, Flag,
|
ThumbsUp, MoreHorizontal, Flag,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
@@ -51,6 +51,7 @@ import { isHtmlEmpty } from '../utils/postContent';
|
|||||||
import { Tooltip } from './ui/Tooltip';
|
import { Tooltip } from './ui/Tooltip';
|
||||||
import UserLink from './UserLink';
|
import UserLink from './UserLink';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { pinAwardedCommentTree } from '../utils/bounty';
|
||||||
|
|
||||||
function isCommentAuthor(c: Comment, user?: User | null): boolean {
|
function isCommentAuthor(c: Comment, user?: User | null): boolean {
|
||||||
return !!user && c.user_id > 0 && c.user_id === user.id;
|
return !!user && c.user_id > 0 && c.user_id === user.id;
|
||||||
@@ -83,6 +84,13 @@ interface ItemProps {
|
|||||||
onRequireLogin?: (actionLabel: string) => void;
|
onRequireLogin?: (actionLabel: string) => void;
|
||||||
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
|
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
|
||||||
renderReplyBox?: (comment: Comment) => ReactNode;
|
renderReplyBox?: (comment: Comment) => ReactNode;
|
||||||
|
bountyAward?: {
|
||||||
|
open: boolean;
|
||||||
|
awardedCommentId?: number;
|
||||||
|
postAuthorId: number;
|
||||||
|
canAward: boolean;
|
||||||
|
onAward: (commentId: number) => void;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 单条评论(支持嵌套子回复 + 内联回复框 + 编辑/删除) */
|
/** 单条评论(支持嵌套子回复 + 内联回复框 + 编辑/删除) */
|
||||||
@@ -103,12 +111,14 @@ function CommentItem({
|
|||||||
onRequireLogin,
|
onRequireLogin,
|
||||||
onLikeUpdate,
|
onLikeUpdate,
|
||||||
renderReplyBox,
|
renderReplyBox,
|
||||||
|
bountyAward,
|
||||||
}: ItemProps) {
|
}: ItemProps) {
|
||||||
const { limits } = useForumLimits();
|
const { limits } = useForumLimits();
|
||||||
const c = node.comment;
|
const c = node.comment;
|
||||||
const nick = commentNick(c);
|
const nick = commentNick(c);
|
||||||
const guest = isGuestComment(c);
|
const guest = isGuestComment(c);
|
||||||
const isHighlighted = highlightFloor === c.floor;
|
const isHighlighted = highlightFloor === c.floor;
|
||||||
|
const isBountyAwarded = bountyAward?.awardedCommentId === c.id;
|
||||||
const hidden = !!c.content_hidden;
|
const hidden = !!c.content_hidden;
|
||||||
const isReplying = replyToId === c.id;
|
const isReplying = replyToId === c.id;
|
||||||
const isEditing = editingId === c.id;
|
const isEditing = editingId === c.id;
|
||||||
@@ -215,7 +225,12 @@ function CommentItem({
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
id={`floor-${c.floor}`}
|
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 ? (
|
{!guest && c.user_id ? (
|
||||||
<UserLink
|
<UserLink
|
||||||
@@ -255,6 +270,12 @@ function CommentItem({
|
|||||||
) : (
|
) : (
|
||||||
<span className="waline-comment-author">{nick}</span>
|
<span className="waline-comment-author">{nick}</span>
|
||||||
)}
|
)}
|
||||||
|
{isBountyAwarded && (
|
||||||
|
<span className="waline-comment-bounty-badge" title="悬赏已采纳">
|
||||||
|
<Check size={12} aria-hidden />
|
||||||
|
已采纳
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
{!hidden && (
|
{!hidden && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -351,6 +372,17 @@ function CommentItem({
|
|||||||
编辑
|
编辑
|
||||||
</button>
|
</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 && (
|
{!hidden && !isEditing && isAdmin && showEdited && (
|
||||||
<button type="button" className="waline-comment-reply-btn" onClick={() => setRevOpen(true)}>
|
<button type="button" className="waline-comment-reply-btn" onClick={() => setRevOpen(true)}>
|
||||||
<History size={14} />
|
<History size={14} />
|
||||||
@@ -481,6 +513,7 @@ function CommentItem({
|
|||||||
onRequireLogin={onRequireLogin}
|
onRequireLogin={onRequireLogin}
|
||||||
onLikeUpdate={onLikeUpdate}
|
onLikeUpdate={onLikeUpdate}
|
||||||
renderReplyBox={renderReplyBox}
|
renderReplyBox={renderReplyBox}
|
||||||
|
bountyAward={bountyAward}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -506,6 +539,7 @@ interface Props {
|
|||||||
onRequireLogin?: (actionLabel: string) => void;
|
onRequireLogin?: (actionLabel: string) => void;
|
||||||
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
|
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
|
||||||
renderReplyBox?: (comment: Comment) => ReactNode;
|
renderReplyBox?: (comment: Comment) => ReactNode;
|
||||||
|
bountyAward?: ItemProps['bountyAward'];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Waline 嵌套楼层评论列表 */
|
/** Waline 嵌套楼层评论列表 */
|
||||||
@@ -525,8 +559,12 @@ export default function CommentThreadList({
|
|||||||
onRequireLogin,
|
onRequireLogin,
|
||||||
onLikeUpdate,
|
onLikeUpdate,
|
||||||
renderReplyBox,
|
renderReplyBox,
|
||||||
|
bountyAward,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const tree = buildCommentTree(comments);
|
const tree = pinAwardedCommentTree(
|
||||||
|
buildCommentTree(comments),
|
||||||
|
bountyAward?.awardedCommentId,
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="comment-thread-list">
|
<div className="comment-thread-list">
|
||||||
@@ -548,6 +586,7 @@ export default function CommentThreadList({
|
|||||||
onRequireLogin={onRequireLogin}
|
onRequireLogin={onRequireLogin}
|
||||||
onLikeUpdate={onLikeUpdate}
|
onLikeUpdate={onLikeUpdate}
|
||||||
renderReplyBox={renderReplyBox}
|
renderReplyBox={renderReplyBox}
|
||||||
|
bountyAward={bountyAward}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Users, FileText, LayoutGrid } from 'lucide-react';
|
import { Users, FileText, LayoutGrid } from 'lucide-react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import type { Board, ForumStats } from '../api/types';
|
import type { Board, ForumStats } from '../api/types';
|
||||||
|
import { navigateFeed } from '../utils/feedCache';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
boardId: number;
|
boardId: number;
|
||||||
@@ -81,7 +82,7 @@ export default function FeedHeader({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="feed-head__clear"
|
className="feed-head__clear"
|
||||||
onClick={() => nav('/')}
|
onClick={() => navigateFeed(nav, '/')}
|
||||||
>
|
>
|
||||||
{tag ? '清除标签' : '清除搜索'}
|
{tag ? '清除标签' : '清除搜索'}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import PostListSkeleton from './PostListSkeleton';
|
import PostListSkeleton from './PostListSkeleton';
|
||||||
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
|
|
||||||
/** 首页 Feed 初始骨架(标题区 + 排序栏 + 列表) */
|
/** 首页 Feed 初始骨架(标题区 + 排序栏 + 列表) */
|
||||||
export default function FeedPageSkeleton() {
|
export default function FeedPageSkeleton() {
|
||||||
|
const { limits } = useForumLimits();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="page-wrap page-wrap--feed" aria-busy="true" aria-label="内容加载中">
|
<div className="page-wrap page-wrap--feed" aria-busy="true" aria-label="内容加载中">
|
||||||
<div className="feed-panel">
|
<div className="feed-panel">
|
||||||
@@ -27,7 +30,7 @@ export default function FeedPageSkeleton() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="post-list-scroll">
|
<div className="post-list-scroll">
|
||||||
<PostListSkeleton />
|
<PostListSkeleton listStyle={limits.feed_list_style ?? 'title'} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { useRef } from 'react';
|
import { useRef } from 'react';
|
||||||
|
import { boardPath, type PermalinkOpts } from '../utils/permalink';
|
||||||
|
import { getCachedForumLimits } from '../hooks/useForumLimits';
|
||||||
import { Clock, MessageCircle, Flame } from 'lucide-react';
|
import { Clock, MessageCircle, Flame } from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { moveTabIndex } from '../hooks/useOverlayA11y';
|
import { moveTabIndex } from '../hooks/useOverlayA11y';
|
||||||
@@ -30,10 +32,9 @@ export function parseFeedSort(raw: string | null): FeedSort {
|
|||||||
export function buildHomeUrl(
|
export function buildHomeUrl(
|
||||||
boardId: number,
|
boardId: number,
|
||||||
sort: FeedSort = 'latest',
|
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();
|
const p = new URLSearchParams();
|
||||||
if (boardId) p.set('board', String(boardId));
|
|
||||||
const tag = opts?.tag?.trim();
|
const tag = opts?.tag?.trim();
|
||||||
const keyword = opts?.keyword?.trim();
|
const keyword = opts?.keyword?.trim();
|
||||||
const author = opts?.author?.trim();
|
const author = opts?.author?.trim();
|
||||||
@@ -48,6 +49,11 @@ export function buildHomeUrl(
|
|||||||
}
|
}
|
||||||
if (sort !== 'latest') p.set('sort', sort);
|
if (sort !== 'latest') p.set('sort', sort);
|
||||||
const qs = p.toString();
|
const qs = p.toString();
|
||||||
|
|
||||||
|
if (boardId) {
|
||||||
|
const base = boardPath(boardId, opts?.permalink ?? getCachedForumLimits());
|
||||||
|
return qs ? `${base}?${qs}` : base;
|
||||||
|
}
|
||||||
return qs ? `/?${qs}` : '/';
|
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 { memo } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { Eye, Image as ImageIcon, MessageCircle, ThumbsUp } from 'lucide-react';
|
import { Eye, Image as ImageIcon, MessageCircle, ThumbsUp } from 'lucide-react';
|
||||||
import BoardBadge from '@/components/BoardBadge';
|
|
||||||
import FeaturedIcon from '@/components/FeaturedIcon';
|
import FeaturedIcon from '@/components/FeaturedIcon';
|
||||||
import UserLink from '@/components/UserLink';
|
import UserLink from '@/components/UserLink';
|
||||||
import type { PostItem } from '../api/types';
|
import type { PostItem } from '../api/types';
|
||||||
import type { FeedSort } from './FeedSortBar';
|
import type { FeedSort } from './FeedSortBar';
|
||||||
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
import { formatTime } from '../utils/content';
|
import { formatTime } from '../utils/content';
|
||||||
import { postPath } from '../utils/permalink';
|
import { postPath } from '../utils/permalink';
|
||||||
|
import { toPostImageThumbSrc } from '../utils/postContent';
|
||||||
import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText';
|
import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText';
|
||||||
import { parseTags } from './TagInput';
|
import { parseTags } from './TagInput';
|
||||||
|
|
||||||
@@ -19,6 +20,11 @@ interface Props {
|
|||||||
|
|
||||||
function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
||||||
const nav = useNavigate();
|
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 initial = post.user?.nickname?.[0] || '?';
|
||||||
const timeLabel = sort === 'reply'
|
const timeLabel = sort === 'reply'
|
||||||
? (post.last_reply_at
|
? (post.last_reply_at
|
||||||
@@ -29,8 +35,10 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
|||||||
const likeCount = post.like_count ?? 0;
|
const likeCount = post.like_count ?? 0;
|
||||||
const viewCount = post.view_count ?? 0;
|
const viewCount = post.view_count ?? 0;
|
||||||
const href = postPath(post.id);
|
const href = postPath(post.id);
|
||||||
const excerpt = excerptFromHTML(post.content || '', 72);
|
const firstImage = firstImageFromHTML(post.content || '');
|
||||||
const hasImage = !!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 tagList = parseTags(post.tags || '').slice(0, 3);
|
||||||
|
|
||||||
const openPost = () => onSelect(post.id);
|
const openPost = () => onSelect(post.id);
|
||||||
@@ -41,7 +49,6 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
const onTitleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
|
const onTitleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
|
||||||
// 修饰键 / 非左键:交给浏览器(新标签等)
|
|
||||||
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
|
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
return;
|
return;
|
||||||
@@ -51,9 +58,107 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
|||||||
openPost();
|
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 (
|
return (
|
||||||
<div
|
<div
|
||||||
className="post-row"
|
className={`post-row post-row--v2${thumbSrc ? ' post-row--has-thumb' : ''}`}
|
||||||
role="link"
|
role="link"
|
||||||
tabIndex={0}
|
tabIndex={0}
|
||||||
onClick={openPost}
|
onClick={openPost}
|
||||||
@@ -71,88 +176,32 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
|||||||
: initial}
|
: initial}
|
||||||
</UserLink>
|
</UserLink>
|
||||||
|
|
||||||
<div className="post-body">
|
{thumbSrc ? (
|
||||||
<div className="post-head">
|
<div className="post-main post-main--with-thumb">
|
||||||
<div className="post-head-meta">
|
<div className="post-content">
|
||||||
<UserLink user={post.user} stopPropagation className="post-author" showBadges />
|
{titleRow}
|
||||||
<span className="post-head-dot" aria-hidden>·</span>
|
{excerpt && <p className="post-excerpt">{excerpt}</p>}
|
||||||
<span className="post-time">{timeLabel}</span>
|
<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>
|
</div>
|
||||||
|
) : (
|
||||||
<div className="post-title-row">
|
<div className="post-main">
|
||||||
{post.pinned && (
|
<div className="post-text">
|
||||||
<span className="post-pin-badge" title="全局置顶">全局置顶</span>
|
{titleRow}
|
||||||
)}
|
{excerpt && <p className="post-excerpt">{excerpt}</p>}
|
||||||
{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>
|
</div>
|
||||||
<div className="post-stats">
|
<div className="post-meta">
|
||||||
{hasImage && (
|
{metaLeft}
|
||||||
<span className="post-stat post-stat--media" title="含图片">
|
{stats}
|
||||||
<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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +1,73 @@
|
|||||||
import { Skeleton } from '@/components/ui/skeleton';
|
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 {
|
interface Props {
|
||||||
count?: number;
|
count?: number;
|
||||||
|
listStyle?: FeedListStyle;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 帖子列表加载骨架屏(对齐卡片式列表) */
|
/** 帖子列表加载骨架屏(对齐 v2 紧凑列表) */
|
||||||
export default function PostListSkeleton({ count = 8 }: Props) {
|
export default function PostListSkeleton({ count = 8, listStyle = 'title' }: Props) {
|
||||||
|
const showExcerpt = listStyle === 'excerpt' || listStyle === 'thumbnail';
|
||||||
|
const showThumb = listStyle === 'thumbnail';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="post-list-skeleton" aria-busy="true" aria-label="加载中">
|
<div className="post-list-skeleton" aria-busy="true" aria-label="加载中">
|
||||||
{Array.from({ length: count }, (_, i) => (
|
{Array.from({ length: count }, (_, i) => {
|
||||||
<div key={i} className="post-row post-row--skeleton">
|
const hasThumb = showThumb && i % 3 === 0;
|
||||||
<Skeleton className="skeleton--avatar" />
|
return (
|
||||||
<div className="post-body">
|
<div key={i} className={`post-row post-row--v2 post-row--skeleton${hasThumb ? ' post-row--has-thumb' : ''}`}>
|
||||||
<div className="post-head">
|
<Skeleton className="skeleton--avatar skeleton--avatar-v2" />
|
||||||
<div className="skeleton-meta-row">
|
{hasThumb ? (
|
||||||
<Skeleton className="skeleton--meta" />
|
<div className="post-main post-main--with-thumb">
|
||||||
<Skeleton className="skeleton--meta skeleton--meta-short" />
|
<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>
|
</div>
|
||||||
{i % 4 === 0 && <Skeleton className="skeleton--badge" />}
|
) : (
|
||||||
</div>
|
<div className="post-main">
|
||||||
<Skeleton className="skeleton--title" style={{ width: `${58 + (i % 4) * 9}%` }} />
|
<div className="post-text">
|
||||||
<Skeleton className="skeleton--excerpt" style={{ width: `${72 + (i % 3) * 8}%` }} />
|
<Skeleton className="skeleton--title skeleton--title-v2" style={{ width: `${58 + (i % 4) * 9}%` }} />
|
||||||
<div className="post-foot">
|
{showExcerpt && (
|
||||||
<Skeleton className="skeleton--badge" />
|
<Skeleton className="skeleton--excerpt skeleton--excerpt-v2" style={{ width: `${72 + (i % 3) * 8}%` }} />
|
||||||
<div className="post-stats">
|
)}
|
||||||
<Skeleton className="skeleton--stat" />
|
</div>
|
||||||
<Skeleton className="skeleton--stat" />
|
<div className="post-meta">
|
||||||
<Skeleton className="skeleton--stat" />
|
<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>
|
||||||
</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 { useMemo } from 'react';
|
||||||
import { useLocation, useSearchParams } from 'react-router-dom';
|
import { ListTree, MessageCircle, Tags, Link2 } from 'lucide-react';
|
||||||
|
import { useLocation, useSearchParams, useNavigate } from 'react-router-dom';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
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 type { PostHeading } from '../utils/postHeadings';
|
||||||
import { useSiteBranding } from '../hooks/useSiteBranding';
|
import { useSiteBranding } from '../hooks/useSiteBranding';
|
||||||
import { formatShortDateTime, formatTime } from '../utils/content';
|
import { formatShortDateTime, formatTime } from '../utils/content';
|
||||||
|
import { resolveAsideWidgets } from '../utils/asideWidgets';
|
||||||
import TagCloud from './TagCloud';
|
import TagCloud from './TagCloud';
|
||||||
import UserLink from './UserLink';
|
import UserLink from './UserLink';
|
||||||
import ArticleOutline from './ArticleOutline';
|
import ArticleOutline from './ArticleOutline';
|
||||||
import PostAuthorCard from './PostAuthorCard';
|
import PostAuthorCard from './PostAuthorCard';
|
||||||
|
import AsideCheckInStrip from './AsideCheckInStrip';
|
||||||
|
|
||||||
export type PostDetailAside = {
|
export type PostDetailAside = {
|
||||||
author?: User | null;
|
author?: User | null;
|
||||||
@@ -20,38 +24,29 @@ export type PostDetailAside = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
hot: PostItem[];
|
|
||||||
recentComments: RecentComment[];
|
recentComments: RecentComment[];
|
||||||
tags?: TagCount[];
|
tags?: TagCount[];
|
||||||
tagsLoading?: boolean;
|
tagsLoading?: boolean;
|
||||||
|
stats?: ForumStats | null;
|
||||||
onPostClick: (id: number, opts?: { floor?: number }) => void;
|
onPostClick: (id: number, opts?: { floor?: number }) => void;
|
||||||
/** 首次拉取中,显示骨架避免空态闪烁 */
|
/** 首次拉取中,显示骨架避免空态闪烁 */
|
||||||
loading?: boolean;
|
loading?: boolean;
|
||||||
|
/** 右侧栏可选组件顺序与开关 */
|
||||||
|
asideWidgets: AsideWidget[];
|
||||||
/** 帖子详情:右侧顶部展示作者与目录 */
|
/** 帖子详情:右侧顶部展示作者与目录 */
|
||||||
postDetail?: PostDetailAside | null;
|
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() {
|
function CommentSkeleton() {
|
||||||
return (
|
return (
|
||||||
<div className="widget-skeleton" aria-busy="true" aria-label="评论加载中">
|
<div className="widget-skeleton" aria-busy="true" aria-label="评论加载中">
|
||||||
{Array.from({ length: 5 }, (_, i) => (
|
{Array.from({ length: 5 }, (_, i) => (
|
||||||
<div key={i} className="widget-item widget-item--comment widget-item--skeleton">
|
<div key={i} className="widget-item widget-item--comment widget-item--skeleton">
|
||||||
<Skeleton className="skeleton--widget-avatar" />
|
<Skeleton className="skeleton--widget-avatar" />
|
||||||
<Skeleton className="skeleton--widget-title" style={{ width: `${55 + (i % 3) * 12}%` }} />
|
<div className="widget-item-comment-main">
|
||||||
<Skeleton className="skeleton--widget-time" />
|
<Skeleton className="skeleton--widget-title" style={{ width: `${72 + (i % 3) * 8}%` }} />
|
||||||
|
<Skeleton className="skeleton--widget-meta" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -59,21 +54,24 @@ function CommentSkeleton() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function RightPanel({
|
export default function RightPanel({
|
||||||
hot,
|
|
||||||
recentComments,
|
recentComments,
|
||||||
tags = [],
|
tags = [],
|
||||||
tagsLoading = false,
|
tagsLoading = false,
|
||||||
|
stats = null,
|
||||||
onPostClick,
|
onPostClick,
|
||||||
loading = false,
|
loading = false,
|
||||||
|
asideWidgets,
|
||||||
postDetail = null,
|
postDetail = null,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const { branding } = useSiteBranding();
|
const { branding } = useSiteBranding();
|
||||||
|
const nav = useNavigate();
|
||||||
const loc = useLocation();
|
const loc = useLocation();
|
||||||
const [params] = useSearchParams();
|
const [params] = useSearchParams();
|
||||||
const activeTag = params.get('tag') || '';
|
const activeTag = params.get('tag') || '';
|
||||||
const hotList = hot?.slice(0, 8) ?? [];
|
|
||||||
const commentList = recentComments?.slice(0, 6) ?? [];
|
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 === '/'
|
const isSiteHome = loc.pathname === '/'
|
||||||
&& !params.get('board')
|
&& !params.get('board')
|
||||||
&& !params.get('keyword')
|
&& !params.get('keyword')
|
||||||
@@ -81,13 +79,144 @@ export default function RightPanel({
|
|||||||
&& !params.get('author');
|
&& !params.get('author');
|
||||||
const description = branding.description?.trim() || '';
|
const description = branding.description?.trim() || '';
|
||||||
const slogan = branding.slogan?.trim() || '';
|
const slogan = branding.slogan?.trim() || '';
|
||||||
// 有独立简介时展示简介;否则用欢迎语,避免与页脚 slogan 三连重复
|
const introText = description || slogan;
|
||||||
const aboutText = description || '欢迎参与讨论,发帖、评论,一起把小圈子聊热。';
|
|
||||||
// 有近期讨论则展示「正在聊」;否则显示欢迎引导
|
|
||||||
const showActive = loading || hotList.length > 0;
|
|
||||||
const showWelcome = !loading && hotList.length === 0;
|
|
||||||
const isPostDetail = !!postDetail;
|
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 (
|
return (
|
||||||
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
|
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
|
||||||
{isPostDetail && (
|
{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 && (
|
{!isPostDetail && (
|
||||||
<div className="widget-card widget-card--about">
|
<div className="widget-card widget-card--about">
|
||||||
<div className="widget-card-body">
|
<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-title">{branding.name}</p>
|
||||||
)}
|
)}
|
||||||
<p className="widget-about-desc">{aboutText}</p>
|
{introText && (
|
||||||
{description && slogan && slogan !== description && (
|
<p className="widget-about-desc">{introText}</p>
|
||||||
<p className="widget-about-slogan">{slogan}</p>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</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>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{!isPostDetail && enabledWidgets.map(renderWidget)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft,
|
Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft, FileText, Link2,
|
||||||
} from 'lucide-react';
|
} 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 { Board } from '../api/types';
|
||||||
import type { PostHeading } from '../utils/postHeadings';
|
import type { PostHeading } from '../utils/postHeadings';
|
||||||
import { useAuth } from '../hooks/useAuth';
|
import { useAuth } from '../hooks/useAuth';
|
||||||
@@ -12,9 +12,12 @@ import { navigateFeed } from '../utils/feedCache';
|
|||||||
import BoardIconDisplay from './BoardIconDisplay';
|
import BoardIconDisplay from './BoardIconDisplay';
|
||||||
import { getBoardThemeIndex } from '../utils/boardTheme';
|
import { getBoardThemeIndex } from '../utils/boardTheme';
|
||||||
import ArticleOutline from './ArticleOutline';
|
import ArticleOutline from './ArticleOutline';
|
||||||
|
import { useSitePages } from '../hooks/useSitePages';
|
||||||
|
import { pagePath } from '../utils/permalink';
|
||||||
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
|
|
||||||
// 内容页不参与左侧栏高亮(非 feed 浏览上下文)
|
// 内容页不参与左侧栏高亮(非 feed 浏览上下文)
|
||||||
const NEUTRAL_SIDEBAR_PREFIXES = ['/post/', '/profile', '/user/'];
|
const NEUTRAL_SIDEBAR_PREFIXES = ['/post/', '/profile', '/user/', '/page/'];
|
||||||
|
|
||||||
export function isNeutralSidebarRoute(pathname: string): boolean {
|
export function isNeutralSidebarRoute(pathname: string): boolean {
|
||||||
return NEUTRAL_SIDEBAR_PREFIXES.some(prefix => pathname.startsWith(prefix));
|
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 (keyword.trim()) return null;
|
||||||
if (pathname.startsWith('/favorites')) return 'favorites';
|
if (pathname.startsWith('/favorites')) return 'favorites';
|
||||||
if (pathname.startsWith('/projects')) return 'projects';
|
if (pathname.startsWith('/projects')) return 'projects';
|
||||||
|
if (pathname.startsWith('/links')) return 'links';
|
||||||
|
if (pathname.startsWith('/page/')) return 'pages';
|
||||||
if (pathname.startsWith('/admin')) return 'admin';
|
if (pathname.startsWith('/admin')) return 'admin';
|
||||||
return activeBoard === 0 ? 'all' : String(activeBoard);
|
return activeBoard === 0 ? 'all' : String(activeBoard);
|
||||||
}
|
}
|
||||||
@@ -59,9 +64,37 @@ export default function Sidebar({
|
|||||||
const sort = parseFeedSort(params.get('sort'));
|
const sort = parseFeedSort(params.get('sort'));
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const isAdmin = user?.role === 'admin';
|
const isAdmin = user?.role === 'admin';
|
||||||
|
const { navPages } = useSitePages();
|
||||||
|
const { limits } = useForumLimits();
|
||||||
|
|
||||||
const keyword = params.get('keyword') || '';
|
const keyword = params.get('keyword') || '';
|
||||||
const menuKey = resolveMenuKey(loc.pathname, activeBoard, 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) => (
|
const navItem = (key: string, label: React.ReactNode, icon?: React.ReactNode, onClick?: () => void) => (
|
||||||
<button
|
<button
|
||||||
@@ -99,9 +132,10 @@ export default function Sidebar({
|
|||||||
<aside className="sidebar">
|
<aside className="sidebar">
|
||||||
<div className="sidebar-section">浏览</div>
|
<div className="sidebar-section">浏览</div>
|
||||||
<nav className="sidebar-nav">
|
<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'))}
|
{user && navItem('favorites', '我的收藏', <Star aria-hidden />, () => nav('/favorites'))}
|
||||||
{navItem('projects', '开源码桶', <FolderGit2 aria-hidden />, () => nav('/projects'))}
|
{navItem('projects', '开源码桶', <FolderGit2 aria-hidden />, () => nav('/projects'))}
|
||||||
|
{navItem('links', '友情链接', <Link2 aria-hidden />, () => nav('/links'))}
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
{(boardsLoading && boards.length === 0) ? (
|
{(boardsLoading && boards.length === 0) ? (
|
||||||
@@ -123,29 +157,27 @@ export default function Sidebar({
|
|||||||
{boards.map(b => {
|
{boards.map(b => {
|
||||||
const isActive = menuKey != null && menuKey === String(b.id);
|
const isActive = menuKey != null && menuKey === String(b.id);
|
||||||
const themeIdx = getBoardThemeIndex(b);
|
const themeIdx = getBoardThemeIndex(b);
|
||||||
return (
|
const boardUrl = buildHomeUrl(b.id, sort, permalinkOpts);
|
||||||
<button
|
const postMeta = (b.post_count ?? 0) > 0 ? (
|
||||||
type="button"
|
<span className="sidebar-nav-item__meta" title={`${b.post_count} 篇帖子`}>
|
||||||
key={b.id}
|
{b.post_count} 帖
|
||||||
className={cn(
|
</span>
|
||||||
'sidebar-nav-item',
|
) : null;
|
||||||
'sidebar-nav-item--board',
|
return feedNavLink(
|
||||||
isActive && 'active',
|
String(b.id),
|
||||||
isActive && `sidebar-nav-item--board-${themeIdx}`,
|
boardUrl,
|
||||||
)}
|
b.name,
|
||||||
onClick={() => { onSelectBoard(b.id); navigateFeed(nav, buildHomeUrl(b.id, sort)); }}
|
<BoardIconDisplay
|
||||||
>
|
board={b}
|
||||||
<BoardIconDisplay
|
className={cn('sidebar-board-icon', `sidebar-board-icon--${themeIdx}`)}
|
||||||
board={b}
|
/>,
|
||||||
className={cn('sidebar-board-icon', `sidebar-board-icon--${themeIdx}`)}
|
b.id,
|
||||||
/>
|
cn(
|
||||||
<span className="flex-1 truncate">{b.name}</span>
|
'sidebar-nav-item--board',
|
||||||
{(b.post_count ?? 0) > 0 && (
|
isActive && 'active',
|
||||||
<span className="sidebar-nav-item__meta" title={`${b.post_count} 篇帖子`}>
|
isActive && `sidebar-nav-item--board-${themeIdx}`,
|
||||||
{b.post_count} 帖
|
),
|
||||||
</span>
|
postMeta,
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</nav>
|
</nav>
|
||||||
@@ -159,6 +191,17 @@ export default function Sidebar({
|
|||||||
</>
|
</>
|
||||||
) : null}
|
) : 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 && (
|
{isAdmin && (
|
||||||
<>
|
<>
|
||||||
<div className="sidebar-section sidebar-section--spaced">管理</div>
|
<div className="sidebar-section sidebar-section--spaced">管理</div>
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
import { useSiteBranding } from '../hooks/useSiteBranding';
|
import { useSiteBranding } from '../hooks/useSiteBranding';
|
||||||
import { useMediaQuery } from '../hooks/useTheme';
|
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() {
|
function FooterSep() {
|
||||||
return <span className="site-footer__sep" aria-hidden>·</span>;
|
return <span className="site-footer__sep" aria-hidden>·</span>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 站点页脚:版权、Sitemap、友链、备案号 */
|
/** 站点页脚:版权、Sitemap、备案号 */
|
||||||
export default function SiteFooter() {
|
export default function SiteFooter() {
|
||||||
const { branding } = useSiteBranding();
|
const { branding } = useSiteBranding();
|
||||||
|
const { footerPages } = useSitePages();
|
||||||
|
const { limits } = useForumLimits();
|
||||||
const year = new Date().getFullYear();
|
const year = new Date().getFullYear();
|
||||||
const links = Array.isArray(branding.friend_links) ? branding.friend_links : [];
|
|
||||||
const icp = branding.icp_beian?.trim() || '';
|
const icp = branding.icp_beian?.trim() || '';
|
||||||
const icpURL = branding.icp_beian_url?.trim() || 'https://beian.miit.gov.cn/';
|
const icpURL = branding.icp_beian_url?.trim() || 'https://beian.miit.gov.cn/';
|
||||||
|
|
||||||
@@ -29,31 +33,30 @@ export default function SiteFooter() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{(links.length > 0 || icp) && (
|
<nav className="site-footer__nav" aria-label="站点链接">
|
||||||
<nav className="site-footer__nav" aria-label="站点链接">
|
<span className="site-footer__friend">
|
||||||
{links.map((link: FriendLink, i) => (
|
<Link to="/links">友情链接</Link>
|
||||||
<span key={`${link.name}-${link.url}`} className="site-footer__friend">
|
</span>
|
||||||
{i > 0 && <FooterSep />}
|
{footerPages.map(p => (
|
||||||
<a href={link.url} target="_blank" rel="noopener noreferrer">
|
<span key={p.slug} className="site-footer__friend">
|
||||||
{link.name}
|
<FooterSep />
|
||||||
</a>
|
<Link to={pagePath(p.slug, limits)}>{p.title}</Link>
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
{icp && (
|
{icp && (
|
||||||
<>
|
<>
|
||||||
{links.length > 0 && <FooterSep />}
|
<FooterSep />
|
||||||
<a
|
<a
|
||||||
href={icpURL}
|
href={icpURL}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="site-footer__icp"
|
className="site-footer__icp"
|
||||||
>
|
>
|
||||||
{icp}
|
{icp}
|
||||||
</a>
|
</a>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</nav>
|
</nav>
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,10 +4,11 @@ import { useVirtualizer } from '@tanstack/react-virtual';
|
|||||||
import { Inbox, SearchX } from 'lucide-react';
|
import { Inbox, SearchX } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import PostListItem from './PostListItem';
|
import PostListItem from './PostListItem';
|
||||||
import PostListSkeleton from './PostListSkeleton';
|
import PostListSkeleton, { feedListRowEstimate } from './PostListSkeleton';
|
||||||
import FeedPagination from './FeedPagination';
|
import FeedPagination from './FeedPagination';
|
||||||
import { InFlowSiteFooter } from './SiteFooter';
|
import { InFlowSiteFooter } from './SiteFooter';
|
||||||
import { useAuth } from '../hooks/useAuth';
|
import { useAuth } from '../hooks/useAuth';
|
||||||
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
import { useMediaQuery } from '../hooks/useTheme';
|
import { useMediaQuery } from '../hooks/useTheme';
|
||||||
import { loginPath } from '../utils/authRedirect';
|
import { loginPath } from '../utils/authRedirect';
|
||||||
import type { PostItem } from '../api/types';
|
import type { PostItem } from '../api/types';
|
||||||
@@ -67,7 +68,10 @@ export default function VirtualPostList({
|
|||||||
}: Props) {
|
}: Props) {
|
||||||
const nav = useNavigate();
|
const nav = useNavigate();
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
|
const { limits } = useForumLimits();
|
||||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||||
|
const feedStyle = limits.feed_list_style ?? 'title';
|
||||||
|
const rowEstimate = feedListRowEstimate(feedStyle);
|
||||||
const parentRef = useRef<HTMLDivElement>(null);
|
const parentRef = useRef<HTMLDivElement>(null);
|
||||||
const restoredRef = useRef(false);
|
const restoredRef = useRef(false);
|
||||||
const onScrollTopChangeRef = useRef(onScrollTopChange);
|
const onScrollTopChangeRef = useRef(onScrollTopChange);
|
||||||
@@ -116,7 +120,7 @@ export default function VirtualPostList({
|
|||||||
const virtualizer = useVirtualizer({
|
const virtualizer = useVirtualizer({
|
||||||
count: posts.length,
|
count: posts.length,
|
||||||
getScrollElement,
|
getScrollElement,
|
||||||
estimateSize: () => 108,
|
estimateSize: () => rowEstimate,
|
||||||
overscan: 8,
|
overscan: 8,
|
||||||
scrollMargin: isMobile ? scrollMargin : 0,
|
scrollMargin: isMobile ? scrollMargin : 0,
|
||||||
measureElement:
|
measureElement:
|
||||||
@@ -214,7 +218,7 @@ export default function VirtualPostList({
|
|||||||
return (
|
return (
|
||||||
<div className="post-list-scroll" ref={parentRef}>
|
<div className="post-list-scroll" ref={parentRef}>
|
||||||
{isInitialLoad ? (
|
{isInitialLoad ? (
|
||||||
<PostListSkeleton />
|
<PostListSkeleton listStyle={feedStyle} />
|
||||||
) : isEmpty ? (
|
) : isEmpty ? (
|
||||||
<div className="empty-feed" role="status">
|
<div className="empty-feed" role="status">
|
||||||
{isSearchEmpty
|
{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 { getBoardThemeIndex } from '../../utils/boardTheme';
|
||||||
import type { Board, ForumLimitsPublic } from '../../api/types';
|
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 {
|
interface Props {
|
||||||
isEdit: boolean;
|
isEdit: boolean;
|
||||||
@@ -32,34 +38,93 @@ export default function ComposeContextBar({
|
|||||||
onTagsChange,
|
onTagsChange,
|
||||||
limits,
|
limits,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
|
const isSpecialEdit = isEdit && (postType === 'poll' || postType === 'bounty' || postType === 'lottery');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="compose-context" aria-label="发布设置">
|
<section className="compose-context" aria-label="发布设置">
|
||||||
<div className="compose-context-row">
|
<div className="compose-context-row">
|
||||||
<span className="compose-context-label">类型</span>
|
<span className="compose-context-label">类型</span>
|
||||||
<div className="compose-type-field">
|
<div className="compose-type-field">
|
||||||
<div className="compose-type-pills" role="radiogroup" aria-label="帖子类型">
|
<div className="compose-type-pills" role="radiogroup" aria-label="帖子类型">
|
||||||
<button
|
{isSpecialEdit ? (
|
||||||
type="button"
|
<button
|
||||||
role="radio"
|
type="button"
|
||||||
aria-checked={postType === 'normal'}
|
role="radio"
|
||||||
className={`compose-type-pill${postType === 'normal' ? ' active' : ''}`}
|
aria-checked
|
||||||
onClick={() => onPostTypeChange('normal')}
|
className="compose-type-pill active"
|
||||||
>
|
disabled
|
||||||
讨论
|
>
|
||||||
</button>
|
{SPECIAL_TYPE_LABELS[postType]}
|
||||||
<button
|
</button>
|
||||||
type="button"
|
) : (
|
||||||
role="radio"
|
<>
|
||||||
aria-checked={postType === 'question'}
|
<button
|
||||||
className={`compose-type-pill${postType === 'question' ? ' active' : ''}`}
|
type="button"
|
||||||
onClick={() => onPostTypeChange('question')}
|
role="radio"
|
||||||
>
|
aria-checked={postType === 'normal'}
|
||||||
问答
|
className={`compose-type-pill${postType === 'normal' ? ' active' : ''}`}
|
||||||
</button>
|
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>
|
</div>
|
||||||
{postType === 'question' && (
|
{postType === 'question' && (
|
||||||
<span className="compose-type-hint">问答可标记解决状态</span>
|
<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>
|
</div>
|
||||||
<div className="compose-context-row">
|
<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 { useEffect, useState } from 'react';
|
||||||
import { api } from '../api/client';
|
import { api } from '../api/client';
|
||||||
import type { ForumLimitsPublic } from '../api/types';
|
import type { ForumLimitsPublic } from '../api/types';
|
||||||
|
import { DEFAULT_ASIDE_WIDGETS } from '../api/types';
|
||||||
|
|
||||||
const DEFAULT_LIMITS: ForumLimitsPublic = {
|
const DEFAULT_LIMITS: ForumLimitsPublic = {
|
||||||
post_title_max: 128,
|
post_title_max: 128,
|
||||||
@@ -16,6 +17,11 @@ const DEFAULT_LIMITS: ForumLimitsPublic = {
|
|||||||
signature_max: 200,
|
signature_max: 200,
|
||||||
open_posts_in_new_tab: true,
|
open_posts_in_new_tab: true,
|
||||||
open_content_links_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_enabled: false,
|
||||||
permalink_ext: 'html',
|
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 { useEffect, useState, useCallback, useRef } from 'react';
|
||||||
import { Outlet, NavLink, useNavigate, useLocation } from 'react-router-dom';
|
import { Outlet, NavLink, useNavigate, useLocation } from 'react-router-dom';
|
||||||
import {
|
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';
|
} from 'lucide-react';
|
||||||
import { Spinner } from '@/components/ui/spinner';
|
import { Spinner } from '@/components/ui/spinner';
|
||||||
import { useAuth } from '../hooks/useAuth';
|
import { useAuth } from '../hooks/useAuth';
|
||||||
@@ -16,7 +16,7 @@ import { useNoIndexSEO } from '../hooks/usePageSEO';
|
|||||||
import SiteBrandMark from '../components/SiteBrandMark';
|
import SiteBrandMark from '../components/SiteBrandMark';
|
||||||
import { api } from '../api/client';
|
import { api } from '../api/client';
|
||||||
|
|
||||||
type BadgeKey = 'posts' | 'comments' | 'reports';
|
type BadgeKey = 'posts' | 'comments' | 'reports' | 'links';
|
||||||
|
|
||||||
type NavItem = {
|
type NavItem = {
|
||||||
to: string;
|
to: string;
|
||||||
@@ -50,8 +50,10 @@ const NAV_GROUPS: NavGroup[] = [
|
|||||||
label: '社区',
|
label: '社区',
|
||||||
items: [
|
items: [
|
||||||
{ to: '/admin/boards', label: '板块管理', icon: FolderKanban },
|
{ to: '/admin/boards', label: '板块管理', icon: FolderKanban },
|
||||||
|
{ to: '/admin/pages', label: '单页管理', icon: BookOpen },
|
||||||
{ to: '/admin/users', label: '用户管理', icon: Users },
|
{ to: '/admin/users', label: '用户管理', icon: Users },
|
||||||
{ to: '/admin/badges', label: '徽章管理', icon: Award },
|
{ to: '/admin/badges', label: '徽章管理', icon: Award },
|
||||||
|
{ to: '/admin/links', label: '友情链接', icon: Link2, badgeKey: 'links' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -67,6 +69,7 @@ type PendingCounts = {
|
|||||||
posts: number;
|
posts: number;
|
||||||
comments: number;
|
comments: number;
|
||||||
reports: number;
|
reports: number;
|
||||||
|
links: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
function formatNavBadge(n: number) {
|
function formatNavBadge(n: number) {
|
||||||
@@ -82,7 +85,7 @@ export default function AdminLayout() {
|
|||||||
useNoIndexSEO('管理后台');
|
useNoIndexSEO('管理后台');
|
||||||
const isNarrow = useMediaQuery('(max-width: 768px)');
|
const isNarrow = useMediaQuery('(max-width: 768px)');
|
||||||
const [navOpen, setNavOpen] = useState(false);
|
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 nav = useNavigate();
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const drawerRef = useRef<HTMLElement>(null);
|
const drawerRef = useRef<HTMLElement>(null);
|
||||||
@@ -99,10 +102,23 @@ export default function AdminLayout() {
|
|||||||
posts: d.pending_posts ?? 0,
|
posts: d.pending_posts ?? 0,
|
||||||
comments: d.pending_comments ?? 0,
|
comments: d.pending_comments ?? 0,
|
||||||
reports: d.pending_reports ?? 0,
|
reports: d.pending_reports ?? 0,
|
||||||
|
links: d.pending_friend_links ?? 0,
|
||||||
}))
|
}))
|
||||||
.catch(() => {});
|
.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(() => {
|
useEffect(() => {
|
||||||
if (loading) return;
|
if (loading) return;
|
||||||
if (!user) {
|
if (!user) {
|
||||||
|
|||||||
@@ -14,13 +14,14 @@ import { useAuth } from '../hooks/useAuth';
|
|||||||
import { useTheme, useMediaQuery } from '../hooks/useTheme';
|
import { useTheme, useMediaQuery } from '../hooks/useTheme';
|
||||||
import { useOverlayA11y, moveTabIndex } from '../hooks/useOverlayA11y';
|
import { useOverlayA11y, moveTabIndex } from '../hooks/useOverlayA11y';
|
||||||
import { api } from '../api/client';
|
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 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 Sidebar, { isNeutralSidebarRoute } from '../components/Sidebar';
|
||||||
import RightPanel from '../components/RightPanel';
|
import RightPanel from '../components/RightPanel';
|
||||||
import BackToTop from '../components/BackToTop';
|
import BackToTop from '../components/BackToTop';
|
||||||
import { useForumLimits } from '../hooks/useForumLimits';
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
|
import { resolveAsideWidgets } from '../utils/asideWidgets';
|
||||||
import { buildHomeUrl, parseFeedSort } from '../components/FeedSortBar';
|
import { buildHomeUrl, parseFeedSort } from '../components/FeedSortBar';
|
||||||
import { navigateFeed } from '../utils/feedCache';
|
import { navigateFeed } from '../utils/feedCache';
|
||||||
import { notify } from '@/lib/notify';
|
import { notify } from '@/lib/notify';
|
||||||
@@ -32,6 +33,7 @@ import { useSiteBranding } from '../hooks/useSiteBranding';
|
|||||||
import SiteBrandMark from '../components/SiteBrandMark';
|
import SiteBrandMark from '../components/SiteBrandMark';
|
||||||
import SiteFooter from '../components/SiteFooter';
|
import SiteFooter from '../components/SiteFooter';
|
||||||
import { userPath } from '../utils/userPath';
|
import { userPath } from '../utils/userPath';
|
||||||
|
import { parsePermalinkID } from '../utils/permalink';
|
||||||
|
|
||||||
export default function MainLayout() {
|
export default function MainLayout() {
|
||||||
const { user, loading: authLoading, logout } = useAuth();
|
const { user, loading: authLoading, logout } = useAuth();
|
||||||
@@ -46,7 +48,6 @@ export default function MainLayout() {
|
|||||||
|
|
||||||
const [boards, setBoards] = useState<Board[]>(() => getCachedBoards());
|
const [boards, setBoards] = useState<Board[]>(() => getCachedBoards());
|
||||||
const [stats, setStats] = useState<ForumStats | null>(() => getCachedStats());
|
const [stats, setStats] = useState<ForumStats | null>(() => getCachedStats());
|
||||||
const [hot, setHot] = useState<PostItem[]>(() => getCachedHot());
|
|
||||||
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
|
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
|
||||||
const [unreadMessages, setUnreadMessages] = useState(0);
|
const [unreadMessages, setUnreadMessages] = useState(0);
|
||||||
const [tags, setTags] = useState<TagCount[]>(() => getCachedTags());
|
const [tags, setTags] = useState<TagCount[]>(() => getCachedTags());
|
||||||
@@ -66,7 +67,11 @@ export default function MainLayout() {
|
|||||||
const [asideLoading, setAsideLoading] = useState(() => !hasCachedAside());
|
const [asideLoading, setAsideLoading] = useState(() => !hasCachedAside());
|
||||||
const [boardsLoading, setBoardsLoading] = useState(() => getCachedBoards().length === 0);
|
const [boardsLoading, setBoardsLoading] = useState(() => getCachedBoards().length === 0);
|
||||||
const asideEverLoaded = useRef(false);
|
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 [keyword, setKeyword] = useState(params.get('keyword') || '');
|
||||||
const [searchAuthor, setSearchAuthor] = useState(params.get('author') || '');
|
const [searchAuthor, setSearchAuthor] = useState(params.get('author') || '');
|
||||||
const [searchTitleOnly, setSearchTitleOnly] = useState(params.get('title_only') === '1');
|
const [searchTitleOnly, setSearchTitleOnly] = useState(params.get('title_only') === '1');
|
||||||
@@ -74,6 +79,9 @@ export default function MainLayout() {
|
|||||||
const [searchAdvanced, setSearchAdvanced] = useState(false);
|
const [searchAdvanced, setSearchAdvanced] = useState(false);
|
||||||
const feedSort = parseFeedSort(params.get('sort'));
|
const feedSort = parseFeedSort(params.get('sort'));
|
||||||
const { limits: forumLimits } = useForumLimits();
|
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 asideDrawerRef = useRef<HTMLElement>(null);
|
||||||
const asideCloseRef = useRef<HTMLButtonElement>(null);
|
const asideCloseRef = useRef<HTMLButtonElement>(null);
|
||||||
@@ -99,7 +107,14 @@ export default function MainLayout() {
|
|||||||
initialFocusRef: sidebarCloseRef,
|
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(() => {
|
useEffect(() => {
|
||||||
setKeyword(params.get('keyword') || '');
|
setKeyword(params.get('keyword') || '');
|
||||||
setSearchAuthor(params.get('author') || '');
|
setSearchAuthor(params.get('author') || '');
|
||||||
@@ -183,7 +198,7 @@ export default function MainLayout() {
|
|||||||
|
|
||||||
// 标签云:进页/离开发帖页时拉取;不跟 posts-refresh 联动(置顶/精华等不改标签)
|
// 标签云:进页/离开发帖页时拉取;不跟 posts-refresh 联动(置顶/精华等不改标签)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isCompose) return;
|
if (isCompose || !showTagCloud) return;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
if (getCachedTags().length === 0) setTagsLoading(true);
|
if (getCachedTags().length === 0) setTagsLoading(true);
|
||||||
api.tags(40).then(d => {
|
api.tags(40).then(d => {
|
||||||
@@ -197,31 +212,24 @@ export default function MainLayout() {
|
|||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, [isCompose]);
|
}, [isCompose, showTagCloud]);
|
||||||
|
|
||||||
const needAsideData = !isCompose && (!hideAside || asideOpen);
|
const needAsideData = !isCompose && (!hideAside || asideOpen);
|
||||||
|
const needRecentComments = needAsideData && showRecentComments;
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!needAsideData) return;
|
if (!needRecentComments) return;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
// 无缓存时才显示加载态,有缓存则静默刷新,避免抽屉高度跳动
|
// 无缓存时才显示加载态,有缓存则静默刷新,避免抽屉高度跳动
|
||||||
if (!asideEverLoaded.current && !hasCachedAside()) {
|
if (!asideEverLoaded.current && !hasCachedAside()) {
|
||||||
setAsideLoading(true);
|
setAsideLoading(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
Promise.all([
|
api.recentComments().then(d => {
|
||||||
api.hotPosts().then(d => {
|
if (cancelled) return;
|
||||||
if (cancelled) return;
|
const next = Array.isArray(d.comments) ? d.comments : [];
|
||||||
const next = Array.isArray(d.posts) ? d.posts : [];
|
setRecentComments(next);
|
||||||
setHot(next);
|
setCachedRecentComments(next);
|
||||||
setCachedHot(next);
|
}).catch(() => {}).finally(() => {
|
||||||
}).catch(() => {}),
|
|
||||||
api.recentComments().then(d => {
|
|
||||||
if (cancelled) return;
|
|
||||||
const next = Array.isArray(d.comments) ? d.comments : [];
|
|
||||||
setRecentComments(next);
|
|
||||||
setCachedRecentComments(next);
|
|
||||||
}).catch(() => {}),
|
|
||||||
]).finally(() => {
|
|
||||||
if (!cancelled) {
|
if (!cancelled) {
|
||||||
asideEverLoaded.current = true;
|
asideEverLoaded.current = true;
|
||||||
setAsideLoading(false);
|
setAsideLoading(false);
|
||||||
@@ -231,7 +239,7 @@ export default function MainLayout() {
|
|||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, [needAsideData]);
|
}, [needRecentComments]);
|
||||||
|
|
||||||
const doSearch = () => {
|
const doSearch = () => {
|
||||||
const kw = keyword.trim();
|
const kw = keyword.trim();
|
||||||
@@ -239,7 +247,7 @@ export default function MainLayout() {
|
|||||||
const activeKw = (params.get('keyword') || '').trim();
|
const activeKw = (params.get('keyword') || '').trim();
|
||||||
const activeAuthor = (params.get('author') || '').trim();
|
const activeAuthor = (params.get('author') || '').trim();
|
||||||
const activeTitleOnly = params.get('title_only') === '1';
|
const activeTitleOnly = params.get('title_only') === '1';
|
||||||
const activeBoard = Number(params.get('board')) || 0;
|
const activeBoard = boardId;
|
||||||
if (!kw && !author) {
|
if (!kw && !author) {
|
||||||
if (activeKw || activeAuthor) navigateFeed(nav, '/');
|
if (activeKw || activeAuthor) navigateFeed(nav, '/');
|
||||||
return;
|
return;
|
||||||
@@ -260,9 +268,10 @@ export default function MainLayout() {
|
|||||||
keyword: kw,
|
keyword: kw,
|
||||||
author,
|
author,
|
||||||
titleOnly: !!kw && searchTitleOnly,
|
titleOnly: !!kw && searchTitleOnly,
|
||||||
|
permalink: forumLimits,
|
||||||
});
|
});
|
||||||
const same =
|
const same =
|
||||||
loc.pathname === '/'
|
(loc.pathname === '/' || /^\/board\/\d+/.test(loc.pathname))
|
||||||
&& activeKw === kw
|
&& activeKw === kw
|
||||||
&& activeAuthor === author
|
&& activeAuthor === author
|
||||||
&& activeTitleOnly === (!!kw && searchTitleOnly)
|
&& activeTitleOnly === (!!kw && searchTitleOnly)
|
||||||
@@ -280,7 +289,7 @@ export default function MainLayout() {
|
|||||||
}, [nav, forumLimits.open_posts_in_new_tab]);
|
}, [nav, forumLimits.open_posts_in_new_tab]);
|
||||||
|
|
||||||
const userInitial = user?.nickname?.charAt(0) || '?';
|
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 outletKeyword = params.get('keyword') || '';
|
||||||
const outletTag = params.get('tag') || '';
|
const outletTag = params.get('tag') || '';
|
||||||
const outletAuthor = params.get('author') || '';
|
const outletAuthor = params.get('author') || '';
|
||||||
@@ -318,7 +327,7 @@ export default function MainLayout() {
|
|||||||
|
|
||||||
const selectBoardChip = (id: number) => {
|
const selectBoardChip = (id: number) => {
|
||||||
setBoardId(id);
|
setBoardId(id);
|
||||||
navigateFeed(nav, buildHomeUrl(id, feedSort));
|
navigateFeed(nav, buildHomeUrl(id, feedSort, { permalink: forumLimits }));
|
||||||
};
|
};
|
||||||
|
|
||||||
const onBoardBarKeyDown = (e: React.KeyboardEvent) => {
|
const onBoardBarKeyDown = (e: React.KeyboardEvent) => {
|
||||||
@@ -632,11 +641,12 @@ export default function MainLayout() {
|
|||||||
{!isCompose && (
|
{!isCompose && (
|
||||||
<aside className="aside-panel">
|
<aside className="aside-panel">
|
||||||
<RightPanel
|
<RightPanel
|
||||||
hot={hot}
|
|
||||||
recentComments={recentComments}
|
recentComments={recentComments}
|
||||||
tags={tags}
|
tags={tags}
|
||||||
tagsLoading={tagsLoading}
|
tagsLoading={tagsLoading}
|
||||||
|
stats={stats}
|
||||||
loading={asideLoading}
|
loading={asideLoading}
|
||||||
|
asideWidgets={asideWidgets}
|
||||||
onPostClick={openPost}
|
onPostClick={openPost}
|
||||||
postDetail={isPostDetail ? {
|
postDetail={isPostDetail ? {
|
||||||
author: postOutline?.author ?? null,
|
author: postOutline?.author ?? null,
|
||||||
@@ -746,11 +756,12 @@ export default function MainLayout() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="aside-drawer-body">
|
<div className="aside-drawer-body">
|
||||||
<RightPanel
|
<RightPanel
|
||||||
hot={hot}
|
|
||||||
recentComments={recentComments}
|
recentComments={recentComments}
|
||||||
tags={tags}
|
tags={tags}
|
||||||
tagsLoading={tagsLoading}
|
tagsLoading={tagsLoading}
|
||||||
|
stats={stats}
|
||||||
loading={asideLoading}
|
loading={asideLoading}
|
||||||
|
asideWidgets={asideWidgets}
|
||||||
onPostClick={openPost}
|
onPostClick={openPost}
|
||||||
postDetail={isPostDetail ? {
|
postDetail={isPostDetail ? {
|
||||||
author: postOutline?.author ?? null,
|
author: postOutline?.author ?? null,
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ import type { Board } from '../api/types';
|
|||||||
import { BoardColorPicker, BoardIconPicker } from '../components/BoardAppearancePicker';
|
import { BoardColorPicker, BoardIconPicker } from '../components/BoardAppearancePicker';
|
||||||
import BoardIconDisplay from '../components/BoardIconDisplay';
|
import BoardIconDisplay from '../components/BoardIconDisplay';
|
||||||
import { getBoardThemeIndex } from '../utils/boardTheme';
|
import { getBoardThemeIndex } from '../utils/boardTheme';
|
||||||
|
import AdminSortableList, { SortableDragHandle, SortableMoveButtons } from '../components/admin/AdminSortableList';
|
||||||
|
import { persistSortOrderChanges, shouldShowSortableMoveButtons } from '../utils/sortOrder';
|
||||||
|
|
||||||
const boardSchema = z.object({
|
const boardSchema = z.object({
|
||||||
name: z.string().min(1, '请输入名称').max(64),
|
name: z.string().min(1, '请输入名称').max(64),
|
||||||
@@ -48,6 +50,7 @@ export default function BoardsManagePage() {
|
|||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState<Board | null>(null);
|
const [editing, setEditing] = useState<Board | null>(null);
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [reordering, setReordering] = useState(false);
|
||||||
|
|
||||||
const form = useForm<BoardFormValues>({
|
const form = useForm<BoardFormValues>({
|
||||||
resolver: zodResolver(boardSchema),
|
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) {
|
if (!ready) {
|
||||||
return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
|
return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
|
||||||
}
|
}
|
||||||
@@ -152,60 +181,76 @@ export default function BoardsManagePage() {
|
|||||||
<Table>
|
<Table>
|
||||||
<TableHeader>
|
<TableHeader>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
|
<TableHead className="w-[72px]">排序</TableHead>
|
||||||
<TableHead className="w-[60px]">ID</TableHead>
|
<TableHead className="w-[60px]">ID</TableHead>
|
||||||
<TableHead className="w-[52px]">图标</TableHead>
|
<TableHead className="w-[52px]">图标</TableHead>
|
||||||
<TableHead>名称</TableHead>
|
<TableHead>名称</TableHead>
|
||||||
<TableHead>简介</TableHead>
|
<TableHead>简介</TableHead>
|
||||||
<TableHead className="w-[70px]">排序</TableHead>
|
<TableHead className="w-[70px]">权重</TableHead>
|
||||||
<TableHead className="w-[80px]">帖子数</TableHead>
|
<TableHead className="w-[80px]">帖子数</TableHead>
|
||||||
<TableHead className="w-[160px]">操作</TableHead>
|
<TableHead className="w-[160px]">操作</TableHead>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<AdminSortableList
|
||||||
{boards.map(board => {
|
as={TableBody}
|
||||||
|
items={boards}
|
||||||
|
getId={board => board.id}
|
||||||
|
onReorder={handleBoardReorder}
|
||||||
|
showMoveButtons="auto"
|
||||||
|
renderItem={(board, _index, controls) => {
|
||||||
const themeIdx = getBoardThemeIndex(board);
|
const themeIdx = getBoardThemeIndex(board);
|
||||||
return (
|
return (
|
||||||
<TableRow key={board.id}>
|
<TableRow
|
||||||
<TableCell>{board.id}</TableCell>
|
ref={controls.setNodeRef}
|
||||||
<TableCell>
|
style={controls.style}
|
||||||
<span className={cn('board-table-icon', `sidebar-board-icon--${themeIdx}`)}>
|
className={cn('admin-sortable-table-row', controls.isDragging && 'is-dragging')}
|
||||||
<BoardIconDisplay board={board} />
|
>
|
||||||
</span>
|
<TableCell>
|
||||||
</TableCell>
|
<div className="flex items-center gap-0">
|
||||||
<TableCell><strong>{board.name}</strong></TableCell>
|
<SortableDragHandle label={`拖拽调整「${board.name}」顺序`} {...controls.dragHandleProps} />
|
||||||
<TableCell className="max-w-[200px] truncate">{board.description}</TableCell>
|
{showMoveButtons && <SortableMoveButtons controls={controls} />}
|
||||||
<TableCell>{board.sort_order}</TableCell>
|
</div>
|
||||||
<TableCell><Badge variant="secondary">{board.post_count ?? 0}</Badge></TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>{board.id}</TableCell>
|
||||||
<div className="flex items-center gap-1">
|
<TableCell>
|
||||||
<Button variant="ghost" size="sm" onClick={() => openEdit(board)}>编辑</Button>
|
<span className={cn('board-table-icon', `sidebar-board-icon--${themeIdx}`)}>
|
||||||
<AlertDialog>
|
<BoardIconDisplay board={board} />
|
||||||
<AlertDialogTrigger asChild>
|
</span>
|
||||||
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive">
|
</TableCell>
|
||||||
删除
|
<TableCell><strong>{board.name}</strong></TableCell>
|
||||||
</Button>
|
<TableCell className="max-w-[200px] truncate">{board.description}</TableCell>
|
||||||
</AlertDialogTrigger>
|
<TableCell>{board.sort_order}</TableCell>
|
||||||
<AlertDialogContent>
|
<TableCell><Badge variant="secondary">{board.post_count ?? 0}</Badge></TableCell>
|
||||||
<AlertDialogHeader>
|
<TableCell>
|
||||||
<AlertDialogTitle>确定删除该板块?</AlertDialogTitle>
|
<div className="flex items-center gap-1">
|
||||||
<AlertDialogDescription>
|
<Button variant="ghost" size="sm" onClick={() => openEdit(board)} disabled={reordering}>编辑</Button>
|
||||||
删除后该板块下的帖子将无法通过板块筛选,此操作不可撤销。
|
<AlertDialog>
|
||||||
</AlertDialogDescription>
|
<AlertDialogTrigger asChild>
|
||||||
</AlertDialogHeader>
|
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive" disabled={reordering}>
|
||||||
<AlertDialogFooter>
|
|
||||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
|
||||||
<AlertDialogAction onClick={() => handleDelete(board.id)}>
|
|
||||||
删除
|
删除
|
||||||
</AlertDialogAction>
|
</Button>
|
||||||
</AlertDialogFooter>
|
</AlertDialogTrigger>
|
||||||
</AlertDialogContent>
|
<AlertDialogContent>
|
||||||
</AlertDialog>
|
<AlertDialogHeader>
|
||||||
</div>
|
<AlertDialogTitle>确定删除该板块?</AlertDialogTitle>
|
||||||
</TableCell>
|
<AlertDialogDescription>
|
||||||
</TableRow>
|
删除后该板块下的帖子将无法通过板块筛选,此操作不可撤销。
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||||
|
<AlertDialogAction onClick={() => handleDelete(board.id)}>
|
||||||
|
删除
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
);
|
);
|
||||||
})}
|
}}
|
||||||
</TableBody>
|
/>
|
||||||
</Table>
|
</Table>
|
||||||
{boards.length === 0 && (
|
{boards.length === 0 && (
|
||||||
<div className="empty-state">
|
<div className="empty-state">
|
||||||
|
|||||||
@@ -13,7 +13,16 @@ import { serializeTags, parseTags } from '../components/TagInput';
|
|||||||
import { Spinner } from '@/components/ui/spinner';
|
import { Spinner } from '@/components/ui/spinner';
|
||||||
import ComposeHeader from '../components/compose/ComposeHeader';
|
import ComposeHeader from '../components/compose/ComposeHeader';
|
||||||
import ComposeContextBar, { type PostType } from '../components/compose/ComposeContextBar';
|
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 ComposeDocument from '../components/compose/ComposeDocument';
|
||||||
|
import { sortBoardsForCompose } from '../utils/board';
|
||||||
import { getCachedBoards } from '../utils/layoutCache';
|
import { getCachedBoards } from '../utils/layoutCache';
|
||||||
import type { LayoutCtx } from '../layouts/MainLayout';
|
import type { LayoutCtx } from '../layouts/MainLayout';
|
||||||
import { loginPath } from '../utils/authRedirect';
|
import { loginPath } from '../utils/authRedirect';
|
||||||
@@ -36,8 +45,8 @@ interface ComposeBaseline {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function resolveBoards(ctxBoards?: Board[]): Board[] {
|
function resolveBoards(ctxBoards?: Board[]): Board[] {
|
||||||
if (ctxBoards && ctxBoards.length > 0) return ctxBoards;
|
const raw = ctxBoards && ctxBoards.length > 0 ? ctxBoards : getCachedBoards();
|
||||||
return getCachedBoards();
|
return sortBoardsForCompose(raw);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 格式化剩余可编辑时间 */
|
/** 格式化剩余可编辑时间 */
|
||||||
@@ -74,6 +83,13 @@ export default function ComposePage() {
|
|||||||
const [tags, setTags] = useState('');
|
const [tags, setTags] = useState('');
|
||||||
const [content, setContent] = useState('');
|
const [content, setContent] = useState('');
|
||||||
const [postType, setPostType] = useState<PostType>('normal');
|
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 [publishing, setPublishing] = useState(false);
|
||||||
const [loading, setLoading] = useState(isEdit);
|
const [loading, setLoading] = useState(isEdit);
|
||||||
/** 新建帖:板块列表是否已就绪(避免请求中误显空态) */
|
/** 新建帖:板块列表是否已就绪(避免请求中误显空态) */
|
||||||
@@ -101,7 +117,7 @@ export default function ComposePage() {
|
|||||||
: api.boards();
|
: api.boards();
|
||||||
Promise.all([boardsPromise, api.post(editId!, { skipView: true })])
|
Promise.all([boardsPromise, api.post(editId!, { skipView: true })])
|
||||||
.then(([boardsData, postData]) => {
|
.then(([boardsData, postData]) => {
|
||||||
const list = boardsData.boards ?? [];
|
const list = sortBoardsForCompose(boardsData.boards ?? []);
|
||||||
setBoards(list);
|
setBoards(list);
|
||||||
const post = postData.post;
|
const post = postData.post;
|
||||||
const isOwnerOrAdmin = user.role === 'admin' || post.user_id === user.id;
|
const isOwnerOrAdmin = user.role === 'admin' || post.user_id === user.id;
|
||||||
@@ -116,7 +132,13 @@ export default function ComposePage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const loadedBoardId = String(post.board_id);
|
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 = {
|
const serverBaseline: ComposeBaseline = {
|
||||||
title: post.title,
|
title: post.title,
|
||||||
tags: post.tags ?? '',
|
tags: post.tags ?? '',
|
||||||
@@ -130,6 +152,18 @@ export default function ComposePage() {
|
|||||||
setTags(serverBaseline.tags);
|
setTags(serverBaseline.tags);
|
||||||
setContent(serverBaseline.content);
|
setContent(serverBaseline.content);
|
||||||
setPostType(loadedType);
|
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;
|
const windowHours = postData.post_edit_window_hours ?? 0;
|
||||||
if (user.role !== 'admin' && windowHours > 0) {
|
if (user.role !== 'admin' && windowHours > 0) {
|
||||||
@@ -175,6 +209,13 @@ export default function ComposePage() {
|
|||||||
setTags(draft.tags);
|
setTags(draft.tags);
|
||||||
setContent(draft.content);
|
setContent(draft.content);
|
||||||
setPostType(draft.postType);
|
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);
|
setBaseline(emptyBaseline);
|
||||||
setDraftHint('已恢复本地草稿,编辑中将自动保存');
|
setDraftHint('已恢复本地草稿,编辑中将自动保存');
|
||||||
return;
|
return;
|
||||||
@@ -229,11 +270,18 @@ export default function ComposePage() {
|
|||||||
content,
|
content,
|
||||||
boardId,
|
boardId,
|
||||||
postType,
|
postType,
|
||||||
|
...(postType === 'poll' ? {
|
||||||
|
pollOptions,
|
||||||
|
pollMulti,
|
||||||
|
pollMaxChoices,
|
||||||
|
pollEndsAt,
|
||||||
|
pollNoEndTime,
|
||||||
|
} : {}),
|
||||||
});
|
});
|
||||||
setDraftHint('草稿已自动保存到本机');
|
setDraftHint('草稿已自动保存到本机');
|
||||||
}, 800);
|
}, 800);
|
||||||
return () => window.clearTimeout(timer);
|
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 {
|
const {
|
||||||
dialogOpen,
|
dialogOpen,
|
||||||
@@ -307,15 +355,42 @@ export default function ComposePage() {
|
|||||||
if (!boardId) { notify.warning('请选择板块'); return; }
|
if (!boardId) { notify.warning('请选择板块'); return; }
|
||||||
if (!trimmedTitle) { notify.warning('请输入标题'); return; }
|
if (!trimmedTitle) { notify.warning('请输入标题'); return; }
|
||||||
if (isHtmlEmpty(content)) { 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);
|
setPublishing(true);
|
||||||
try {
|
try {
|
||||||
|
const pollEndsAtISO = postType === 'poll' && !pollNoEndTime
|
||||||
|
? pollEndsAtLocalToISO(pollEndsAt)
|
||||||
|
: null;
|
||||||
const payload = {
|
const payload = {
|
||||||
title: trimmedTitle,
|
title: trimmedTitle,
|
||||||
content: content.trim(),
|
content: content.trim(),
|
||||||
tags: serializeTags(parseTags(tags)),
|
tags: serializeTags(parseTags(tags)),
|
||||||
board_id: boardId,
|
board_id: boardId,
|
||||||
post_type: postType,
|
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) {
|
if (isEdit) {
|
||||||
await api.updatePost(editId!, payload);
|
await api.updatePost(editId!, payload);
|
||||||
@@ -372,6 +447,25 @@ export default function ComposePage() {
|
|||||||
onTagsChange={setTags}
|
onTagsChange={setTags}
|
||||||
limits={limits}
|
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>
|
</ComposeDocument>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
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 { notify } from '@/lib/notify';
|
||||||
import { api } from '../api/client';
|
import { api } from '../api/client';
|
||||||
import type { PostItem } from '../api/types';
|
import type { PostItem } from '../api/types';
|
||||||
@@ -20,17 +20,35 @@ import {
|
|||||||
import { openForumPost } from '../utils/openPost';
|
import { openForumPost } from '../utils/openPost';
|
||||||
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
|
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
|
||||||
import { siteMetaDescription, useSiteBranding } from '../hooks/useSiteBranding';
|
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() {
|
export default function HomePage() {
|
||||||
const nav = useNavigate();
|
const nav = useNavigate();
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
const { id: boardRouteId } = useParams();
|
||||||
const [params] = useSearchParams();
|
const [params] = useSearchParams();
|
||||||
const ctx = useOutletContext<LayoutCtx>();
|
const ctx = useOutletContext<LayoutCtx>();
|
||||||
const { branding } = useSiteBranding();
|
const { branding } = useSiteBranding();
|
||||||
const { limits, loading: limitsLoading } = useForumLimits();
|
const { limits, loading: limitsLoading } = useForumLimits();
|
||||||
const pageSize = Math.max(1, limits.page_size_default);
|
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 keyword = params.get('keyword') || '';
|
||||||
const tag = params.get('tag') || '';
|
const tag = params.get('tag') || '';
|
||||||
const author = params.get('author') || '';
|
const author = params.get('author') || '';
|
||||||
@@ -51,11 +69,30 @@ export default function HomePage() {
|
|||||||
canonicalPath: tag
|
canonicalPath: tag
|
||||||
? `/?tag=${encodeURIComponent(tag)}`
|
? `/?tag=${encodeURIComponent(tag)}`
|
||||||
: boardId
|
: boardId
|
||||||
? `/?board=${boardId}`
|
? boardPath(boardId, limits)
|
||||||
: '/',
|
: '/',
|
||||||
ogType: 'website',
|
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 [posts, setPosts] = useState<PostItem[]>([]);
|
||||||
const [postTotal, setPostTotal] = useState(0);
|
const [postTotal, setPostTotal] = useState(0);
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
@@ -137,7 +174,7 @@ export default function HomePage() {
|
|||||||
|
|
||||||
// 等限制就绪后再拉列表;筛选变化时重载
|
// 等限制就绪后再拉列表;筛选变化时重载
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (limitsLoading) return;
|
if (limitsLoading || isInvalidBoardRoute || isMissingBoard) return;
|
||||||
|
|
||||||
const forceRefresh = (location.state as FeedNavState | null)?.refreshFeed;
|
const forceRefresh = (location.state as FeedNavState | null)?.refreshFeed;
|
||||||
if (forceRefresh) {
|
if (forceRefresh) {
|
||||||
@@ -174,6 +211,8 @@ export default function HomePage() {
|
|||||||
location.state,
|
location.state,
|
||||||
loadFirst,
|
loadFirst,
|
||||||
beginFeedRefresh,
|
beginFeedRefresh,
|
||||||
|
isInvalidBoardRoute,
|
||||||
|
isMissingBoard,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// 筛选未变时同步列表快照;变筛选的那一帧先保留旧快照供 cleanup 写入
|
// 筛选未变时同步列表快照;变筛选的那一帧先保留旧快照供 cleanup 写入
|
||||||
@@ -230,13 +269,22 @@ export default function HomePage() {
|
|||||||
loadFirst();
|
loadFirst();
|
||||||
return;
|
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;
|
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 />;
|
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';
|
} from '@/components/ui/dialog';
|
||||||
import { notify } from '@/lib/notify';
|
import { notify } from '@/lib/notify';
|
||||||
import { api } from '../api/client';
|
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 { REPORT_REASON_OPTIONS } from '../utils/report';
|
||||||
import CommentThreadList from '../components/CommentThreadList';
|
import CommentThreadList from '../components/CommentThreadList';
|
||||||
import CommentBox, { type CommentSubmitData } from '../components/CommentBox';
|
import CommentBox, { type CommentSubmitData } from '../components/CommentBox';
|
||||||
import PostContent from '../components/PostContent';
|
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 PostRevisionPanel from '../components/PostRevisionPanel';
|
||||||
import ArticleOutline from '../components/ArticleOutline';
|
import ArticleOutline from '../components/ArticleOutline';
|
||||||
import { useAuth } from '../hooks/useAuth';
|
import { useAuth } from '../hooks/useAuth';
|
||||||
@@ -81,6 +85,8 @@ export default function PostDetailPage() {
|
|||||||
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
|
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
|
||||||
|
|
||||||
const [post, setPost] = useState<PostItem | null>(null);
|
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 [comments, setComments] = useState<Comment[]>([]);
|
||||||
const [liked, setLiked] = useState(false);
|
const [liked, setLiked] = useState(false);
|
||||||
const [favorited, setFavorited] = useState(false);
|
const [favorited, setFavorited] = useState(false);
|
||||||
@@ -104,6 +110,11 @@ export default function PostDetailPage() {
|
|||||||
const [rejectOpen, setRejectOpen] = useState(false);
|
const [rejectOpen, setRejectOpen] = useState(false);
|
||||||
const [rejectReason, setRejectReason] = useState('');
|
const [rejectReason, setRejectReason] = useState('');
|
||||||
const [rejecting, setRejecting] = useState(false);
|
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 pageRef = useRef<HTMLDivElement>(null);
|
||||||
const commentSectionRef = useRef<HTMLDivElement>(null);
|
const commentSectionRef = useRef<HTMLDivElement>(null);
|
||||||
@@ -189,12 +200,17 @@ export default function PostDetailPage() {
|
|||||||
]);
|
]);
|
||||||
if (seq !== loadSeq.current) return;
|
if (seq !== loadSeq.current) return;
|
||||||
setPost(detail.post);
|
setPost(detail.post);
|
||||||
|
setPoll(detail.poll ?? null);
|
||||||
|
setLottery(detail.lottery ?? null);
|
||||||
setLiked(detail.liked);
|
setLiked(detail.liked);
|
||||||
setFavorited(detail.favorited);
|
setFavorited(detail.favorited);
|
||||||
setCanEdit(detail.can_edit ?? false);
|
setCanEdit(detail.can_edit ?? false);
|
||||||
setIsEdited(detail.is_edited ?? isTimeDiffSignificant(detail.post.created_at, detail.post.updated_at ?? detail.post.created_at));
|
setIsEdited(detail.is_edited ?? isTimeDiffSignificant(detail.post.created_at, detail.post.updated_at ?? detail.post.created_at));
|
||||||
setEditBlockReason(detail.edit_block_reason ?? '');
|
setEditBlockReason(detail.edit_block_reason ?? '');
|
||||||
setEditWindowHours(detail.post_edit_window_hours ?? 0);
|
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 : []);
|
setComments(Array.isArray(comm.comments) ? comm.comments : []);
|
||||||
void refresh();
|
void refresh();
|
||||||
} catch {
|
} catch {
|
||||||
@@ -218,6 +234,11 @@ export default function PostDetailPage() {
|
|||||||
try {
|
try {
|
||||||
const detail = await api.post(postId, { skipView: true });
|
const detail = await api.post(postId, { skipView: true });
|
||||||
setPost(detail.post);
|
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 {
|
} catch {
|
||||||
// 评论已成功,正文刷新失败不阻断
|
// 评论已成功,正文刷新失败不阻断
|
||||||
}
|
}
|
||||||
@@ -547,6 +568,32 @@ export default function PostDetailPage() {
|
|||||||
? formatEditRemaining(post.created_at, editWindowHours)
|
? 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 () => {
|
const handlePin = async () => {
|
||||||
if (!post) return;
|
if (!post) return;
|
||||||
try {
|
try {
|
||||||
@@ -729,6 +776,20 @@ export default function PostDetailPage() {
|
|||||||
{post.question_resolved ? '已解决' : '未解决'}
|
{post.question_resolved ? '已解决' : '未解决'}
|
||||||
</span>
|
</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}
|
{post.title}
|
||||||
</h1>
|
</h1>
|
||||||
<div className="post-detail-author-row">
|
<div className="post-detail-author-row">
|
||||||
@@ -791,6 +852,34 @@ export default function PostDetailPage() {
|
|||||||
</details>
|
</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
|
<PostContent
|
||||||
html={post.content || ''}
|
html={post.content || ''}
|
||||||
isLoggedIn={!!user}
|
isLoggedIn={!!user}
|
||||||
@@ -1078,10 +1167,42 @@ export default function PostDetailPage() {
|
|||||||
inline
|
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>
|
||||||
</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 />
|
<InFlowSiteFooter />
|
||||||
</article>
|
</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,
|
badgeIcon,
|
||||||
formatBadgeCondition,
|
formatBadgeCondition,
|
||||||
} from '../../utils/badgeIcons';
|
} from '../../utils/badgeIcons';
|
||||||
|
import AdminSortableList, { SortableDragHandle, SortableMoveButtons } from '../../components/admin/AdminSortableList';
|
||||||
|
import { mergeReorderedSubset, persistSortOrderChanges, shouldShowSortableMoveButtons } from '../../utils/sortOrder';
|
||||||
|
|
||||||
type KindTab = 'all' | 'auto' | 'limited';
|
type KindTab = 'all' | 'auto' | 'limited';
|
||||||
|
|
||||||
@@ -62,6 +64,7 @@ export default function AdminBadgesPage() {
|
|||||||
const [form, setForm] = useState<Partial<BadgeDef>>({ ...EMPTY });
|
const [form, setForm] = useState<Partial<BadgeDef>>({ ...EMPTY });
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [togglingId, setTogglingId] = useState<number | null>(null);
|
const [togglingId, setTogglingId] = useState<number | null>(null);
|
||||||
|
const [reordering, setReordering] = useState(false);
|
||||||
|
|
||||||
const load = () => {
|
const load = () => {
|
||||||
setLoading(true);
|
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;
|
if (!ready) return null;
|
||||||
|
|
||||||
const PreviewIcon = badgeIcon(form.icon);
|
const PreviewIcon = badgeIcon(form.icon);
|
||||||
@@ -249,14 +273,30 @@ export default function AdminBadgesPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="admin-badge-grid">
|
<AdminSortableList
|
||||||
{filtered.map(b => {
|
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);
|
const Icon = badgeIcon(b.icon);
|
||||||
return (
|
return (
|
||||||
<article
|
<article
|
||||||
key={b.id}
|
ref={controls.setNodeRef}
|
||||||
className={cn('admin-badge-card', !b.enabled && 'is-disabled')}
|
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="admin-badge-card-top">
|
||||||
<div className={cn('admin-badge-preview', b.kind === 'limited' && 'is-limited')}>
|
<div className={cn('admin-badge-preview', b.kind === 'limited' && 'is-limited')}>
|
||||||
<Icon size={22} aria-hidden />
|
<Icon size={22} aria-hidden />
|
||||||
@@ -283,15 +323,16 @@ export default function AdminBadgesPage() {
|
|||||||
{formatBadgeCondition(b)}
|
{formatBadgeCondition(b)}
|
||||||
</span>
|
</span>
|
||||||
<div className="admin-badge-card-actions">
|
<div className="admin-badge-card-actions">
|
||||||
|
{showMoveButtons && <SortableMoveButtons controls={controls} />}
|
||||||
<label className="admin-badge-switch" title={b.enabled ? '点击停用' : '点击启用'}>
|
<label className="admin-badge-switch" title={b.enabled ? '点击停用' : '点击启用'}>
|
||||||
<span className="sr-only">启用</span>
|
<span className="sr-only">启用</span>
|
||||||
<Switch
|
<Switch
|
||||||
checked={b.enabled}
|
checked={b.enabled}
|
||||||
disabled={togglingId === b.id}
|
disabled={togglingId === b.id || reordering}
|
||||||
onCheckedChange={() => toggleEnabled(b)}
|
onCheckedChange={() => toggleEnabled(b)}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<Button size="sm" variant="outline" onClick={() => openEdit(b)}>
|
<Button size="sm" variant="outline" onClick={() => openEdit(b)} disabled={reordering}>
|
||||||
<Pencil size={13} />
|
<Pencil size={13} />
|
||||||
编辑
|
编辑
|
||||||
</Button>
|
</Button>
|
||||||
@@ -299,8 +340,8 @@ export default function AdminBadgesPage() {
|
|||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
);
|
);
|
||||||
})}
|
}}
|
||||||
</div>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Dialog open={dialogOpen} onOpenChange={(open) => {
|
<Dialog open={dialogOpen} onOpenChange={(open) => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
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 { Spinner } from '@/components/ui/spinner';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { api } from '../../api/client';
|
import { api } from '../../api/client';
|
||||||
@@ -29,7 +29,8 @@ export default function AdminDashboardPage() {
|
|||||||
const pendingPosts = data.pending_posts ?? 0;
|
const pendingPosts = data.pending_posts ?? 0;
|
||||||
const pendingComments = data.pending_comments ?? 0;
|
const pendingComments = data.pending_comments ?? 0;
|
||||||
const pendingReports = data.pending_reports ?? 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 = [
|
const stats = [
|
||||||
{ label: '注册用户', value: data.users },
|
{ label: '注册用户', value: data.users },
|
||||||
@@ -63,6 +64,14 @@ export default function AdminDashboardPage() {
|
|||||||
to: '/admin/reports',
|
to: '/admin/reports',
|
||||||
icon: Flag,
|
icon: Flag,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'links',
|
||||||
|
label: '待审友链',
|
||||||
|
count: pendingFriendLinks,
|
||||||
|
hint: '用户提交的友情链接申请',
|
||||||
|
to: '/admin/links',
|
||||||
|
icon: Link2,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
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 { invalidateForumLimitsCache } from '../../hooks/useForumLimits';
|
||||||
import { DEFAULT_BRANDING, seedSiteBrandingCache } from '../../hooks/useSiteBranding';
|
import { DEFAULT_BRANDING, seedSiteBrandingCache } from '../../hooks/useSiteBranding';
|
||||||
import { clearAllFeedCache } from '../../utils/feedCache';
|
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';
|
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 }[] = [
|
const NAV_TOGGLES: { key: BoolLimitKey; label: string; hint: string }[] = [
|
||||||
{
|
{
|
||||||
@@ -241,6 +246,7 @@ export default function AdminSettingsPage() {
|
|||||||
const { ready } = useAdminGuard();
|
const { ready } = useAdminGuard();
|
||||||
const [settings, setSettings] = useState<AdminSettings | null>(null);
|
const [settings, setSettings] = useState<AdminSettings | null>(null);
|
||||||
const [limits, setLimits] = useState<ForumLimits | 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 [branding, setBranding] = useState<SiteBranding>(DEFAULT_BRANDING);
|
||||||
const [mail, setMail] = useState<MailConfig>(EMPTY_MAIL);
|
const [mail, setMail] = useState<MailConfig>(EMPTY_MAIL);
|
||||||
const [oidc, setOidc] = useState<OIDCConfig>(EMPTY_OIDC);
|
const [oidc, setOidc] = useState<OIDCConfig>(EMPTY_OIDC);
|
||||||
@@ -277,13 +283,28 @@ export default function AdminSettingsPage() {
|
|||||||
api.adminSettings()
|
api.adminSettings()
|
||||||
.then(s => {
|
.then(s => {
|
||||||
setSettings(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_posts_in_new_tab: true,
|
||||||
open_content_links_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_enabled: false,
|
||||||
permalink_ext: 'html',
|
permalink_ext: 'html',
|
||||||
...s.limits,
|
...s.limits,
|
||||||
});
|
};
|
||||||
|
setLimits(mergeForumLimitsWithAsideWidgets(baseLimits, loadedAsideWidgets));
|
||||||
setBranding({ ...DEFAULT_BRANDING, ...(s.branding ?? {}) });
|
setBranding({ ...DEFAULT_BRANDING, ...(s.branding ?? {}) });
|
||||||
setMail({ ...EMPTY_MAIL, ...s.mail, password: '' });
|
setMail({ ...EMPTY_MAIL, ...s.mail, password: '' });
|
||||||
setOidc({ ...EMPTY_OIDC, ...(s.oidc ?? {}) });
|
setOidc({ ...EMPTY_OIDC, ...(s.oidc ?? {}) });
|
||||||
@@ -306,6 +327,20 @@ export default function AdminSettingsPage() {
|
|||||||
setLimits(prev => prev ? { ...prev, [key]: checked } : prev);
|
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) => {
|
const applyBranding = (next: SiteBranding) => {
|
||||||
setBranding({ ...DEFAULT_BRANDING, ...next });
|
setBranding({ ...DEFAULT_BRANDING, ...next });
|
||||||
setSettings(s => s ? { ...s, branding: next } : s);
|
setSettings(s => s ? { ...s, branding: next } : s);
|
||||||
@@ -314,21 +349,15 @@ export default function AdminSettingsPage() {
|
|||||||
|
|
||||||
const handleSaveBranding = async () => {
|
const handleSaveBranding = async () => {
|
||||||
if (!limits) return;
|
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);
|
setSavingBranding(true);
|
||||||
try {
|
try {
|
||||||
const r = await api.adminUpdateBranding({ ...branding, friend_links: links });
|
const r = await api.adminUpdateBranding(branding);
|
||||||
applyBranding(r.branding);
|
applyBranding(r.branding);
|
||||||
// 伪静态与品牌同属站点呈现,一并保存
|
const forumPayload = mergeForumLimitsWithAsideWidgets(limits, asideWidgets);
|
||||||
const forum = await api.adminUpdateForumSettings(limits);
|
// 伪静态、右侧栏、浏览与链接、列表呈现同属站点呈现,一并保存
|
||||||
setLimits(forum.limits);
|
const forum = await api.adminUpdateForumSettings(forumPayload);
|
||||||
invalidateForumLimitsCache();
|
applySavedForumLimits(asideWidgets, forum.limits);
|
||||||
|
clearAllFeedCache();
|
||||||
notify.success('站点设置已保存');
|
notify.success('站点设置已保存');
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
notify.error(e instanceof Error ? e.message : '保存失败');
|
notify.error(e instanceof Error ? e.message : '保存失败');
|
||||||
@@ -368,12 +397,13 @@ export default function AdminSettingsPage() {
|
|||||||
if (!limits) return;
|
if (!limits) return;
|
||||||
setSavingForum(true);
|
setSavingForum(true);
|
||||||
try {
|
try {
|
||||||
const r = await api.adminUpdateForumSettings(limits);
|
const forumPayload = mergeForumLimitsWithAsideWidgets(limits, asideWidgets);
|
||||||
|
const r = await api.adminUpdateForumSettings(forumPayload);
|
||||||
notify.success(r.message);
|
notify.success(r.message);
|
||||||
invalidateForumLimitsCache();
|
invalidateForumLimitsCache();
|
||||||
clearAllFeedCache();
|
clearAllFeedCache();
|
||||||
setLimits(r.limits);
|
const merged = applySavedForumLimits(asideWidgets, r.limits);
|
||||||
setSettings(s => s ? { ...s, limits: r.limits } : s);
|
setSettings(s => s ? { ...s, limits: merged } : s);
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
notify.error(e instanceof Error ? e.message : '保存失败');
|
notify.error(e instanceof Error ? e.message : '保存失败');
|
||||||
} finally {
|
} finally {
|
||||||
@@ -645,7 +675,7 @@ export default function AdminSettingsPage() {
|
|||||||
<section className="admin-settings-section" id="settings-brand-identity">
|
<section className="admin-settings-section" id="settings-brand-identity">
|
||||||
<div className="admin-settings-section-head">
|
<div className="admin-settings-section-head">
|
||||||
<h3>品牌标识</h3>
|
<h3>品牌标识</h3>
|
||||||
<p>名称、标语、简介与字标;简介用于首页展示与搜索引擎 description</p>
|
<p>名称、标语、简介与字标;简介用于右侧栏顶部展示与搜索引擎 description</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-mail-grid">
|
<div className="admin-mail-grid">
|
||||||
<div className="admin-mail-field">
|
<div className="admin-mail-field">
|
||||||
@@ -691,7 +721,7 @@ export default function AdminSettingsPage() {
|
|||||||
rows={3}
|
rows={3}
|
||||||
/>
|
/>
|
||||||
<span className="admin-mail-field-hint">
|
<span className="admin-mail-field-hint">
|
||||||
用于右侧栏介绍与 SEO description;未填写时回退到标语(建议 80–160 字)
|
用于右侧栏顶部论坛简介与 SEO description;未填写时回退到标语(建议 80–160 字)
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-mail-field admin-mail-field--span2">
|
<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">
|
<section className="admin-settings-section" id="settings-brand-footer">
|
||||||
<div className="admin-settings-section-head">
|
<div className="admin-settings-section-head">
|
||||||
<h3>页脚信息</h3>
|
<h3>页脚信息</h3>
|
||||||
<p>备案号与友情链接,显示在站点底部</p>
|
<p>备案号显示在站点底部;友情链接请在「社区 → 友情链接」管理</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-mail-grid">
|
<div className="admin-mail-grid">
|
||||||
<div className="admin-mail-field">
|
<div className="admin-mail-field">
|
||||||
@@ -835,69 +865,81 @@ export default function AdminSettingsPage() {
|
|||||||
<span className="admin-mail-field-hint">留空则用工信部默认页</span>
|
<span className="admin-mail-field-hint">留空则用工信部默认页</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-friend-links" style={{ marginTop: 12 }}>
|
</section>
|
||||||
<div className="admin-friend-links-list">
|
|
||||||
{(branding.friend_links ?? []).map((link, idx) => (
|
<section className="admin-settings-section" id="settings-aside">
|
||||||
<div key={idx} className="admin-friend-links-row">
|
<div className="admin-settings-section-head">
|
||||||
<Input
|
<h3>右侧栏组件</h3>
|
||||||
value={link.name}
|
<p>「站点简介」固定在最上方;以下模块可拖拽排序,保存后同步影响桌面右侧栏与手机「社区动态」抽屉</p>
|
||||||
placeholder="友链名称"
|
</div>
|
||||||
maxLength={32}
|
<AsideWidgetList
|
||||||
onChange={e => {
|
widgets={asideWidgets}
|
||||||
const name = e.target.value;
|
onChange={handleAsideWidgetsChange}
|
||||||
setBranding(b => {
|
/>
|
||||||
const next = [...(b.friend_links ?? [])];
|
</section>
|
||||||
next[idx] = { ...next[idx], name };
|
|
||||||
return { ...b, friend_links: next };
|
<section className="admin-settings-section" id="settings-nav">
|
||||||
});
|
<div className="admin-settings-section-head">
|
||||||
}}
|
<h3>浏览与链接</h3>
|
||||||
/>
|
<p>控制打开帖子与正文链接时是否新开浏览器标签页</p>
|
||||||
<Input
|
</div>
|
||||||
value={link.url}
|
<div className="admin-settings-table" role="group" aria-label="浏览与链接">
|
||||||
placeholder="https://example.com"
|
{NAV_TOGGLES.map(row => (
|
||||||
maxLength={512}
|
<div key={row.key} className="admin-settings-row">
|
||||||
onChange={e => {
|
<span className="admin-settings-row-label" id={`limit-label-${row.key}`}>
|
||||||
const url = e.target.value;
|
{row.label}
|
||||||
setBranding(b => {
|
</span>
|
||||||
const next = [...(b.friend_links ?? [])];
|
<div className="admin-settings-row-input">
|
||||||
next[idx] = { ...next[idx], url };
|
<button
|
||||||
return { ...b, friend_links: next };
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
id={`limit-${row.key}`}
|
||||||
size="sm"
|
role="switch"
|
||||||
onClick={() => {
|
aria-checked={!!limits[row.key]}
|
||||||
setBranding(b => ({
|
aria-labelledby={`limit-label-${row.key}`}
|
||||||
...b,
|
className={`admin-settings-switch${limits[row.key] ? ' is-on' : ''}`}
|
||||||
friend_links: (b.friend_links ?? []).filter((_, i) => i !== idx),
|
onClick={() => handleBoolLimitChange(row.key, !limits[row.key])}
|
||||||
}));
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
删除
|
<span className="admin-settings-switch-ui" aria-hidden />
|
||||||
</Button>
|
</button>
|
||||||
</div>
|
</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>
|
</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>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -968,7 +1010,7 @@ export default function AdminSettingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-settings-bar">
|
<div className="admin-settings-bar">
|
||||||
<p>保存后立即影响顶栏、页脚、伪静态链接与浏览器标题</p>
|
<p>保存后立即影响顶栏、页脚、列表样式、链接打开方式、伪静态链接与浏览器标题</p>
|
||||||
<Button onClick={handleSaveBranding} loading={savingBranding}>
|
<Button onClick={handleSaveBranding} loading={savingBranding}>
|
||||||
保存站点设置
|
保存站点设置
|
||||||
</Button>
|
</Button>
|
||||||
@@ -981,39 +1023,10 @@ export default function AdminSettingsPage() {
|
|||||||
<div className="admin-card admin-settings-card">
|
<div className="admin-card admin-settings-card">
|
||||||
<div className="admin-card-head">
|
<div className="admin-card-head">
|
||||||
<span>论坛限制</span>
|
<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>
|
||||||
<div className="admin-card-body">
|
<div className="admin-card-body">
|
||||||
<SettingTable sections={SETTING_SECTIONS} limits={limits} onChange={handleLimitChange} />
|
<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>
|
</div>
|
||||||
<div className="admin-settings-bar">
|
<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'];
|
const BOARD_COLORS = ['#2d8a55', '#3498db', '#9b59b6', '#e67e22', '#1abc9c', '#e74c3c', '#34495e'];
|
||||||
|
|
||||||
@@ -8,3 +10,30 @@ export function boardColor(id: number) {
|
|||||||
export function boardInitial(name: string) {
|
export function boardInitial(name: string) {
|
||||||
return (name?.trim()?.[0] || '?').toUpperCase();
|
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) */
|
/** 新建帖本地草稿(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 = {
|
export type ComposeDraft = {
|
||||||
title: string;
|
title: string;
|
||||||
tags: string;
|
tags: string;
|
||||||
content: string;
|
content: string;
|
||||||
boardId: string;
|
boardId: string;
|
||||||
postType: 'normal' | 'question';
|
postType: ComposeDraftPostType;
|
||||||
|
pollOptions?: string[];
|
||||||
|
pollMulti?: boolean;
|
||||||
|
pollMaxChoices?: number;
|
||||||
|
pollEndsAt?: string;
|
||||||
|
pollNoEndTime?: boolean;
|
||||||
savedAt: number;
|
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 {
|
export function loadComposeDraft(): ComposeDraft | null {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(STORAGE_KEY);
|
const raw = localStorage.getItem(STORAGE_KEY);
|
||||||
if (!raw) return null;
|
if (!raw) return null;
|
||||||
const data = JSON.parse(raw) as Partial<ComposeDraft>;
|
const data = JSON.parse(raw) as Partial<ComposeDraft>;
|
||||||
if (!data || typeof data !== 'object') return null;
|
if (!data || typeof data !== 'object') return null;
|
||||||
return {
|
const postType = normalizePostType(data.postType);
|
||||||
|
const draft: ComposeDraft = {
|
||||||
title: typeof data.title === 'string' ? data.title : '',
|
title: typeof data.title === 'string' ? data.title : '',
|
||||||
tags: typeof data.tags === 'string' ? data.tags : '',
|
tags: typeof data.tags === 'string' ? data.tags : '',
|
||||||
content: typeof data.content === 'string' ? data.content : '',
|
content: typeof data.content === 'string' ? data.content : '',
|
||||||
boardId: typeof data.boardId === 'string' ? data.boardId : '',
|
boardId: typeof data.boardId === 'string' ? data.boardId : '',
|
||||||
postType: data.postType === 'question' ? 'question' : 'normal',
|
postType,
|
||||||
savedAt: typeof data.savedAt === 'number' ? data.savedAt : Date.now(),
|
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 {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -42,6 +71,8 @@ export function saveComposeDraft(draft: Omit<ComposeDraft, 'savedAt'>): void {
|
|||||||
export function clearComposeDraft(): void {
|
export function clearComposeDraft(): void {
|
||||||
try {
|
try {
|
||||||
localStorage.removeItem(STORAGE_KEY);
|
localStorage.removeItem(STORAGE_KEY);
|
||||||
|
// 清理旧版草稿键
|
||||||
|
localStorage.removeItem('j13-compose-draft-v1');
|
||||||
} catch {
|
} catch {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
@@ -50,10 +81,14 @@ export function clearComposeDraft(): void {
|
|||||||
/** 草稿是否有实质内容 */
|
/** 草稿是否有实质内容 */
|
||||||
export function composeDraftHasContent(d: ComposeDraft | null | undefined): boolean {
|
export function composeDraftHasContent(d: ComposeDraft | null | undefined): boolean {
|
||||||
if (!d) return false;
|
if (!d) return false;
|
||||||
|
const hasPollOptions = d.postType === 'poll'
|
||||||
|
&& Array.isArray(d.pollOptions)
|
||||||
|
&& d.pollOptions.some(o => o.trim());
|
||||||
return !!(
|
return !!(
|
||||||
d.title.trim()
|
d.title.trim()
|
||||||
|| d.tags.trim()
|
|| d.tags.trim()
|
||||||
|| d.content.trim()
|
|| d.content.trim()
|
||||||
|| (d.content && d.content.replace(/<[^>]*>/g, '').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 BOARDS_KEY = 'j13-cache-boards';
|
||||||
const STATS_KEY = 'j13-cache-stats';
|
const STATS_KEY = 'j13-cache-stats';
|
||||||
const HOT_KEY = 'j13-cache-hot';
|
|
||||||
const RECENT_COMMENTS_KEY = 'j13-cache-recent-comments';
|
const RECENT_COMMENTS_KEY = 'j13-cache-recent-comments';
|
||||||
const TAGS_KEY = 'j13-cache-tags';
|
const TAGS_KEY = 'j13-cache-tags';
|
||||||
|
|
||||||
@@ -33,12 +32,6 @@ export function getCachedStats(): ForumStats | null {
|
|||||||
return readJson<ForumStats>(STATS_KEY);
|
return readJson<ForumStats>(STATS_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 读取缓存的热门帖子,避免右栏/抽屉首屏高度跳动 */
|
|
||||||
export function getCachedHot(): PostItem[] {
|
|
||||||
const list = readJson<PostItem[]>(HOT_KEY);
|
|
||||||
return Array.isArray(list) ? list : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 读取缓存的最新评论,避免右栏/抽屉首屏高度跳动 */
|
/** 读取缓存的最新评论,避免右栏/抽屉首屏高度跳动 */
|
||||||
export function getCachedRecentComments(): RecentComment[] {
|
export function getCachedRecentComments(): RecentComment[] {
|
||||||
const list = readJson<RecentComment[]>(RECENT_COMMENTS_KEY);
|
const list = readJson<RecentComment[]>(RECENT_COMMENTS_KEY);
|
||||||
@@ -54,7 +47,7 @@ export function getCachedTags(): TagCount[] {
|
|||||||
/** 右栏是否已有可展示的 session 缓存(含空列表) */
|
/** 右栏是否已有可展示的 session 缓存(含空列表) */
|
||||||
export function hasCachedAside(): boolean {
|
export function hasCachedAside(): boolean {
|
||||||
try {
|
try {
|
||||||
return sessionStorage.getItem(HOT_KEY) != null || sessionStorage.getItem(RECENT_COMMENTS_KEY) != null;
|
return sessionStorage.getItem(RECENT_COMMENTS_KEY) != null;
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -68,10 +61,6 @@ export function setCachedStats(stats: ForumStats) {
|
|||||||
writeJson(STATS_KEY, stats);
|
writeJson(STATS_KEY, stats);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setCachedHot(posts: PostItem[]) {
|
|
||||||
writeJson(HOT_KEY, posts);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setCachedRecentComments(list: RecentComment[]) {
|
export function setCachedRecentComments(list: RecentComment[]) {
|
||||||
writeJson(RECENT_COMMENTS_KEY, list);
|
writeJson(RECENT_COMMENTS_KEY, list);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,6 +30,25 @@ export function userPath(id: number | string, opts?: PermalinkOpts): string {
|
|||||||
return `/user/${id}${suffix(opts)}`;
|
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) */
|
/** 从路由参数解析数字 ID(兼容 123 / 123.html) */
|
||||||
export function parsePermalinkID(raw: string | undefined): number {
|
export function parsePermalinkID(raw: string | undefined): number {
|
||||||
if (!raw) return NaN;
|
if (!raw) return NaN;
|
||||||
@@ -39,13 +58,17 @@ export function parsePermalinkID(raw: string | undefined): number {
|
|||||||
|
|
||||||
/** 客户端:若当前 URL 非规范伪静态路径则返回应跳转的目标 */
|
/** 客户端:若当前 URL 非规范伪静态路径则返回应跳转的目标 */
|
||||||
export function canonicalRedirectPath(
|
export function canonicalRedirectPath(
|
||||||
kind: 'post' | 'user',
|
kind: 'post' | 'user' | 'board',
|
||||||
id: number,
|
id: number,
|
||||||
currentPathname: string,
|
currentPathname: string,
|
||||||
opts?: PermalinkOpts,
|
opts?: PermalinkOpts,
|
||||||
): string | null {
|
): string | null {
|
||||||
if (!id || Number.isNaN(id)) return 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 cur = currentPathname.replace(/\/$/, '') || '/';
|
||||||
const want = target.replace(/\/$/, '') || '/';
|
const want = target.replace(/\/$/, '') || '/';
|
||||||
return cur === want ? null : target;
|
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;
|
||||||
|
}
|
||||||
@@ -70,12 +70,16 @@ func (h *Handlers) APIHealth(c *gin.Context) {
|
|||||||
|
|
||||||
// APIStats 论坛概览统计
|
// APIStats 论坛概览统计
|
||||||
func (h *Handlers) APIStats(c *gin.Context) {
|
func (h *Handlers) APIStats(c *gin.Context) {
|
||||||
var userCount, postCount, boardCount int64
|
var userCount, postCount, boardCount, commentCount int64
|
||||||
model.DB.Model(&model.User{}).Count(&userCount)
|
model.DB.Model(&model.User{}).Count(&userCount)
|
||||||
model.DB.Model(&model.Post{}).Where("status = ?", model.ContentStatusPublished).Count(&postCount)
|
model.DB.Model(&model.Post{}).Where("status = ?", model.ContentStatusPublished).Count(&postCount)
|
||||||
model.DB.Model(&model.Board{}).Count(&boardCount)
|
model.DB.Model(&model.Board{}).Count(&boardCount)
|
||||||
|
model.DB.Model(&model.Comment{}).Where("status = ?", model.ContentStatusPublished).Count(&commentCount)
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"users": userCount, "posts": postCount, "boards": boardCount,
|
"users": userCount,
|
||||||
|
"posts": postCount,
|
||||||
|
"boards": boardCount,
|
||||||
|
"comments": commentCount,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,6 +151,7 @@ func (h *Handlers) APIAdminDashboard(c *gin.Context) {
|
|||||||
pendingPosts, _ := h.Post.PendingPostCount()
|
pendingPosts, _ := h.Post.PendingPostCount()
|
||||||
pendingComments, _ := h.Comment.PendingCommentCount()
|
pendingComments, _ := h.Comment.PendingCommentCount()
|
||||||
pendingReports, _ := h.Report.PendingCount()
|
pendingReports, _ := h.Report.PendingCount()
|
||||||
|
pendingFriendLinks, _ := h.FriendLinkApply.PendingCount()
|
||||||
recentPosts, _, _ := h.Post.List(service.PostListQuery{
|
recentPosts, _, _ := h.Post.List(service.PostListQuery{
|
||||||
Page: 1, Size: 8, ViewerIsAdmin: true, Status: "all",
|
Page: 1, Size: 8, ViewerIsAdmin: true, Status: "all",
|
||||||
})
|
})
|
||||||
@@ -159,6 +164,7 @@ func (h *Handlers) APIAdminDashboard(c *gin.Context) {
|
|||||||
"pending_posts": pendingPosts,
|
"pending_posts": pendingPosts,
|
||||||
"pending_comments": pendingComments,
|
"pending_comments": pendingComments,
|
||||||
"pending_reports": pendingReports,
|
"pending_reports": pendingReports,
|
||||||
|
"pending_friend_links": pendingFriendLinks,
|
||||||
"recent_posts": recentPosts,
|
"recent_posts": recentPosts,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -575,7 +581,9 @@ func (h *Handlers) APIAdminSettings(c *gin.Context) {
|
|||||||
|
|
||||||
// APISiteBranding 前台公开的站点品牌配置
|
// APISiteBranding 前台公开的站点品牌配置
|
||||||
func (h *Handlers) APISiteBranding(c *gin.Context) {
|
func (h *Handlers) APISiteBranding(c *gin.Context) {
|
||||||
c.JSON(http.StatusOK, h.Settings.SiteBranding())
|
brand := h.Settings.SiteBranding()
|
||||||
|
brand.SiteURL = h.publicBaseURL(c)
|
||||||
|
c.JSON(http.StatusOK, brand)
|
||||||
}
|
}
|
||||||
|
|
||||||
// APIAdminUpdateBranding 更新站点品牌文案
|
// APIAdminUpdateBranding 更新站点品牌文案
|
||||||
@@ -1039,7 +1047,7 @@ func (h *Handlers) APIPostDetail(c *gin.Context) {
|
|||||||
editReason = h.Post.UserEditBlockReason(post, uid, isAdmin)
|
editReason = h.Post.UserEditBlockReason(post, uid, isAdmin)
|
||||||
}
|
}
|
||||||
isEdited := post.UpdatedAt.Sub(post.CreatedAt) > time.Minute
|
isEdited := post.UpdatedAt.Sub(post.CreatedAt) > time.Minute
|
||||||
c.JSON(http.StatusOK, gin.H{
|
resp := gin.H{
|
||||||
"post": post,
|
"post": post,
|
||||||
"comment_count": len(comments),
|
"comment_count": len(comments),
|
||||||
"liked": h.Post.IsLiked(uid, uint(id)),
|
"liked": h.Post.IsLiked(uid, uint(id)),
|
||||||
@@ -1049,7 +1057,26 @@ func (h *Handlers) APIPostDetail(c *gin.Context) {
|
|||||||
"edit_block_reason": editReason,
|
"edit_block_reason": editReason,
|
||||||
"is_edited": isEdited,
|
"is_edited": isEdited,
|
||||||
"post_edit_window_hours": h.Settings.PostEditWindowHours(),
|
"post_edit_window_hours": h.Settings.PostEditWindowHours(),
|
||||||
})
|
}
|
||||||
|
if post.PostType == model.PostTypePoll {
|
||||||
|
if poll, err := service.GetPollView(uint(id), uid); err == nil {
|
||||||
|
resp["poll"] = poll
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if post.PostType == model.PostTypeLottery {
|
||||||
|
if lottery, err := service.GetPostLotteryView(post); err == nil && lottery != nil {
|
||||||
|
resp["lottery"] = lottery
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if post.PostType == model.PostTypeBounty && post.BountyStatus == model.BountyStatusOpen && post.BountyPoints > 0 {
|
||||||
|
canRefund, blockReason := service.CanRefundBounty(post, isAdmin)
|
||||||
|
resp["bounty_can_refund"] = canRefund
|
||||||
|
resp["bounty_refund_block_reason"] = blockReason
|
||||||
|
if n, err := service.CountEligibleBountyReplies(model.DB, post.ID, post.UserID); err == nil {
|
||||||
|
resp["bounty_eligible_reply_count"] = n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
// APIPostComments 楼层列表
|
// APIPostComments 楼层列表
|
||||||
|
|||||||
@@ -39,6 +39,16 @@ func (h *Handlers) APIMePoints(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// APIMeCheckInGet 今日签到状态
|
||||||
|
func (h *Handlers) APIMeCheckInGet(c *gin.Context) {
|
||||||
|
st, err := h.Points.GetCheckInStatus(h.currentUserID(c))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"check_in": st})
|
||||||
|
}
|
||||||
|
|
||||||
// APIMeCheckIn 每日签到
|
// APIMeCheckIn 每日签到
|
||||||
func (h *Handlers) APIMeCheckIn(c *gin.Context) {
|
func (h *Handlers) APIMeCheckIn(c *gin.Context) {
|
||||||
st, err := h.Points.CheckIn(h.currentUserID(c))
|
st, err := h.Points.CheckIn(h.currentUserID(c))
|
||||||
|
|||||||
244
handler/friend_link.go
Normal file
244
handler/friend_link.go
Normal file
@@ -0,0 +1,244 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/service"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// APIApplyFriendLink 提交友情链接申请
|
||||||
|
func (h *Handlers) APIApplyFriendLink(c *gin.Context) {
|
||||||
|
uid := h.currentUserID(c)
|
||||||
|
if uid == 0 {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
Logo string `json:"logo"`
|
||||||
|
LinkOnHomepage bool `json:"link_on_homepage"`
|
||||||
|
ReciprocalPageURL string `json:"reciprocal_page_url"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result, err := h.FriendLinkApply.Create(service.FriendLinkApplyInput{
|
||||||
|
UserID: uid,
|
||||||
|
Name: req.Name,
|
||||||
|
URL: req.URL,
|
||||||
|
Logo: req.Logo,
|
||||||
|
LinkOnHomepage: req.LinkOnHomepage,
|
||||||
|
ReciprocalPageURL: req.ReciprocalPageURL,
|
||||||
|
OurSiteURL: h.publicBaseURL(c),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resp := gin.H{
|
||||||
|
"message": friendLinkApplySubmittedMessage(h.Settings.FriendLinkReciprocalCheckEnabled(), false),
|
||||||
|
"apply": result.Apply,
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIUploadFriendLinkLogo 上传友链申请 LOGO
|
||||||
|
func (h *Handlers) APIUploadFriendLinkLogo(c *gin.Context) {
|
||||||
|
uid := h.currentUserID(c)
|
||||||
|
if uid == 0 {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
file, err := c.FormFile("logo")
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请选择 LOGO 图片"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
maxBytes := int64(h.Settings.AvatarMaxMB()) * 1024 * 1024
|
||||||
|
if file.Size > maxBytes {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "图片文件过大"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
url, err := service.SaveUploadedImage(
|
||||||
|
h.Store,
|
||||||
|
file,
|
||||||
|
service.UploadCategorySite,
|
||||||
|
fmt.Sprintf("fl_%d", uid),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "LOGO 已上传", "url": url})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIAdminFriendLinkApplies 管理员友链申请列表
|
||||||
|
func (h *Handlers) APIAdminFriendLinkApplies(c *gin.Context) {
|
||||||
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||||
|
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
||||||
|
status := strings.TrimSpace(c.DefaultQuery("status", "pending"))
|
||||||
|
list, total, err := h.FriendLinkApply.ListAdmin(service.FriendLinkApplyListQuery{
|
||||||
|
Page: page, Size: size, Status: status,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pending, _ := h.FriendLinkApply.PendingCount()
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"applies": list,
|
||||||
|
"total": total,
|
||||||
|
"page": page,
|
||||||
|
"pending_count": pending,
|
||||||
|
"reciprocal_check_enabled": h.Settings.FriendLinkReciprocalCheckEnabled(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIAdminUpdateFriendLinkSettings 更新友链回链检测开关
|
||||||
|
func (h *Handlers) APIAdminUpdateFriendLinkSettings(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
ReciprocalCheckEnabled *bool `json:"reciprocal_check_enabled"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil || req.ReciprocalCheckEnabled == nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.Settings.SetFriendLinkReciprocalCheckEnabled(*req.ReciprocalCheckEnabled); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
enabled := *req.ReciprocalCheckEnabled
|
||||||
|
msg := "已开启回链检测"
|
||||||
|
if !enabled {
|
||||||
|
msg = "已关闭回链检测"
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": msg,
|
||||||
|
"reciprocal_check_enabled": enabled,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIAdminApproveFriendLinkApply 通过友链申请
|
||||||
|
func (h *Handlers) APIAdminApproveFriendLinkApply(c *gin.Context) {
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
apply, err := h.FriendLinkApply.Approve(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "已通过并加入友情链接", "apply": apply})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIAdminRejectFriendLinkApply 拒绝友链申请
|
||||||
|
func (h *Handlers) APIAdminRejectFriendLinkApply(c *gin.Context) {
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
var req struct {
|
||||||
|
Note string `json:"note"`
|
||||||
|
}
|
||||||
|
_ = c.ShouldBindJSON(&req)
|
||||||
|
apply, err := h.FriendLinkApply.Reject(uint(id), req.Note)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "已拒绝申请", "apply": apply})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIMyFriendLinkApplies 当前用户的友链申请列表
|
||||||
|
func (h *Handlers) APIMyFriendLinkApplies(c *gin.Context) {
|
||||||
|
uid := h.currentUserID(c)
|
||||||
|
if uid == 0 {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
list, err := h.FriendLinkApply.ListMine(uid)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"applies": list})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APICancelFriendLinkApply 撤销待审友链申请
|
||||||
|
func (h *Handlers) APICancelFriendLinkApply(c *gin.Context) {
|
||||||
|
uid := h.currentUserID(c)
|
||||||
|
if uid == 0 {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err := h.FriendLinkApply.Cancel(uid, uint(id)); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "已撤销申请"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIUpdateFriendLinkApply 修改并重新提交友链申请
|
||||||
|
func (h *Handlers) APIUpdateFriendLinkApply(c *gin.Context) {
|
||||||
|
uid := h.currentUserID(c)
|
||||||
|
if uid == 0 {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
Logo string `json:"logo"`
|
||||||
|
LinkOnHomepage bool `json:"link_on_homepage"`
|
||||||
|
ReciprocalPageURL string `json:"reciprocal_page_url"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result, err := h.FriendLinkApply.Update(uid, uint(id), service.FriendLinkApplyInput{
|
||||||
|
UserID: uid,
|
||||||
|
Name: req.Name,
|
||||||
|
URL: req.URL,
|
||||||
|
Logo: req.Logo,
|
||||||
|
LinkOnHomepage: req.LinkOnHomepage,
|
||||||
|
ReciprocalPageURL: req.ReciprocalPageURL,
|
||||||
|
OurSiteURL: h.publicBaseURL(c),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resp := gin.H{
|
||||||
|
"message": friendLinkApplySubmittedMessage(h.Settings.FriendLinkReciprocalCheckEnabled(), true),
|
||||||
|
"apply": result.Apply,
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIAdminRecheckFriendLinkApply 管理员重新检测回链
|
||||||
|
func (h *Handlers) APIAdminRecheckFriendLinkApply(c *gin.Context) {
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
apply, err := h.FriendLinkApply.RecheckReciprocal(uint(id), h.publicBaseURL(c))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "已开始重新检测回链", "apply": apply})
|
||||||
|
}
|
||||||
|
|
||||||
|
func friendLinkApplySubmittedMessage(checkEnabled, isUpdate bool) string {
|
||||||
|
if isUpdate {
|
||||||
|
if checkEnabled {
|
||||||
|
return "申请已更新,回链检测将在后台进行"
|
||||||
|
}
|
||||||
|
return "申请已更新"
|
||||||
|
}
|
||||||
|
if checkEnabled {
|
||||||
|
return "申请已提交,回链检测将在后台进行"
|
||||||
|
}
|
||||||
|
return "申请已提交"
|
||||||
|
}
|
||||||
@@ -38,6 +38,8 @@ type Handlers struct {
|
|||||||
Gitea *service.GiteaService
|
Gitea *service.GiteaService
|
||||||
Points *service.PointsService
|
Points *service.PointsService
|
||||||
Badge *service.BadgeService
|
Badge *service.BadgeService
|
||||||
|
SitePage *service.SitePageService
|
||||||
|
FriendLinkApply *service.FriendLinkApplyService
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handlers) setAuthCookie(c *gin.Context, token string) {
|
func (h *Handlers) setAuthCookie(c *gin.Context, token string) {
|
||||||
@@ -419,6 +421,18 @@ func (h *Handlers) APICreatePost(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
extras := service.ParsePostExtrasFromForm(
|
||||||
|
c.PostForm("poll_options"),
|
||||||
|
c.PostForm("bounty_points"),
|
||||||
|
c.PostForm("lottery_winner_count"),
|
||||||
|
)
|
||||||
|
if post.PostType == model.PostTypePoll || post.PostType == model.PostTypeBounty || post.PostType == model.PostTypeLottery {
|
||||||
|
if err := service.FinalizeSpecialPostCreate(post, h.currentUserID(c), extras); err != nil {
|
||||||
|
_ = h.Post.Delete(h.currentUserID(c), post.ID, true)
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
msg := "发帖成功"
|
msg := "发帖成功"
|
||||||
if post.Status == model.ContentStatusPending {
|
if post.Status == model.ContentStatusPending {
|
||||||
msg = "已提交审核,通过后将公开显示"
|
msg = "已提交审核,通过后将公开显示"
|
||||||
|
|||||||
142
handler/seo.go
142
handler/seo.go
@@ -2,6 +2,8 @@ package handler
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"html"
|
||||||
"net/http"
|
"net/http"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -15,8 +17,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
seoPostEditRe = regexp.MustCompile(`^/post/(\d+)/edit/?$`)
|
seoPostEditRe = regexp.MustCompile(`^/post/(\d+)/edit/?$`)
|
||||||
seoBoardPathRe = regexp.MustCompile(`^/board/(\d+)/?$`)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -58,15 +59,17 @@ func (h *Handlers) SitemapXML(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
now := time.Now().UTC()
|
now := time.Now().UTC()
|
||||||
|
permalink := h.Settings.Permalink()
|
||||||
urls := []service.SitemapURL{
|
urls := []service.SitemapURL{
|
||||||
{Loc: base + "/", LastMod: now, ChangeFreq: "hourly", Priority: "1.0"},
|
{Loc: base + "/", LastMod: now, ChangeFreq: "hourly", Priority: "1.0"},
|
||||||
{Loc: base + "/projects", LastMod: now, ChangeFreq: "daily", Priority: "0.6"},
|
{Loc: base + "/projects", LastMod: now, ChangeFreq: "daily", Priority: "0.6"},
|
||||||
|
{Loc: base + "/links", LastMod: now, ChangeFreq: "weekly", Priority: "0.6"},
|
||||||
}
|
}
|
||||||
|
|
||||||
if boards, err := h.Board.List(); err == nil {
|
if boards, err := h.Board.List(); err == nil {
|
||||||
for _, board := range boards {
|
for _, board := range boards {
|
||||||
urls = append(urls, service.SitemapURL{
|
urls = append(urls, service.SitemapURL{
|
||||||
Loc: base + service.QueryBoardHome(board.ID),
|
Loc: base + service.QueryBoardHome(board.ID, permalink),
|
||||||
LastMod: board.UpdatedAt.UTC(),
|
LastMod: board.UpdatedAt.UTC(),
|
||||||
ChangeFreq: "daily",
|
ChangeFreq: "daily",
|
||||||
Priority: "0.7",
|
Priority: "0.7",
|
||||||
@@ -74,8 +77,7 @@ func (h *Handlers) SitemapXML(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
permalink := h.Settings.Permalink()
|
if posts, e1 := h.Post.ListSitemap(seoSitemapLimit); e1 == nil {
|
||||||
if posts, err := h.Post.ListSitemap(seoSitemapLimit); err == nil {
|
|
||||||
for _, p := range posts {
|
for _, p := range posts {
|
||||||
lm := p.UpdatedAt
|
lm := p.UpdatedAt
|
||||||
if lm.IsZero() {
|
if lm.IsZero() {
|
||||||
@@ -90,7 +92,7 @@ func (h *Handlers) SitemapXML(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if users, err := h.User.ListSitemap(seoSitemapLimit); err == nil {
|
if users, e2 := h.User.ListSitemap(seoSitemapLimit); e2 == nil {
|
||||||
for _, u := range users {
|
for _, u := range users {
|
||||||
urls = append(urls, service.SitemapURL{
|
urls = append(urls, service.SitemapURL{
|
||||||
Loc: base + permalink.UserPath(u.ID),
|
Loc: base + permalink.UserPath(u.ID),
|
||||||
@@ -101,6 +103,21 @@ func (h *Handlers) SitemapXML(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if pages, e3 := h.SitePage.ListSitemap(seoSitemapLimit); e3 == nil {
|
||||||
|
for _, p := range pages {
|
||||||
|
lm := p.UpdatedAt
|
||||||
|
if lm.IsZero() {
|
||||||
|
lm = p.CreatedAt
|
||||||
|
}
|
||||||
|
urls = append(urls, service.SitemapURL{
|
||||||
|
Loc: base + permalink.PagePath(p.Slug),
|
||||||
|
LastMod: lm.UTC(),
|
||||||
|
ChangeFreq: "monthly",
|
||||||
|
Priority: "0.5",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
b.WriteString(`<?xml version="1.0" encoding="UTF-8"?>`)
|
b.WriteString(`<?xml version="1.0" encoding="UTF-8"?>`)
|
||||||
b.WriteString(`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`)
|
b.WriteString(`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`)
|
||||||
@@ -137,11 +154,6 @@ func (h *Handlers) SitemapXML(c *gin.Context) {
|
|||||||
func (h *Handlers) ServePublicSPA(c *gin.Context) {
|
func (h *Handlers) ServePublicSPA(c *gin.Context) {
|
||||||
path := c.Request.URL.Path
|
path := c.Request.URL.Path
|
||||||
|
|
||||||
if m := seoBoardPathRe.FindStringSubmatch(path); len(m) == 2 {
|
|
||||||
c.Redirect(http.StatusMovedPermanently, "/?board="+m[1])
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
brand := h.Settings.SiteBranding()
|
brand := h.Settings.SiteBranding()
|
||||||
base := h.publicBaseURL(c)
|
base := h.publicBaseURL(c)
|
||||||
siteName := strings.TrimSpace(brand.Name)
|
siteName := strings.TrimSpace(brand.Name)
|
||||||
@@ -152,11 +164,59 @@ func (h *Handlers) ServePublicSPA(c *gin.Context) {
|
|||||||
siteKeywords := brand.MetaKeywords()
|
siteKeywords := brand.MetaKeywords()
|
||||||
permalink := h.Settings.Permalink()
|
permalink := h.Settings.Permalink()
|
||||||
|
|
||||||
|
// 旧版 /?board=id → 规范板块路径
|
||||||
|
if path == "/" || path == "" {
|
||||||
|
if boardID, err := strconv.ParseUint(c.Query("board"), 10, 64); err == nil && boardID > 0 {
|
||||||
|
target := service.QueryBoardHome(uint(boardID), permalink)
|
||||||
|
if q := c.Request.URL.RawQuery; q != "" {
|
||||||
|
// 保留 sort/keyword 等 query,去掉 board
|
||||||
|
vals := c.Request.URL.Query()
|
||||||
|
vals.Del("board")
|
||||||
|
if rest := vals.Encode(); rest != "" {
|
||||||
|
target += "?" + rest
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.Redirect(http.StatusMovedPermanently, target)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
isBot := service.IsSEOCrawler(c.Request.UserAgent())
|
isBot := service.IsSEOCrawler(c.Request.UserAgent())
|
||||||
if isBot {
|
if isBot {
|
||||||
c.Header("Vary", "User-Agent")
|
c.Header("Vary", "User-Agent")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 板块首页(含可选伪静态后缀)
|
||||||
|
if bm := permalink.MatchBoardPath(path); bm.OK {
|
||||||
|
if bm.NeedsCanonicalRedirect(path) {
|
||||||
|
c.Redirect(http.StatusMovedPermanently, bm.Canonical+preserveQueryExceptBoard(c))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
board, err := h.Board.GetByID(bm.ID)
|
||||||
|
if err != nil {
|
||||||
|
h.serveNotFound(c, base, siteName, siteKeywords, path, isBot)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
desc := strings.TrimSpace(board.Description)
|
||||||
|
if desc == "" {
|
||||||
|
desc = brand.MetaDescription()
|
||||||
|
}
|
||||||
|
meta := attachSiteSEO(&embed_static.SPAPageMeta{
|
||||||
|
Title: pageTitle(board.Name, siteName),
|
||||||
|
Description: service.TruncateRunes(desc, seoDescMax),
|
||||||
|
Keywords: service.JoinSEOKeywords(board.Name, siteKeywords),
|
||||||
|
Canonical: service.AbsoluteURL(base, bm.Canonical),
|
||||||
|
OGType: "website",
|
||||||
|
OGImage: defaultImage,
|
||||||
|
}, siteName, siteKeywords)
|
||||||
|
if isBot {
|
||||||
|
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(h.botBoardHTML(meta, *board)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
embed_static.ServeSPAWithMeta(c, meta)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// 帖子详情(含可选伪静态后缀)
|
// 帖子详情(含可选伪静态后缀)
|
||||||
if pm := permalink.MatchPostPath(path); pm.OK {
|
if pm := permalink.MatchPostPath(path); pm.OK {
|
||||||
if pm.NeedsCanonicalRedirect(path) {
|
if pm.NeedsCanonicalRedirect(path) {
|
||||||
@@ -196,6 +256,35 @@ func (h *Handlers) ServePublicSPA(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 自定义单页
|
||||||
|
if pg := permalink.MatchPagePath(path); pg.OK {
|
||||||
|
if strings.TrimSuffix(path, "/") != strings.TrimSuffix(pg.Canonical, "/") {
|
||||||
|
c.Redirect(http.StatusMovedPermanently, pg.Canonical)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, err := h.SitePage.GetBySlug(pg.Slug, h.isAdmin(c))
|
||||||
|
if err != nil {
|
||||||
|
h.serveNotFound(c, base, siteName, siteKeywords, path, isBot)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
desc := service.ExcerptFromHTML(page.Content, seoDescMax)
|
||||||
|
meta := attachSiteSEO(&embed_static.SPAPageMeta{
|
||||||
|
Title: pageTitle(page.Title, siteName),
|
||||||
|
Description: desc,
|
||||||
|
Keywords: service.JoinSEOKeywords(page.Title, siteKeywords),
|
||||||
|
Canonical: service.AbsoluteURL(base, pg.Canonical),
|
||||||
|
OGType: "article",
|
||||||
|
OGImage: defaultImage,
|
||||||
|
}, siteName, siteKeywords)
|
||||||
|
if isBot {
|
||||||
|
body := fmt.Sprintf(`<h1>%s</h1><div>%s</div>`, html.EscapeString(page.Title), page.Content)
|
||||||
|
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(renderBotHTML(meta, body)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
embed_static.ServeSPAWithMeta(c, meta)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// 未知路径 → 404
|
// 未知路径 → 404
|
||||||
if !isKnownPublicPath(path) {
|
if !isKnownPublicPath(path) {
|
||||||
h.serveNotFound(c, base, siteName, siteKeywords, path, isBot)
|
h.serveNotFound(c, base, siteName, siteKeywords, path, isBot)
|
||||||
@@ -246,12 +335,19 @@ func attachSiteSEO(meta *embed_static.SPAPageMeta, siteName, keywords string) *e
|
|||||||
|
|
||||||
func isKnownPublicPath(path string) bool {
|
func isKnownPublicPath(path string) bool {
|
||||||
switch path {
|
switch path {
|
||||||
case "/", "/login", "/register", "/compose", "/profile", "/favorites", "/projects", "/boards":
|
case "/", "/login", "/register", "/compose", "/profile", "/favorites", "/projects", "/links", "/boards":
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if seoPostEditRe.MatchString(path) {
|
if seoPostEditRe.MatchString(path) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
permalink := service.PermalinkConfig{}
|
||||||
|
if permalink.MatchBoardPath(path).OK {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if permalink.MatchPagePath(path).OK {
|
||||||
|
return true
|
||||||
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -284,7 +380,7 @@ func (h *Handlers) buildSPAPageMeta(c *gin.Context, path string, brand service.S
|
|||||||
}
|
}
|
||||||
meta.Title = pageTitle(board.Name, siteName)
|
meta.Title = pageTitle(board.Name, siteName)
|
||||||
meta.Description = service.TruncateRunes(desc, seoDescMax)
|
meta.Description = service.TruncateRunes(desc, seoDescMax)
|
||||||
meta.Canonical = service.AbsoluteURL(base, service.QueryBoardHome(board.ID))
|
meta.Canonical = service.AbsoluteURL(base, service.QueryBoardHome(board.ID, h.Settings.Permalink()))
|
||||||
meta.Keywords = service.JoinSEOKeywords(board.Name, siteKeywords)
|
meta.Keywords = service.JoinSEOKeywords(board.Name, siteKeywords)
|
||||||
return meta
|
return meta
|
||||||
}
|
}
|
||||||
@@ -307,6 +403,12 @@ func (h *Handlers) buildSPAPageMeta(c *gin.Context, path string, brand service.S
|
|||||||
meta.Keywords = service.JoinSEOKeywords("项目", siteKeywords)
|
meta.Keywords = service.JoinSEOKeywords("项目", siteKeywords)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if path == "/links" {
|
||||||
|
meta.Title = pageTitle("友情链接", siteName)
|
||||||
|
meta.Description = service.TruncateRunes(siteName+" 的友情链接与申请入口", seoDescMax)
|
||||||
|
meta.Keywords = service.JoinSEOKeywords("友情链接", siteKeywords)
|
||||||
|
}
|
||||||
|
|
||||||
return meta
|
return meta
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -436,12 +538,13 @@ func pathWithQuery(c *gin.Context) string {
|
|||||||
if path == "" {
|
if path == "" {
|
||||||
path = "/"
|
path = "/"
|
||||||
}
|
}
|
||||||
|
permalink := service.PermalinkConfig{} // 由调用方在 buildSPAPageMeta 中单独处理 board
|
||||||
if q := c.Request.URL.RawQuery; q != "" {
|
if q := c.Request.URL.RawQuery; q != "" {
|
||||||
// 首页排序/搜索不作为 canonical;板块筛选保留
|
|
||||||
if path == "/" {
|
if path == "/" {
|
||||||
board := c.Query("board")
|
board := c.Query("board")
|
||||||
if board != "" {
|
if board != "" {
|
||||||
return service.QueryBoardHome(uint(parseUintOrZero(board)))
|
_ = permalink
|
||||||
|
return service.LegacyQueryBoardHome(uint(parseUintOrZero(board)))
|
||||||
}
|
}
|
||||||
return "/"
|
return "/"
|
||||||
}
|
}
|
||||||
@@ -450,6 +553,15 @@ func pathWithQuery(c *gin.Context) string {
|
|||||||
return path
|
return path
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func preserveQueryExceptBoard(c *gin.Context) string {
|
||||||
|
vals := c.Request.URL.Query()
|
||||||
|
vals.Del("board")
|
||||||
|
if rest := vals.Encode(); rest != "" {
|
||||||
|
return "?" + rest
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
func parseUintOrZero(s string) uint64 {
|
func parseUintOrZero(s string) uint64 {
|
||||||
n, _ := strconv.ParseUint(s, 10, 64)
|
n, _ := strconv.ParseUint(s, 10, 64)
|
||||||
return n
|
return n
|
||||||
|
|||||||
@@ -87,6 +87,18 @@ func writeEscapedMeta(b *strings.Builder, attr, key, content string) {
|
|||||||
b.WriteString("<meta " + attr + "=\"" + html.EscapeString(key) + "\" content=\"" + html.EscapeString(content) + "\"/>")
|
b.WriteString("<meta " + attr + "=\"" + html.EscapeString(key) + "\" content=\"" + html.EscapeString(content) + "\"/>")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) botBoardHTML(meta *embed_static.SPAPageMeta, board model.Board) string {
|
||||||
|
desc := strings.TrimSpace(board.Description)
|
||||||
|
if desc == "" {
|
||||||
|
desc = meta.Description
|
||||||
|
}
|
||||||
|
body := fmt.Sprintf(`<h1>%s</h1><p class="meta">%s</p>`,
|
||||||
|
html.EscapeString(board.Name),
|
||||||
|
html.EscapeString(desc),
|
||||||
|
)
|
||||||
|
return renderBotHTML(meta, body)
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handlers) botHomeHTML(meta *embed_static.SPAPageMeta, brand service.SiteBranding) string {
|
func (h *Handlers) botHomeHTML(meta *embed_static.SPAPageMeta, brand service.SiteBranding) string {
|
||||||
name := strings.TrimSpace(brand.Name)
|
name := strings.TrimSpace(brand.Name)
|
||||||
if name == "" {
|
if name == "" {
|
||||||
|
|||||||
158
handler/special.go
Normal file
158
handler/special.go
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/service"
|
||||||
|
)
|
||||||
|
|
||||||
|
// APIPages 已发布单页摘要列表
|
||||||
|
func (h *Handlers) APIPages(c *gin.Context) {
|
||||||
|
pages, err := h.SitePage.ListPublished()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if pages == nil {
|
||||||
|
pages = []service.SitePageSummary{}
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"pages": pages})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIPageDetail 单页详情
|
||||||
|
func (h *Handlers) APIPageDetail(c *gin.Context) {
|
||||||
|
slug := c.Param("slug")
|
||||||
|
allowDraft := h.isAdmin(c)
|
||||||
|
page, err := h.SitePage.GetBySlug(slug, allowDraft)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "页面不存在"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"page": page})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIAdminPages 管理端单页列表
|
||||||
|
func (h *Handlers) APIAdminPages(c *gin.Context) {
|
||||||
|
pages, err := h.SitePage.ListAll()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if pages == nil {
|
||||||
|
pages = []model.SitePage{}
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"pages": pages})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIAdminCreatePage 创建单页
|
||||||
|
func (h *Handlers) APIAdminCreatePage(c *gin.Context) {
|
||||||
|
var in service.SitePageInput
|
||||||
|
if err := c.ShouldBindJSON(&in); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式无效"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, err := h.SitePage.Create(in)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "单页已创建", "page": page})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIAdminUpdatePage 更新单页
|
||||||
|
func (h *Handlers) APIAdminUpdatePage(c *gin.Context) {
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
var in service.SitePageInput
|
||||||
|
if err := c.ShouldBindJSON(&in); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式无效"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.SitePage.Update(uint(id), in); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "单页已更新"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIAdminDeletePage 删除单页
|
||||||
|
func (h *Handlers) APIAdminDeletePage(c *gin.Context) {
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err := h.SitePage.Delete(uint(id)); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "单页已删除"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIPollVote 投票
|
||||||
|
func (h *Handlers) APIPollVote(c *gin.Context) {
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
var body struct {
|
||||||
|
OptionIDs []uint `json:"option_ids"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&body); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式无效"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := service.VotePoll(uint(id), h.currentUserID(c), body.OptionIDs); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
poll, _ := service.GetPollView(uint(id), h.currentUserID(c))
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "投票成功", "poll": poll})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIPollClose 结束投票
|
||||||
|
func (h *Handlers) APIPollClose(c *gin.Context) {
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
post, err := h.Post.FindByID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "帖子不存在"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := service.ClosePoll(uint(id), h.currentUserID(c), h.isAdmin(c), post.UserID); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
poll, _ := service.GetPollView(uint(id), h.currentUserID(c))
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "投票已结束", "poll": poll})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIBountyAward 采纳悬赏
|
||||||
|
func (h *Handlers) APIBountyAward(c *gin.Context) {
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
commentID, _ := strconv.ParseUint(c.PostForm("comment_id"), 10, 64)
|
||||||
|
if commentID == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请选择评论"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := service.AwardBounty(uint(id), h.currentUserID(c), h.isAdmin(c), uint(commentID)); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "悬赏已发放"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIBountyRefund 退回悬赏
|
||||||
|
func (h *Handlers) APIBountyRefund(c *gin.Context) {
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err := service.RefundBounty(uint(id), h.currentUserID(c), h.isAdmin(c)); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "悬赏已退回"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// APILotteryDraw 帖内抽奖开奖
|
||||||
|
func (h *Handlers) APILotteryDraw(c *gin.Context) {
|
||||||
|
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
view, err := service.DrawPostLottery(uint(id), h.currentUserID(c), h.isAdmin(c))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "开奖完成", "lottery": view})
|
||||||
|
}
|
||||||
@@ -38,10 +38,11 @@ func InitDB(dbPath string) error {
|
|||||||
&PostLike{}, &CommentLike{}, &PostFavorite{}, &PostRevision{}, &CommentRevision{}, &ForumSetting{},
|
&PostLike{}, &CommentLike{}, &PostFavorite{}, &PostRevision{}, &CommentRevision{}, &ForumSetting{},
|
||||||
&OAuthClient{}, &OAuthAuthCode{},
|
&OAuthClient{}, &OAuthAuthCode{},
|
||||||
&GiteaRepo{},
|
&GiteaRepo{},
|
||||||
&PrivateMessage{}, &PostReport{},
|
&PrivateMessage{}, &PostReport{}, &FriendLinkApply{},
|
||||||
&Media{},
|
&Media{},
|
||||||
&PointLedger{}, &CheckIn{}, &LotteryDraw{}, &PostContentUnlock{},
|
&PointLedger{}, &CheckIn{}, &LotteryDraw{}, &PostContentUnlock{},
|
||||||
&BadgeDef{}, &UserBadge{},
|
&BadgeDef{}, &UserBadge{},
|
||||||
|
&SitePage{}, &Poll{}, &PollOption{}, &PollVote{}, &PostLotteryWinner{},
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return fmt.Errorf("自动迁移失败: %w", err)
|
return fmt.Errorf("自动迁移失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
108
model/models.go
108
model/models.go
@@ -25,6 +25,22 @@ const (
|
|||||||
const (
|
const (
|
||||||
PostTypeNormal = "normal" // 普通讨论
|
PostTypeNormal = "normal" // 普通讨论
|
||||||
PostTypeQuestion = "question" // 问答(未解决 / 已解决)
|
PostTypeQuestion = "question" // 问答(未解决 / 已解决)
|
||||||
|
PostTypePoll = "poll" // 投票
|
||||||
|
PostTypeBounty = "bounty" // 悬赏
|
||||||
|
PostTypeLottery = "lottery" // 抽奖
|
||||||
|
)
|
||||||
|
|
||||||
|
// 悬赏状态
|
||||||
|
const (
|
||||||
|
BountyStatusOpen = "open"
|
||||||
|
BountyStatusAwarded = "awarded"
|
||||||
|
BountyStatusRefunded = "refunded"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 帖内抽奖状态
|
||||||
|
const (
|
||||||
|
PostLotteryStatusOpen = "open"
|
||||||
|
PostLotteryStatusDrawn = "drawn"
|
||||||
)
|
)
|
||||||
|
|
||||||
// User 用户表
|
// User 用户表
|
||||||
@@ -90,8 +106,13 @@ type Post struct {
|
|||||||
Content string `gorm:"type:text;not null" json:"content"`
|
Content string `gorm:"type:text;not null" json:"content"`
|
||||||
ContentPlain string `gorm:"type:text" json:"-"` // 正文纯文本,供搜索索引
|
ContentPlain string `gorm:"type:text" json:"-"` // 正文纯文本,供搜索索引
|
||||||
Tags string `gorm:"size:256" json:"tags"`
|
Tags string `gorm:"size:256" json:"tags"`
|
||||||
PostType string `gorm:"size:16;default:normal;index" json:"post_type"` // normal|question
|
PostType string `gorm:"size:16;default:normal;index" json:"post_type"` // normal|question|poll|bounty|lottery
|
||||||
QuestionResolved bool `gorm:"default:false;index" json:"question_resolved"` // 仅 question 有意义
|
QuestionResolved bool `gorm:"default:false;index" json:"question_resolved"` // 仅 question 有意义
|
||||||
|
BountyPoints int `gorm:"default:0" json:"bounty_points"` // 悬赏积分(仅 bounty)
|
||||||
|
BountyStatus string `gorm:"size:16;default:'';index" json:"bounty_status"` // open|awarded|refunded
|
||||||
|
BountyCommentID uint `gorm:"default:0" json:"bounty_comment_id"` // 采纳的评论
|
||||||
|
LotteryWinnerCount int `gorm:"default:1" json:"lottery_winner_count"` // 抽奖人数(仅 lottery)
|
||||||
|
LotteryStatus string `gorm:"size:16;default:'';index" json:"lottery_status"` // open|drawn
|
||||||
Pinned bool `gorm:"default:false" json:"pinned"` // 全局置顶
|
Pinned bool `gorm:"default:false" json:"pinned"` // 全局置顶
|
||||||
BoardPinned bool `gorm:"default:false" json:"board_pinned"` // 板块内置顶
|
BoardPinned bool `gorm:"default:false" json:"board_pinned"` // 板块内置顶
|
||||||
Featured bool `gorm:"default:false;index" json:"featured"` // 精华帖
|
Featured bool `gorm:"default:false;index" json:"featured"` // 精华帖
|
||||||
@@ -236,6 +257,36 @@ const (
|
|||||||
ReportReasonOther = "other"
|
ReportReasonOther = "other"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 友链申请状态
|
||||||
|
const (
|
||||||
|
FriendLinkApplyStatusPending = "pending"
|
||||||
|
FriendLinkApplyStatusApproved = "approved"
|
||||||
|
FriendLinkApplyStatusRejected = "rejected"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FriendLinkApply 友情链接申请
|
||||||
|
type FriendLinkApply struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
UserID uint `gorm:"index;not null" json:"user_id"`
|
||||||
|
Name string `gorm:"size:32;not null" json:"name"`
|
||||||
|
URL string `gorm:"size:512;not null" json:"url"`
|
||||||
|
Description string `gorm:"size:200;default:''" json:"description,omitempty"`
|
||||||
|
Logo string `gorm:"size:512;default:''" json:"logo"`
|
||||||
|
ReciprocalPageURL string `gorm:"size:512;default:''" json:"reciprocal_page_url"`
|
||||||
|
LinkOnHomepage bool `gorm:"default:true" json:"link_on_homepage"`
|
||||||
|
ReciprocalVerified bool `gorm:"default:false" json:"reciprocal_verified"`
|
||||||
|
ReciprocalCheckNote string `gorm:"size:256;default:''" json:"reciprocal_check_note,omitempty"`
|
||||||
|
ReciprocalCheckedAt *time.Time `json:"reciprocal_checked_at,omitempty"`
|
||||||
|
Status string `gorm:"size:16;default:pending;index" json:"status"`
|
||||||
|
ReviewNote string `gorm:"size:256;default:''" json:"review_note,omitempty"`
|
||||||
|
ReviewedAt *time.Time `json:"reviewed_at,omitempty"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||||
|
|
||||||
|
User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// PostReport 帖子/评论举报(CommentID 有值时为评论举报)
|
// PostReport 帖子/评论举报(CommentID 有值时为评论举报)
|
||||||
type PostReport struct {
|
type PostReport struct {
|
||||||
ID uint `gorm:"primaryKey" json:"id"`
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
@@ -277,6 +328,9 @@ const (
|
|||||||
PointReasonUnlockSpend = "unlock_spend"
|
PointReasonUnlockSpend = "unlock_spend"
|
||||||
PointReasonCreatorIncome = "creator_income"
|
PointReasonCreatorIncome = "creator_income"
|
||||||
PointReasonAdminAdjust = "admin_adjust"
|
PointReasonAdminAdjust = "admin_adjust"
|
||||||
|
PointReasonBountyEscrow = "bounty_escrow"
|
||||||
|
PointReasonBountyAward = "bounty_award"
|
||||||
|
PointReasonBountyRefund = "bounty_refund"
|
||||||
)
|
)
|
||||||
|
|
||||||
// PointLedger 积分流水
|
// PointLedger 积分流水
|
||||||
@@ -321,6 +375,58 @@ type PostContentUnlock struct {
|
|||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SitePage 自定义单页(关于我们、版规等)
|
||||||
|
type SitePage struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
Title string `gorm:"size:128;not null" json:"title"`
|
||||||
|
Slug string `gorm:"uniqueIndex;size:64;not null" json:"slug"`
|
||||||
|
Content string `gorm:"type:text;not null" json:"content"`
|
||||||
|
Published bool `gorm:"default:false;index" json:"published"`
|
||||||
|
SortOrder int `gorm:"default:0" json:"sort_order"`
|
||||||
|
ShowInFooter bool `gorm:"default:false" json:"show_in_footer"`
|
||||||
|
ShowInNav bool `gorm:"default:false" json:"show_in_nav"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Poll 投票帖配置
|
||||||
|
type Poll struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
PostID uint `gorm:"uniqueIndex;not null" json:"post_id"`
|
||||||
|
Multi bool `gorm:"default:false" json:"multi"`
|
||||||
|
MaxChoices int `gorm:"default:1" json:"max_choices"`
|
||||||
|
Closed bool `gorm:"default:false;index" json:"closed"`
|
||||||
|
EndsAt *time.Time `gorm:"index" json:"ends_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PollOption 投票选项
|
||||||
|
type PollOption struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
PostID uint `gorm:"index;not null" json:"post_id"`
|
||||||
|
Text string `gorm:"size:64;not null" json:"text"`
|
||||||
|
SortOrder int `gorm:"default:0" json:"sort_order"`
|
||||||
|
VoteCount int `gorm:"default:0" json:"vote_count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PollVote 投票记录
|
||||||
|
type PollVote struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
PostID uint `gorm:"uniqueIndex:idx_poll_vote_multi;index;not null" json:"post_id"`
|
||||||
|
OptionID uint `gorm:"uniqueIndex:idx_poll_vote_multi;index;not null" json:"option_id"`
|
||||||
|
UserID uint `gorm:"uniqueIndex:idx_poll_vote_multi;index;not null" json:"user_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PostLotteryWinner 帖内抽奖中奖记录
|
||||||
|
type PostLotteryWinner struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
PostID uint `gorm:"index;not null" json:"post_id"`
|
||||||
|
UserID uint `gorm:"index;not null" json:"user_id"`
|
||||||
|
CommentID uint `gorm:"default:0" json:"comment_id"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// 徽章类型
|
// 徽章类型
|
||||||
const (
|
const (
|
||||||
BadgeKindAuto = "auto"
|
BadgeKindAuto = "auto"
|
||||||
|
|||||||
@@ -7,12 +7,12 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"git.iioio.com/freefire/jiang13-forum/config"
|
"git.iioio.com/freefire/jiang13-forum/config"
|
||||||
"git.iioio.com/freefire/jiang13-forum/embed_static"
|
"git.iioio.com/freefire/jiang13-forum/embed_static"
|
||||||
"git.iioio.com/freefire/jiang13-forum/handler"
|
"git.iioio.com/freefire/jiang13-forum/handler"
|
||||||
"git.iioio.com/freefire/jiang13-forum/middleware"
|
"git.iioio.com/freefire/jiang13-forum/middleware"
|
||||||
"git.iioio.com/freefire/jiang13-forum/service"
|
"git.iioio.com/freefire/jiang13-forum/service"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Setup(cfg *config.Config) (*gin.Engine, error) {
|
func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||||
@@ -61,6 +61,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
mailSvc := service.NewMailService(settingsSvc)
|
mailSvc := service.NewMailService(settingsSvc)
|
||||||
emailCodeSvc := service.NewEmailCodeService(mailSvc)
|
emailCodeSvc := service.NewEmailCodeService(mailSvc)
|
||||||
notifySvc := service.NewNotifyService(messageSvc, mailSvc, settingsSvc)
|
notifySvc := service.NewNotifyService(messageSvc, mailSvc, settingsSvc)
|
||||||
|
friendLinkApplySvc := service.NewFriendLinkApplyService(settingsSvc, messageSvc)
|
||||||
oidcSvc, err := service.NewOIDCService(cfg, settingsSvc)
|
oidcSvc, err := service.NewOIDCService(cfg, settingsSvc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -91,6 +92,8 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
Captcha: captchaSvc, Mail: mailSvc, EmailCode: emailCodeSvc,
|
Captcha: captchaSvc, Mail: mailSvc, EmailCode: emailCodeSvc,
|
||||||
OIDC: oidcSvc, Gitea: giteaSvc,
|
OIDC: oidcSvc, Gitea: giteaSvc,
|
||||||
Points: service.NewPointsService(), Badge: service.NewBadgeService(),
|
Points: service.NewPointsService(), Badge: service.NewBadgeService(),
|
||||||
|
SitePage: service.NewSitePageService(filter),
|
||||||
|
FriendLinkApply: friendLinkApplySvc,
|
||||||
}
|
}
|
||||||
authMW := middleware.NewAuthMiddleware(authSvc)
|
authMW := middleware.NewAuthMiddleware(authSvc)
|
||||||
|
|
||||||
@@ -123,6 +126,8 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
pubAPI.GET("/stats", h.APIStats)
|
pubAPI.GET("/stats", h.APIStats)
|
||||||
pubAPI.GET("/forum-limits", h.APIForumLimits)
|
pubAPI.GET("/forum-limits", h.APIForumLimits)
|
||||||
pubAPI.GET("/site-branding", h.APISiteBranding)
|
pubAPI.GET("/site-branding", h.APISiteBranding)
|
||||||
|
pubAPI.GET("/pages", h.APIPages)
|
||||||
|
pubAPI.GET("/pages/:slug", h.APIPageDetail)
|
||||||
pubAPI.GET("/captcha", h.APICaptcha)
|
pubAPI.GET("/captcha", h.APICaptcha)
|
||||||
pubAPI.GET("/register/config", h.APIRegisterConfig)
|
pubAPI.GET("/register/config", h.APIRegisterConfig)
|
||||||
pubAPI.POST("/register/email-code", middleware.RateLimitMiddleware(limiter, "register"), h.APISendRegisterEmailCode)
|
pubAPI.POST("/register/email-code", middleware.RateLimitMiddleware(limiter, "register"), h.APISendRegisterEmailCode)
|
||||||
@@ -162,6 +167,11 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
api.POST("/posts/:id/like", h.APIToggleLike)
|
api.POST("/posts/:id/like", h.APIToggleLike)
|
||||||
api.POST("/posts/:id/favorite", h.APIToggleFavorite)
|
api.POST("/posts/:id/favorite", h.APIToggleFavorite)
|
||||||
api.POST("/posts/:id/resolve", h.APISetQuestionResolved)
|
api.POST("/posts/:id/resolve", h.APISetQuestionResolved)
|
||||||
|
api.POST("/posts/:id/poll/vote", h.APIPollVote)
|
||||||
|
api.POST("/posts/:id/poll/close", h.APIPollClose)
|
||||||
|
api.POST("/posts/:id/bounty/award", h.APIBountyAward)
|
||||||
|
api.POST("/posts/:id/bounty/refund", h.APIBountyRefund)
|
||||||
|
api.POST("/posts/:id/lottery/draw", h.APILotteryDraw)
|
||||||
api.POST("/posts/:id/report", middleware.RateLimitMiddleware(limiter, "report"), h.APICreatePostReport)
|
api.POST("/posts/:id/report", middleware.RateLimitMiddleware(limiter, "report"), h.APICreatePostReport)
|
||||||
api.GET("/messages/unread-count", h.APIMessageUnreadCount)
|
api.GET("/messages/unread-count", h.APIMessageUnreadCount)
|
||||||
api.GET("/messages/notifications", h.APIMessageNotifications)
|
api.GET("/messages/notifications", h.APIMessageNotifications)
|
||||||
@@ -176,10 +186,16 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
api.DELETE("/comments/:id", h.APIDeleteComment)
|
api.DELETE("/comments/:id", h.APIDeleteComment)
|
||||||
api.PUT("/comments/:id", h.APIUpdateComment)
|
api.PUT("/comments/:id", h.APIUpdateComment)
|
||||||
api.GET("/me/points", h.APIMePoints)
|
api.GET("/me/points", h.APIMePoints)
|
||||||
|
api.GET("/me/check-in", h.APIMeCheckInGet)
|
||||||
api.POST("/me/check-in", h.APIMeCheckIn)
|
api.POST("/me/check-in", h.APIMeCheckIn)
|
||||||
api.GET("/me/lottery", h.APIMeLotteryGet)
|
api.GET("/me/lottery", h.APIMeLotteryGet)
|
||||||
api.POST("/me/lottery", h.APIMeLotteryDraw)
|
api.POST("/me/lottery", h.APIMeLotteryDraw)
|
||||||
api.POST("/posts/:id/unlock", middleware.RateLimitMiddleware(limiter, "post"), h.APIUnlockPostBlock)
|
api.POST("/posts/:id/unlock", middleware.RateLimitMiddleware(limiter, "post"), h.APIUnlockPostBlock)
|
||||||
|
api.POST("/friend-links/apply", middleware.RateLimitMiddleware(limiter, "friend_link"), h.APIApplyFriendLink)
|
||||||
|
api.POST("/friend-links/logo", middleware.RateLimitMiddleware(limiter, "post"), h.APIUploadFriendLinkLogo)
|
||||||
|
api.GET("/friend-links/my-applies", h.APIMyFriendLinkApplies)
|
||||||
|
api.PUT("/friend-links/applies/:id", middleware.RateLimitMiddleware(limiter, "friend_link"), h.APIUpdateFriendLinkApply)
|
||||||
|
api.DELETE("/friend-links/applies/:id", h.APICancelFriendLinkApply)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 管理员 API(React SPA 后台统一使用 JSON)
|
// 管理员 API(React SPA 后台统一使用 JSON)
|
||||||
@@ -206,6 +222,15 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
adminAPI.POST("/boards", h.APIAdminCreateBoard)
|
adminAPI.POST("/boards", h.APIAdminCreateBoard)
|
||||||
adminAPI.PUT("/boards/:id", h.APIAdminUpdateBoard)
|
adminAPI.PUT("/boards/:id", h.APIAdminUpdateBoard)
|
||||||
adminAPI.DELETE("/boards/:id", h.APIAdminDeleteBoard)
|
adminAPI.DELETE("/boards/:id", h.APIAdminDeleteBoard)
|
||||||
|
adminAPI.GET("/pages", h.APIAdminPages)
|
||||||
|
adminAPI.POST("/pages", h.APIAdminCreatePage)
|
||||||
|
adminAPI.PUT("/pages/:id", h.APIAdminUpdatePage)
|
||||||
|
adminAPI.DELETE("/pages/:id", h.APIAdminDeletePage)
|
||||||
|
adminAPI.GET("/friend-link-applies", h.APIAdminFriendLinkApplies)
|
||||||
|
adminAPI.PUT("/friend-link-settings", h.APIAdminUpdateFriendLinkSettings)
|
||||||
|
adminAPI.POST("/friend-link-applies/:id/approve", h.APIAdminApproveFriendLinkApply)
|
||||||
|
adminAPI.POST("/friend-link-applies/:id/reject", h.APIAdminRejectFriendLinkApply)
|
||||||
|
adminAPI.POST("/friend-link-applies/:id/recheck", h.APIAdminRecheckFriendLinkApply)
|
||||||
adminAPI.GET("/posts", h.APIAdminPosts)
|
adminAPI.GET("/posts", h.APIAdminPosts)
|
||||||
adminAPI.GET("/posts/trash", h.APIAdminTrashPosts)
|
adminAPI.GET("/posts/trash", h.APIAdminTrashPosts)
|
||||||
adminAPI.POST("/posts/:id/pin", h.APIAdminPinPost)
|
adminAPI.POST("/posts/:id/pin", h.APIAdminPinPost)
|
||||||
@@ -254,7 +279,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
adminAuth := admin.Group("/", authMW.RequireAuth(), authMW.RequireAdmin())
|
adminAuth := admin.Group("/", authMW.RequireAuth(), authMW.RequireAdmin())
|
||||||
{
|
{
|
||||||
adminAuth.GET("/", func(c *gin.Context) { c.Redirect(http.StatusFound, "/admin/dashboard") })
|
adminAuth.GET("/", func(c *gin.Context) { c.Redirect(http.StatusFound, "/admin/dashboard") })
|
||||||
for _, page := range []string{"dashboard", "boards", "posts", "comments", "reports", "users", "badges", "media", "settings"} {
|
for _, page := range []string{"dashboard", "boards", "pages", "links", "posts", "comments", "reports", "users", "badges", "media", "settings"} {
|
||||||
adminAuth.GET("/"+page, embed_static.ServeSPANoIndex)
|
adminAuth.GET("/"+page, embed_static.ServeSPANoIndex)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
36
service/aside_widgets_test.go
Normal file
36
service/aside_widgets_test.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestNormalizeAsideWidgetsPreservesOrder(t *testing.T) {
|
||||||
|
in := []AsideWidget{
|
||||||
|
{ID: AsideWidgetFriendLinks, Enabled: true},
|
||||||
|
{ID: AsideWidgetTagCloud, Enabled: true},
|
||||||
|
{ID: AsideWidgetRecentComments, Enabled: false},
|
||||||
|
}
|
||||||
|
out := NormalizeAsideWidgets(in)
|
||||||
|
if len(out) != 3 {
|
||||||
|
t.Fatalf("want 3 widgets, got %d", len(out))
|
||||||
|
}
|
||||||
|
want := []string{AsideWidgetFriendLinks, AsideWidgetTagCloud, AsideWidgetRecentComments}
|
||||||
|
for i, id := range want {
|
||||||
|
if out[i].ID != id {
|
||||||
|
t.Fatalf("index %d: want %s, got %s", i, id, out[i].ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !out[0].Enabled || !out[1].Enabled || out[2].Enabled {
|
||||||
|
t.Fatalf("enabled flags mismatch: %+v", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAsideBoolsFromWidgets(t *testing.T) {
|
||||||
|
widgets := []AsideWidget{
|
||||||
|
{ID: AsideWidgetRecentComments, Enabled: true},
|
||||||
|
{ID: AsideWidgetFriendLinks, Enabled: false},
|
||||||
|
{ID: AsideWidgetTagCloud, Enabled: true},
|
||||||
|
}
|
||||||
|
bools := asideBoolsFromWidgets(widgets)
|
||||||
|
if !bools.tagCloud || !bools.recentComments || bools.friendLinks {
|
||||||
|
t.Fatalf("unexpected bools: %+v", bools)
|
||||||
|
}
|
||||||
|
}
|
||||||
150
service/bounty.go
Normal file
150
service/bounty.go
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrBountyNotOpen = errors.New("悬赏已结束或已退回")
|
||||||
|
ErrBountySelfAward = errors.New("不能采纳自己的回复")
|
||||||
|
ErrBountyInvalidPoint = errors.New("悬赏积分至少为 1")
|
||||||
|
ErrBountyRefundBlocked = errors.New("已有用户回复,无法自行取消悬赏,请采纳优质回复或联系管理员")
|
||||||
|
)
|
||||||
|
|
||||||
|
const bountyRefundBlockReason = "已有用户回复,无法自行取消悬赏,请采纳优质回复或联系管理员"
|
||||||
|
|
||||||
|
// CountEligibleBountyReplies 统计他人已发布的有效回复数(不含楼主)
|
||||||
|
func CountEligibleBountyReplies(db *gorm.DB, postID, authorID uint) (int64, error) {
|
||||||
|
if db == nil {
|
||||||
|
db = model.DB
|
||||||
|
}
|
||||||
|
var n int64
|
||||||
|
err := db.Model(&model.Comment{}).
|
||||||
|
Where("post_id = ? AND status = ? AND user_id != ?", postID, model.ContentStatusPublished, authorID).
|
||||||
|
Count(&n).Error
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// CanRefundBounty 当前查看者是否可取消悬赏(管理员始终可强制取消)
|
||||||
|
func CanRefundBounty(post *model.Post, viewerIsAdmin bool) (bool, string) {
|
||||||
|
if post == nil || post.PostType != model.PostTypeBounty {
|
||||||
|
return false, ""
|
||||||
|
}
|
||||||
|
if post.BountyStatus != model.BountyStatusOpen || post.BountyPoints < 1 {
|
||||||
|
return false, ""
|
||||||
|
}
|
||||||
|
if viewerIsAdmin {
|
||||||
|
return true, ""
|
||||||
|
}
|
||||||
|
n, err := CountEligibleBountyReplies(model.DB, post.ID, post.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return false, ""
|
||||||
|
}
|
||||||
|
if n > 0 {
|
||||||
|
return false, bountyRefundBlockReason
|
||||||
|
}
|
||||||
|
return true, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// EscrowBounty 发帖时托管悬赏积分
|
||||||
|
func EscrowBounty(tx *gorm.DB, userID, postID uint, points int) error {
|
||||||
|
if points < 1 {
|
||||||
|
return ErrBountyInvalidPoint
|
||||||
|
}
|
||||||
|
_, err := AdjustPointsTx(tx, userID, -points, model.PointReasonBountyEscrow, "post", postID, "发布悬赏帖")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// AwardBounty 采纳评论并发放悬赏
|
||||||
|
func AwardBounty(postID, operatorID uint, isAdmin bool, commentID uint) error {
|
||||||
|
var post model.Post
|
||||||
|
if err := model.DB.First(&post, postID).Error; err != nil {
|
||||||
|
return ErrPostNotFound
|
||||||
|
}
|
||||||
|
if post.PostType != model.PostTypeBounty {
|
||||||
|
return errors.New("非悬赏帖")
|
||||||
|
}
|
||||||
|
if !isAdmin && post.UserID != operatorID {
|
||||||
|
return ErrPermissionDenied
|
||||||
|
}
|
||||||
|
if post.BountyStatus != model.BountyStatusOpen || post.BountyPoints < 1 {
|
||||||
|
return ErrBountyNotOpen
|
||||||
|
}
|
||||||
|
var comment model.Comment
|
||||||
|
if err := model.DB.First(&comment, commentID).Error; err != nil {
|
||||||
|
return errors.New("评论不存在")
|
||||||
|
}
|
||||||
|
if comment.PostID != postID || comment.Status != model.ContentStatusPublished {
|
||||||
|
return errors.New("评论无效")
|
||||||
|
}
|
||||||
|
if comment.UserID == post.UserID {
|
||||||
|
return ErrBountySelfAward
|
||||||
|
}
|
||||||
|
points := post.BountyPoints
|
||||||
|
return model.DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if _, err := AdjustPointsTx(tx, comment.UserID, points, model.PointReasonBountyAward, "post", postID, "悬赏采纳"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Model(&post).Updates(map[string]interface{}{
|
||||||
|
"bounty_status": model.BountyStatusAwarded,
|
||||||
|
"bounty_comment_id": commentID,
|
||||||
|
}).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// RefundBounty 取消悬赏并退回积分
|
||||||
|
func RefundBounty(postID, operatorID uint, isAdmin bool) error {
|
||||||
|
var post model.Post
|
||||||
|
if err := model.DB.First(&post, postID).Error; err != nil {
|
||||||
|
return ErrPostNotFound
|
||||||
|
}
|
||||||
|
if post.PostType != model.PostTypeBounty {
|
||||||
|
return errors.New("非悬赏帖")
|
||||||
|
}
|
||||||
|
if !isAdmin && post.UserID != operatorID {
|
||||||
|
return ErrPermissionDenied
|
||||||
|
}
|
||||||
|
if post.BountyStatus != model.BountyStatusOpen || post.BountyPoints < 1 {
|
||||||
|
return ErrBountyNotOpen
|
||||||
|
}
|
||||||
|
if !isAdmin {
|
||||||
|
n, err := CountEligibleBountyReplies(model.DB, post.ID, post.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n > 0 {
|
||||||
|
return ErrBountyRefundBlocked
|
||||||
|
}
|
||||||
|
}
|
||||||
|
points := post.BountyPoints
|
||||||
|
return model.DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if _, err := AdjustPointsTx(tx, post.UserID, points, model.PointReasonBountyRefund, "post", postID, "悬赏退回"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Model(&post).Updates(map[string]interface{}{
|
||||||
|
"bounty_status": model.BountyStatusRefunded,
|
||||||
|
"bounty_points": 0,
|
||||||
|
}).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// RefundBountyIfOpen 删帖时自动退回未采纳悬赏
|
||||||
|
func RefundBountyIfOpen(tx *gorm.DB, post *model.Post) error {
|
||||||
|
if post == nil || post.PostType != model.PostTypeBounty {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if post.BountyStatus != model.BountyStatusOpen || post.BountyPoints < 1 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
points := post.BountyPoints
|
||||||
|
if _, err := AdjustPointsTx(tx, post.UserID, points, model.PointReasonBountyRefund, "post", post.ID, "删帖退回悬赏"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Model(post).Updates(map[string]interface{}{
|
||||||
|
"bounty_status": model.BountyStatusRefunded,
|
||||||
|
"bounty_points": 0,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
175
service/bounty_test.go
Normal file
175
service/bounty_test.go
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/glebarez/sqlite"
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func setupBountyTestDB(t *testing.T) *gorm.DB {
|
||||||
|
t.Helper()
|
||||||
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&model.User{}, &model.Post{}, &model.Comment{}, &model.PointLedger{}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
prev := model.DB
|
||||||
|
model.DB = db
|
||||||
|
t.Cleanup(func() { model.DB = prev })
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedBountyPost(t *testing.T, db *gorm.DB, authorID uint, points int) model.Post {
|
||||||
|
t.Helper()
|
||||||
|
post := model.Post{
|
||||||
|
UserID: authorID,
|
||||||
|
BoardID: 1,
|
||||||
|
Title: "悬赏测试",
|
||||||
|
Content: "内容",
|
||||||
|
PostType: model.PostTypeBounty,
|
||||||
|
BountyPoints: points,
|
||||||
|
BountyStatus: model.BountyStatusOpen,
|
||||||
|
Status: model.ContentStatusPublished,
|
||||||
|
}
|
||||||
|
if err := db.Create(&post).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return post
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedUser(t *testing.T, db *gorm.DB, id uint, points int) {
|
||||||
|
t.Helper()
|
||||||
|
u := model.User{
|
||||||
|
ID: id,
|
||||||
|
Username: "user" + string(rune('0'+id)),
|
||||||
|
Password: "hash",
|
||||||
|
Nickname: "测试",
|
||||||
|
Points: points,
|
||||||
|
}
|
||||||
|
if err := db.Create(&u).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedComment(t *testing.T, db *gorm.DB, postID, userID uint, floor int, status string) {
|
||||||
|
t.Helper()
|
||||||
|
c := model.Comment{
|
||||||
|
PostID: postID,
|
||||||
|
UserID: userID,
|
||||||
|
Floor: floor,
|
||||||
|
Content: "回复",
|
||||||
|
Status: status,
|
||||||
|
}
|
||||||
|
if err := db.Create(&c).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCountEligibleBountyReplies(t *testing.T) {
|
||||||
|
db := setupBountyTestDB(t)
|
||||||
|
post := seedBountyPost(t, db, 1, 10)
|
||||||
|
|
||||||
|
n, err := CountEligibleBountyReplies(db, post.ID, 1)
|
||||||
|
if err != nil || n != 0 {
|
||||||
|
t.Fatalf("无回复时期望 0,得到 %d err=%v", n, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
seedComment(t, db, post.ID, 1, 1, model.ContentStatusPublished)
|
||||||
|
n, err = CountEligibleBountyReplies(db, post.ID, 1)
|
||||||
|
if err != nil || n != 0 {
|
||||||
|
t.Fatalf("楼主自己的回复不应计入,得到 %d", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
seedComment(t, db, post.ID, 2, 2, model.ContentStatusPublished)
|
||||||
|
n, err = CountEligibleBountyReplies(db, post.ID, 1)
|
||||||
|
if err != nil || n != 1 {
|
||||||
|
t.Fatalf("他人 published 回复期望 1,得到 %d", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
seedComment(t, db, post.ID, 3, 3, model.ContentStatusPending)
|
||||||
|
n, err = CountEligibleBountyReplies(db, post.ID, 1)
|
||||||
|
if err != nil || n != 1 {
|
||||||
|
t.Fatalf("pending 回复不应增加计数,得到 %d", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
seedComment(t, db, post.ID, 0, 4, model.ContentStatusPublished)
|
||||||
|
n, err = CountEligibleBountyReplies(db, post.ID, 1)
|
||||||
|
if err != nil || n != 2 {
|
||||||
|
t.Fatalf("游客回复应计入,得到 %d", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCanRefundBounty(t *testing.T) {
|
||||||
|
db := setupBountyTestDB(t)
|
||||||
|
post := seedBountyPost(t, db, 1, 5)
|
||||||
|
|
||||||
|
can, reason := CanRefundBounty(&post, false)
|
||||||
|
if !can || reason != "" {
|
||||||
|
t.Fatalf("无回复时楼主应可退,can=%v reason=%q", can, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
seedComment(t, db, post.ID, 2, 1, model.ContentStatusPublished)
|
||||||
|
can, reason = CanRefundBounty(&post, false)
|
||||||
|
if can || reason != bountyRefundBlockReason {
|
||||||
|
t.Fatalf("有他人回复时楼主不可退,can=%v reason=%q", can, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
can, reason = CanRefundBounty(&post, true)
|
||||||
|
if !can || reason != "" {
|
||||||
|
t.Fatalf("管理员应可强制退,can=%v reason=%q", can, reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRefundBountyBlockedForAuthorWithReplies(t *testing.T) {
|
||||||
|
db := setupBountyTestDB(t)
|
||||||
|
seedUser(t, db, 1, 0)
|
||||||
|
seedUser(t, db, 2, 0)
|
||||||
|
post := seedBountyPost(t, db, 1, 8)
|
||||||
|
seedComment(t, db, post.ID, 2, 1, model.ContentStatusPublished)
|
||||||
|
|
||||||
|
err := RefundBounty(post.ID, 1, false)
|
||||||
|
if !errors.Is(err, ErrBountyRefundBlocked) {
|
||||||
|
t.Fatalf("楼主有他人回复时应拒绝退回,err=%v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRefundBountyAllowedWithoutReplies(t *testing.T) {
|
||||||
|
db := setupBountyTestDB(t)
|
||||||
|
seedUser(t, db, 1, 0)
|
||||||
|
post := seedBountyPost(t, db, 1, 6)
|
||||||
|
|
||||||
|
if err := RefundBounty(post.ID, 1, false); err != nil {
|
||||||
|
t.Fatalf("无回复时楼主应可退回,err=%v", err)
|
||||||
|
}
|
||||||
|
var updated model.Post
|
||||||
|
if err := db.First(&updated, post.ID).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if updated.BountyStatus != model.BountyStatusRefunded || updated.BountyPoints != 0 {
|
||||||
|
t.Fatalf("状态应为 refunded 且积分为 0,得到 status=%s points=%d", updated.BountyStatus, updated.BountyPoints)
|
||||||
|
}
|
||||||
|
var author model.User
|
||||||
|
if err := db.First(&author, 1).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if author.Points != 6 {
|
||||||
|
t.Fatalf("楼主应收回 6 积分,余额=%d", author.Points)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRefundBountyAdminBypassWithReplies(t *testing.T) {
|
||||||
|
db := setupBountyTestDB(t)
|
||||||
|
seedUser(t, db, 1, 0)
|
||||||
|
seedUser(t, db, 2, 0)
|
||||||
|
post := seedBountyPost(t, db, 1, 4)
|
||||||
|
seedComment(t, db, post.ID, 2, 1, model.ContentStatusPublished)
|
||||||
|
|
||||||
|
if err := RefundBounty(post.ID, 99, true); err != nil {
|
||||||
|
t.Fatalf("管理员应可强制退回,err=%v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
473
service/friend_link.go
Normal file
473
service/friend_link.go
Normal file
@@ -0,0 +1,473 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrFriendLinkApplyPending = errors.New("该 URL 已有待审核申请")
|
||||||
|
ErrFriendLinkApplyExists = errors.New("该 URL 已在友情链接中")
|
||||||
|
ErrFriendLinkApplyNotFound = errors.New("申请不存在")
|
||||||
|
ErrFriendLinkApplyHandled = errors.New("申请已处理")
|
||||||
|
ErrFriendLinkApplyFull = errors.New("友情链接已达上限(20 条)")
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
maxFriendLinkApplyDesc = 200
|
||||||
|
)
|
||||||
|
|
||||||
|
type FriendLinkApplyListQuery struct {
|
||||||
|
Page int
|
||||||
|
Size int
|
||||||
|
Status string
|
||||||
|
}
|
||||||
|
|
||||||
|
type FriendLinkApplyInput struct {
|
||||||
|
UserID uint
|
||||||
|
Name string
|
||||||
|
URL string
|
||||||
|
Logo string
|
||||||
|
LinkOnHomepage bool
|
||||||
|
ReciprocalPageURL string
|
||||||
|
OurSiteURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
type FriendLinkApplyCreateResult struct {
|
||||||
|
Apply *model.FriendLinkApply
|
||||||
|
}
|
||||||
|
|
||||||
|
type FriendLinkApplyService struct {
|
||||||
|
settings *ForumSettingsService
|
||||||
|
messages *MessageService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFriendLinkApplyService(settings *ForumSettingsService, messages *MessageService) *FriendLinkApplyService {
|
||||||
|
return &FriendLinkApplyService{settings: settings, messages: messages}
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeFriendLinkApplyURL(raw string) (string, error) {
|
||||||
|
href := strings.TrimSpace(raw)
|
||||||
|
if href == "" {
|
||||||
|
return "", errors.New("请填写 URL")
|
||||||
|
}
|
||||||
|
u, err := url.Parse(href)
|
||||||
|
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||||
|
return "", errors.New("URL 格式无效")
|
||||||
|
}
|
||||||
|
scheme := strings.ToLower(u.Scheme)
|
||||||
|
if scheme != "http" && scheme != "https" {
|
||||||
|
return "", errors.New("URL 需为 http 或 https")
|
||||||
|
}
|
||||||
|
return href, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func friendLinkURLKey(href string) string {
|
||||||
|
u, err := url.Parse(strings.TrimSpace(href))
|
||||||
|
if err != nil {
|
||||||
|
return strings.ToLower(strings.TrimSpace(href))
|
||||||
|
}
|
||||||
|
u.Scheme = strings.ToLower(u.Scheme)
|
||||||
|
u.Host = strings.ToLower(u.Host)
|
||||||
|
u.Path = strings.TrimSuffix(u.Path, "/")
|
||||||
|
return u.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *FriendLinkApplyService) urlInFriendLinks(href string) bool {
|
||||||
|
key := friendLinkURLKey(href)
|
||||||
|
brand := s.settings.SiteBranding()
|
||||||
|
for _, l := range brand.FriendLinks {
|
||||||
|
if friendLinkURLKey(l.URL) == key {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create 提交友链申请
|
||||||
|
func (s *FriendLinkApplyService) Create(in FriendLinkApplyInput) (*FriendLinkApplyCreateResult, error) {
|
||||||
|
name, href, logo, reciprocal, err := s.prepareApplyFields(in, "")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dup, err := s.hasPendingApplyForURL(in.UserID, 0, href)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if dup {
|
||||||
|
return nil, ErrFriendLinkApplyPending
|
||||||
|
}
|
||||||
|
|
||||||
|
apply := &model.FriendLinkApply{
|
||||||
|
UserID: in.UserID,
|
||||||
|
Name: name,
|
||||||
|
URL: href,
|
||||||
|
Logo: logo,
|
||||||
|
ReciprocalPageURL: reciprocal,
|
||||||
|
LinkOnHomepage: in.LinkOnHomepage,
|
||||||
|
Status: model.FriendLinkApplyStatusPending,
|
||||||
|
}
|
||||||
|
if err := model.DB.Create(apply).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
s.startReciprocalCheck(apply.ID, reciprocal, in.OurSiteURL)
|
||||||
|
_ = model.DB.Preload("User").First(apply, apply.ID).Error
|
||||||
|
return &FriendLinkApplyCreateResult{Apply: apply}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PendingCount 待审数量
|
||||||
|
func (s *FriendLinkApplyService) PendingCount() (int64, error) {
|
||||||
|
var n int64
|
||||||
|
err := model.DB.Model(&model.FriendLinkApply{}).
|
||||||
|
Where("status = ?", model.FriendLinkApplyStatusPending).
|
||||||
|
Count(&n).Error
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListAdmin 管理员列表
|
||||||
|
func (s *FriendLinkApplyService) ListAdmin(q FriendLinkApplyListQuery) ([]model.FriendLinkApply, int64, error) {
|
||||||
|
if q.Page < 1 {
|
||||||
|
q.Page = 1
|
||||||
|
}
|
||||||
|
if q.Size < 1 || q.Size > 50 {
|
||||||
|
q.Size = 20
|
||||||
|
}
|
||||||
|
db := model.DB.Model(&model.FriendLinkApply{})
|
||||||
|
status := strings.TrimSpace(q.Status)
|
||||||
|
if status != "" && status != "all" {
|
||||||
|
db = db.Where("status = ?", status)
|
||||||
|
}
|
||||||
|
var total int64
|
||||||
|
if err := db.Count(&total).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
var list []model.FriendLinkApply
|
||||||
|
err := db.Preload("User").
|
||||||
|
Order("CASE WHEN status = 'pending' THEN 0 ELSE 1 END, id DESC").
|
||||||
|
Offset((q.Page - 1) * q.Size).
|
||||||
|
Limit(q.Size).
|
||||||
|
Find(&list).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
return list, total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *FriendLinkApplyService) getPending(id uint) (*model.FriendLinkApply, error) {
|
||||||
|
var apply model.FriendLinkApply
|
||||||
|
if err := model.DB.Preload("User").First(&apply, id).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrFriendLinkApplyNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if apply.Status != model.FriendLinkApplyStatusPending {
|
||||||
|
return nil, ErrFriendLinkApplyHandled
|
||||||
|
}
|
||||||
|
return &apply, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Approve 通过申请并写入友链
|
||||||
|
func (s *FriendLinkApplyService) Approve(id uint) (*model.FriendLinkApply, error) {
|
||||||
|
apply, err := s.getPending(id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if s.urlInFriendLinks(apply.URL) {
|
||||||
|
return nil, ErrFriendLinkApplyExists
|
||||||
|
}
|
||||||
|
|
||||||
|
brand := s.settings.SiteBranding()
|
||||||
|
if len(brand.FriendLinks) >= maxFriendLinks {
|
||||||
|
return nil, ErrFriendLinkApplyFull
|
||||||
|
}
|
||||||
|
nextLinks := append(brand.FriendLinks, FriendLink{
|
||||||
|
Name: apply.Name,
|
||||||
|
URL: apply.URL,
|
||||||
|
Logo: normalizeFriendLinkLogoOptional(apply.Logo),
|
||||||
|
})
|
||||||
|
if err := s.settings.UpdateSiteBranding(SiteBranding{
|
||||||
|
Name: brand.Name,
|
||||||
|
Slogan: brand.Slogan,
|
||||||
|
Description: brand.Description,
|
||||||
|
Keywords: brand.Keywords,
|
||||||
|
LogoMark: brand.LogoMark,
|
||||||
|
Logo: brand.Logo,
|
||||||
|
Favicon: brand.Favicon,
|
||||||
|
OGImage: brand.OGImage,
|
||||||
|
ICPBeian: brand.ICPBeian,
|
||||||
|
ICPBeianURL: brand.ICPBeianURL,
|
||||||
|
FriendLinks: nextLinks,
|
||||||
|
}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
if err := model.DB.Model(apply).Updates(map[string]interface{}{
|
||||||
|
"status": model.FriendLinkApplyStatusApproved,
|
||||||
|
"reviewed_at": now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
apply.Status = model.FriendLinkApplyStatusApproved
|
||||||
|
apply.ReviewedAt = &now
|
||||||
|
|
||||||
|
if s.messages != nil && apply.UserID > 0 {
|
||||||
|
subject := "友情链接申请已通过"
|
||||||
|
content := fmt.Sprintf(
|
||||||
|
"你申请的友情链接「%s」(%s)已通过审核,现已展示在友情链接页面。\n\n如有疑问,可回复本私信联系管理员。",
|
||||||
|
apply.Name, apply.URL,
|
||||||
|
)
|
||||||
|
_, _ = s.messages.SendSystem(apply.UserID, subject, content, model.MessageKindSystem, nil, nil)
|
||||||
|
}
|
||||||
|
return apply, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reject 拒绝申请
|
||||||
|
func (s *FriendLinkApplyService) Reject(id uint, note string) (*model.FriendLinkApply, error) {
|
||||||
|
apply, err := s.getPending(id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
note = strings.TrimSpace(note)
|
||||||
|
now := time.Now()
|
||||||
|
if err := model.DB.Model(apply).Updates(map[string]interface{}{
|
||||||
|
"status": model.FriendLinkApplyStatusRejected,
|
||||||
|
"review_note": note,
|
||||||
|
"reviewed_at": now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
apply.Status = model.FriendLinkApplyStatusRejected
|
||||||
|
apply.ReviewNote = note
|
||||||
|
apply.ReviewedAt = &now
|
||||||
|
|
||||||
|
if s.messages != nil && apply.UserID > 0 {
|
||||||
|
subject := "友情链接申请未通过"
|
||||||
|
reason := note
|
||||||
|
if reason == "" {
|
||||||
|
reason = "未说明具体原因"
|
||||||
|
}
|
||||||
|
content := fmt.Sprintf(
|
||||||
|
"你申请的友情链接「%s」(%s)未通过审核。\n\n原因:\n%s\n\n如有疑问,可回复本私信联系管理员。",
|
||||||
|
apply.Name, apply.URL, reason,
|
||||||
|
)
|
||||||
|
_, _ = s.messages.SendSystem(apply.UserID, subject, content, model.MessageKindReject, nil, nil)
|
||||||
|
}
|
||||||
|
return apply, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *FriendLinkApplyService) prepareApplyFields(in FriendLinkApplyInput, allowPublishedURL string) (name, href, logo, reciprocal string, err error) {
|
||||||
|
name = strings.TrimSpace(in.Name)
|
||||||
|
href, err = normalizeFriendLinkApplyURL(in.URL)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
logo, err = normalizeFriendLinkLogo(in.Logo)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if name == "" {
|
||||||
|
err = errors.New("请填写站点名称")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(name) > maxFriendLinkName {
|
||||||
|
err = fmt.Errorf("站点名称最多 %d 字", maxFriendLinkName)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if s.urlInFriendLinks(href) && friendLinkURLKey(href) != friendLinkURLKey(allowPublishedURL) {
|
||||||
|
err = ErrFriendLinkApplyExists
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
reciprocal = strings.TrimSpace(in.ReciprocalPageURL)
|
||||||
|
if in.LinkOnHomepage {
|
||||||
|
reciprocal = href
|
||||||
|
} else {
|
||||||
|
reciprocal, err = normalizeFriendLinkApplyURL(reciprocal)
|
||||||
|
if err != nil {
|
||||||
|
err = errors.New("请填写添加本站链接的页面地址")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *FriendLinkApplyService) hasPendingApplyForURL(userID, excludeID uint, href string) (bool, error) {
|
||||||
|
db := model.DB.Model(&model.FriendLinkApply{}).
|
||||||
|
Where("user_id = ? AND status = ? AND url = ?", userID, model.FriendLinkApplyStatusPending, href)
|
||||||
|
if excludeID > 0 {
|
||||||
|
db = db.Where("id <> ?", excludeID)
|
||||||
|
}
|
||||||
|
var pending int64
|
||||||
|
if err := db.Count(&pending).Error; err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return pending > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *FriendLinkApplyService) removePublishedFriendLink(href string) error {
|
||||||
|
key := friendLinkURLKey(href)
|
||||||
|
brand := s.settings.SiteBranding()
|
||||||
|
next := make([]FriendLink, 0, len(brand.FriendLinks))
|
||||||
|
removed := false
|
||||||
|
for _, l := range brand.FriendLinks {
|
||||||
|
if friendLinkURLKey(l.URL) == key {
|
||||||
|
removed = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
next = append(next, l)
|
||||||
|
}
|
||||||
|
if !removed {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return s.settings.UpdateSiteBranding(SiteBranding{
|
||||||
|
Name: brand.Name,
|
||||||
|
Slogan: brand.Slogan,
|
||||||
|
Description: brand.Description,
|
||||||
|
Keywords: brand.Keywords,
|
||||||
|
LogoMark: brand.LogoMark,
|
||||||
|
Logo: brand.Logo,
|
||||||
|
Favicon: brand.Favicon,
|
||||||
|
OGImage: brand.OGImage,
|
||||||
|
ICPBeian: brand.ICPBeian,
|
||||||
|
ICPBeianURL: brand.ICPBeianURL,
|
||||||
|
FriendLinks: next,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update 修改并重新提交友链申请(待审 / 已拒绝 / 已通过)
|
||||||
|
func (s *FriendLinkApplyService) Update(userID, id uint, in FriendLinkApplyInput) (*FriendLinkApplyCreateResult, error) {
|
||||||
|
var apply model.FriendLinkApply
|
||||||
|
if err := model.DB.First(&apply, id).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrFriendLinkApplyNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if apply.UserID != userID {
|
||||||
|
return nil, errors.New("无权操作该申请")
|
||||||
|
}
|
||||||
|
if apply.Status != model.FriendLinkApplyStatusPending &&
|
||||||
|
apply.Status != model.FriendLinkApplyStatusRejected &&
|
||||||
|
apply.Status != model.FriendLinkApplyStatusApproved {
|
||||||
|
return nil, errors.New("该申请不可修改")
|
||||||
|
}
|
||||||
|
|
||||||
|
wasApproved := apply.Status == model.FriendLinkApplyStatusApproved
|
||||||
|
allowPublishedURL := ""
|
||||||
|
if wasApproved {
|
||||||
|
allowPublishedURL = apply.URL
|
||||||
|
}
|
||||||
|
|
||||||
|
name, href, logo, reciprocal, err := s.prepareApplyFields(in, allowPublishedURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
dup, err := s.hasPendingApplyForURL(userID, id, href)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if dup {
|
||||||
|
return nil, ErrFriendLinkApplyPending
|
||||||
|
}
|
||||||
|
|
||||||
|
if wasApproved {
|
||||||
|
if err := s.removePublishedFriendLink(apply.URL); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
updates := map[string]interface{}{
|
||||||
|
"name": name,
|
||||||
|
"url": href,
|
||||||
|
"logo": logo,
|
||||||
|
"reciprocal_page_url": reciprocal,
|
||||||
|
"link_on_homepage": in.LinkOnHomepage,
|
||||||
|
"reciprocal_verified": false,
|
||||||
|
"reciprocal_check_note": "",
|
||||||
|
"reciprocal_checked_at": nil,
|
||||||
|
"status": model.FriendLinkApplyStatusPending,
|
||||||
|
"review_note": "",
|
||||||
|
"reviewed_at": nil,
|
||||||
|
}
|
||||||
|
if err := model.DB.Model(&apply).Updates(updates).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
s.startReciprocalCheck(apply.ID, reciprocal, in.OurSiteURL)
|
||||||
|
_ = model.DB.Preload("User").First(&apply, apply.ID).Error
|
||||||
|
return &FriendLinkApplyCreateResult{Apply: &apply}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecheckReciprocal 管理员触发重新检测回链
|
||||||
|
func (s *FriendLinkApplyService) RecheckReciprocal(id uint, ourSiteURL string) (*model.FriendLinkApply, error) {
|
||||||
|
if !s.settings.FriendLinkReciprocalCheckEnabled() {
|
||||||
|
return nil, errors.New("回链检测已关闭")
|
||||||
|
}
|
||||||
|
var apply model.FriendLinkApply
|
||||||
|
if err := model.DB.Preload("User").First(&apply, id).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrFriendLinkApplyNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(apply.ReciprocalPageURL) == "" {
|
||||||
|
return nil, errors.New("该申请未填写回链页")
|
||||||
|
}
|
||||||
|
ResetReciprocalCheckState(apply.ID)
|
||||||
|
EnqueueReciprocalCheck(apply.ID, apply.ReciprocalPageURL, ourSiteURL)
|
||||||
|
apply.ReciprocalVerified = false
|
||||||
|
apply.ReciprocalCheckNote = ""
|
||||||
|
apply.ReciprocalCheckedAt = nil
|
||||||
|
return &apply, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// startReciprocalCheck 按开关启动回链检测;关闭时标记为已结束,避免前台一直显示「检测中」
|
||||||
|
func (s *FriendLinkApplyService) startReciprocalCheck(applyID uint, pageURL, ourSiteURL string) {
|
||||||
|
if s.settings.FriendLinkReciprocalCheckEnabled() {
|
||||||
|
EnqueueReciprocalCheck(applyID, pageURL, ourSiteURL)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
_ = model.DB.Model(&model.FriendLinkApply{}).Where("id = ?", applyID).Updates(map[string]interface{}{
|
||||||
|
"reciprocal_verified": false,
|
||||||
|
"reciprocal_check_note": "",
|
||||||
|
"reciprocal_checked_at": now,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListMine 当前用户的友链申请
|
||||||
|
func (s *FriendLinkApplyService) ListMine(userID uint) ([]model.FriendLinkApply, error) {
|
||||||
|
var list []model.FriendLinkApply
|
||||||
|
err := model.DB.Where("user_id = ?", userID).
|
||||||
|
Order("id DESC").
|
||||||
|
Limit(50).
|
||||||
|
Find(&list).Error
|
||||||
|
return list, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cancel 撤销待审申请
|
||||||
|
func (s *FriendLinkApplyService) Cancel(userID, id uint) error {
|
||||||
|
var apply model.FriendLinkApply
|
||||||
|
if err := model.DB.First(&apply, id).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrFriendLinkApplyNotFound
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if apply.UserID != userID {
|
||||||
|
return errors.New("无权操作该申请")
|
||||||
|
}
|
||||||
|
if apply.Status != model.FriendLinkApplyStatusPending {
|
||||||
|
return ErrFriendLinkApplyHandled
|
||||||
|
}
|
||||||
|
return model.DB.Delete(&apply).Error
|
||||||
|
}
|
||||||
93
service/friend_link_enrich.go
Normal file
93
service/friend_link_enrich.go
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EnrichFriendLinksLogos 为缺少 LOGO 的已发布友链,从已通过申请中按 URL 回填
|
||||||
|
func EnrichFriendLinksLogos(links []FriendLink) []FriendLink {
|
||||||
|
if len(links) == 0 {
|
||||||
|
return links
|
||||||
|
}
|
||||||
|
needKeys := make(map[string]int)
|
||||||
|
for i, l := range links {
|
||||||
|
if strings.TrimSpace(l.Logo) != "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
key := friendLinkURLKey(l.URL)
|
||||||
|
if key == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
needKeys[key] = i
|
||||||
|
}
|
||||||
|
if len(needKeys) == 0 {
|
||||||
|
return links
|
||||||
|
}
|
||||||
|
|
||||||
|
var applies []model.FriendLinkApply
|
||||||
|
_ = model.DB.
|
||||||
|
Where("status = ? AND logo <> ''", model.FriendLinkApplyStatusApproved).
|
||||||
|
Order("id DESC").
|
||||||
|
Find(&applies).Error
|
||||||
|
|
||||||
|
logoByURL := make(map[string]string, len(applies))
|
||||||
|
for _, a := range applies {
|
||||||
|
key := friendLinkURLKey(a.URL)
|
||||||
|
if key == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := logoByURL[key]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
logo := normalizeFriendLinkLogoOptional(a.Logo)
|
||||||
|
if logo != "" {
|
||||||
|
logoByURL[key] = logo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(logoByURL) == 0 {
|
||||||
|
return links
|
||||||
|
}
|
||||||
|
|
||||||
|
out := make([]FriendLink, len(links))
|
||||||
|
copy(out, links)
|
||||||
|
for key, idx := range needKeys {
|
||||||
|
if logo, ok := logoByURL[key]; ok {
|
||||||
|
out[idx].Logo = logo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func friendLinksLogoSnapshot(links []FriendLink) string {
|
||||||
|
type snap struct {
|
||||||
|
URL string `json:"url"`
|
||||||
|
Logo string `json:"logo"`
|
||||||
|
}
|
||||||
|
items := make([]snap, len(links))
|
||||||
|
for i, l := range links {
|
||||||
|
items[i] = snap{URL: friendLinkURLKey(l.URL), Logo: strings.TrimSpace(l.Logo)}
|
||||||
|
}
|
||||||
|
b, _ := json.Marshal(items)
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// maybePersistEnrichedFriendLinks 若回填产生新 LOGO,写回 site_friend_links
|
||||||
|
func (s *ForumSettingsService) maybePersistEnrichedFriendLinks(enriched []FriendLink) error {
|
||||||
|
raw := s.getString(SettingSiteFriendLinks, "[]")
|
||||||
|
before := parseFriendLinksJSON(raw)
|
||||||
|
if friendLinksLogoSnapshot(before) == friendLinksLogoSnapshot(enriched) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
normalized, err := normalizeFriendLinks(enriched)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
linksJSON, err := json.Marshal(normalized)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return s.setString(SettingSiteFriendLinks, string(linksJSON))
|
||||||
|
}
|
||||||
269
service/friend_link_reciprocal.go
Normal file
269
service/friend_link_reciprocal.go
Normal file
@@ -0,0 +1,269 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
reciprocalCheckTimeout = 8 * time.Second // 整次检测硬上限(DNS / 抓取 / 解析)
|
||||||
|
reciprocalFetchTimeout = 5 * time.Second
|
||||||
|
reciprocalMaxBodyBytes = 512 * 1024
|
||||||
|
reciprocalMaxHrefs = 4000
|
||||||
|
)
|
||||||
|
|
||||||
|
var hrefRe = regexp.MustCompile(`(?i)<a[^>]+href=["']([^"']+)["']`)
|
||||||
|
|
||||||
|
// VerifyReciprocalLink 检测页面 HTML 是否包含指向本站的链接
|
||||||
|
func VerifyReciprocalLink(pageURL, ourSiteURL string) (verified bool, note string) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), reciprocalCheckTimeout)
|
||||||
|
defer cancel()
|
||||||
|
return verifyReciprocalLink(ctx, pageURL, ourSiteURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyReciprocalLink(ctx context.Context, pageURL, ourSiteURL string) (verified bool, note string) {
|
||||||
|
pageURL = strings.TrimSpace(pageURL)
|
||||||
|
ourSiteURL = strings.TrimSpace(ourSiteURL)
|
||||||
|
if pageURL == "" {
|
||||||
|
return false, "未提供回链页地址"
|
||||||
|
}
|
||||||
|
if ourSiteURL == "" {
|
||||||
|
return false, "本站 URL 未配置"
|
||||||
|
}
|
||||||
|
|
||||||
|
pageParsed, err := normalizeFriendLinkApplyURL(pageURL)
|
||||||
|
if err != nil {
|
||||||
|
return false, err.Error()
|
||||||
|
}
|
||||||
|
ourParsed, err := url.Parse(ourSiteURL)
|
||||||
|
if err != nil || ourParsed.Host == "" {
|
||||||
|
return false, "本站 URL 无效"
|
||||||
|
}
|
||||||
|
ourHost := strings.ToLower(strings.TrimSuffix(ourParsed.Host, ":443"))
|
||||||
|
ourHost = strings.TrimSuffix(ourHost, ":80")
|
||||||
|
|
||||||
|
if err := assertSafeFetchURL(ctx, pageParsed); err != nil {
|
||||||
|
return false, err.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := fetchHTMLBody(ctx, pageParsed)
|
||||||
|
if err != nil {
|
||||||
|
if isTimeoutErr(err) || ctx.Err() != nil {
|
||||||
|
return false, "访问回链页超时"
|
||||||
|
}
|
||||||
|
return false, fmt.Sprintf("无法访问回链页:%v", err)
|
||||||
|
}
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return false, "访问回链页超时"
|
||||||
|
}
|
||||||
|
|
||||||
|
if pageContainsLinkToHost(body, pageParsed, ourParsed, ourHost) {
|
||||||
|
return true, "已检测到本站链接"
|
||||||
|
}
|
||||||
|
return false, "未在该页面检测到指向本站的链接"
|
||||||
|
}
|
||||||
|
|
||||||
|
func isTimeoutErr(err error) bool {
|
||||||
|
if err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
var ne net.Error
|
||||||
|
return errors.As(err, &ne) && ne.Timeout()
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertSafeFetchURL(ctx context.Context, raw string) error {
|
||||||
|
u, err := url.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("URL 无效")
|
||||||
|
}
|
||||||
|
if u.Scheme != "http" && u.Scheme != "https" {
|
||||||
|
return fmt.Errorf("仅支持 http/https")
|
||||||
|
}
|
||||||
|
host := u.Hostname()
|
||||||
|
if host == "" {
|
||||||
|
return fmt.Errorf("URL 无效")
|
||||||
|
}
|
||||||
|
lower := strings.ToLower(host)
|
||||||
|
if lower == "localhost" || strings.HasSuffix(lower, ".localhost") || lower == "0.0.0.0" {
|
||||||
|
return fmt.Errorf("不允许访问内网地址")
|
||||||
|
}
|
||||||
|
ips, err := lookupHostIPs(ctx, host)
|
||||||
|
if err != nil {
|
||||||
|
if isTimeoutErr(err) {
|
||||||
|
return fmt.Errorf("解析域名超时")
|
||||||
|
}
|
||||||
|
return fmt.Errorf("无法解析域名")
|
||||||
|
}
|
||||||
|
for _, ip := range ips {
|
||||||
|
if isPrivateOrLoopbackIP(ip) {
|
||||||
|
return fmt.Errorf("不允许访问内网地址")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookupHostIPs(ctx context.Context, host string) ([]net.IP, error) {
|
||||||
|
addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ips := make([]net.IP, 0, len(addrs))
|
||||||
|
for _, a := range addrs {
|
||||||
|
if a.IP != nil {
|
||||||
|
ips = append(ips, a.IP)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ips, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func isPrivateOrLoopbackIP(ip net.IP) bool {
|
||||||
|
if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if ip4 := ip.To4(); ip4 != nil {
|
||||||
|
return ip4[0] == 10 ||
|
||||||
|
(ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31) ||
|
||||||
|
(ip4[0] == 192 && ip4[1] == 168) ||
|
||||||
|
(ip4[0] == 127) ||
|
||||||
|
(ip4[0] == 169 && ip4[1] == 254) ||
|
||||||
|
(ip4[0] == 0)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchHTMLBody(ctx context.Context, rawURL string) (string, error) {
|
||||||
|
client := &http.Client{
|
||||||
|
Timeout: reciprocalFetchTimeout,
|
||||||
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
|
if len(via) >= 5 {
|
||||||
|
return fmt.Errorf("重定向过多")
|
||||||
|
}
|
||||||
|
if err := assertSafeFetchURL(req.Context(), req.URL.String()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
req.Close = true
|
||||||
|
req.Header.Set("User-Agent", "Jiang13Forum-FriendLinkCheck/1.0")
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
|
||||||
|
return "", fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
limited := io.LimitReader(resp.Body, reciprocalMaxBodyBytes+1)
|
||||||
|
data, err := io.ReadAll(limited)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(data) > reciprocalMaxBodyBytes {
|
||||||
|
return "", fmt.Errorf("页面过大")
|
||||||
|
}
|
||||||
|
return string(data), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func pageContainsLinkToHost(html, pageURL string, ourURL *url.URL, ourHost string) bool {
|
||||||
|
ourHost = strings.ToLower(ourHost)
|
||||||
|
ourPath := strings.TrimSuffix(ourURL.Path, "/")
|
||||||
|
if ourPath == "" {
|
||||||
|
ourPath = "/"
|
||||||
|
}
|
||||||
|
|
||||||
|
base, err := url.Parse(pageURL)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
checkHref := func(href string) bool {
|
||||||
|
href = strings.TrimSpace(href)
|
||||||
|
if href == "" || strings.HasPrefix(strings.ToLower(href), "javascript:") || strings.HasPrefix(strings.ToLower(href), "mailto:") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
resolved, err := url.Parse(href)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
resolved = base.ResolveReference(resolved)
|
||||||
|
host := strings.ToLower(resolved.Hostname())
|
||||||
|
if host == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
host = strings.TrimSuffix(strings.TrimSuffix(host, ":443"), ":80")
|
||||||
|
if host != ourHost {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
path := strings.TrimSuffix(resolved.Path, "/")
|
||||||
|
if path == "" {
|
||||||
|
path = "/"
|
||||||
|
}
|
||||||
|
// 允许首页或完整路径匹配
|
||||||
|
if ourPath == "/" || path == ourPath || strings.HasPrefix(path, ourPath+"/") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return path == "/" || ourPath == path
|
||||||
|
}
|
||||||
|
|
||||||
|
// 逐条扫描,命中即停;限制条数避免超大页面占用过多 CPU
|
||||||
|
rest := html
|
||||||
|
for i := 0; i < reciprocalMaxHrefs; i++ {
|
||||||
|
loc := hrefRe.FindStringSubmatchIndex(rest)
|
||||||
|
if loc == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if loc[2] >= 0 && loc[3] >= loc[2] && checkHref(rest[loc[2]:loc[3]]) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if loc[1] <= 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
rest = rest[loc[1]:]
|
||||||
|
}
|
||||||
|
// 兜底:页面源码中包含本站域名
|
||||||
|
lower := strings.ToLower(html)
|
||||||
|
if strings.Contains(lower, ourHost) {
|
||||||
|
return strings.Contains(lower, ourHost+"/") ||
|
||||||
|
strings.Contains(lower, "://"+ourHost)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeFriendLinkLogo(raw string) (string, error) {
|
||||||
|
logo := strings.TrimSpace(raw)
|
||||||
|
if logo == "" {
|
||||||
|
return "", fmt.Errorf("请填写或上传网站 LOGO")
|
||||||
|
}
|
||||||
|
if len(logo) > maxFriendLinkURL {
|
||||||
|
return "", fmt.Errorf("LOGO 地址过长")
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(logo, "/uploads/") {
|
||||||
|
return logo, nil
|
||||||
|
}
|
||||||
|
return normalizeFriendLinkApplyURL(logo)
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalizeFriendLinkLogoOptional LOGO 可选(友链列表项)
|
||||||
|
func normalizeFriendLinkLogoOptional(raw string) string {
|
||||||
|
logo, err := normalizeFriendLinkLogo(raw)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return logo
|
||||||
|
}
|
||||||
62
service/friend_link_reciprocal_async.go
Normal file
62
service/friend_link_reciprocal_async.go
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
const reciprocalCheckConcurrency = 3
|
||||||
|
|
||||||
|
var (
|
||||||
|
reciprocalCheckMu sync.Mutex
|
||||||
|
reciprocalCheckGen = map[uint]uint64{}
|
||||||
|
reciprocalCheckSem = make(chan struct{}, reciprocalCheckConcurrency)
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
for i := 0; i < reciprocalCheckConcurrency; i++ {
|
||||||
|
reciprocalCheckSem <- struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnqueueReciprocalCheck 异步检测回链;同一申请多次入队时仅保留最后一次结果
|
||||||
|
func EnqueueReciprocalCheck(applyID uint, pageURL, ourSiteURL string) {
|
||||||
|
reciprocalCheckMu.Lock()
|
||||||
|
reciprocalCheckGen[applyID]++
|
||||||
|
gen := reciprocalCheckGen[applyID]
|
||||||
|
reciprocalCheckMu.Unlock()
|
||||||
|
|
||||||
|
go runReciprocalCheck(applyID, gen, pageURL, ourSiteURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runReciprocalCheck(applyID uint, gen uint64, pageURL, ourSiteURL string) {
|
||||||
|
reciprocalCheckSem <- struct{}{}
|
||||||
|
defer func() { <-reciprocalCheckSem }()
|
||||||
|
|
||||||
|
verified, note := VerifyReciprocalLink(pageURL, ourSiteURL)
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
reciprocalCheckMu.Lock()
|
||||||
|
if reciprocalCheckGen[applyID] != gen {
|
||||||
|
reciprocalCheckMu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reciprocalCheckMu.Unlock()
|
||||||
|
|
||||||
|
_ = model.DB.Model(&model.FriendLinkApply{}).Where("id = ?", applyID).Updates(map[string]interface{}{
|
||||||
|
"reciprocal_verified": verified,
|
||||||
|
"reciprocal_check_note": note,
|
||||||
|
"reciprocal_checked_at": now,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResetReciprocalCheckState 重置为检测中,供重新检测使用
|
||||||
|
func ResetReciprocalCheckState(applyID uint) {
|
||||||
|
_ = model.DB.Model(&model.FriendLinkApply{}).Where("id = ?", applyID).Updates(map[string]interface{}{
|
||||||
|
"reciprocal_verified": false,
|
||||||
|
"reciprocal_check_note": "",
|
||||||
|
"reciprocal_checked_at": nil,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
46
service/friend_link_reciprocal_test.go
Normal file
46
service/friend_link_reciprocal_test.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPageContainsLinkToHost(t *testing.T) {
|
||||||
|
our, err := url.Parse("https://forum.example.com")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
page := "https://friend.example/links.html"
|
||||||
|
host := "forum.example.com"
|
||||||
|
|
||||||
|
if !pageContainsLinkToHost(`<a href="https://forum.example.com/">本站</a>`, page, our, host) {
|
||||||
|
t.Fatal("应检测到绝对回链")
|
||||||
|
}
|
||||||
|
if pageContainsLinkToHost(`<a href="https://other.example/">其他</a>`, page, our, host) {
|
||||||
|
t.Fatal("不应把外站当成回链")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPageContainsLinkToHost_LargeHTMLFast(t *testing.T) {
|
||||||
|
our, err := url.Parse("https://forum.example.com")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
b.Grow(512 * 1024)
|
||||||
|
for b.Len() < 400*1024 {
|
||||||
|
b.WriteString(`<a href="https://noise.example/page">x</a>`)
|
||||||
|
}
|
||||||
|
b.WriteString(`<a href="https://forum.example.com/">本站</a>`)
|
||||||
|
html := b.String()
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
if !pageContainsLinkToHost(html, "https://friend.example/", our, "forum.example.com") {
|
||||||
|
t.Fatal("应在大量无关链接中找到回链")
|
||||||
|
}
|
||||||
|
if elapsed := time.Since(start); elapsed > 500*time.Millisecond {
|
||||||
|
t.Fatalf("解析耗时过长: %s", elapsed)
|
||||||
|
}
|
||||||
|
}
|
||||||
150
service/lottery_post.go
Normal file
150
service/lottery_post.go
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"errors"
|
||||||
|
"math/big"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrLotteryAlreadyDrawn = errors.New("已开奖")
|
||||||
|
ErrLotteryNotEnough = errors.New("参与人数不足")
|
||||||
|
)
|
||||||
|
|
||||||
|
// PostLotteryView 帖内抽奖视图
|
||||||
|
type PostLotteryView struct {
|
||||||
|
WinnerCount int `json:"winner_count"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
ParticipantCount int `json:"participant_count"`
|
||||||
|
Winners []PostLotteryWinnerView `json:"winners,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PostLotteryWinnerView struct {
|
||||||
|
UserID uint `json:"user_id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Nickname string `json:"nickname"`
|
||||||
|
CommentID uint `json:"comment_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// InitPostLottery 初始化抽奖帖
|
||||||
|
func InitPostLottery(postID uint, winnerCount int) error {
|
||||||
|
if winnerCount < 1 || winnerCount > 20 {
|
||||||
|
return errors.New("开奖人数需 1-20")
|
||||||
|
}
|
||||||
|
return model.DB.Model(&model.Post{}).Where("id = ?", postID).Updates(map[string]interface{}{
|
||||||
|
"lottery_winner_count": winnerCount,
|
||||||
|
"lottery_status": model.PostLotteryStatusOpen,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPostLotteryView 获取抽奖视图
|
||||||
|
func GetPostLotteryView(post *model.Post) (*PostLotteryView, error) {
|
||||||
|
if post == nil || post.PostType != model.PostTypeLottery {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
participants, err := lotteryParticipants(post.ID, post.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
view := &PostLotteryView{
|
||||||
|
WinnerCount: post.LotteryWinnerCount,
|
||||||
|
Status: post.LotteryStatus,
|
||||||
|
ParticipantCount: len(participants),
|
||||||
|
}
|
||||||
|
if post.LotteryStatus == model.PostLotteryStatusDrawn {
|
||||||
|
var winners []model.PostLotteryWinner
|
||||||
|
model.DB.Preload("User").Where("post_id = ?", post.ID).Find(&winners)
|
||||||
|
for _, w := range winners {
|
||||||
|
view.Winners = append(view.Winners, PostLotteryWinnerView{
|
||||||
|
UserID: w.UserID, Username: w.User.Username, Nickname: w.User.Nickname,
|
||||||
|
CommentID: w.CommentID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return view, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func lotteryParticipants(postID, authorID uint) ([]model.Comment, error) {
|
||||||
|
var comments []model.Comment
|
||||||
|
err := model.DB.Where("post_id = ? AND status = ? AND user_id <> ?", postID, model.ContentStatusPublished, authorID).
|
||||||
|
Order("id ASC").Find(&comments).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
seen := map[uint]bool{}
|
||||||
|
var unique []model.Comment
|
||||||
|
for _, c := range comments {
|
||||||
|
if seen[c.UserID] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[c.UserID] = true
|
||||||
|
unique = append(unique, c)
|
||||||
|
}
|
||||||
|
return unique, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DrawPostLottery 开奖
|
||||||
|
func DrawPostLottery(postID, operatorID uint, isAdmin bool) (*PostLotteryView, error) {
|
||||||
|
var post model.Post
|
||||||
|
if err := model.DB.First(&post, postID).Error; err != nil {
|
||||||
|
return nil, ErrPostNotFound
|
||||||
|
}
|
||||||
|
if post.PostType != model.PostTypeLottery {
|
||||||
|
return nil, errors.New("非抽奖帖")
|
||||||
|
}
|
||||||
|
if !isAdmin && post.UserID != operatorID {
|
||||||
|
return nil, ErrPermissionDenied
|
||||||
|
}
|
||||||
|
if post.LotteryStatus == model.PostLotteryStatusDrawn {
|
||||||
|
return nil, ErrLotteryAlreadyDrawn
|
||||||
|
}
|
||||||
|
participants, err := lotteryParticipants(postID, post.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
need := post.LotteryWinnerCount
|
||||||
|
if need < 1 {
|
||||||
|
need = 1
|
||||||
|
}
|
||||||
|
if len(participants) < need {
|
||||||
|
return nil, ErrLotteryNotEnough
|
||||||
|
}
|
||||||
|
picked := randomPickComments(participants, need)
|
||||||
|
err = model.DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
for _, c := range picked {
|
||||||
|
w := model.PostLotteryWinner{PostID: postID, UserID: c.UserID, CommentID: c.ID}
|
||||||
|
if err := tx.Create(&w).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tx.Model(&post).Update("lottery_status", model.PostLotteryStatusDrawn).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
post.LotteryStatus = model.PostLotteryStatusDrawn
|
||||||
|
return GetPostLotteryView(&post)
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomPickComments(comments []model.Comment, n int) []model.Comment {
|
||||||
|
pool := append([]model.Comment{}, comments...)
|
||||||
|
out := make([]model.Comment, 0, n)
|
||||||
|
for i := 0; i < n && len(pool) > 0; i++ {
|
||||||
|
idx, err := rand.Int(rand.Reader, big.NewInt(int64(len(pool))))
|
||||||
|
if err != nil {
|
||||||
|
idx = big.NewInt(0)
|
||||||
|
}
|
||||||
|
j := int(idx.Int64())
|
||||||
|
out = append(out, pool[j])
|
||||||
|
pool = append(pool[:j], pool[j+1:]...)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteLotteryData 删帖清理
|
||||||
|
func DeleteLotteryData(tx *gorm.DB, postID uint) {
|
||||||
|
tx.Where("post_id = ?", postID).Delete(&model.PostLotteryWinner{})
|
||||||
|
}
|
||||||
@@ -15,9 +15,12 @@ const (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
permalinkExtRe = regexp.MustCompile(`(?i)^[a-z0-9]{1,16}$`)
|
permalinkExtRe = regexp.MustCompile(`(?i)^[a-z0-9]{1,16}$`)
|
||||||
|
slugPermalinkRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$`)
|
||||||
// /post/123 或 /post/123.html
|
// /post/123 或 /post/123.html
|
||||||
postPermalinkRe = regexp.MustCompile(`^/post/(\d+)(?:\.([A-Za-z0-9]{1,16}))?/?$`)
|
postPermalinkRe = regexp.MustCompile(`^/post/(\d+)(?:\.([A-Za-z0-9]{1,16}))?/?$`)
|
||||||
userPermalinkRe = regexp.MustCompile(`^/user/(\d+)(?:\.([A-Za-z0-9]{1,16}))?/?$`)
|
userPermalinkRe = regexp.MustCompile(`^/user/(\d+)(?:\.([A-Za-z0-9]{1,16}))?/?$`)
|
||||||
|
boardPermalinkRe = regexp.MustCompile(`^/board/(\d+)(?:\.([A-Za-z0-9]{1,16}))?/?$`)
|
||||||
|
pagePermalinkRe = regexp.MustCompile(`^/page/([a-z0-9][a-z0-9-]*[a-z0-9]|[a-z0-9])(?:\.([A-Za-z0-9]{1,16}))?/?$`)
|
||||||
)
|
)
|
||||||
|
|
||||||
// PermalinkConfig 伪静态(固定链接)配置
|
// PermalinkConfig 伪静态(固定链接)配置
|
||||||
@@ -74,6 +77,32 @@ func (p PermalinkConfig) UserPath(id uint) string {
|
|||||||
return fmt.Sprintf("/user/%d%s", id, p.Suffix())
|
return fmt.Sprintf("/user/%d%s", id, p.Suffix())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BoardPath 板块规范路径
|
||||||
|
func (p PermalinkConfig) BoardPath(id uint) string {
|
||||||
|
return fmt.Sprintf("/board/%d%s", id, p.Suffix())
|
||||||
|
}
|
||||||
|
|
||||||
|
// PagePath 自定义单页规范路径
|
||||||
|
func (p PermalinkConfig) PagePath(slug string) string {
|
||||||
|
slug = strings.TrimSpace(strings.ToLower(slug))
|
||||||
|
if slug == "" {
|
||||||
|
return "/"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("/page/%s%s", slug, p.Suffix())
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizePageSlug 校验单页 slug
|
||||||
|
func NormalizePageSlug(raw string) (string, bool) {
|
||||||
|
slug := strings.TrimSpace(strings.ToLower(raw))
|
||||||
|
if slug == "" || len(slug) > 64 {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
if !slugPermalinkRe.MatchString(slug) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return slug, true
|
||||||
|
}
|
||||||
|
|
||||||
// PermalinkMatch 路径解析结果
|
// PermalinkMatch 路径解析结果
|
||||||
type PermalinkMatch struct {
|
type PermalinkMatch struct {
|
||||||
ID uint
|
ID uint
|
||||||
@@ -105,6 +134,56 @@ func (p PermalinkConfig) MatchPostPath(path string) PermalinkMatch {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MatchBoardPath 解析板块公开路径
|
||||||
|
func (p PermalinkConfig) MatchBoardPath(path string) PermalinkMatch {
|
||||||
|
m := boardPermalinkRe.FindStringSubmatch(path)
|
||||||
|
if len(m) < 2 {
|
||||||
|
return PermalinkMatch{}
|
||||||
|
}
|
||||||
|
id64, err := strconv.ParseUint(m[1], 10, 64)
|
||||||
|
if err != nil || id64 == 0 {
|
||||||
|
return PermalinkMatch{}
|
||||||
|
}
|
||||||
|
ext := ""
|
||||||
|
if len(m) > 2 {
|
||||||
|
ext = strings.ToLower(m[2])
|
||||||
|
}
|
||||||
|
id := uint(id64)
|
||||||
|
return PermalinkMatch{
|
||||||
|
ID: id,
|
||||||
|
Ext: ext,
|
||||||
|
Canonical: p.BoardPath(id),
|
||||||
|
OK: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PagePermalinkMatch slug 型路径解析结果
|
||||||
|
type PagePermalinkMatch struct {
|
||||||
|
Slug string
|
||||||
|
Ext string
|
||||||
|
Canonical string
|
||||||
|
OK bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// MatchPagePath 解析自定义单页路径
|
||||||
|
func (p PermalinkConfig) MatchPagePath(path string) PagePermalinkMatch {
|
||||||
|
m := pagePermalinkRe.FindStringSubmatch(path)
|
||||||
|
if len(m) < 2 {
|
||||||
|
return PagePermalinkMatch{}
|
||||||
|
}
|
||||||
|
slug := strings.ToLower(m[1])
|
||||||
|
ext := ""
|
||||||
|
if len(m) > 2 {
|
||||||
|
ext = strings.ToLower(m[2])
|
||||||
|
}
|
||||||
|
return PagePermalinkMatch{
|
||||||
|
Slug: slug,
|
||||||
|
Ext: ext,
|
||||||
|
Canonical: p.PagePath(slug),
|
||||||
|
OK: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// MatchUserPath 解析用户公开路径
|
// MatchUserPath 解析用户公开路径
|
||||||
func (p PermalinkConfig) MatchUserPath(path string) PermalinkMatch {
|
func (p PermalinkConfig) MatchUserPath(path string) PermalinkMatch {
|
||||||
m := userPermalinkRe.FindStringSubmatch(path)
|
m := userPermalinkRe.FindStringSubmatch(path)
|
||||||
|
|||||||
280
service/poll.go
Normal file
280
service/poll.go
Normal file
@@ -0,0 +1,280 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrPollClosed = errors.New("投票已结束")
|
||||||
|
ErrPollAlreadyVoted = errors.New("已投过票")
|
||||||
|
ErrPollInvalidVote = errors.New("无效的投票选项")
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
pollEndsAtMinLead = 5 * time.Minute
|
||||||
|
pollEndsAtMaxWindow = 365 * 24 * time.Hour
|
||||||
|
)
|
||||||
|
|
||||||
|
// PollOptionInput 创建投票时的选项
|
||||||
|
type PollOptionInput struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PollView 投票帖详情视图
|
||||||
|
type PollView struct {
|
||||||
|
Multi bool `json:"multi"`
|
||||||
|
MaxChoices int `json:"max_choices"`
|
||||||
|
Closed bool `json:"closed"`
|
||||||
|
EndsAt *time.Time `json:"ends_at,omitempty"`
|
||||||
|
Options []PollOptionView `json:"options"`
|
||||||
|
MyOptionIDs []uint `json:"my_option_ids,omitempty"`
|
||||||
|
TotalVotes int `json:"total_votes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PollOptionView struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
VoteCount int `json:"vote_count"`
|
||||||
|
Percent int `json:"percent,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreatePollForPost 为投票帖创建投票配置与选项
|
||||||
|
func CreatePollForPost(tx *gorm.DB, postID uint, multi bool, maxChoices int, endsAt *time.Time, options []PollOptionInput) error {
|
||||||
|
if len(options) < 2 || len(options) > 10 {
|
||||||
|
return errors.New("投票选项需 2-10 个")
|
||||||
|
}
|
||||||
|
if !multi {
|
||||||
|
maxChoices = 1
|
||||||
|
} else if maxChoices < 1 || maxChoices > len(options) {
|
||||||
|
maxChoices = len(options)
|
||||||
|
}
|
||||||
|
poll := model.Poll{PostID: postID, Multi: multi, MaxChoices: maxChoices, EndsAt: endsAt}
|
||||||
|
if err := tx.Create(&poll).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for i, opt := range options {
|
||||||
|
text := strings.TrimSpace(opt.Text)
|
||||||
|
if text == "" {
|
||||||
|
return errors.New("投票选项不能为空")
|
||||||
|
}
|
||||||
|
if len([]rune(text)) > 64 {
|
||||||
|
return errors.New("投票选项最多 64 字")
|
||||||
|
}
|
||||||
|
row := model.PollOption{PostID: postID, Text: text, SortOrder: i}
|
||||||
|
if err := tx.Create(&row).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParsePollOptionsJSON 解析发帖表单中的 poll_options JSON
|
||||||
|
func ParsePollOptionsJSON(raw string) ([]PollOptionInput, bool, int, *time.Time, error) {
|
||||||
|
raw = strings.TrimSpace(raw)
|
||||||
|
if raw == "" {
|
||||||
|
return nil, false, 1, nil, errors.New("投票选项不能为空")
|
||||||
|
}
|
||||||
|
var payload struct {
|
||||||
|
Multi bool `json:"multi"`
|
||||||
|
MaxChoices int `json:"max_choices"`
|
||||||
|
EndsAt string `json:"ends_at"`
|
||||||
|
Options []PollOptionInput `json:"options"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal([]byte(raw), &payload); err != nil {
|
||||||
|
return nil, false, 1, nil, err
|
||||||
|
}
|
||||||
|
endsAt, err := parsePollEndsAt(payload.EndsAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, 1, nil, err
|
||||||
|
}
|
||||||
|
return payload.Options, payload.Multi, payload.MaxChoices, endsAt, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parsePollEndsAt(raw string) (*time.Time, error) {
|
||||||
|
raw = strings.TrimSpace(raw)
|
||||||
|
if raw == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
var parsed time.Time
|
||||||
|
var ok bool
|
||||||
|
for _, layout := range []string{
|
||||||
|
time.RFC3339Nano,
|
||||||
|
time.RFC3339,
|
||||||
|
"2006-01-02T15:04:05",
|
||||||
|
"2006-01-02 15:04:05",
|
||||||
|
} {
|
||||||
|
if t, err := time.Parse(layout, raw); err == nil {
|
||||||
|
parsed = t
|
||||||
|
ok = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("投票截止时间格式无效")
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
if !parsed.After(now.Add(pollEndsAtMinLead)) {
|
||||||
|
return nil, errors.New("投票截止时间须晚于当前时间至少 5 分钟")
|
||||||
|
}
|
||||||
|
if parsed.After(now.Add(pollEndsAtMaxWindow)) {
|
||||||
|
return nil, errors.New("投票截止时间不能超过 365 天")
|
||||||
|
}
|
||||||
|
utc := parsed.UTC()
|
||||||
|
return &utc, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// closePollIfExpired 若已过截止时间则自动关闭投票
|
||||||
|
func closePollIfExpired(postID uint) error {
|
||||||
|
var poll model.Poll
|
||||||
|
if err := model.DB.Where("post_id = ?", postID).First(&poll).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if poll.Closed || poll.EndsAt == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if time.Now().Before(*poll.EndsAt) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
res := model.DB.Model(&poll).Where("post_id = ? AND closed = ?", postID, false).Update("closed", true)
|
||||||
|
return res.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPollView 获取投票视图
|
||||||
|
func GetPollView(postID, viewerID uint) (*PollView, error) {
|
||||||
|
if err := closePollIfExpired(postID); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var poll model.Poll
|
||||||
|
if err := model.DB.Where("post_id = ?", postID).First(&poll).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var opts []model.PollOption
|
||||||
|
if err := model.DB.Where("post_id = ?", postID).Order("sort_order ASC, id ASC").Find(&opts).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
total := 0
|
||||||
|
for _, o := range opts {
|
||||||
|
total += o.VoteCount
|
||||||
|
}
|
||||||
|
showResults := poll.Closed
|
||||||
|
var myIDs []uint
|
||||||
|
if viewerID > 0 {
|
||||||
|
var votes []model.PollVote
|
||||||
|
model.DB.Where("post_id = ? AND user_id = ?", postID, viewerID).Find(&votes)
|
||||||
|
for _, v := range votes {
|
||||||
|
myIDs = append(myIDs, v.OptionID)
|
||||||
|
}
|
||||||
|
if len(myIDs) > 0 {
|
||||||
|
showResults = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
views := make([]PollOptionView, len(opts))
|
||||||
|
for i, o := range opts {
|
||||||
|
v := PollOptionView{ID: o.ID, Text: o.Text, VoteCount: o.VoteCount}
|
||||||
|
if showResults && total > 0 {
|
||||||
|
v.Percent = o.VoteCount * 100 / total
|
||||||
|
}
|
||||||
|
views[i] = v
|
||||||
|
}
|
||||||
|
return &PollView{
|
||||||
|
Multi: poll.Multi, MaxChoices: poll.MaxChoices, Closed: poll.Closed,
|
||||||
|
EndsAt: poll.EndsAt, Options: views, MyOptionIDs: myIDs, TotalVotes: total,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VotePoll 用户投票
|
||||||
|
func VotePoll(postID, userID uint, optionIDs []uint) error {
|
||||||
|
if userID == 0 {
|
||||||
|
return ErrPermissionDenied
|
||||||
|
}
|
||||||
|
if err := closePollIfExpired(postID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var poll model.Poll
|
||||||
|
if err := model.DB.Where("post_id = ?", postID).First(&poll).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if poll.Closed {
|
||||||
|
return ErrPollClosed
|
||||||
|
}
|
||||||
|
var existing int64
|
||||||
|
model.DB.Model(&model.PollVote{}).Where("post_id = ? AND user_id = ?", postID, userID).Count(&existing)
|
||||||
|
if existing > 0 {
|
||||||
|
return ErrPollAlreadyVoted
|
||||||
|
}
|
||||||
|
if len(optionIDs) == 0 {
|
||||||
|
return ErrPollInvalidVote
|
||||||
|
}
|
||||||
|
if !poll.Multi && len(optionIDs) != 1 {
|
||||||
|
return errors.New("本投票为单选")
|
||||||
|
}
|
||||||
|
if poll.Multi && len(optionIDs) > poll.MaxChoices {
|
||||||
|
return errors.New("超出最多可选数")
|
||||||
|
}
|
||||||
|
seen := map[uint]bool{}
|
||||||
|
for _, oid := range optionIDs {
|
||||||
|
if oid == 0 || seen[oid] {
|
||||||
|
return ErrPollInvalidVote
|
||||||
|
}
|
||||||
|
seen[oid] = true
|
||||||
|
var opt model.PollOption
|
||||||
|
if err := model.DB.Where("id = ? AND post_id = ?", oid, postID).First(&opt).Error; err != nil {
|
||||||
|
return ErrPollInvalidVote
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return model.DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
for _, oid := range optionIDs {
|
||||||
|
v := model.PollVote{PostID: postID, OptionID: oid, UserID: userID}
|
||||||
|
if err := tx.Create(&v).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Model(&model.PollOption{}).Where("id = ?", oid).
|
||||||
|
UpdateColumn("vote_count", gorm.Expr("vote_count + 1")).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClosePoll 结束投票
|
||||||
|
func ClosePoll(postID, userID uint, isAdmin bool, postAuthorID uint) error {
|
||||||
|
if !isAdmin && userID != postAuthorID {
|
||||||
|
return ErrPermissionDenied
|
||||||
|
}
|
||||||
|
res := model.DB.Model(&model.Poll{}).Where("post_id = ?", postID).Update("closed", true)
|
||||||
|
if res.Error != nil {
|
||||||
|
return res.Error
|
||||||
|
}
|
||||||
|
if res.RowsAffected == 0 {
|
||||||
|
return errors.New("投票不存在")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LockPollOptions 编辑时锁定选项(已发布帖不允许改选项文案)
|
||||||
|
func LockPollOptions(postID uint) bool {
|
||||||
|
var n int64
|
||||||
|
model.DB.Model(&model.PollVote{}).Where("post_id = ?", postID).Count(&n)
|
||||||
|
return n > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsurePollExists 检查投票帖是否有 poll 记录
|
||||||
|
func EnsurePollExists(postID uint) bool {
|
||||||
|
var n int64
|
||||||
|
model.DB.Model(&model.Poll{}).Where("post_id = ?", postID).Count(&n)
|
||||||
|
return n > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeletePollData 删帖时清理投票数据
|
||||||
|
func DeletePollData(tx *gorm.DB, postID uint) {
|
||||||
|
tx.Where("post_id = ?", postID).Delete(&model.PollVote{})
|
||||||
|
tx.Where("post_id = ?", postID).Delete(&model.PollOption{})
|
||||||
|
tx.Where("post_id = ?", postID).Delete(&model.Poll{})
|
||||||
|
}
|
||||||
@@ -23,11 +23,21 @@ func normalizePostType(raw string) string {
|
|||||||
switch strings.TrimSpace(raw) {
|
switch strings.TrimSpace(raw) {
|
||||||
case model.PostTypeQuestion:
|
case model.PostTypeQuestion:
|
||||||
return model.PostTypeQuestion
|
return model.PostTypeQuestion
|
||||||
|
case model.PostTypePoll:
|
||||||
|
return model.PostTypePoll
|
||||||
|
case model.PostTypeBounty:
|
||||||
|
return model.PostTypeBounty
|
||||||
|
case model.PostTypeLottery:
|
||||||
|
return model.PostTypeLottery
|
||||||
default:
|
default:
|
||||||
return model.PostTypeNormal
|
return model.PostTypeNormal
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isSpecialPostType(t string) bool {
|
||||||
|
return t == model.PostTypePoll || t == model.PostTypeBounty || t == model.PostTypeLottery
|
||||||
|
}
|
||||||
|
|
||||||
type PostListQuery struct {
|
type PostListQuery struct {
|
||||||
BoardID uint
|
BoardID uint
|
||||||
UserID uint // >0 时仅返回该用户的帖子
|
UserID uint // >0 时仅返回该用户的帖子
|
||||||
@@ -479,6 +489,13 @@ func (s *PostService) Update(userID, postID uint, isAdmin, skipModeration bool,
|
|||||||
if strings.TrimSpace(postType) != "" {
|
if strings.TrimSpace(postType) != "" {
|
||||||
nextType = normalizePostType(postType)
|
nextType = normalizePostType(postType)
|
||||||
}
|
}
|
||||||
|
// 不允许修改特殊帖子类型(含 poll→normal、normal→poll)
|
||||||
|
if isSpecialPostType(post.PostType) && nextType != post.PostType {
|
||||||
|
return errors.New("不能修改特殊帖子类型")
|
||||||
|
}
|
||||||
|
if isSpecialPostType(nextType) && post.PostType != nextType {
|
||||||
|
return errors.New("不能改为特殊帖子类型")
|
||||||
|
}
|
||||||
nextResolved := post.QuestionResolved
|
nextResolved := post.QuestionResolved
|
||||||
if nextType != model.PostTypeQuestion {
|
if nextType != model.PostTypeQuestion {
|
||||||
nextResolved = false
|
nextResolved = false
|
||||||
@@ -646,6 +663,11 @@ func (s *PostService) Delete(userID, postID uint, isAdmin bool) error {
|
|||||||
return ErrPostNotFound
|
return ErrPostNotFound
|
||||||
}
|
}
|
||||||
return model.DB.Transaction(func(tx *gorm.DB) error {
|
return model.DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := RefundBountyIfOpen(tx, &post); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
DeletePollData(tx, postID)
|
||||||
|
DeleteLotteryData(tx, postID)
|
||||||
if err := tx.Where("post_id = ?", postID).Delete(&model.Comment{}).Error; err != nil {
|
if err := tx.Where("post_id = ?", postID).Delete(&model.Comment{}).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
69
service/post_special.go
Normal file
69
service/post_special.go
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PostCreateExtras 特殊帖创建附加参数
|
||||||
|
type PostCreateExtras struct {
|
||||||
|
PollOptionsJSON string
|
||||||
|
BountyPoints int
|
||||||
|
LotteryWinnerCount int
|
||||||
|
}
|
||||||
|
|
||||||
|
// FinalizeSpecialPostCreate 创建帖后初始化投票/悬赏/抽奖
|
||||||
|
func FinalizeSpecialPostCreate(post *model.Post, userID uint, extras PostCreateExtras) error {
|
||||||
|
if post == nil {
|
||||||
|
return errors.New("帖子不存在")
|
||||||
|
}
|
||||||
|
return model.DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
switch post.PostType {
|
||||||
|
case model.PostTypePoll:
|
||||||
|
opts, multi, maxChoices, endsAt, err := ParsePollOptionsJSON(extras.PollOptionsJSON)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return CreatePollForPost(tx, post.ID, multi, maxChoices, endsAt, opts)
|
||||||
|
case model.PostTypeBounty:
|
||||||
|
if extras.BountyPoints < 1 {
|
||||||
|
return ErrBountyInvalidPoint
|
||||||
|
}
|
||||||
|
if err := tx.Model(post).Updates(map[string]interface{}{
|
||||||
|
"bounty_points": extras.BountyPoints,
|
||||||
|
"bounty_status": model.BountyStatusOpen,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return EscrowBounty(tx, userID, post.ID, extras.BountyPoints)
|
||||||
|
case model.PostTypeLottery:
|
||||||
|
count := extras.LotteryWinnerCount
|
||||||
|
if count < 1 {
|
||||||
|
count = 1
|
||||||
|
}
|
||||||
|
if count > 20 {
|
||||||
|
return errors.New("开奖人数最多 20")
|
||||||
|
}
|
||||||
|
return tx.Model(post).Updates(map[string]interface{}{
|
||||||
|
"lottery_winner_count": count,
|
||||||
|
"lottery_status": model.PostLotteryStatusOpen,
|
||||||
|
}).Error
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParsePostExtrasFromForm 从表单解析特殊帖参数
|
||||||
|
func ParsePostExtrasFromForm(pollJSON, bountyRaw, lotteryRaw string) PostCreateExtras {
|
||||||
|
bounty, _ := strconv.Atoi(bountyRaw)
|
||||||
|
lottery, _ := strconv.Atoi(lotteryRaw)
|
||||||
|
return PostCreateExtras{
|
||||||
|
PollOptionsJSON: pollJSON,
|
||||||
|
BountyPoints: bounty,
|
||||||
|
LotteryWinnerCount: lottery,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,8 +23,8 @@ func NewRateLimiter(settings *ForumSettingsService) *RateLimiter {
|
|||||||
|
|
||||||
// Allow 检查 action+key 是否允许操作
|
// Allow 检查 action+key 是否允许操作
|
||||||
func (r *RateLimiter) Allow(action, key string) bool {
|
func (r *RateLimiter) Allow(action, key string) bool {
|
||||||
limit := r.settings.RateLimitFor(action)
|
limit := r.limitFor(action)
|
||||||
window := time.Duration(r.settings.RateLimitWindowSec()) * time.Second
|
window := r.windowFor(action)
|
||||||
if limit <= 0 {
|
if limit <= 0 {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -50,12 +50,26 @@ func (r *RateLimiter) Allow(action, key string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *RateLimiter) limitFor(action string) int {
|
||||||
|
if action == "friend_link" {
|
||||||
|
return 5
|
||||||
|
}
|
||||||
|
return r.settings.RateLimitFor(action)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RateLimiter) windowFor(action string) time.Duration {
|
||||||
|
if action == "friend_link" {
|
||||||
|
return time.Hour
|
||||||
|
}
|
||||||
|
return time.Duration(r.settings.RateLimitWindowSec()) * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
func (r *RateLimiter) cleanup() {
|
func (r *RateLimiter) cleanup() {
|
||||||
ticker := time.NewTicker(5 * time.Minute)
|
ticker := time.NewTicker(5 * time.Minute)
|
||||||
for range ticker.C {
|
for range ticker.C {
|
||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
window := time.Duration(r.settings.RateLimitWindowSec()) * time.Second
|
// 使用最大窗口清理,覆盖友链 1 小时窗口
|
||||||
cutoff := time.Now().Add(-window * 2)
|
cutoff := time.Now().Add(-time.Hour * 2)
|
||||||
for k, times := range r.records {
|
for k, times := range r.records {
|
||||||
var valid []time.Time
|
var valid []time.Time
|
||||||
for _, t := range times {
|
for _, t := range times {
|
||||||
|
|||||||
@@ -99,8 +99,16 @@ func DisplayName(u *model.User) string {
|
|||||||
return strings.TrimSpace(u.Username)
|
return strings.TrimSpace(u.Username)
|
||||||
}
|
}
|
||||||
|
|
||||||
// QueryBoardHome 板块首页相对路径
|
// QueryBoardHome 板块首页相对路径(规范伪静态路径)
|
||||||
func QueryBoardHome(boardID uint) string {
|
func QueryBoardHome(boardID uint, p PermalinkConfig) string {
|
||||||
|
if boardID == 0 {
|
||||||
|
return "/"
|
||||||
|
}
|
||||||
|
return p.BoardPath(boardID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LegacyQueryBoardHome 旧版 query 形式(/?board=id),仅用于 301 重定向
|
||||||
|
func LegacyQueryBoardHome(boardID uint) string {
|
||||||
if boardID == 0 {
|
if boardID == 0 {
|
||||||
return "/"
|
return "/"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import (
|
|||||||
|
|
||||||
// 论坛设置键名
|
// 论坛设置键名
|
||||||
const (
|
const (
|
||||||
SettingPostEditWindowHours = "post_edit_window_hours"
|
SettingPostEditWindowHours = "post_edit_window_hours"
|
||||||
SettingCommentEditWindowMinutes = "comment_edit_window_minutes"
|
SettingCommentEditWindowMinutes = "comment_edit_window_minutes"
|
||||||
|
|
||||||
SettingRateLimitPost = "rate_limit_post"
|
SettingRateLimitPost = "rate_limit_post"
|
||||||
@@ -39,6 +39,11 @@ const (
|
|||||||
|
|
||||||
SettingOpenPostsInNewTab = "open_posts_in_new_tab"
|
SettingOpenPostsInNewTab = "open_posts_in_new_tab"
|
||||||
SettingOpenContentLinksInNewTab = "open_content_links_in_new_tab"
|
SettingOpenContentLinksInNewTab = "open_content_links_in_new_tab"
|
||||||
|
SettingAsideShowTagCloud = "aside_show_tag_cloud"
|
||||||
|
SettingAsideShowRecentComments = "aside_show_recent_comments"
|
||||||
|
SettingAsideShowFriendLinks = "aside_show_friend_links"
|
||||||
|
SettingAsideWidgets = "aside_widgets"
|
||||||
|
SettingFeedListStyle = "feed_list_style"
|
||||||
|
|
||||||
// 伪静态键名见 permalink.go:SettingPermalinkEnabled / SettingPermalinkExt
|
// 伪静态键名见 permalink.go:SettingPermalinkEnabled / SettingPermalinkExt
|
||||||
|
|
||||||
@@ -73,17 +78,18 @@ const (
|
|||||||
SettingStorageForcePathStyle = "storage_force_path_style"
|
SettingStorageForcePathStyle = "storage_force_path_style"
|
||||||
SettingStorageImageDelivery = "storage_image_delivery"
|
SettingStorageImageDelivery = "storage_image_delivery"
|
||||||
|
|
||||||
SettingSiteName = "site_name"
|
SettingSiteName = "site_name"
|
||||||
SettingSiteSlogan = "site_slogan"
|
SettingSiteSlogan = "site_slogan"
|
||||||
SettingSiteDescription = "site_description"
|
SettingSiteDescription = "site_description"
|
||||||
SettingSiteKeywords = "site_keywords"
|
SettingSiteKeywords = "site_keywords"
|
||||||
SettingSiteLogoMark = "site_logo_mark"
|
SettingSiteLogoMark = "site_logo_mark"
|
||||||
SettingSiteLogo = "site_logo"
|
SettingSiteLogo = "site_logo"
|
||||||
SettingSiteFavicon = "site_favicon"
|
SettingSiteFavicon = "site_favicon"
|
||||||
SettingSiteOGImage = "site_og_image"
|
SettingSiteOGImage = "site_og_image"
|
||||||
SettingSiteICPBeian = "site_icp_beian"
|
SettingSiteICPBeian = "site_icp_beian"
|
||||||
SettingSiteICPBeianURL = "site_icp_beian_url"
|
SettingSiteICPBeianURL = "site_icp_beian_url"
|
||||||
SettingSiteFriendLinks = "site_friend_links"
|
SettingSiteFriendLinks = "site_friend_links"
|
||||||
|
SettingFriendLinkReciprocalCheck = "friend_link_reciprocal_check"
|
||||||
|
|
||||||
// pageSizeAPIMax 单次列表请求条数硬上限(防客户端传超大 size),非后台可配项
|
// pageSizeAPIMax 单次列表请求条数硬上限(防客户端传超大 size),非后台可配项
|
||||||
pageSizeAPIMax = 100
|
pageSizeAPIMax = 100
|
||||||
@@ -118,10 +124,35 @@ type ForumLimits struct {
|
|||||||
OpenPostsInNewTab bool `json:"open_posts_in_new_tab"`
|
OpenPostsInNewTab bool `json:"open_posts_in_new_tab"`
|
||||||
OpenContentLinksInNewTab bool `json:"open_content_links_in_new_tab"`
|
OpenContentLinksInNewTab bool `json:"open_content_links_in_new_tab"`
|
||||||
|
|
||||||
|
AsideShowTagCloud bool `json:"aside_show_tag_cloud"`
|
||||||
|
AsideShowRecentComments bool `json:"aside_show_recent_comments"`
|
||||||
|
AsideShowFriendLinks bool `json:"aside_show_friend_links"`
|
||||||
|
AsideWidgets []AsideWidget `json:"aside_widgets"`
|
||||||
|
|
||||||
|
FeedListStyle string `json:"feed_list_style"`
|
||||||
|
|
||||||
PermalinkEnabled bool `json:"permalink_enabled"`
|
PermalinkEnabled bool `json:"permalink_enabled"`
|
||||||
PermalinkExt string `json:"permalink_ext"`
|
PermalinkExt string `json:"permalink_ext"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AsideWidget 右侧栏可选组件
|
||||||
|
type AsideWidget struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
AsideWidgetTagCloud = "tag_cloud"
|
||||||
|
AsideWidgetRecentComments = "recent_comments"
|
||||||
|
AsideWidgetFriendLinks = "friend_links"
|
||||||
|
)
|
||||||
|
|
||||||
|
var asideWidgetDefaultOrder = []string{
|
||||||
|
AsideWidgetTagCloud,
|
||||||
|
AsideWidgetRecentComments,
|
||||||
|
AsideWidgetFriendLinks,
|
||||||
|
}
|
||||||
|
|
||||||
// ForumLimitsPublic 前台可见的限制(不含限流等内部配置)
|
// ForumLimitsPublic 前台可见的限制(不含限流等内部配置)
|
||||||
type ForumLimitsPublic struct {
|
type ForumLimitsPublic struct {
|
||||||
PostTitleMax int `json:"post_title_max"`
|
PostTitleMax int `json:"post_title_max"`
|
||||||
@@ -140,15 +171,22 @@ type ForumLimitsPublic struct {
|
|||||||
OpenPostsInNewTab bool `json:"open_posts_in_new_tab"`
|
OpenPostsInNewTab bool `json:"open_posts_in_new_tab"`
|
||||||
OpenContentLinksInNewTab bool `json:"open_content_links_in_new_tab"`
|
OpenContentLinksInNewTab bool `json:"open_content_links_in_new_tab"`
|
||||||
|
|
||||||
|
AsideShowTagCloud bool `json:"aside_show_tag_cloud"`
|
||||||
|
AsideShowRecentComments bool `json:"aside_show_recent_comments"`
|
||||||
|
AsideShowFriendLinks bool `json:"aside_show_friend_links"`
|
||||||
|
AsideWidgets []AsideWidget `json:"aside_widgets"`
|
||||||
|
|
||||||
|
FeedListStyle string `json:"feed_list_style"`
|
||||||
|
|
||||||
PermalinkEnabled bool `json:"permalink_enabled"`
|
PermalinkEnabled bool `json:"permalink_enabled"`
|
||||||
PermalinkExt string `json:"permalink_ext"`
|
PermalinkExt string `json:"permalink_ext"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type settingDef struct {
|
type settingDef struct {
|
||||||
key string
|
key string
|
||||||
defaultVal string
|
defaultVal string
|
||||||
min int
|
min int
|
||||||
max int // 0 表示不限制上限
|
max int // 0 表示不限制上限
|
||||||
}
|
}
|
||||||
|
|
||||||
var forumSettingDefs = []settingDef{
|
var forumSettingDefs = []settingDef{
|
||||||
@@ -180,6 +218,17 @@ var forumSettingDefs = []settingDef{
|
|||||||
{SettingOpenContentLinksInNewTab, "1", 0, 1},
|
{SettingOpenContentLinksInNewTab, "1", 0, 1},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var feedSettingDefaults = map[string]string{
|
||||||
|
SettingFeedListStyle: "title",
|
||||||
|
}
|
||||||
|
|
||||||
|
var asideSettingDefaults = map[string]string{
|
||||||
|
SettingAsideShowTagCloud: "0",
|
||||||
|
SettingAsideShowRecentComments: "0",
|
||||||
|
SettingAsideShowFriendLinks: "1",
|
||||||
|
SettingAsideWidgets: `[{"id":"tag_cloud","enabled":false},{"id":"recent_comments","enabled":false},{"id":"friend_links","enabled":true}]`,
|
||||||
|
}
|
||||||
|
|
||||||
var mailSettingDefaults = map[string]string{
|
var mailSettingDefaults = map[string]string{
|
||||||
SettingSMTPEnabled: "0",
|
SettingSMTPEnabled: "0",
|
||||||
SettingSMTPHost: "",
|
SettingSMTPHost: "",
|
||||||
@@ -219,6 +268,10 @@ var storageSettingDefaults = map[string]string{
|
|||||||
SettingStorageImageDelivery: ImageDeliveryWebP,
|
SettingStorageImageDelivery: ImageDeliveryWebP,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var friendLinkSettingDefaults = map[string]string{
|
||||||
|
SettingFriendLinkReciprocalCheck: "0", // 默认关闭回链检测
|
||||||
|
}
|
||||||
|
|
||||||
var siteBrandingDefaults = map[string]string{
|
var siteBrandingDefaults = map[string]string{
|
||||||
SettingSiteName: "姜十三论坛",
|
SettingSiteName: "姜十三论坛",
|
||||||
SettingSiteSlogan: "拾三一隅,自在交流",
|
SettingSiteSlogan: "拾三一隅,自在交流",
|
||||||
@@ -245,10 +298,11 @@ const (
|
|||||||
defaultICPBeianURL = "https://beian.miit.gov.cn/"
|
defaultICPBeianURL = "https://beian.miit.gov.cn/"
|
||||||
)
|
)
|
||||||
|
|
||||||
// FriendLink 页脚友情链接
|
// FriendLink 友情链接
|
||||||
type FriendLink struct {
|
type FriendLink struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
|
Logo string `json:"logo,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SiteBranding 站点品牌配置(名称、Logo、Favicon、页脚等)
|
// SiteBranding 站点品牌配置(名称、Logo、Favicon、页脚等)
|
||||||
@@ -264,6 +318,7 @@ type SiteBranding struct {
|
|||||||
ICPBeian string `json:"icp_beian"`
|
ICPBeian string `json:"icp_beian"`
|
||||||
ICPBeianURL string `json:"icp_beian_url"`
|
ICPBeianURL string `json:"icp_beian_url"`
|
||||||
FriendLinks []FriendLink `json:"friend_links"`
|
FriendLinks []FriendLink `json:"friend_links"`
|
||||||
|
SiteURL string `json:"site_url,omitempty" gorm:"-"` // 公开站点根 URL,仅 API 填充
|
||||||
}
|
}
|
||||||
|
|
||||||
// DocumentTitle 浏览器标签标题:站点名 - 副标题(标语)
|
// DocumentTitle 浏览器标签标题:站点名 - 副标题(标语)
|
||||||
@@ -343,6 +398,20 @@ func (s *ForumSettingsService) ensureDefaults() {
|
|||||||
model.DB.Create(&model.ForumSetting{Key: def.key, Value: def.defaultVal})
|
model.DB.Create(&model.ForumSetting{Key: def.key, Value: def.defaultVal})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for key, val := range feedSettingDefaults {
|
||||||
|
var count int64
|
||||||
|
model.DB.Model(&model.ForumSetting{}).Where("`key` = ?", key).Count(&count)
|
||||||
|
if count == 0 {
|
||||||
|
model.DB.Create(&model.ForumSetting{Key: key, Value: val})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for key, val := range asideSettingDefaults {
|
||||||
|
var count int64
|
||||||
|
model.DB.Model(&model.ForumSetting{}).Where("`key` = ?", key).Count(&count)
|
||||||
|
if count == 0 {
|
||||||
|
model.DB.Create(&model.ForumSetting{Key: key, Value: val})
|
||||||
|
}
|
||||||
|
}
|
||||||
for key, val := range mailSettingDefaults {
|
for key, val := range mailSettingDefaults {
|
||||||
var count int64
|
var count int64
|
||||||
model.DB.Model(&model.ForumSetting{}).Where("`key` = ?", key).Count(&count)
|
model.DB.Model(&model.ForumSetting{}).Where("`key` = ?", key).Count(&count)
|
||||||
@@ -378,6 +447,13 @@ func (s *ForumSettingsService) ensureDefaults() {
|
|||||||
model.DB.Create(&model.ForumSetting{Key: key, Value: val})
|
model.DB.Create(&model.ForumSetting{Key: key, Value: val})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for key, val := range friendLinkSettingDefaults {
|
||||||
|
var count int64
|
||||||
|
model.DB.Model(&model.ForumSetting{}).Where("`key` = ?", key).Count(&count)
|
||||||
|
if count == 0 {
|
||||||
|
model.DB.Create(&model.ForumSetting{Key: key, Value: val})
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *ForumSettingsService) getString(key, fallback string) string {
|
func (s *ForumSettingsService) getString(key, fallback string) string {
|
||||||
@@ -426,6 +502,8 @@ func (s *ForumSettingsService) setInt(key string, value int) error {
|
|||||||
|
|
||||||
func (s *ForumSettingsService) Limits() ForumLimits {
|
func (s *ForumSettingsService) Limits() ForumLimits {
|
||||||
permalink := s.Permalink()
|
permalink := s.Permalink()
|
||||||
|
widgets := s.AsideWidgets()
|
||||||
|
bools := asideBoolsFromWidgets(widgets)
|
||||||
return ForumLimits{
|
return ForumLimits{
|
||||||
PostEditWindowHours: s.PostEditWindowHours(),
|
PostEditWindowHours: s.PostEditWindowHours(),
|
||||||
CommentEditWindowMinutes: s.CommentEditWindowMinutes(),
|
CommentEditWindowMinutes: s.CommentEditWindowMinutes(),
|
||||||
@@ -454,6 +532,13 @@ func (s *ForumSettingsService) Limits() ForumLimits {
|
|||||||
OpenPostsInNewTab: s.OpenPostsInNewTab(),
|
OpenPostsInNewTab: s.OpenPostsInNewTab(),
|
||||||
OpenContentLinksInNewTab: s.OpenContentLinksInNewTab(),
|
OpenContentLinksInNewTab: s.OpenContentLinksInNewTab(),
|
||||||
|
|
||||||
|
AsideShowTagCloud: bools.tagCloud,
|
||||||
|
AsideShowRecentComments: bools.recentComments,
|
||||||
|
AsideShowFriendLinks: bools.friendLinks,
|
||||||
|
AsideWidgets: widgets,
|
||||||
|
|
||||||
|
FeedListStyle: s.FeedListStyle(),
|
||||||
|
|
||||||
PermalinkEnabled: permalink.Enabled,
|
PermalinkEnabled: permalink.Enabled,
|
||||||
PermalinkExt: permalink.Ext,
|
PermalinkExt: permalink.Ext,
|
||||||
}
|
}
|
||||||
@@ -478,6 +563,13 @@ func (s *ForumSettingsService) PublicLimits() ForumLimitsPublic {
|
|||||||
OpenPostsInNewTab: limits.OpenPostsInNewTab,
|
OpenPostsInNewTab: limits.OpenPostsInNewTab,
|
||||||
OpenContentLinksInNewTab: limits.OpenContentLinksInNewTab,
|
OpenContentLinksInNewTab: limits.OpenContentLinksInNewTab,
|
||||||
|
|
||||||
|
AsideShowTagCloud: limits.AsideShowTagCloud,
|
||||||
|
AsideShowRecentComments: limits.AsideShowRecentComments,
|
||||||
|
AsideShowFriendLinks: limits.AsideShowFriendLinks,
|
||||||
|
AsideWidgets: limits.AsideWidgets,
|
||||||
|
|
||||||
|
FeedListStyle: limits.FeedListStyle,
|
||||||
|
|
||||||
PermalinkEnabled: limits.PermalinkEnabled,
|
PermalinkEnabled: limits.PermalinkEnabled,
|
||||||
PermalinkExt: limits.PermalinkExt,
|
PermalinkExt: limits.PermalinkExt,
|
||||||
}
|
}
|
||||||
@@ -487,21 +579,21 @@ func (s *ForumSettingsService) UpdateLimits(in ForumLimits) error {
|
|||||||
updates := map[string]int{
|
updates := map[string]int{
|
||||||
SettingPostEditWindowHours: in.PostEditWindowHours,
|
SettingPostEditWindowHours: in.PostEditWindowHours,
|
||||||
SettingCommentEditWindowMinutes: in.CommentEditWindowMinutes,
|
SettingCommentEditWindowMinutes: in.CommentEditWindowMinutes,
|
||||||
SettingRateLimitPost: in.RateLimitPost,
|
SettingRateLimitPost: in.RateLimitPost,
|
||||||
SettingRateLimitComment: in.RateLimitComment,
|
SettingRateLimitComment: in.RateLimitComment,
|
||||||
SettingRateLimitRegister: in.RateLimitRegister,
|
SettingRateLimitRegister: in.RateLimitRegister,
|
||||||
SettingRateLimitLogin: in.RateLimitLogin,
|
SettingRateLimitLogin: in.RateLimitLogin,
|
||||||
SettingRateLimitWindow: in.RateLimitWindowSec,
|
SettingRateLimitWindow: in.RateLimitWindowSec,
|
||||||
SettingPostTitleMax: in.PostTitleMax,
|
SettingPostTitleMax: in.PostTitleMax,
|
||||||
SettingPostTagsMax: in.PostTagsMax,
|
SettingPostTagsMax: in.PostTagsMax,
|
||||||
SettingPostContentMax: in.PostContentMax,
|
SettingPostContentMax: in.PostContentMax,
|
||||||
SettingCommentMax: in.CommentMax,
|
SettingCommentMax: in.CommentMax,
|
||||||
SettingSearchKeywordMin: in.SearchKeywordMin,
|
SettingSearchKeywordMin: in.SearchKeywordMin,
|
||||||
SettingSearchKeywordMax: in.SearchKeywordMax,
|
SettingSearchKeywordMax: in.SearchKeywordMax,
|
||||||
SettingPageSizeDefault: in.PageSizeDefault,
|
SettingPageSizeDefault: in.PageSizeDefault,
|
||||||
SettingPasswordMinLen: in.PasswordMinLen,
|
SettingPasswordMinLen: in.PasswordMinLen,
|
||||||
SettingAvatarMaxMB: in.AvatarMaxMB,
|
SettingAvatarMaxMB: in.AvatarMaxMB,
|
||||||
SettingSignatureMax: in.SignatureMax,
|
SettingSignatureMax: in.SignatureMax,
|
||||||
}
|
}
|
||||||
if in.SearchKeywordMax > 0 && in.SearchKeywordMin > in.SearchKeywordMax {
|
if in.SearchKeywordMax > 0 && in.SearchKeywordMin > in.SearchKeywordMax {
|
||||||
return ErrInvalidSetting
|
return ErrInvalidSetting
|
||||||
@@ -511,9 +603,17 @@ func (s *ForumSettingsService) UpdateLimits(in ForumLimits) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
widgets := NormalizeAsideWidgets(in.AsideWidgets)
|
||||||
|
if len(widgets) == 0 {
|
||||||
|
widgets = asideWidgetsFromBools(in.AsideShowTagCloud, in.AsideShowRecentComments, in.AsideShowFriendLinks)
|
||||||
|
}
|
||||||
|
bools := asideBoolsFromWidgets(widgets)
|
||||||
boolUpdates := map[string]bool{
|
boolUpdates := map[string]bool{
|
||||||
SettingOpenPostsInNewTab: in.OpenPostsInNewTab,
|
SettingOpenPostsInNewTab: in.OpenPostsInNewTab,
|
||||||
SettingOpenContentLinksInNewTab: in.OpenContentLinksInNewTab,
|
SettingOpenContentLinksInNewTab: in.OpenContentLinksInNewTab,
|
||||||
|
SettingAsideShowTagCloud: bools.tagCloud,
|
||||||
|
SettingAsideShowRecentComments: bools.recentComments,
|
||||||
|
SettingAsideShowFriendLinks: bools.friendLinks,
|
||||||
SettingPermalinkEnabled: in.PermalinkEnabled,
|
SettingPermalinkEnabled: in.PermalinkEnabled,
|
||||||
}
|
}
|
||||||
for key, on := range boolUpdates {
|
for key, on := range boolUpdates {
|
||||||
@@ -525,6 +625,13 @@ func (s *ForumSettingsService) UpdateLimits(in ForumLimits) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
widgetsJSON, err := json.Marshal(widgets)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.setString(SettingAsideWidgets, string(widgetsJSON)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
ext, ok := NormalizePermalinkExt(in.PermalinkExt)
|
ext, ok := NormalizePermalinkExt(in.PermalinkExt)
|
||||||
if !ok {
|
if !ok {
|
||||||
return ErrInvalidSetting
|
return ErrInvalidSetting
|
||||||
@@ -532,6 +639,13 @@ func (s *ForumSettingsService) UpdateLimits(in ForumLimits) error {
|
|||||||
if err := s.setString(SettingPermalinkExt, ext); err != nil {
|
if err := s.setString(SettingPermalinkExt, ext); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
style, ok := NormalizeFeedListStyle(in.FeedListStyle)
|
||||||
|
if !ok {
|
||||||
|
return ErrInvalidSetting
|
||||||
|
}
|
||||||
|
if err := s.setString(SettingFeedListStyle, style); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -584,6 +698,126 @@ func (s *ForumSettingsService) OpenContentLinksInNewTab() bool {
|
|||||||
return s.getString(SettingOpenContentLinksInNewTab, "1") == "1"
|
return s.getString(SettingOpenContentLinksInNewTab, "1") == "1"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FriendLinkReciprocalCheckEnabled 是否启用友链回链检测;缺省为关闭
|
||||||
|
func (s *ForumSettingsService) FriendLinkReciprocalCheckEnabled() bool {
|
||||||
|
return s.getString(SettingFriendLinkReciprocalCheck, "0") == "1"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ForumSettingsService) SetFriendLinkReciprocalCheckEnabled(enabled bool) error {
|
||||||
|
v := "0"
|
||||||
|
if enabled {
|
||||||
|
v = "1"
|
||||||
|
}
|
||||||
|
return s.setString(SettingFriendLinkReciprocalCheck, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
type asideWidgetBools struct {
|
||||||
|
tagCloud bool
|
||||||
|
recentComments bool
|
||||||
|
friendLinks bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func asideWidgetsFromBools(tagCloud, recentComments, friendLinks bool) []AsideWidget {
|
||||||
|
return []AsideWidget{
|
||||||
|
{ID: AsideWidgetTagCloud, Enabled: tagCloud},
|
||||||
|
{ID: AsideWidgetRecentComments, Enabled: recentComments},
|
||||||
|
{ID: AsideWidgetFriendLinks, Enabled: friendLinks},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func asideBoolsFromWidgets(widgets []AsideWidget) asideWidgetBools {
|
||||||
|
out := asideWidgetBools{}
|
||||||
|
for _, w := range widgets {
|
||||||
|
switch w.ID {
|
||||||
|
case AsideWidgetTagCloud:
|
||||||
|
out.tagCloud = w.Enabled
|
||||||
|
case AsideWidgetRecentComments:
|
||||||
|
out.recentComments = w.Enabled
|
||||||
|
case AsideWidgetFriendLinks:
|
||||||
|
out.friendLinks = w.Enabled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func isValidAsideWidgetID(id string) bool {
|
||||||
|
switch id {
|
||||||
|
case AsideWidgetTagCloud, AsideWidgetRecentComments, AsideWidgetFriendLinks:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizeAsideWidgets 校验并补全右侧栏组件列表(顺序保留,缺失项按默认顺序追加)
|
||||||
|
func NormalizeAsideWidgets(in []AsideWidget) []AsideWidget {
|
||||||
|
seen := make(map[string]bool, len(asideWidgetDefaultOrder))
|
||||||
|
out := make([]AsideWidget, 0, len(asideWidgetDefaultOrder))
|
||||||
|
for _, w := range in {
|
||||||
|
id := strings.TrimSpace(w.ID)
|
||||||
|
if !isValidAsideWidgetID(id) || seen[id] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[id] = true
|
||||||
|
out = append(out, AsideWidget{ID: id, Enabled: w.Enabled})
|
||||||
|
}
|
||||||
|
for _, id := range asideWidgetDefaultOrder {
|
||||||
|
if seen[id] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, AsideWidget{ID: id, Enabled: false})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ForumSettingsService) AsideWidgets() []AsideWidget {
|
||||||
|
raw := strings.TrimSpace(s.getString(SettingAsideWidgets, ""))
|
||||||
|
if raw != "" {
|
||||||
|
var widgets []AsideWidget
|
||||||
|
if err := json.Unmarshal([]byte(raw), &widgets); err == nil {
|
||||||
|
normalized := NormalizeAsideWidgets(widgets)
|
||||||
|
if len(normalized) > 0 {
|
||||||
|
return normalized
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return asideWidgetsFromBools(s.AsideShowTagCloud(), s.AsideShowRecentComments(), s.AsideShowFriendLinks())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ForumSettingsService) AsideShowTagCloud() bool {
|
||||||
|
return s.getString(SettingAsideShowTagCloud, "0") == "1"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ForumSettingsService) AsideShowRecentComments() bool {
|
||||||
|
return s.getString(SettingAsideShowRecentComments, "0") == "1"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ForumSettingsService) AsideShowFriendLinks() bool {
|
||||||
|
return s.getString(SettingAsideShowFriendLinks, "1") == "1"
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizeFeedListStyle 校验首页列表样式
|
||||||
|
func NormalizeFeedListStyle(v string) (string, bool) {
|
||||||
|
switch strings.TrimSpace(strings.ToLower(v)) {
|
||||||
|
case "title", "":
|
||||||
|
return "title", true
|
||||||
|
case "excerpt":
|
||||||
|
return "excerpt", true
|
||||||
|
case "thumbnail":
|
||||||
|
return "thumbnail", true
|
||||||
|
default:
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ForumSettingsService) FeedListStyle() string {
|
||||||
|
v, ok := NormalizeFeedListStyle(s.getString(SettingFeedListStyle, feedSettingDefaults[SettingFeedListStyle]))
|
||||||
|
if !ok {
|
||||||
|
return "title"
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
// MailConfig 读取 SMTP 配置(密码不回显明文)
|
// MailConfig 读取 SMTP 配置(密码不回显明文)
|
||||||
func (s *ForumSettingsService) MailConfig() MailConfig {
|
func (s *ForumSettingsService) MailConfig() MailConfig {
|
||||||
port, _ := strconv.Atoi(s.getString(SettingSMTPPort, "465"))
|
port, _ := strconv.Atoi(s.getString(SettingSMTPPort, "465"))
|
||||||
@@ -903,6 +1137,11 @@ func (s *ForumSettingsService) SiteBranding() SiteBranding {
|
|||||||
mark = string(runes[0])
|
mark = string(runes[0])
|
||||||
}
|
}
|
||||||
links := parseFriendLinksJSON(s.getString(SettingSiteFriendLinks, "[]"))
|
links := parseFriendLinksJSON(s.getString(SettingSiteFriendLinks, "[]"))
|
||||||
|
links = EnrichFriendLinksLogos(links)
|
||||||
|
if err := s.maybePersistEnrichedFriendLinks(links); err != nil {
|
||||||
|
// 回填失败不阻断读取
|
||||||
|
_ = err
|
||||||
|
}
|
||||||
return SiteBranding{
|
return SiteBranding{
|
||||||
Name: name,
|
Name: name,
|
||||||
Slogan: strings.TrimSpace(s.getString(SettingSiteSlogan, siteBrandingDefaults[SettingSiteSlogan])),
|
Slogan: strings.TrimSpace(s.getString(SettingSiteSlogan, siteBrandingDefaults[SettingSiteSlogan])),
|
||||||
@@ -1111,7 +1350,7 @@ func normalizeFriendLinks(in []FriendLink) ([]FriendLink, error) {
|
|||||||
if scheme != "http" && scheme != "https" {
|
if scheme != "http" && scheme != "https" {
|
||||||
return nil, ErrInvalidSetting
|
return nil, ErrInvalidSetting
|
||||||
}
|
}
|
||||||
out = append(out, FriendLink{Name: name, URL: href})
|
out = append(out, FriendLink{Name: name, URL: href, Logo: normalizeFriendLinkLogoOptional(item.Logo)})
|
||||||
}
|
}
|
||||||
if out == nil {
|
if out == nil {
|
||||||
out = []FriendLink{}
|
out = []FriendLink{}
|
||||||
|
|||||||
176
service/site_page.go
Normal file
176
service/site_page.go
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrSitePageNotFound = errors.New("单页不存在")
|
||||||
|
ErrSitePageSlugUsed = errors.New("slug 已被占用")
|
||||||
|
)
|
||||||
|
|
||||||
|
// SitePageService 自定义单页
|
||||||
|
type SitePageService struct {
|
||||||
|
filter *SensitiveFilter
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSitePageService(filter *SensitiveFilter) *SitePageService {
|
||||||
|
return &SitePageService{filter: filter}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SitePageSummary 公开列表摘要
|
||||||
|
type SitePageSummary struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
ShowInFooter bool `json:"show_in_footer"`
|
||||||
|
ShowInNav bool `json:"show_in_nav"`
|
||||||
|
SortOrder int `json:"sort_order"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SitePageService) ListPublished() ([]SitePageSummary, error) {
|
||||||
|
var rows []model.SitePage
|
||||||
|
err := model.DB.Where("published = ?", true).
|
||||||
|
Order("sort_order ASC, id ASC").
|
||||||
|
Find(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make([]SitePageSummary, len(rows))
|
||||||
|
for i, p := range rows {
|
||||||
|
out[i] = SitePageSummary{
|
||||||
|
ID: p.ID, Title: p.Title, Slug: p.Slug,
|
||||||
|
ShowInFooter: p.ShowInFooter, ShowInNav: p.ShowInNav, SortOrder: p.SortOrder,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SitePageService) ListAll() ([]model.SitePage, error) {
|
||||||
|
var rows []model.SitePage
|
||||||
|
err := model.DB.Order("sort_order ASC, id ASC").Find(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return rows, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SitePageService) GetBySlug(slug string, allowUnpublished bool) (*model.SitePage, error) {
|
||||||
|
slug, ok := NormalizePageSlug(slug)
|
||||||
|
if !ok {
|
||||||
|
return nil, ErrSitePageNotFound
|
||||||
|
}
|
||||||
|
var page model.SitePage
|
||||||
|
q := model.DB.Where("slug = ?", slug)
|
||||||
|
if !allowUnpublished {
|
||||||
|
q = q.Where("published = ?", true)
|
||||||
|
}
|
||||||
|
if err := q.First(&page).Error; err != nil {
|
||||||
|
return nil, ErrSitePageNotFound
|
||||||
|
}
|
||||||
|
page.Content = SanitizePostHTML(page.Content)
|
||||||
|
return &page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SitePageService) GetByID(id uint) (*model.SitePage, error) {
|
||||||
|
var page model.SitePage
|
||||||
|
if err := model.DB.First(&page, id).Error; err != nil {
|
||||||
|
return nil, ErrSitePageNotFound
|
||||||
|
}
|
||||||
|
return &page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type SitePageInput struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
Published bool `json:"published"`
|
||||||
|
SortOrder int `json:"sort_order"`
|
||||||
|
ShowInFooter bool `json:"show_in_footer"`
|
||||||
|
ShowInNav bool `json:"show_in_nav"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SitePageService) Create(in SitePageInput) (*model.SitePage, error) {
|
||||||
|
page, err := s.normalizeInput(in)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var exists int64
|
||||||
|
model.DB.Model(&model.SitePage{}).Where("slug = ?", page.Slug).Count(&exists)
|
||||||
|
if exists > 0 {
|
||||||
|
return nil, ErrSitePageSlugUsed
|
||||||
|
}
|
||||||
|
if err := model.DB.Create(page).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SitePageService) Update(id uint, in SitePageInput) error {
|
||||||
|
page, err := s.GetByID(id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
next, err := s.normalizeInput(in)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var exists int64
|
||||||
|
model.DB.Model(&model.SitePage{}).Where("slug = ? AND id <> ?", next.Slug, id).Count(&exists)
|
||||||
|
if exists > 0 {
|
||||||
|
return ErrSitePageSlugUsed
|
||||||
|
}
|
||||||
|
return model.DB.Model(page).Updates(map[string]interface{}{
|
||||||
|
"title": next.Title,
|
||||||
|
"slug": next.Slug,
|
||||||
|
"content": next.Content,
|
||||||
|
"published": next.Published,
|
||||||
|
"sort_order": next.SortOrder,
|
||||||
|
"show_in_footer": next.ShowInFooter,
|
||||||
|
"show_in_nav": next.ShowInNav,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SitePageService) Delete(id uint) error {
|
||||||
|
res := model.DB.Delete(&model.SitePage{}, id)
|
||||||
|
if res.Error != nil {
|
||||||
|
return res.Error
|
||||||
|
}
|
||||||
|
if res.RowsAffected == 0 {
|
||||||
|
return ErrSitePageNotFound
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SitePageService) ListSitemap(limit int) ([]model.SitePage, error) {
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = 500
|
||||||
|
}
|
||||||
|
var rows []model.SitePage
|
||||||
|
err := model.DB.Where("published = ?", true).
|
||||||
|
Order("updated_at DESC").Limit(limit).Find(&rows).Error
|
||||||
|
return rows, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SitePageService) normalizeInput(in SitePageInput) (*model.SitePage, error) {
|
||||||
|
title := s.filter.Filter(strings.TrimSpace(in.Title))
|
||||||
|
slug, ok := NormalizePageSlug(in.Slug)
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("slug 格式无效(2-64 位小写字母、数字、连字符)")
|
||||||
|
}
|
||||||
|
content := s.filter.Filter(SanitizePostHTML(in.Content))
|
||||||
|
if title == "" {
|
||||||
|
return nil, errors.New("标题不能为空")
|
||||||
|
}
|
||||||
|
if content == "" {
|
||||||
|
return nil, errors.New("正文不能为空")
|
||||||
|
}
|
||||||
|
return &model.SitePage{
|
||||||
|
Title: title, Slug: slug, Content: content,
|
||||||
|
Published: in.Published, SortOrder: in.SortOrder,
|
||||||
|
ShowInFooter: in.ShowInFooter, ShowInNav: in.ShowInNav,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user