feat: add path navigation and shared settings transitions

This commit is contained in:
lezi-fun committed 2026-08-13 12:29:09 +08:00
1 parent caad17d195
commit 84c9e97451
25 files changed
+689 -151

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ This block is written and re-added by `next dev` — verify at `node_modules/nex
## Architecture
- `app/page.js` and `app/HomeClient.js` render the application shell. Most navigation is SPA-style state managed by `components/AppProvider.js` and synchronized to `?post=`, `?user=`, and `?page=` query parameters.
- `app/page.js` and `app/HomeClient.js` render the application shell. Most navigation is SPA-style state managed by `components/AppProvider.js` and synchronized to `/post/:number`, `/user/:username`, built-in page paths, and direct custom-page paths. Legacy `?post=`, `?user=`, and `?page=` links are normalized on load.
- `app/api/**/route.js` contains the Next.js Route Handlers. Keep authentication and authorization checks on the server even when the UI already hides an action.
- `components/` contains client UI. Reuse `AppProvider`, `Toast`, `Icons`, and existing component patterns instead of introducing parallel state or notification systems.
- `app/globals.css` owns the theme, responsive layout, glass/card styling, page transitions, and View Transition pseudo-elements. Check nearby selectors before adding another override.
+13
View File
@@ -0,0 +1,13 @@
import { cookies } from 'next/headers';
import HomeClient from './HomeClient';
export default async function ForumPage() {
let cachedName = '';
try {
const cookieStore = await cookies();
cachedName = decodeURIComponent(cookieStore.get('forumlify-name')?.value || '');
} catch {
cachedName = '';
}
return <HomeClient cachedName={cachedName} />;
}
+7
View File
@@ -0,0 +1,7 @@
import ForumPage from '../ForumPage';
export const dynamic = 'force-dynamic';
export default function NamedPage() {
return <ForumPage />;
}
+6
View File
@@ -5,6 +5,9 @@ import { getUser, requireAdmin } from '@/lib/auth';
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
export const dynamic = 'force-dynamic';
const RESERVED_PAGE_NAMES = new Set([
'api', 'post', 'user', 'settings', 'messages', 'admin', 'new', 'uploads',
]);
export async function GET(req) {
const user = getUser(req);
@@ -33,6 +36,9 @@ export async function POST(req) {
if (!/^[a-zA-Z0-9\-_]+$/.test(name)) {
return Response.json({ error: '页面名称只允许字母、数字、短横线和下划线' }, { status: 400 });
}
if (RESERVED_PAGE_NAMES.has(name.toLowerCase())) {
return Response.json({ error: '该页面名称为系统保留路径' }, { status: 400 });
}
try {
const r = await pool.query(
`INSERT INTO custom_pages (name, title, content)
+10 -12
View File
@@ -2,29 +2,27 @@
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
import { createNotification } from '@/lib/notify';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
import { resolvePostReference } from '@/lib/post-reference';
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
if (!UUID_RE.test((await params).id)) {
return Response.json({ error: '帖子不存在' }, { status: 404 });
}
try {
const post = await pool.query('SELECT id, user_id FROM posts WHERE id = $1', [(await params).id]);
if (post.rows.length === 0) {
const reference = await resolvePostReference((await params).id);
if (!reference) {
return Response.json({ error: '帖子不存在' }, { status: 404 });
}
const check = await pool.query('SELECT is_pinned FROM posts WHERE id = $1', [(await params).id]);
const isPinned = check.rows[0].is_pinned;
const post = await pool.query(
'SELECT id, user_id, post_number, is_pinned FROM posts WHERE id = $1',
[reference.id]
);
const isPinned = post.rows[0].is_pinned;
const r = await pool.query(
`UPDATE posts SET is_pinned = $1, pinned_at = $2 WHERE id = $3 RETURNING *`,
[!isPinned, !isPinned ? new Date().toISOString() : null, (await params).id]
[!isPinned, !isPinned ? new Date().toISOString() : null, reference.id]
);
await createNotification(
@@ -32,7 +30,7 @@ export async function PUT(req, { params }) {
'system',
isPinned ? '你的帖子已被取消置顶' : '你的帖子已被置顶',
isPinned ? '管理员取消了你的帖子置顶' : '管理员把你的帖子置顶了',
'/?post=' + (await params).id
'/post/' + post.rows[0].post_number
);
return Response.json(r.rows[0]);
+7 -2
View File
@@ -5,6 +5,7 @@ import { jsonWithEtag } from '@/lib/http-cache';
import { verifyCaptcha } from '@/lib/captcha';
import { logAudit } from '@/lib/audit';
import { getReplySchemaCapabilities } from '@/lib/reply-schema';
import { resolvePostReference } from '@/lib/post-reference';
function repliesSelectSql(capabilities) {
if (capabilities.replyToId) {
@@ -42,8 +43,10 @@ function repliesSelectSql(capabilities) {
export async function GET(req, { params }) {
try {
const reference = await resolvePostReference((await params).id);
if (!reference) return Response.json({ error: '帖子不存在' }, { status: 404 });
const capabilities = await getReplySchemaCapabilities();
const r = await pool.query(repliesSelectSql(capabilities), [(await params).id]);
const r = await pool.query(repliesSelectSql(capabilities), [reference.id]);
return jsonWithEtag(req, r.rows);
} catch (error) {
console.error('[replies] list failed:', error?.code || error?.message);
@@ -65,7 +68,9 @@ export async function POST(req, { params }) {
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
}
try {
const postId = (await params).id;
const reference = await resolvePostReference((await params).id);
if (!reference) return Response.json({ error: '帖子不存在' }, { status: 404 });
const postId = reference.id;
const capabilities = await getReplySchemaCapabilities();
let replyTargetUsername = null;
+12 -10
View File
@@ -2,22 +2,22 @@
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
import { jsonWithEtag } from '@/lib/http-cache';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
import { resolvePostReference } from '@/lib/post-reference';
function invalidId() {
return Response.json({ error: '帖子不存在' }, { status: 404 });
}
export async function GET(req, { params }) {
if (!UUID_RE.test((await params).id)) return invalidId();
try {
const reference = await resolvePostReference((await params).id);
if (!reference) return invalidId();
const r = await pool.query(
`SELECT p.*, u.username, u.avatar_url, u.signature
FROM posts p
JOIN users u ON p.user_id = u.id
WHERE p.id = $1`,
[(await params).id]
[reference.id]
);
if (r.rows.length === 0) {
return invalidId();
@@ -29,7 +29,6 @@ export async function GET(req, { params }) {
}
export async function PUT(req, { params }) {
if (!UUID_RE.test((await params).id)) return invalidId();
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
@@ -39,7 +38,9 @@ export async function PUT(req, { params }) {
return Response.json({ error: '请填写内容' }, { status: 400 });
}
try {
const post = await pool.query('SELECT user_id, images FROM posts WHERE id = $1', [(await params).id]);
const reference = await resolvePostReference((await params).id);
if (!reference) return invalidId();
const post = await pool.query('SELECT user_id, images FROM posts WHERE id = $1', [reference.id]);
if (post.rows.length === 0) return invalidId();
if (post.rows[0].user_id !== user.id) {
return Response.json({ error: '无权限编辑此帖子' }, { status: 403 });
@@ -47,7 +48,7 @@ export async function PUT(req, { params }) {
// images: 可选,传入完整图片 URL 数组(编辑时替换全部图片);不传则保留原图
const r = await pool.query(
`UPDATE posts SET title = $1, content = $2, images = $3, edited_at = NOW() WHERE id = $4 RETURNING *`,
[title || '无标题', content, Array.isArray(images) ? images : post.rows[0].images || [], (await params).id]
[title || '无标题', content, Array.isArray(images) ? images : post.rows[0].images || [], reference.id]
);
return Response.json(r.rows[0]);
} catch {
@@ -56,13 +57,14 @@ export async function PUT(req, { params }) {
}
export async function DELETE(req, { params }) {
if (!UUID_RE.test((await params).id)) return invalidId();
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
try {
const post = await pool.query('SELECT user_id FROM posts WHERE id = $1', [(await params).id]);
const reference = await resolvePostReference((await params).id);
if (!reference) return invalidId();
const post = await pool.query('SELECT user_id FROM posts WHERE id = $1', [reference.id]);
if (post.rows.length === 0) {
return invalidId();
}
@@ -70,7 +72,7 @@ export async function DELETE(req, { params }) {
if (post.rows[0].user_id !== user.id && u.rows[0]?.role !== 'admin') {
return Response.json({ error: '无权限删除此帖子' }, { status: 403 });
}
await pool.query('DELETE FROM posts WHERE id = $1', [(await params).id]);
await pool.query('DELETE FROM posts WHERE id = $1', [reference.id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
+3
View File
@@ -4,6 +4,7 @@ import { getUser } from '@/lib/auth';
import { jsonWithEtag } from '@/lib/http-cache';
import { verifyCaptcha } from '@/lib/captcha';
import { logAudit } from '@/lib/audit';
import { ensurePostNumberSchema } from '@/lib/post-reference';
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
export const dynamic = 'force-dynamic';
@@ -21,6 +22,7 @@ export async function GET(req) {
const offset = (safePage - 1) * limit;
try {
await ensurePostNumberSchema();
const params = [];
let where = '';
if (userId) {
@@ -68,6 +70,7 @@ export async function POST(req) {
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
}
try {
await ensurePostNumberSchema();
const r = await pool.query(
`INSERT INTO posts (user_id, title, content, images)
VALUES ($1, $2, $3, $4)
+5 -2
View File
@@ -1,6 +1,7 @@
// GET /api/reports, POST /api/reports
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
import { resolvePostReference } from '@/lib/post-reference';
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
export const dynamic = 'force-dynamic';
@@ -40,9 +41,11 @@ export async function POST(req) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
try {
const post = await resolvePostReference(post_id);
if (!post) return Response.json({ error: '帖子不存在' }, { status: 404 });
const existing = await pool.query(
'SELECT id FROM reports WHERE post_id = $1 AND reporter_id = $2 AND status = $3',
[post_id, user.id, 'pending']
[post.id, user.id, 'pending']
);
if (existing.rows.length > 0) {
return Response.json({ error: '你已经举报过此帖子,请等待处理' }, { status: 400 });
@@ -50,7 +53,7 @@ export async function POST(req) {
await pool.query(
`INSERT INTO reports (post_id, reporter_id, reason)
VALUES ($1, $2, $3)`,
[post_id, user.id, reason]
[post.id, user.id, reason]
);
return Response.json({ success: true });
} catch {
+169 -16
View File
@@ -898,14 +898,13 @@ svg {
overflow-y: auto;
transition: background 0.3s ease;
}
.page-slide.active {
.page-slide.active:not(#pagePost):not(#pageUser):not(#pageSettings) {
display: block;
animation: slideIn 0.35s cubic-bezier(0.22, 1, 0.36, 1);
}
#pagePost.page-slide.active,
#pageUser.page-slide.active {
animation: none;
.page-slide.active:is(#pagePost, #pageUser, #pageSettings) {
display: block;
}
#pageUser {
@@ -1043,6 +1042,136 @@ html.user-transition-settled #pageUser .user-profile-posts {
animation: userPageContentReveal 0.28s ease-out both;
}
/* ===== 设置页共享元素过渡 ===== */
html.settings-view-transition #navbar {
view-transition-name: persistent-navbar;
}
html.settings-view-transition #pageSettings {
animation: none;
}
html.settings-view-transition #pageSettings .settings-profile-avatar {
view-transition-name: settings-avatar;
}
html.settings-view-transition #pageSettings .settings-profile-name {
view-transition-name: settings-user-name;
}
.settings-profile-name {
display: block;
width: fit-content;
max-width: 100%;
margin-left: auto !important;
margin-right: auto !important;
overflow-wrap: anywhere;
}
html.settings-view-transition::view-transition {
background: linear-gradient(145deg, var(--bg-start) 0%, var(--bg-end) 100%);
pointer-events: none;
}
html.settings-view-transition::view-transition-group(settings-avatar),
html.settings-view-transition::view-transition-group(settings-user-name) {
z-index: 20;
animation-duration: 0.82s;
animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
}
html.settings-view-transition::view-transition-image-pair(settings-avatar),
html.settings-view-transition::view-transition-old(settings-avatar),
html.settings-view-transition::view-transition-new(settings-avatar) {
border-radius: 50%;
overflow: clip;
mix-blend-mode: normal;
}
html.settings-view-transition::view-transition-old(settings-avatar),
html.settings-view-transition::view-transition-new(settings-avatar),
html.settings-view-transition::view-transition-old(settings-user-name),
html.settings-view-transition::view-transition-new(settings-user-name) {
animation: none;
font-size: 14px;
font-weight: 600;
mix-blend-mode: normal;
}
html.settings-view-transition.settings-name-fade-only::view-transition-new(settings-user-name) {
animation: settingsNameReveal 0.26s 0.56s ease-out both;
}
html.settings-view-transition::view-transition-old(root) {
animation: settingsSourceFadeOut 0.34s 0.16s ease-out both;
}
html.settings-view-transition::view-transition-new(root) {
animation: settingsShellReveal 0.3s 0.52s ease-out both;
}
html.settings-view-transition.returning-settings-home::view-transition-old(root) {
animation: settingsShellHide 0.3s 0.06s ease-in both;
}
html.settings-view-transition.returning-settings-home::view-transition-new(root) {
animation: settingsFeedReveal 0.34s 0.3s ease-out both;
}
html.settings-view-transition.returning-settings-home.settings-name-return-fade-only::view-transition-old(settings-user-name) {
animation: settingsNameReturnHide 0.26s 0.34s ease-in both;
}
html.settings-view-transition::view-transition-group(persistent-navbar),
html.settings-view-transition::view-transition-old(persistent-navbar),
html.settings-view-transition::view-transition-new(persistent-navbar) {
animation: none;
mix-blend-mode: normal;
}
html.settings-navbar-avatar-hidden #navbar #userDropdown .avatar {
opacity: 0;
}
html.settings-navbar-avatar-reveal #navbar #userDropdown .avatar {
animation: settingsNavbarAvatarReveal 0.32s ease-out both;
}
@keyframes settingsSourceFadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
@keyframes settingsShellReveal {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes settingsShellHide {
from { opacity: 1; }
to { opacity: 0; }
}
@keyframes settingsFeedReveal {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes settingsNameReveal {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes settingsNameReturnHide {
from { opacity: 1; transform: translateY(0); }
to { opacity: 0; transform: translateY(4px); }
}
@keyframes settingsNavbarAvatarReveal {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes userAvatarSourceOut {
from { opacity: 1; }
to { opacity: 0; }
@@ -1158,7 +1287,7 @@ html.home-view-transition.returning-home #pagePost .post-detail-card > .post-con
html.post-view-transition #pagePost .post-detail-card > .post-images,
html.home-view-transition.returning-home #pagePost .post-detail-card > .post-images {
view-transition-name: post-detail-media;
view-transition-name: post-media;
}
html.post-view-transition #pagePost .post-detail-card .post-pin-state,
@@ -1273,6 +1402,31 @@ html.home-view-transition.returning-home::view-transition-image-pair(post-body)
overflow: clip;
}
html.post-view-transition::view-transition-group(post-media),
html.home-view-transition.returning-home::view-transition-group(post-media) {
z-index: 12;
animation-duration: 0.96s;
animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1);
}
html.home-view-transition.returning-home::view-transition-group(post-media) {
animation-duration: 1.1s;
}
html.post-view-transition::view-transition-image-pair(post-media),
html.home-view-transition.returning-home::view-transition-image-pair(post-media) {
overflow: clip;
}
html.post-view-transition::view-transition-old(post-media),
html.post-view-transition::view-transition-new(post-media),
html.home-view-transition.returning-home::view-transition-old(post-media),
html.home-view-transition.returning-home::view-transition-new(post-media) {
animation: none;
opacity: 1;
mix-blend-mode: normal;
}
html.post-view-transition::view-transition-group(post-time) {
animation-duration: 0.8s;
animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1);
@@ -1377,14 +1531,8 @@ html.post-view-transition::view-transition-new(post-body) {
object-position: left top;
}
html.post-view-transition::view-transition-old(post-feed-media) {
animation: none;
opacity: 0;
}
html.post-view-transition::view-transition-new(post-detail-controls),
html.post-view-transition::view-transition-new(post-detail-signature),
html.post-view-transition::view-transition-new(post-detail-media) {
html.post-view-transition::view-transition-new(post-detail-signature) {
animation: detailOnlyPartIn 0.22s 0.62s ease-out both;
}
@@ -1504,8 +1652,7 @@ html.home-view-transition.returning-home::view-transition-new(post-edited-label)
}
html.home-view-transition.returning-home::view-transition-old(post-detail-controls),
html.home-view-transition.returning-home::view-transition-old(post-detail-signature),
html.home-view-transition.returning-home::view-transition-old(post-detail-media) {
html.home-view-transition.returning-home::view-transition-old(post-detail-signature) {
animation: returnDetailOnlyPartOut 0.22s 0.12s ease-out both;
}
@@ -1576,8 +1723,7 @@ html.home-view-transition.returning-home::view-transition-old(reply-loading-retu
}
}
html.home-view-transition.returning-home::view-transition-new(post-feed-actions),
html.home-view-transition.returning-home::view-transition-new(post-feed-media) {
html.home-view-transition.returning-home::view-transition-new(post-feed-actions) {
animation: returnFeedOnlyPartIn 0.28s 0.44s ease-out both;
}
@@ -1603,6 +1749,13 @@ html.home-view-transition.returning-home::view-transition-new(post-body) {
to { opacity: 1; }
}
@media (prefers-reduced-motion: reduce) {
.page-slide.active,
html.settings-navbar-avatar-reveal #navbar #userDropdown .avatar {
animation: none !important;
}
}
@keyframes returnSharedPartOut {
from { opacity: 1; }
to { opacity: 0; }
+4 -14
View File
@@ -1,19 +1,9 @@
// 主页:Server Component —— 从 cookie 读取缓存论坛名(SSR 首帧即输出),
// 其余逻辑在客户端 HomeClient 中
import { cookies } from 'next/headers';
import HomeClient from './HomeClient';
// 主页:Server Component,路径页面共用同一个客户端应用外壳。
import ForumPage from './ForumPage';
// cookies() 是动态 API:禁止静态优化,每次请求 SSR
export const dynamic = 'force-dynamic';
export default async function Home() {
let cachedName = '';
try {
// Next 15+:cookies() 返回 Promise,必须 await
const cookieStore = await cookies();
cachedName = decodeURIComponent(cookieStore.get('forumlify-name')?.value || '');
} catch (e) {
cachedName = '';
}
return <HomeClient cachedName={cachedName} />;
export default function Home() {
return <ForumPage />;
}
+7
View File
@@ -0,0 +1,7 @@
import ForumPage from '../../ForumPage';
export const dynamic = 'force-dynamic';
export default function PostPage() {
return <ForumPage />;
}
+7
View File
@@ -0,0 +1,7 @@
import ForumPage from '../../ForumPage';
export const dynamic = 'force-dynamic';
export default function UserPage() {
return <ForumPage />;
}
+274 -79
View File
@@ -13,7 +13,7 @@ const POST_TRANSITION_PARTS = [
['.post-title', 'post-heading'],
['.post-time', 'post-time'],
['.post-content', 'post-body'],
['.post-images', 'post-feed-media'],
['.post-images', 'post-media'],
['.post-pin-state', 'post-pin-state'],
['.post-edited-label', 'post-edited-label'],
['.post-actions', 'post-feed-actions'],
@@ -35,6 +35,143 @@ function clearPostTransitionParts(elements) {
});
}
const SETTINGS_AVATAR_SELECTOR = [
'.post-avatar',
'.reply-avatar',
'.user-profile-avatar',
'.admin-user-avatar',
].join(', ');
const SETTINGS_NAME_SELECTOR = [
'.post-username',
'.reply-username',
'.user-profile-name',
'.admin-user-name',
].join(', ');
function visibleAreaRatio(element) {
if (!element?.isConnected) return 0;
const style = window.getComputedStyle(element);
if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return 0;
const bounds = element.getBoundingClientRect();
const totalArea = bounds.width * bounds.height;
if (totalArea <= 0) return 0;
let left = Math.max(0, bounds.left);
let top = Math.max(0, bounds.top);
let right = Math.min(window.innerWidth, bounds.right);
let bottom = Math.min(window.innerHeight, bounds.bottom);
// Account for scroll/clip containers, but deliberately do not treat the
// translucent navbar as an occluder: content underneath it is still visible.
for (let parent = element.parentElement; parent && parent !== document.body; parent = parent.parentElement) {
const parentStyle = window.getComputedStyle(parent);
const clipsX = ['auto', 'scroll', 'hidden', 'clip'].includes(parentStyle.overflowX);
const clipsY = ['auto', 'scroll', 'hidden', 'clip'].includes(parentStyle.overflowY);
if (!clipsX && !clipsY) continue;
const parentBounds = parent.getBoundingClientRect();
if (clipsX) {
left = Math.max(left, parentBounds.left);
right = Math.min(right, parentBounds.right);
}
if (clipsY) {
top = Math.max(top, parentBounds.top);
bottom = Math.min(bottom, parentBounds.bottom);
}
}
return Math.max(0, right - left) * Math.max(0, bottom - top) / totalArea;
}
function randomElement(elements) {
return elements[Math.floor(Math.random() * elements.length)] || null;
}
function findSettingsTransitionSource(username) {
const groups = Array.from(document.querySelectorAll('[data-username]')).filter(
(element) => !element.closest('#navbar') && element.dataset.username === String(username || '')
);
const candidates = groups.map((group) => {
const avatarElement = group.querySelector(SETTINGS_AVATAR_SELECTOR);
const nameElement = group.querySelector(SETTINGS_NAME_SELECTOR);
return {
avatarElement: visibleAreaRatio(avatarElement) >= 0.5 ? avatarElement : null,
nameElement: visibleAreaRatio(nameElement) >= 0.5 ? nameElement : null,
};
});
const completeCandidates = candidates.filter(({ avatarElement, nameElement }) => avatarElement && nameElement);
if (completeCandidates.length > 0) return randomElement(completeCandidates);
return randomElement(candidates.filter(({ avatarElement, nameElement }) => avatarElement || nameElement)) || {
avatarElement: null,
nameElement: null,
};
}
const BUILT_IN_PAGES = new Set(['messages', 'settings', 'admin', 'new']);
function cleanPathSegment(value) {
return encodeURIComponent(String(value || '').trim());
}
function pathForPage(page) {
return page === 'feed' ? '/' : `/${cleanPathSegment(page)}`;
}
function pathForUser(username) {
return `/user/${cleanPathSegment(username)}`;
}
function pathForPost(postRef) {
return `/post/${cleanPathSegment(postRef)}`;
}
function pathForCustomPage(pageName) {
return `/${cleanPathSegment(pageName)}`;
}
function routeFromLocation(location) {
const parts = location.pathname.split('/').filter(Boolean).map((part) => {
try { return decodeURIComponent(part); } catch { return part; }
});
const legacy = new URLSearchParams(location.search);
const legacyPost = legacy.get('post');
const legacyUser = legacy.get('user');
const legacyPage = legacy.get('page');
if (parts[0] === 'post' && parts.length === 2) return { page: 'post', postId: parts[1] };
if (parts[0] === 'user' && parts.length === 2) return { page: 'user', username: parts[1] };
if (parts.length === 1 && BUILT_IN_PAGES.has(parts[0])) return { page: parts[0] };
if (parts.length === 1) return { page: 'custom', pageName: parts[0] };
// Compatibility for links created before path-based navigation.
if (legacyPost) return { page: 'post', postId: legacyPost, legacy: true };
if (legacyUser) return { page: 'user', username: legacyUser, legacy: true };
if (legacyPage && BUILT_IN_PAGES.has(legacyPage)) return { page: legacyPage, legacy: true };
if (legacyPage) return { page: 'custom', pageName: legacyPage, legacy: true };
return { page: 'feed' };
}
function pathForRoute(route) {
if (route.page === 'post') return pathForPost(route.postId);
if (route.page === 'user') return pathForUser(route.username);
if (route.page === 'custom') return pathForCustomPage(route.pageName);
return pathForPage(route.page);
}
function clearLegacyPageParams(url) {
url.searchParams.delete('page');
url.searchParams.delete('post');
url.searchParams.delete('user');
return url;
}
function postCardMatches(element, postRef) {
const ref = String(postRef || '');
return element?.dataset.postRef === ref || element?.dataset.postId === ref;
}
function waitForPostImages(container) {
const images = Array.from(container?.querySelectorAll('img') || []);
if (images.length === 0) return Promise.resolve();
@@ -320,39 +457,32 @@ export default function AppProvider({ children, cachedName = '' }) {
if (titleEl) titleEl.textContent = forumName;
}, [ready, forumNameLoaded, forumName]);
// 按 URL 参数初始化视图
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const postParam = params.get('post');
const pageParam = params.get('page');
const userParam = params.get('user');
if (postParam) {
setView('post');
setCurrentPostId(postParam);
} else if (userParam) {
setView('user');
setCurrentUsername(userParam);
} else if (pageParam && ['messages', 'settings', 'admin', 'new'].includes(pageParam)) {
setView(pageParam);
} else if (pageParam) {
// 未知 page 参数视为自定义页面
setView('custom');
setCurrentPageName(pageParam);
}
const applyRoute = useCallback((route, state = {}) => {
setView(route.page);
setCurrentPostId(route.page === 'post' ? route.postId : null);
setCurrentPostPreview(null);
setCurrentPostOrigin(route.page === 'post' ? state.origin || null : null);
setCurrentUsername(route.page === 'user' ? route.username : null);
setCurrentUserPreview(null);
setCurrentUserPostsPreview(null);
setCurrentPageName(route.page === 'custom' ? route.pageName : null);
}, []);
// Initialize from path routes and normalize legacy query-based links.
useEffect(() => {
const route = routeFromLocation(window.location);
applyRoute(route, window.history.state || {});
if (route.legacy) {
const normalized = clearLegacyPageParams(new URL(window.location));
normalized.pathname = pathForRoute(route);
window.history.replaceState({ ...window.history.state, ...route }, '', normalized);
}
}, [applyRoute]);
// 视图切换:同步 URL (pushState,模拟原 SPA 行为)
const navigate = useCallback((page) => {
const url = new URL(window.location);
if (page === 'feed') {
url.searchParams.delete('page');
url.searchParams.delete('post');
url.searchParams.delete('user');
} else {
url.searchParams.set('page', page);
url.searchParams.delete('post');
url.searchParams.delete('user');
}
const url = clearLegacyPageParams(new URL(window.location));
url.pathname = pathForPage(page);
const commitNavigation = (refreshFeed = true) => {
window.history.pushState({ page }, '', url);
setView(page);
@@ -366,6 +496,100 @@ export default function AppProvider({ children, cachedName = '' }) {
};
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
if (page === 'settings' && view !== 'settings' && document.startViewTransition && !reduceMotion) {
const root = document.documentElement;
const visibleSource = findSettingsTransitionSource(currentUser?.username);
const navbarAvatar = document.querySelector('#navbar #userDropdown .avatar');
const sourceAvatar = visibleSource.avatarElement || navbarAvatar;
const sourceName = visibleSource.nameElement;
const avatarFromNavbar = sourceAvatar === navbarAvatar;
if (!sourceAvatar) {
commitNavigation();
return;
}
root.classList.add('settings-view-transition');
if (avatarFromNavbar) root.classList.add('settings-avatar-from-navbar');
if (!sourceName) root.classList.add('settings-name-fade-only');
sourceAvatar.style.viewTransitionName = 'settings-avatar';
if (sourceName) sourceName.style.viewTransitionName = 'settings-user-name';
const transition = document.startViewTransition(() => {
sourceAvatar.style.viewTransitionName = '';
if (sourceName) sourceName.style.viewTransitionName = '';
if (avatarFromNavbar) root.classList.add('settings-navbar-avatar-hidden');
flushSync(() => commitNavigation(false));
});
transition.finished.finally(() => {
root.classList.remove(
'settings-view-transition',
'settings-avatar-from-navbar',
'settings-name-fade-only',
'settings-navbar-avatar-hidden'
);
if (avatarFromNavbar) {
root.classList.add('settings-navbar-avatar-reveal');
window.setTimeout(() => root.classList.remove('settings-navbar-avatar-reveal'), 360);
}
refresh();
});
return;
}
if (page === 'feed' && view === 'settings' && document.startViewTransition && !reduceMotion) {
const root = document.documentElement;
const sourceAvatar = document.querySelector('#pageSettings .settings-profile-avatar');
const sourceName = document.querySelector('#pageSettings .settings-profile-name');
if (!sourceAvatar) {
commitNavigation();
return;
}
let targetAvatar = null;
let targetName = null;
root.classList.add(
'settings-view-transition',
'returning-settings-home',
'settings-navbar-avatar-hidden'
);
const transition = document.startViewTransition(() => {
flushSync(() => commitNavigation(false));
const visibleTarget = findSettingsTransitionSource(currentUser?.username);
const navbarAvatar = document.querySelector('#navbar #userDropdown .avatar');
targetAvatar = visibleTarget.avatarElement || navbarAvatar;
targetName = visibleTarget.nameElement;
// Hide the navbar avatar only in the old snapshot. The new snapshot
// must expose it as the shared target when no visible feed avatar exists.
root.classList.remove('settings-navbar-avatar-hidden');
if (targetAvatar) targetAvatar.style.viewTransitionName = 'settings-avatar';
if (targetName) {
targetName.style.viewTransitionName = 'settings-user-name';
} else {
root.classList.add('settings-name-return-fade-only');
}
});
const clearTargetNames = () => {
if (targetAvatar) targetAvatar.style.viewTransitionName = '';
if (targetName) targetName.style.viewTransitionName = '';
};
transition.ready.then(clearTargetNames, clearTargetNames);
transition.finished.finally(() => {
root.classList.remove(
'settings-view-transition',
'returning-settings-home',
'settings-name-return-fade-only',
'settings-navbar-avatar-hidden'
);
refresh();
});
return;
}
if (page !== 'feed' || view === 'feed' || !document.startViewTransition || reduceMotion) {
commitNavigation();
return;
@@ -377,8 +601,8 @@ export default function AppProvider({ children, cachedName = '' }) {
const sourceName = document.querySelector('#pageUser .user-profile-name');
const findTargetCard = () => {
if (currentUserPreview?.sourcePostId) {
const exact = Array.from(document.querySelectorAll('[data-post-id]')).find(
(element) => element.dataset.postId === String(currentUserPreview.sourcePostId)
const exact = Array.from(document.querySelectorAll('[data-post-ref], [data-post-id]')).find(
(element) => postCardMatches(element, currentUserPreview.sourcePostId)
);
if (exact) return exact;
}
@@ -414,7 +638,7 @@ export default function AppProvider({ children, cachedName = '' }) {
}
let targetCard = currentPostId
? Array.from(document.querySelectorAll('[data-post-id]')).find((element) => element.dataset.postId === String(currentPostId))
? Array.from(document.querySelectorAll('[data-post-ref], [data-post-id]')).find((element) => postCardMatches(element, currentPostId))
: null;
let targetParts = [];
document.documentElement.classList.add('home-view-transition');
@@ -423,7 +647,7 @@ export default function AppProvider({ children, cachedName = '' }) {
const transition = document.startViewTransition(() => {
flushSync(() => commitNavigation(false));
targetCard = currentPostId
? Array.from(document.querySelectorAll('[data-post-id]')).find((element) => element.dataset.postId === String(currentPostId))
? Array.from(document.querySelectorAll('[data-post-ref], [data-post-id]')).find((element) => postCardMatches(element, currentPostId))
: null;
if (targetCard) targetCard.style.viewTransitionName = 'post-expand';
targetParts = namePostTransitionParts(targetCard);
@@ -453,21 +677,20 @@ export default function AppProvider({ children, cachedName = '' }) {
document.documentElement.classList.remove('home-view-transition', 'returning-home');
refresh();
});
}, [currentPostId, currentUsername, currentUserPreview, refresh, view]);
}, [currentPostId, currentUser, currentUsername, currentUserPreview, refresh, view]);
const openPost = useCallback((postId, sourceElement = null, preview = null, origin = null) => {
const url = new URL(window.location);
url.searchParams.set('post', postId);
url.searchParams.delete('page');
url.searchParams.delete('user');
const postRef = preview?.post_number || postId;
const url = clearLegacyPageParams(new URL(window.location));
url.pathname = pathForPost(postRef);
const resolvedOrigin = origin || { view };
const historyOrigin = resolvedOrigin?.view === 'user'
? { view: 'user', username: resolvedOrigin.username }
: { view: resolvedOrigin?.view || 'feed' };
const commitNavigation = () => {
window.history.pushState({ page: 'post', postId, origin: historyOrigin }, '', url);
window.history.pushState({ page: 'post', postId: postRef, origin: historyOrigin }, '', url);
setView('post');
setCurrentPostId(postId);
setCurrentPostId(postRef);
setCurrentPostPreview(preview);
setCurrentPostOrigin(resolvedOrigin);
setCurrentUserPreview(null);
@@ -520,10 +743,8 @@ export default function AppProvider({ children, cachedName = '' }) {
return;
}
const url = new URL(window.location);
url.searchParams.set('user', currentPostOrigin.username);
url.searchParams.delete('page');
url.searchParams.delete('post');
const url = clearLegacyPageParams(new URL(window.location));
url.pathname = pathForUser(currentPostOrigin.username);
const commitNavigation = () => {
window.history.pushState({ page: 'user', username: currentPostOrigin.username }, '', url);
setView('user');
@@ -549,8 +770,8 @@ export default function AppProvider({ children, cachedName = '' }) {
flushSync(commitNavigation);
const userPage = document.getElementById('pageUser');
if (userPage) userPage.scrollTop = currentPostOrigin.scrollTop || 0;
targetCard = Array.from(document.querySelectorAll('#userProfileContent [data-post-id]')).find(
(element) => element.dataset.postId === String(currentPostId)
targetCard = Array.from(document.querySelectorAll('#userProfileContent [data-post-ref], #userProfileContent [data-post-id]')).find(
(element) => postCardMatches(element, currentPostId)
) || null;
if (targetCard) targetCard.style.viewTransitionName = 'post-expand';
targetParts = namePostTransitionParts(targetCard);
@@ -583,10 +804,8 @@ export default function AppProvider({ children, cachedName = '' }) {
}, [currentPostId, currentPostOrigin, navigate]);
const openUser = useCallback((username, source = null, preview = null) => {
const url = new URL(window.location);
url.searchParams.set('user', username);
url.searchParams.delete('page');
url.searchParams.delete('post');
const url = clearLegacyPageParams(new URL(window.location));
url.pathname = pathForUser(username);
const commitNavigation = () => {
window.history.pushState({ page: 'user', username }, '', url);
setView('user');
@@ -628,10 +847,8 @@ export default function AppProvider({ children, cachedName = '' }) {
}, []);
const openCustomPage = useCallback((pageName) => {
const url = new URL(window.location);
url.searchParams.set('page', pageName);
url.searchParams.delete('post');
url.searchParams.delete('user');
const url = clearLegacyPageParams(new URL(window.location));
url.pathname = pathForCustomPage(pageName);
window.history.pushState({ page: 'custom', pageName }, '', url);
setView('custom');
setCurrentPageName(pageName);
@@ -642,33 +859,11 @@ export default function AppProvider({ children, cachedName = '' }) {
useEffect(() => {
const onPop = (e) => {
const state = e.state || {};
if (state.postId) {
setView('post');
setCurrentPostId(state.postId);
setCurrentPostPreview(null);
setCurrentPostOrigin(state.origin || null);
} else if (state.username) {
setView('user');
setCurrentUsername(state.username);
setCurrentUserPreview(null);
setCurrentUserPostsPreview(null);
} else if (state.pageName) {
setView('custom');
setCurrentPageName(state.pageName);
} else {
setView(state.page || 'feed');
setCurrentPostId(null);
setCurrentPostPreview(null);
setCurrentPostOrigin(null);
setCurrentUsername(null);
setCurrentUserPreview(null);
setCurrentUserPostsPreview(null);
setCurrentPageName(null);
}
applyRoute(routeFromLocation(window.location), state);
};
window.addEventListener('popstate', onPop);
return () => window.removeEventListener('popstate', onPop);
}, []);
}, [applyRoute]);
const login = useCallback(async (email, password) => {
const result = await API.login(email, password);
+2 -2
View File
@@ -163,8 +163,8 @@ export default function Feed({ onOpenModal, onReport }) {
posts.map((p) => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
return (
<div key={p.id} className="post-card" data-post-id={p.id} data-username={p.username || ''} style={{ cursor: 'pointer' }}
onClick={(e) => openPost(p.id, e.currentTarget, p)}>
<div key={p.id} className="post-card" data-post-id={p.id} data-post-ref={p.post_number || p.id} data-username={p.username || ''} style={{ cursor: 'pointer' }}
onClick={(e) => openPost(p.post_number || p.id, e.currentTarget, p)}>
{p.is_pinned && (
<div className="post-pin-state" style={{ width: 'fit-content', display: 'flex', alignItems: 'center', gap: 3, fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}><Icon name="pin" size={12} /> {t('feed.pinned')}</div>
)}
+1 -1
View File
@@ -63,7 +63,7 @@ export default function Navbar({ onOpenModal }) {
{customPages.map((p) => (
<a
key={p.id}
href="#"
href={'/' + encodeURIComponent(p.name)}
className="custom-page-nav-link"
data-custom={p.name}
onClick={(e) => { e.preventDefault(); openCustomPage(p.name); }}
+17 -3
View File
@@ -52,9 +52,23 @@ export default function PostDetail({ postId, initialPost = null }) {
const initialRefreshKey = useRef(refreshKey);
useEffect(() => {
if (initialPost?.id === postId && refreshKey === initialRefreshKey.current) return;
const initialReference = initialPost?.post_number || initialPost?.id;
if (String(initialReference || '') === String(postId) && refreshKey === initialRefreshKey.current) return;
load();
}, [initialPost?.id, load, postId, refreshKey]);
}, [initialPost?.id, initialPost?.post_number, load, postId, refreshKey]);
useEffect(() => {
if (!post?.post_number || !window.location.pathname.startsWith('/post/')) return;
const canonicalPath = `/post/${post.post_number}`;
if (window.location.pathname === canonicalPath) return;
const url = new URL(window.location);
url.pathname = canonicalPath;
window.history.replaceState(
{ ...window.history.state, page: 'post', postId: String(post.post_number) },
'',
url
);
}, [post?.post_number]);
const renderedContent = useMemo(() => renderMarkdown(post?.content), [post?.content]);
const renderedSignature = useMemo(() => renderMarkdown(post?.signature), [post?.signature]);
@@ -161,7 +175,7 @@ export default function PostDetail({ postId, initialPost = null }) {
<div className="post-page-layout">
<Sidebar id="postSidebar" />
<div id="postDetailContent" className="post-page-main">
<div className="post-detail-card">
<div className="post-detail-card" data-username={post.username || ''}>
<div className="post-header">
<img
src={post.avatar_url || avatar(post.username)}
+1 -1
View File
@@ -46,7 +46,7 @@ export default function SettingsPage() {
};
return (
<div className="page-slide active" style={{ overflow: 'hidden', height: '100vh', display: 'flex', flexDirection: 'column' }}>
<div id="pageSettings" className="page-slide active" style={{ overflow: 'hidden', height: '100vh', display: 'flex', flexDirection: 'column' }}>
<div className="page-header" style={{ width: '100%', flexShrink: 0 }}>
<h2><Icon name="settings" size={20} /> {t('settings.title')}</h2>
</div>
+2 -2
View File
@@ -56,7 +56,7 @@ export default function SettingsProfile() {
{/* 头像 */}
<div style={{ textAlign: 'center', marginBottom: 24 }}>
<div style={{ position: 'relative', display: 'inline-block' }}>
<img src={avatarSrc} style={{ width: 100, height: 100, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt="" />
<img className="settings-profile-avatar" src={avatarSrc} style={{ width: 100, height: 100, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt="" />
<button
style={{ position: 'absolute', bottom: 0, right: 0, background: 'var(--primary)', color: '#fff', border: 'none', borderRadius: '50%', width: 32, height: 32, cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 2px 8px rgba(99,102,241,0.4)' }}
onClick={() => avatarInputRef.current?.click()}
@@ -67,7 +67,7 @@ export default function SettingsProfile() {
</button>
</div>
<input type="file" ref={avatarInputRef} accept="image/*" style={{ display: 'none' }} onChange={(e) => { if (e.target.files?.[0]) handleAvatar(e.target.files[0]); }} />
<h2 style={{ margin: '12px 0 4px' }}>{currentUser?.username}</h2>
<h2 className="settings-profile-name" style={{ margin: '12px 0 4px', fontSize: 14, fontWeight: 600, color: 'var(--primary)' }}>{currentUser?.username}</h2>
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{bio || t('user.bioEmpty')}</p>
{avatarStatus && (
<div style={{ fontSize: 13, marginTop: 8, color: avatarStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5 }}><Icon name={avatarStatus.ok ? 'success' : 'error'} size={14} /> {avatarStatus.msg}</div>
+3 -2
View File
@@ -69,7 +69,7 @@ export default function UserProfile({ username, initialUser = null, initialPosts
<h2><Icon name="users" size={20} /> 用户主页</h2>
</div>
<div id="userProfileContent" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<div className="user-profile-card" style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 32, textAlign: 'center' }}>
<div className="user-profile-card" data-username={user.username || ''} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 32, textAlign: 'center' }}>
<img className="user-profile-avatar" src={user.avatar_url || avatar(user.username)} style={{ width: 96, height: 96, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt={user.username || ''} />
<h2 className="user-profile-name" style={{ margin: '16px 0 4px', fontSize: 24, color: 'var(--text)' }}>{user.username}</h2>
{user.id && (
@@ -105,9 +105,10 @@ export default function UserProfile({ username, initialUser = null, initialPosts
key={p.id}
className="post-card user-post-card"
data-post-id={p.id}
data-post-ref={p.post_number || p.id}
data-username={user.username || ''}
style={{ cursor: 'pointer' }}
onClick={(event) => openPost(p.id, event.currentTarget, p, {
onClick={(event) => openPost(p.post_number || p.id, event.currentTarget, p, {
view: 'user',
username: user.username,
user,
+3 -2
View File
@@ -56,15 +56,16 @@ export default function AdminUsers() {
const isAdmin = u.role === 'admin';
const isCurrent = currentUser && currentUser.id === u.id;
return (
<tr key={u.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
<tr key={u.id} data-username={u.username || ''} style={{ borderBottom: '1px solid #f1f5f9' }}>
<td style={{ padding: '10px 12px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<img
src={u.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64'}
className="admin-user-avatar"
style={{ width: 28, height: 28, borderRadius: '50%', objectFit: 'cover' }}
alt=""
/>
<span style={{ fontWeight: 500 }}>{u.username}</span>
<span className="admin-user-name" style={{ fontWeight: 500 }}>{u.username}</span>
{isCurrent && <span style={{ fontSize: 11, color: '#94a3b8', background: '#eef2ff', padding: '1px 8px', borderRadius: 4 }}>{t('admin.user.you')}</span>}
</div>
</td>
+85
View File
@@ -0,0 +1,85 @@
import pool from './db';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const POST_NUMBER_RE = /^[1-9]\d*$/;
const MAX_POST_NUMBER = 9223372036854775807n;
let migrationPromise = null;
async function migratePostNumbers() {
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query("SELECT pg_advisory_xact_lock(hashtext('forumlify-post-number-v1'))");
await client.query('CREATE SEQUENCE IF NOT EXISTS posts_post_number_seq START WITH 1');
await client.query('ALTER TABLE posts ADD COLUMN IF NOT EXISTS post_number BIGINT');
await client.query(`
WITH current_max AS (
SELECT COALESCE(MAX(post_number), 0) AS value FROM posts
), numbered AS (
SELECT id, (SELECT value FROM current_max) + ROW_NUMBER() OVER (
ORDER BY created_at ASC, id ASC
) AS value
FROM posts
WHERE post_number IS NULL
)
UPDATE posts
SET post_number = numbered.value
FROM numbered
WHERE posts.id = numbered.id
`);
await client.query(`
SELECT setval(
'posts_post_number_seq',
GREATEST(
COALESCE((SELECT MAX(post_number) FROM posts), 0) + 1,
CASE WHEN is_called THEN last_value + 1 ELSE last_value END
),
false
)
FROM posts_post_number_seq
`);
await client.query("ALTER TABLE posts ALTER COLUMN post_number SET DEFAULT nextval('posts_post_number_seq')");
await client.query('ALTER SEQUENCE posts_post_number_seq OWNED BY posts.post_number');
await client.query('ALTER TABLE posts ALTER COLUMN post_number SET NOT NULL');
await client.query('CREATE UNIQUE INDEX IF NOT EXISTS posts_post_number_key ON posts(post_number)');
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK').catch(() => {});
throw error;
} finally {
client.release();
}
}
export function ensurePostNumberSchema() {
if (!migrationPromise) {
migrationPromise = migratePostNumbers().catch((error) => {
migrationPromise = null;
throw error;
});
}
return migrationPromise;
}
export function isPostReference(value) {
const reference = String(value || '');
if (UUID_RE.test(reference)) return true;
if (!POST_NUMBER_RE.test(reference)) return false;
try {
return BigInt(reference) <= MAX_POST_NUMBER;
} catch {
return false;
}
}
export async function resolvePostReference(value, client = pool) {
await ensurePostNumberSchema();
const reference = String(value || '');
if (!isPostReference(reference)) return null;
const result = UUID_RE.test(reference)
? await client.query('SELECT id, post_number FROM posts WHERE id = $1', [reference])
: await client.query('SELECT id, post_number FROM posts WHERE post_number = $1::bigint', [reference]);
return result.rows[0] || null;
}
+38
View File
@@ -15,9 +15,11 @@ CREATE TABLE IF NOT EXISTS users (
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE SEQUENCE IF NOT EXISTS posts_post_number_seq START WITH 1;
-- 帖子表
CREATE TABLE IF NOT EXISTS posts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
post_number BIGINT NOT NULL UNIQUE DEFAULT nextval('posts_post_number_seq'),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(200) NOT NULL,
content TEXT NOT NULL,
@@ -239,3 +241,39 @@ UPDATE users SET role = 'admin'
WHERE role <> 'admin'
AND NOT EXISTS (SELECT 1 FROM users WHERE role = 'admin')
AND id = (SELECT id FROM users ORDER BY created_at ASC, id ASC LIMIT 1);
-- ============================================================
-- 帖子公开编号迁移(数据库兼容,幂等)
-- UUID 继续作为内部主键;公开编号按发布时间从 1 开始。
-- ============================================================
CREATE SEQUENCE IF NOT EXISTS posts_post_number_seq START WITH 1;
ALTER TABLE posts ADD COLUMN IF NOT EXISTS post_number BIGINT;
WITH current_max AS (
SELECT COALESCE(MAX(post_number), 0) AS value FROM posts
), numbered AS (
SELECT id, (SELECT value FROM current_max) + ROW_NUMBER() OVER (
ORDER BY created_at ASC, id ASC
) AS value
FROM posts
WHERE post_number IS NULL
)
UPDATE posts
SET post_number = numbered.value
FROM numbered
WHERE posts.id = numbered.id;
SELECT setval(
'posts_post_number_seq',
GREATEST(
COALESCE((SELECT MAX(post_number) FROM posts), 0) + 1,
CASE WHEN is_called THEN last_value + 1 ELSE last_value END
),
false
)
FROM posts_post_number_seq;
ALTER TABLE posts ALTER COLUMN post_number SET DEFAULT nextval('posts_post_number_seq');
ALTER SEQUENCE posts_post_number_seq OWNED BY posts.post_number;
ALTER TABLE posts ALTER COLUMN post_number SET NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS posts_post_number_key ON posts(post_number);
+2 -2
View File
@@ -142,13 +142,13 @@ test('统计接口', async () => {
assert.ok(typeof data.users === 'number');
});
test('记录事件日志', async () => {
test('客户端不能伪造事件日志', async () => {
const { status } = await api('/event-logs', {
method: 'POST',
headers: { Authorization: `Bearer ${adminToken}` },
body: JSON.stringify({ action: 'test_action' }),
});
assert.equal(status, 200);
assert.equal(status, 405);
});
test('管理员查看事件日志', async () => {
+10
View File
@@ -23,6 +23,7 @@ let adminToken = null;
let adminId = null;
let userId = null;
let postId = null;
let postNumber = null;
let replyId = null;
const adminUser = { email: `admin${suffix}@test.com`, password: '123456', username: `admin${suffix}` };
@@ -87,7 +88,9 @@ test('发布帖子', async () => {
});
assert.equal(status, 200);
assert.ok(data.id);
assert.ok(Number(data.post_number) >= 1);
postId = data.id;
postNumber = data.post_number;
});
test('帖子列表返回分页结构', async () => {
@@ -110,6 +113,13 @@ test('帖子详情', async () => {
assert.equal(data.title, '测试帖子');
});
test('公开编号可访问同一帖子', async () => {
const { status, data } = await api('/posts/' + postNumber);
assert.equal(status, 200);
assert.equal(data.id, postId);
assert.equal(data.post_number, postNumber);
});
test('不存在的帖子返回 404', async () => {
const { status } = await api('/posts/00000000-0000-0000-0000-000000000000');
assert.equal(status, 404);