Author SHA1 Message Date

2026-08-14

lezi-fun 6202d89e26 fix: update cd command to match new clone directory name 2026-08-14 09:48:50 +08:00
lezi-fun 59edccac45 fix: update docker image reference to forumlify/public 2026-08-14 09:44:05 +08:00
lezi-fun a4b2e47bb2 docs: update repository links to forumlify/public 2026-08-14 09:43:06 +08:00

2026-08-13

lezi e85ced7319 Merge pull request #25 from forumlify/feat/forgot-password-recovery-code
feat: add recovery-code password reset to login
2026-08-13 15:33:16 +08:00
lezi-fun 62a23fb04c fix: clear reset secrets and isolate recovery tests 2026-08-13 15:24:04 +08:00
lezi-fun 63db81e498 feat: add recovery-code password reset to login 2026-08-13 15:13:30 +08:00
lezi-fun 36fc7cbeb8 ci: generate Codecov coverage from Node tests 2026-08-13 14:27:36 +08:00
lezi-fun 4b1481dd41 ci: flush Next coverage before upload 2026-08-13 14:15:08 +08:00
lezi-fun 8911455e5e docs: add Codecov coverage badge 2026-08-13 14:03:05 +08:00
lezi-fun acf5d40e57 ci: add Codecov bundle and test reporting 2026-08-13 13:58:46 +08:00
lezi-fun e6ac6ab03c ci: disable captcha for coverage tests 2026-08-13 13:44:22 +08:00
lezi-fun 053a04a2ea ci: run coverage on Node 24 2026-08-13 13:41:24 +08:00
lezi-fun a4fc48b613 ci: fix Node 20 test file discovery 2026-08-13 13:40:30 +08:00
lezi-fun c58cefdb5a ci: add Codecov coverage reporting 2026-08-13 13:37:35 +08:00
lezi 43dbb75048 Merge pull request #24 from forumlify/feat/path-navigation-settings-transitions-v2
feat: add path navigation and shared settings transitions
2026-08-13 13:27:24 +08:00
lezi-fun 84c9e97451 feat: add path navigation and shared settings transitions 2026-08-13 12:29:09 +08:00

2026-08-12

lezi-fun caad17d195 feat: animate reply loading state 2026-08-12 20:50:51 +08:00
lezi-fun 207b64b705 fix: unify home post card colors 2026-08-12 20:31:34 +08:00
lezi-fun 96e0e6f08e fix: prevent super admin demotion 2026-08-12 20:12:22 +08:00
lezi-fun 3840bb3c54 fix: support replies on legacy databases 2026-08-12 20:05:29 +08:00
lezi-fun 68b58851e8 fix: refine user post transitions 2026-08-12 19:34:42 +08:00
lezi-fun 352f1d57e6 docs: add Forumlify agent guide 2026-08-12 19:34:42 +08:00
lezi 56a5fc903e Update README.md 2026-08-12 10:49:50 +08:00
lezi-fun ac0bd3fe0e chore: add Next.js agent guidance 2026-08-12 10:25:35 +08:00
lezi-fun bbf3262aff feat: animate user profile transitions 2026-08-12 10:24:20 +08:00
lezi 8e67e82eb0 Update docker-compose.yml 2026-08-12 09:57:01 +08:00
lezi-fun 9ae54dff29 fix: synchronize post return handoff 2026-08-12 09:55:13 +08:00
lezi-fun 5e9909ac7a fix: reverse post return transition 2026-08-12 09:34:28 +08:00
lezi-fun 3b4b598ce5 fix: smooth pinned and loading animations 2026-08-12 09:14:55 +08:00
lezi-fun b9d6ca5da8 security: server-owned audit logs + fullscreen custom pages
Port upstream PR #22 + Lite style updates:
- lib/audit.js: server-side logAudit(req, action, userId), records
  IP from x-forwarded-for / cf-connecting-ip
- login/register/create_post/create_reply record server-side
- Remove client logEvent calls (AppProvider/NewPost/ReplyList)
- Remove forgeable POST /api/event-logs endpoint
- CustomPage: fullscreen immersive (fixed, 100vh-nav, mobile 56px
  nav offset) matching upstream Lite
2026-08-12 09:06:50 +08:00

2026-08-11

lezi-fun 45ace3ba75 cleanup: remove chain view + show-more, all replies always visible 2026-08-11 22:26:02 +08:00
lezi-fun 0aac277aea Revert "feat: reply chain view (sub-thread folding)"
This reverts commit 4c0f146338.
2026-08-11 22:22:18 +08:00
lezi-fun 4c0f146338 feat: reply chain view (sub-thread folding)
Build reply tree, show up to 3 children per reply. '继续此消息串' opens a dedicated chain view (only that reply + all descendants). '返回所有回复' goes back.
2026-08-11 22:21:09 +08:00
lezi-fun 84616ff4a1 feat: remove reply indicator, dynamic folding (min 3 replies)
Remove per-reply '正在回复 @xxx' indicator. Collapse replies: show count based on viewport height (min 3). Clean up unused CSS.
2026-08-11 22:07:10 +08:00
lezi-fun a57d29ceed feat: collapse replies (show last 5, 继续此消息串)
When >5 replies, show the latest 5 and a '继续此消息串 (还有N条回复)' button. Click to expand all. Discourse-style folding.
2026-08-11 22:03:12 +08:00
lezi-fun b18cd05455 fix: narrow-only reply-header wrap
Remove global flex-wrap, add @media (max-width:480px) flex-wrap: wrap. Wide: one line. Narrow: flex-wrap naturally wraps buttons as whole units (white-space:nowrap prevents text split).
2026-08-11 22:00:52 +08:00
lezi-fun 32fc3cb599 fix: reply-header flex-wrap (natural wrap, no text split)
Removed compact media query. reply-header gets flex-wrap: wrap so buttons wrap as whole units when width is insufficient (white-space:nowrap prevents text splitting).
2026-08-11 21:47:39 +08:00
lezi-fun f3586ef2aa fix: narrow screen compact reply buttons
Media query (max-width:480px): reply-header flex-wrap, smaller btn padding/ font-size, prevent overflow beyond card border.
2026-08-11 21:43:55 +08:00
lezi-fun 56912d28d6 fix: reply-delete-btn white-space:nowrap (prevent narrow-wrap split) 2026-08-11 21:41:43 +08:00
lezi-fun 6c100ff3a1 fix: reply chain uses reply_to_id (UUID) instead of reply_to_username
- reply_to_id UUID FK: precise parent tracking (username was ambiguous
  when same user wrote multiple replies in a chain)
- GET /api/replies: JOIN replies + users to return reply_to_username
- POST /api/replies: accept reply_to_id (UUID) instead of reply_to_username
- Frontend depth calc: follow reply_to_id chain (not username)
- Preview bar: resolve username from local replies by ID
- Indicator scroll: target by data-reply-id
2026-08-11 21:38:45 +08:00
lezi-fun 59d5fb89c0 fix: nested replies keep border-radius (was set to 0 by indent rule) 2026-08-11 21:33:44 +08:00
lezi-fun 16af1cfd41 fix: reply nesting depth + post detail card radius
- Replies: compute nesting depth via reply_to_username chain (depth
  tracking, max 5 levels, 18px indent per level)
- Post detail card: add border-radius var(--radius)
- Reply preview bar: cleaner bottom-border style (no blue box)
2026-08-11 21:31:06 +08:00
lezi-fun d9c4079619 style: reply hierarchy + cleaner reply-preview bar
- Replies with a reply_to target get left-border + indent (Discourse
  thread feel) via :has() selector
- Reply-box preview bar: removed blue box, now a clean bottom-border
  row (回复 @user + 取消 button)
- reply-to indicator: left border line, primary on hover
- Works in light & dark mode (uses --border/--text-light vars)
2026-08-11 21:22:20 +08:00
lezi-fun 4d0d5edec3 feat: Discourse-style reply-to indicator (↩ @username)
- replies table: add reply_to_username column
- POST /api/replies: accept reply_to_username param
- GET /api/replies: LEFT JOIN users to return reply_to_username
- ReplyList: submit replyTo as reply_to_username on create
- UI: each reply shows '↩ 正在回复 @username' indicator (clickable,
  scrolls to target reply)
- data-username attribute on .reply-item for scroll targeting
2026-08-11 21:18:18 +08:00
lezi-fun 7bf9e37036 fix: reply button always visible (mail-style icon), works on own replies
- Reply button: always visible (opacity 0.5), only icon (no text),
  hover → full opacity + primary color
- Works on own replies (no restriction on replying to self)
- Removed .reply-item:hover .reply-btn (was requiring parent hover)
2026-08-11 21:08:55 +08:00
lezi-fun 2bb1f4227e feat: hover reply button → quote + scroll to reply box
- Each reply shows a 回复 button on hover (always visible on touch)
- Click: sets '正在回复 @user' banner, smooth-scrolls to reply box,
  focuses textarea; 取消 clears it
- New reply icon (corner-up-left); clear replyTo after submit
- Reply markdown already rendered via renderMarkdown (sanitized)
2026-08-11 20:57:48 +08:00
lezi-fun d757bde780 feat: super admin badge — earliest admin shows 超级管理员 in user list
- /api/users: mark is_super for the earliest-registered admin (matches
  the auto-promotion migration semantics)
- AdminUsers: render 超级管理员 badge for is_super, 管理员 otherwise
- i18n keys admin.user.roleSuper (zh/en)
- Mobile settings nav: active tab gets top-left/top-right rounded
  corners only (desktop unchanged)
2026-08-11 20:40:02 +08:00
lezi-fun f0867935ac fix: mobile narrow — post action buttons wrap to own row
@media (max-width:640px): .post-header flex-wrap; .post-detail-controls
full-width right-aligned row (no more icon/text split across lines).
2026-08-11 20:34:05 +08:00
lezi-fun 7188d07aea security: server-side CAPTCHA (HMAC-signed) + magic-byte upload sniff + pagination bounds
Port upstream ac4af62 + PR #14/#17:
- lib/captcha.js: HMAC(CAPTCHA_SECRET, id:answer) challenge; GET
  /api/captcha returns {id, text, sig}; register/createPost/createReply
  verify answer server-side (bad answer / forged sig rejected)
- Frontend (Modals/NewPost/ReplyList): fetch challenge from server,
  submit id+answer+sig; no more client-side answer check (was bypassable)
- Upload: sniff JPEG/PNG/GIF/WebP magic bytes (ignore client MIME), UUID
  filenames — blocks spoofed HTML-as-image (stored XSS)
- Posts pagination: limit cap 50, page cap (deep-pagination DoS)
- CAPTCHA_SECRET env (falls back to JWT_SECRET)
2026-08-11 20:25:16 +08:00
lezi-fun 2780dab8e2 feat: auto-promote earliest-registered user to super admin (idempotent)
users PK is UUID (no uid=1), so bootstrap super admin via semantics:
if no admin exists, promote the user with earliest created_at. Idempotent
(no-op when an admin already exists), safe on any existing database.
Matches the admin-list ordering (earliest user at the bottom).
2026-08-11 20:05:36 +08:00
Furrium Network 684d502deb Update README.md 2026-08-11 20:03:42 +08:00
Furrium Network 1fcea44c49 Update README.md 2026-08-11 20:02:25 +08:00
Furrium Network 07cf69b723 Update README.md 2026-08-11 20:01:41 +08:00
lezi-fun 4ff8488587 fix: settings page portrait layout — flex fill instead of fixed 70vh
Root becomes flex column (header fixed, layout flex:1); scroll
container uses flex:1 + minHeight:0 instead of fixed height:70vh so
portrait/phone screens get full remaining height instead of a short
squished panel.
2026-08-11 19:48:32 +08:00
lezi-fun 8e538fea80 chore: allowedDevOrigins reads ALLOWED_DEV_ORIGINS env (no hardcoded IPs)
Dev-only origin allowlist stays 127.0.0.1 by default; LAN devices can
be enabled per-machine via ALLOWED_DEV_ORIGINS=ip1,ip2 without touching
the repo.
2026-08-11 19:40:52 +08:00
lezi-fun dfe3556987 ci: revert to single multi-arch build job (simplest working version)
One build job pushes linux/amd64 + linux/arm64 together — buildx
creates the multi-arch :next manifest automatically. No manifest job,
no PAT, no repo filter. Node 24.
2026-08-11 19:27:22 +08:00
lezi-fun ab069c4b91 ci: fixed image name + PAT login (publish from upstream next to lezi-fun GHCR)
- IMAGE_NAME pinned to lezi-fun/forumlify-deploy (not github.repository)
- login uses secrets.GHCR_TOKEN (PAT with packages:write) so any repo
  (upstream Furrium/forumlify included) can publish to lezi-fun GHCR
- removed repo filter
2026-08-11 19:26:44 +08:00
lezi-fun 8cbde6dbc4 ci: only build GHCR image in forumlify-deploy repo (skip upstream)
Add job-level if: github.repository == 'lezi-fun/forumlify-deploy' so
pushes to Furrium/forumlify don't trigger broken builds (uppercase repo
name invalid for docker, and image would target wrong GHCR).
2026-08-11 19:22:35 +08:00
lezi-fun d074e27418 ci: fix manifest merge — newline in tags broke shell loop 2026-08-11 19:18:12 +08:00
lezi-fun f96d21ade7 ci: merge per-arch tags into multi-arch manifests (:next etc.)
Separate amd64/arm64 jobs push :next-amd64 / :next-arm64; add manifest
job that merges them into :next, :main, semver and sha tags so the
branch tag is a real multi-arch manifest (both platforms).
2026-08-11 19:13:46 +08:00
lezi-fun de69cd81a1 ci: drop Windows image (official node Windows base images removed)
node:24-windowsservercore* / nanoserver don't exist on Docker Hub (Node
stopped publishing Windows container images; even node:20 Windows tags
are gone). Keep linux/amd64 + linux/arm64 on node 24.
2026-08-11 19:09:27 +08:00
lezi-fun 1cfc61ff45 ci: node 24 + per-platform jobs (linux-amd64, linux-arm64, win64)
- Dockerfile/Dockerfile.windows: node 20 → 24
- 3 parallel jobs: linux/amd64, linux/arm64 (buildx, -arch tags),
  win64 (windows-latest native Windows containers, :next-windows)
- winarm64 dropped (no official Windows ARM64 node base image)
2026-08-11 19:05:48 +08:00
lezi-fun cc90c93673 ci: multi-arch images — linux/amd64 + linux/arm64 + windows/amd64
- Linux: build-push-action platforms linux/amd64,linux/arm64
- Windows: separate job on windows-latest (switch to Windows container
  engine, native docker build with Dockerfile.windows) → :next-windows
- Dockerfile.windows: node:20-windowsservercore-ltsc2022, bun install,
  standalone output
2026-08-11 18:59:22 +08:00
lezi-fun 7c6b816ac7 fix: pinned posts not sorted to top + compose pulls GHCR image
- posts API: ORDER BY is_pinned DESC, pinned_at DESC NULLS LAST before
  sort (matches upstream) — pinned posts now appear first
- docker-compose: app service pulls ghcr.io/lezi-fun/forumlify-deploy:next
  instead of local build (auto-rebuilt on push)
2026-08-11 18:55:10 +08:00
lezi-fun d265caa5bf ci: build & push Docker image to GHCR on push/tag
Trigger: push to next/main, semver tags, manual dispatch.
Tags: branch name, semver, git sha. Uses GHA cache.
2026-08-11 18:17:53 +08:00
lezi-fun d349660944 fix: remove stray merge conflict marker in schema.sql
Line '<<<<<<< HEAD' (no matching =======/>>>>>>>) broke postgres
init in Docker (db container exited 3 → all API 500). Remove it.
2026-08-11 18:06:45 +08:00
lezi 66047c0c4b Delete bun.lock 2026-08-11 18:03:28 +08:00
lezi-fun d304e7e863 fix: remove OpenNext dev hook from next.config (spawns workerd in build)
initOpenNextCloudflareForDev() runs when next.config.js loads → spawns
workerd binary (missing in Docker/node:20-alpine) → build crashes with
ENOENT. The hook is only for opennextjs-cloudflare preview (dev);
production build/deploy doesn't need it.
2026-08-11 18:00:03 +08:00
lezi-fun a53304cefa fix(docker): use bun install (npm reads stale lockfile → react 18) + .dockerignore
Docker build failed at npm run build: stale package-lock.json pins
react@18 while next@16 requires react@19. Switch builder to bun install
(bun.lock is current). Add .dockerignore (was shipping 700MB context).
2026-08-11 17:56:42 +08:00
lezi-fun dce94fd5af feat: auto-detect browser language (SSR Accept-Language + cookie)
- layout (server): derive language from cookie (user choice) > browser
  Accept-Language; set <html lang> accordingly
- I18nInit → I18nProvider: sync initI18n(lng) before children render
  (SSR/CSR first render same language, no hydration mismatch)
- setAppLanguage also writes cookie so SSR first paint uses chosen lang
- Verified: en browser → lang=en, zh → zh-CN, cookie overrides
2026-08-11 17:42:08 +08:00
lezi 08302dc0d7 Update LICENSE 2026-08-11 17:36:34 +08:00
lezi-fun 5a9a454ef3 fix: replies drawer auto-expand, settings no-scroll, title bug, admin links
- PostDetail: replies open as drawer (grid-rows animation) automatically
  after post loads — no toggle button
- SettingsPage: outer frame overflow hidden (100vh), only inner panel
  scrolls; hide #app layout when not on feed (fixes navbar moving when
  scrolling settings)
- Title: metadata 'Loading...' → 'Forumlify' (Next resets <title> to
  metadata on re-render → title became Loading... after load); unify
  title effect (rotate Loading. only while !ready && !forumNameLoaded)
- AdminLinks: link divider uses var(--border) (was #f1f5f9, invisible
  in dark mode); add admin.link i18n keys
- AdminPage i18n nav labels
2026-08-11 17:35:48 +08:00
lezi ad89aa3e04 Update README.md 2026-08-11 17:27:20 +08:00
lezi 77d4cc370a Update README.md 2026-08-11 17:26:37 +08:00
lezi-fun 7cdb7c1ac2 security: sync upstream XSS fix + moderation history (reports SET NULL)
- renderMarkdown: sanitize marked output with sanitize-html (allowed
  tags/attrs whitelist, http/https schemes only, strip on* attrs) —
  prevents stored XSS in posts/replies/signatures
- schema: reports.post_id ON DELETE CASCADE → SET NULL (keep moderation
  history when a reported post is deleted); migration applied to prod DB
2026-08-11 17:06:56 +08:00
lezi-fun 7cc1f0e228 fix: polish post transition details 2026-08-11 16:56:07 +08:00
lezi-fun cb89f1190c fix: stabilize markdown post transition 2026-08-11 15:58:39 +08:00
lezi-fun 0060034dec fix: morph post card content by element 2026-08-11 15:46:46 +08:00
lezi-fun ae2d5e82ca fix: smooth post title and card morph 2026-08-11 15:32:26 +08:00
lezi-fun 608e6b2522 Merge remote-tracking branch 'origin/next' into next
# Conflicts:
#	app/HomeClient.js
#	app/globals.css
#	components/AccountSecurity.js
#	components/AppProvider.js
#	components/Feed.js
#	components/Modals.js
#	components/Navbar.js
#	components/NewPost.js
#	components/PostDetail.js
#	components/RecoveryCodes.js
#	components/ReplyList.js
#	components/SettingsPage.js
#	components/SettingsProfile.js
#	components/Toast.js
#	components/admin/AdminCustomCss.js
#	components/admin/AdminCustomPages.js
#	components/admin/AdminForumSettings.js
#	components/admin/AdminLinks.js
#	components/admin/AdminLogs.js
#	components/admin/AdminReports.js
#	components/admin/AdminUsers.js
#	components/chat/ConversationList.js
#	locales/en.json
#	locales/zh.json
2026-08-11 15:27:27 +08:00
lezi-fun 6947cdaf36 fix: polish forum navigation and interface states 2026-08-11 15:25:05 +08:00
lezi-fun b60aff7c25 fix: restore dark post view and API revalidation 2026-08-11 13:34:44 +08:00
lezi-fun 0933220c70 fix: restore dark post view and API revalidation 2026-08-11 13:32:44 +08:00
lezi 773db0dec7 Update README.md 2026-08-11 12:25:27 +08:00
lezi-fun ef9d8b8f9c fix: Next 16 cookies() is async — await it in Home (page rendering error
cookies().get() without await threw in Next 16 (sync dynamic API
removed), breaking the whole Home SSR render → layout broken, spinner
restart, flash. Await cookies() before reading forumlify-name.
Also raise glass-bg opacity (0.18→0.62 light / 0.35→0.60 dark) so
cards/navbar/modal aren't see-through.
2026-08-11 11:43:27 +08:00
lezi-fun 5c554f27ea fix: Next 16 cookies() is async — await it in Home (page rendering error
cookies().get() without await threw in Next 16 (sync dynamic API
removed), breaking the whole Home SSR render → layout broken, spinner
restart, flash. Await cookies() before reading forumlify-name.
Also raise glass-bg opacity (0.18→0.62 light / 0.35→0.60 dark) so
cards/navbar/modal aren't see-through.
2026-08-11 11:43:10 +08:00
lezi-fun 78ef6cd798 fix: desktop layout — use #app flex container (was .app-container with no CSS)
HomeClient rendered className='app-container' but globals.css only
defines #app (flex) — sidebar/feed fell back to block layout, feed
pushed below. Switch to id='app' to match upstream stylesheet.
Also: AdminPage i18n (nav labels + title).
2026-08-11 11:38:18 +08:00
lezi-fun 72e93ca5bb fix: desktop layout — use #app flex container (was .app-container with no CSS)
HomeClient rendered className='app-container' but globals.css only
defines #app (flex) — sidebar/feed fell back to block layout, feed
pushed below. Switch to id='app' to match upstream stylesheet.
Also: AdminPage i18n (nav labels + title).
2026-08-11 11:38:10 +08:00
lezi-fun 1934edebd5 feat: i18n (i18next + react-i18next) zh/en + hydration fixes
- i18next + react-i18next: zh/en locales, language detection
  (localStorage > navigator > zh), settings language switcher
- Components i18n'd: Navbar, Feed, NewPost, Modals, SettingsPage,
  SettingsProfile, AccountSecurity, RecoveryCodes
- Fix hydration mismatch (spinner restart): forum name via cookie
  (Server Component reads cookie, SSR outputs name, no inline script
  DOM injection); remove createPortal in RecoveryCodes modal; i18n
  sync init (initImmediate) so SSR/CSR text matches
- LoadingScreen: React-state name rendering (no script-injected nodes)
- Fix double spinner in Feed; DM icon emoji → SVG in ConversationList

# Conflicts:
#	components/AppProvider.js
#	components/NewPost.js
2026-08-11 11:33:57 +08:00
lezi-fun 0562dd735a feat: i18n (i18next + react-i18next) zh/en + hydration fixes
- i18next + react-i18next: zh/en locales, language detection
  (localStorage > navigator > zh), settings language switcher
- Components i18n'd: Navbar, Feed, NewPost, Modals, SettingsPage,
  SettingsProfile, AccountSecurity, RecoveryCodes
- Fix hydration mismatch (spinner restart): forum name via cookie
  (Server Component reads cookie, SSR outputs name, no inline script
  DOM injection); remove createPortal in RecoveryCodes modal; i18n
  sync init (initImmediate) so SSR/CSR text matches
- LoadingScreen: React-state name rendering (no script-injected nodes)
- Fix double spinner in Feed; DM icon emoji → SVG in ConversationList
2026-08-11 11:32:15 +08:00
lezi-fun 024b678ad3 fix: hydration mismatch (loading spinner restart) + cache strategy
Root cause of loading spinner restarting / name appearing twice:
React hydration mismatch → whole tree regenerated. Fixed all sources:
- AppProvider: remove typeof window in useState init (SSR/client diff);
  read cached forum name in useEffect instead
- ToastProvider: remove createPortal(document.body) (SSR absent →
  mismatch)
- LoadingScreen: name container uses dangerouslySetInnerHTML('') so
  React never manages/clobbers the inline-script-filled text
- layout.js: inline script moved to body first child (React official
  anti-FOUC pattern)

Cache: dynamic pages/API no-cache + ETag (304 on revalidate); static
/_next/static assets immutable 1y. Verified: 304 + immutable headers.
2026-08-11 10:52:33 +08:00
lezi-fun 82bc2eb885 fix: hydration mismatch (loading spinner restart) + cache strategy
Root cause of loading spinner restarting / name appearing twice:
React hydration mismatch → whole tree regenerated. Fixed all sources:
- AppProvider: remove typeof window in useState init (SSR/client diff);
  read cached forum name in useEffect instead
- ToastProvider: remove createPortal(document.body) (SSR absent →
  mismatch)
- LoadingScreen: name container uses dangerouslySetInnerHTML('') so
  React never manages/clobbers the inline-script-filled text
- layout.js: inline script moved to body first child (React official
  anti-FOUC pattern)

Cache: dynamic pages/API no-cache + ETag (304 on revalidate); static
/_next/static assets immutable 1y. Verified: 304 + immutable headers.
2026-08-11 10:52:21 +08:00
lezi-fun 517661441a fix: long post fade uses mask (text fades out, no white block)
Replace background gradient overlay with mask-image so the text itself
fades to transparent toward the bottom; no solid edge color visible.
2026-08-11 10:30:44 +08:00
lezi-fun b5fafdbc09 fix: long post fade uses mask (text fades out, no white block)
Replace background gradient overlay with mask-image so the text itself
fades to transparent toward the bottom; no solid edge color visible.
2026-08-11 10:30:34 +08:00
lezi-fun c4ec3340de fix: loading title double-render + spinner restart (hydration)
Inline script fills cached name into #loadingTitle before React
hydrate; React then saw text mismatch and rewrote the DOM, making the
name appear twice and restarting the spinner animation. Add
suppressHydrationWarning so React keeps the script-filled content.
2026-08-11 10:25:33 +08:00
lezi-fun 91ab1c6239 fix: loading title double-render + spinner restart (hydration)
Inline script fills cached name into #loadingTitle before React
hydrate; React then saw text mismatch and rewrote the DOM, making the
name appear twice and restarting the spinner animation. Add
suppressHydrationWarning so React keeps the script-filled content.
2026-08-11 10:25:24 +08:00
lezi-fun 1dbcb89fbd fix: user profile avatar + loading spinners + modal opacity
- UserProfile now uses avatar_url (was always default ui-avatars)
- Loading states show spinner-sm spinner instead of plain text
  (Feed, UserProfile, chat, admin panels, custom pages)
- Modal background: semi-transparent glass (0.85 light / 0.88 dark)
2026-08-11 10:23:40 +08:00
lezi-fun 74202f7551 fix: user profile avatar + loading spinners + modal opacity
- UserProfile now uses avatar_url (was always default ui-avatars)
- Loading states show spinner-sm spinner instead of plain text
  (Feed, UserProfile, chat, admin panels, custom pages)
- Modal background: semi-transparent glass (0.85 light / 0.88 dark)
2026-08-11 10:23:33 +08:00
lezi-fun a136d468af fix: show cached forum name at first paint via inline script
Loading screen now always renders the title container; layout.js inline
script fills the cached name on DOMContentLoaded (before React hydrate),
so 2nd+ visits show the forum name immediately instead of waiting for
React to start. Static appear class avoids hydrate clobbering.
2026-08-11 10:18:53 +08:00
lezi-fun bfe8a80822 fix: show cached forum name at first paint via inline script
Loading screen now always renders the title container; layout.js inline
script fills the cached name on DOMContentLoaded (before React hydrate),
so 2nd+ visits show the forum name immediately instead of waiting for
React to start. Static appear class avoids hydrate clobbering.
2026-08-11 10:18:42 +08:00
lezi-fun aeb8adae4c feat: public user profile API + settings swipe navigation
- GET /api/users/profile/:username public endpoint (no auth) for user
  pages, matching upstream main; UserProfile uses it (was admin /users
  search)
- Settings page: vertical scroll-snap panels (profile/security/recovery),
  swipe up/down to switch smoothly; sidebar nav scrolls to panel and
  active highlight follows scroll position
2026-08-11 10:07:30 +08:00
lezi-fun 0b86c54867 feat: public user profile API + settings swipe navigation
- GET /api/users/profile/:username public endpoint (no auth) for user
  pages, matching upstream main; UserProfile uses it (was admin /users
  search)
- Settings page: vertical scroll-snap panels (profile/security/recovery),
  swipe up/down to switch smoothly; sidebar nav scrolls to panel and
  active highlight follows scroll position
2026-08-11 10:07:21 +08:00
lezi-fun 93be3a2880 fix: show cached forum name immediately on reload (no server wait)
- forumNameLoaded initializes true when localStorage has a cached name,
  so 2nd+ visits show the name right away instead of waiting for the
  settings fetch
- layout.js inline script writes cached name to <title> on first paint
  (first request HTML now carries the name)
2026-08-11 10:03:25 +08:00
lezi-fun fe71b03d2e fix: show cached forum name immediately on reload (no server wait)
- forumNameLoaded initializes true when localStorage has a cached name,
  so 2nd+ visits show the name right away instead of waiting for the
  settings fetch
- layout.js inline script writes cached name to <title> on first paint
  (first request HTML now carries the name)
2026-08-11 10:02:03 +08:00
lezi-fun c8a3fcfe3a docs: update Next.js 16 + React 19 in README 2026-08-11 09:51:34 +08:00
lezi-fun c55fce445c docs: update Next.js 16 + React 19 in README 2026-08-11 09:51:22 +08:00
lezi-fun 7966ac0eeb feat: upgrade Next.js 16 + React 19, R2 binding storage, adaptive build
- Next.js 14 → 16.3.0, React 18 → 19.2.8
- Route handlers: async params (await params) for Next 15+ — 17 files
- Fix destructuring params pattern (const {id} = await params) in
  users/[id] and users/[id]/role
- storage.js: prefer Cloudflare R2 binding (FORUMLIFY_BUCKET, no S3
  keys) on Workers; fallback S3-compatible API (Vercel/local)
- wrangler.jsonc: add FORUMLIFY_BUCKET binding to forum bucket
- scripts/build.js: adaptive build (CF env → OpenNext, else next build);
  fix recursion via NEXT_PRIVATE_STANDALONE detection
- 40/40 tests pass on Next 16

# Conflicts:
#	app/api/posts/[id]/route.js
2026-08-11 09:46:51 +08:00
lezi-fun 6d41c6208c feat: upgrade Next.js 16 + React 19, R2 binding storage, adaptive build
- Next.js 14 → 16.3.0, React 18 → 19.2.8
- Route handlers: async params (await params) for Next 15+ — 17 files
- Fix destructuring params pattern (const {id} = await params) in
  users/[id] and users/[id]/role
- storage.js: prefer Cloudflare R2 binding (FORUMLIFY_BUCKET, no S3
  keys) on Workers; fallback S3-compatible API (Vercel/local)
- wrangler.jsonc: add FORUMLIFY_BUCKET binding to forum bucket
- scripts/build.js: adaptive build (CF env → OpenNext, else next build);
  fix recursion via NEXT_PRIVATE_STANDALONE detection
- 40/40 tests pass on Next 16
2026-08-11 09:45:56 +08:00
lezi-fun 3049aa96e4 docs: Cloudflare Workers one-click deploy (OpenNext) in README 2026-08-11 09:27:13 +08:00
lezi-fun 39716b7c8f docs: Cloudflare Workers one-click deploy (OpenNext) in README 2026-08-11 09:27:03 +08:00
lezi-fun dd5372a273 chore: .env is user-local env (gitignored), .env.example is the template 2026-08-11 09:19:26 +08:00
lezi-fun 59227d99a5 chore: .env is user-local env (gitignored), .env.example is the template 2026-08-11 09:19:18 +08:00
lezi-fun a42fe1dd89 feat: Cloudflare Workers deployment (OpenNext adapter)
- Add @opennextjs/cloudflare + wrangler config, open-next.config.ts,
  public/_headers, .dev.vars.example template
- package.json: cf build/preview/deploy/upload scripts
- Verified deployed: https://forumlify.roylikerebecca19930.workers.dev
  (DB read/write via outbound TCP to Postgres, R2 image upload + public
  domain access all working)
2026-08-11 09:18:38 +08:00
lezi-fun 962f7f67c1 feat: Cloudflare Workers deployment (OpenNext adapter)
- Add @opennextjs/cloudflare + wrangler config, open-next.config.ts,
  public/_headers, .dev.vars.example template
- package.json: cf build/preview/deploy/upload scripts
- Verified deployed: https://forumlify.roylikerebecca19930.workers.dev
  (DB read/write via outbound TCP to Postgres, R2 image upload + public
  domain access all working)
2026-08-11 09:18:29 +08:00
lezi-fun 9c4a694394 fix: R2 public URL without bucket prefix (custom domain serves at root)
S3_PUBLIC_URL (custom domain) serves objects at /<name>, not
/<bucket>/<name>. Only include bucket prefix when falling back to the
S3 endpoint path-style URL.
2026-08-11 09:07:19 +08:00
lezi-fun 778c2bcf4c fix: R2 public URL without bucket prefix (custom domain serves at root)
S3_PUBLIC_URL (custom domain) serves objects at /<name>, not
/<bucket>/<name>. Only include bucket prefix when falling back to the
S3 endpoint path-style URL.
2026-08-11 09:06:14 +08:00

2026-08-10

lezi-fun d2f377d380 feat: settings sidebar layout (align upstream) + fix mobile admin bottom bar
- SettingsPage: sidebar layout with 3 tabs (个人资料/安全设置/恢复码),
  extract SettingsProfile component; sync upstream settings CSS
- Fix: .page-slide backdrop-filter created containing block, breaking
  position:fixed children (mobile admin bottom nav floated up on scroll,
  modals mispositioned). Removed it — background is solid gradient
- Add missing user/lock icons
2026-08-10 22:16:57 +08:00
lezi-fun 24379f0ab1 feat: settings sidebar layout (align upstream) + fix mobile admin bottom bar
- SettingsPage: sidebar layout with 3 tabs (个人资料/安全设置/恢复码),
  extract SettingsProfile component; sync upstream settings CSS
- Fix: .page-slide backdrop-filter created containing block, breaking
  position:fixed children (mobile admin bottom nav floated up on scroll,
  modals mispositioned). Removed it — background is solid gradient
- Add missing user/lock icons
2026-08-10 22:15:53 +08:00
Furrium Network bd7899a180 Update dockerfile 2026-08-10 22:11:36 +08:00
lezi-fun 80eb313604 feat: toast notifications, canvas captcha, super admin, mobile fixes
- Toast system (ToastProvider + useToast): right-top colored toasts
  replace alert for publish success/error; CSS + layout mount
- Captcha as canvas image (noise + distortion) in NewPost/ReplyList/
  register modal — blocks bots, click to refresh
- Super admin: first registered user cannot be demoted (isFirstUser by
  created_at, DB-agnostic)
- Admins can delete others' posts/replies (UI buttons shown for admin)
- Mobile: post-actions wrap + compact, feed excerpt 2.5 lines
- Fix: missing sun icon in Icons (dark mode toggle showed nothing)
- Feed long posts: gradient fade mask instead of line-clamp
2026-08-10 21:56:05 +08:00
lezi-fun b2368f68df feat: toast notifications, canvas captcha, super admin, mobile fixes
- Toast system (ToastProvider + useToast): right-top colored toasts
  replace alert for publish success/error; CSS + layout mount
- Captcha as canvas image (noise + distortion) in NewPost/ReplyList/
  register modal — blocks bots, click to refresh
- Super admin: first registered user cannot be demoted (isFirstUser by
  created_at, DB-agnostic)
- Admins can delete others' posts/replies (UI buttons shown for admin)
- Mobile: post-actions wrap + compact, feed excerpt 2.5 lines
- Fix: missing sun icon in Icons (dark mode toggle showed nothing)
- Feed long posts: gradient fade mask instead of line-clamp
2026-08-10 21:54:28 +08:00
lezi-fun c059ad0979 style: sync admin table full-width styles from upstream 2026-08-10 21:26:46 +08:00
lezi-fun e860978aef style: sync admin table full-width styles from upstream 2026-08-10 21:25:30 +08:00
lezi-fun 83d270eada feat: theme follows system preference by default + fix dark mode FOUC
- getTheme: manual localStorage override first, else prefers-color-scheme
- layout: inline head script sets data-theme before first paint (no
  white flash in dark mode on loading screen)
- AppProvider: listen for system theme change when user hasn't overridden
2026-08-10 18:27:17 +08:00
lezi-fun e3afba65fa feat: theme follows system preference by default + fix dark mode FOUC
- getTheme: manual localStorage override first, else prefers-color-scheme
- layout: inline head script sets data-theme before first paint (no
  white flash in dark mode on loading screen)
- AppProvider: listen for system theme change when user hasn't overridden
2026-08-10 18:25:44 +08:00
lezi-fun 156e178160 feat: markdown rendering + dark mode input fixes + DM icon align
- Add marked dependency; render post/reply content and signature via
  marked.parse (matches upstream). lib/markdown.js helper + CSS for
  code/pre/blockquote/tables in glass theme
- Fix hardcoded #e2e8f0 white inputs in dark mode: NewPost title/content,
  Modals report select, ReplyList, AdminForumSettings/Links/Users/Logs
- DM button: replace ✉️ emoji with upstream SVG chat bubble icon
2026-08-10 18:19:56 +08:00
lezi-fun 1a8a588d60 feat: markdown rendering + dark mode input fixes + DM icon align
- Add marked dependency; render post/reply content and signature via
  marked.parse (matches upstream). lib/markdown.js helper + CSS for
  code/pre/blockquote/tables in glass theme
- Fix hardcoded #e2e8f0 white inputs in dark mode: NewPost title/content,
  Modals report select, ReplyList, AdminForumSettings/Links/Users/Logs
- DM button: replace ✉️ emoji with upstream SVG chat bubble icon
2026-08-10 18:18:19 +08:00
lezi-fun 9eed101caa fix: recovery codes modal not showing (portal to body)
Modal rendered inside SettingsPage .page-slide whose slideIn animation
creates a containing block, so position:fixed modal was positioned
relative to the slide (invisible in some browsers). Render via
createPortal to document.body.
2026-08-10 17:57:58 +08:00
lezi-fun bd6314be38 fix: recovery codes modal not showing (portal to body)
Modal rendered inside SettingsPage .page-slide whose slideIn animation
creates a containing block, so position:fixed modal was positioned
relative to the slide (invisible in some browsers). Render via
createPortal to document.body.
2026-08-10 17:55:30 +08:00
lezi-fun 4a30e79269 feat: edit post images (upload/remove) + fix captcha input in dark mode
- PostDetail edit modal: show existing images with delete button, upload
  new images (multi-file, 5MB limit), save replaces image list
- API PUT /posts/:id accepts images array; omitting keeps original
- lib/api updatePost passes images
- NewPost/ReplyList captcha answer input: use CSS vars (was hardcoded
  #e2e8f0 border with white bg — glaring in dark mode)
2026-08-10 17:41:46 +08:00
lezi-fun f317e5eee6 style: sync upstream liquid glass theme (液态玻璃)
- Adopt upstream style.css glassmorphism: glacier-blue palette,
  --glass-* vars, backdrop-filter blur on navbar/cards/modals, gradient bg
- Keep old CSS variable aliases (--text/--bg/--surface/--border etc)
  mapped to glass colors so React components' inline styles keep working
- Re-append loading-screen / app-fade-in styles removed by upstream sync
2026-08-10 17:18:14 +08:00
lezi-fun ebc5201569 style: sync upstream liquid glass theme (液态玻璃)
- Adopt upstream style.css glassmorphism: glacier-blue palette,
  --glass-* vars, backdrop-filter blur on navbar/cards/modals, gradient bg
- Keep old CSS variable aliases (--text/--bg/--surface/--border etc)
  mapped to glass colors so React components' inline styles keep working
- Re-append loading-screen / app-fade-in styles removed by upstream sync
2026-08-10 17:16:34 +08:00
lezi-fun 68b78c7987 fix: loading page logo/name flash, settings name flash, post card radius
- LoadingScreen: remove 🌊 logo; show forum name only after server
  responds (fades in place), delayed 650ms before switching to home
- AppProvider: new forumNameLoaded flag; title rotation already handled
- settings API: always returns forum_name (inserts default if missing)
- AdminForumSettings: name input starts empty, fills after fetch
- PostDetail: add id=pagePost so #pagePost .post-detail-card styles
  apply (border-radius/shadow were missing)
2026-08-10 17:06:12 +08:00
lezi-fun 34c06c206c fix: loading page logo/name flash, settings name flash, post card radius
- LoadingScreen: remove 🌊 logo; show forum name only after server
  responds (fades in place), delayed 650ms before switching to home
- AppProvider: new forumNameLoaded flag; title rotation already handled
- settings API: always returns forum_name (inserts default if missing)
- AdminForumSettings: name input starts empty, fills after fetch
- PostDetail: add id=pagePost so #pagePost .post-detail-card styles
  apply (border-radius/shadow were missing)
2026-08-10 17:05:23 +08:00
lezi-fun ba65f446ec fix: loading screen shows Forumlify on first visit + rotating tab title
- LoadingScreen: drop forumName title (default name flashed on first
  visit before settings loaded); show 🌊 logo + spinner instead
- AppProvider: during init rotate document.title Loading. → Loading..
  → Loading... every second; after ready show actual forum name
- layout: initial metadata title is 'Loading...' (client takes over)
2026-08-10 16:55:49 +08:00
lezi-fun e79c8530e3 fix: loading screen shows Forumlify on first visit + rotating tab title
- LoadingScreen: drop forumName title (default name flashed on first
  visit before settings loaded); show 🌊 logo + spinner instead
- AppProvider: during init rotate document.title Loading. → Loading..
  → Loading... every second; after ready show actual forum name
- layout: initial metadata title is 'Loading...' (client takes over)
2026-08-10 16:55:38 +08:00
lezi-fun 9880d2b0d0 fix: browser tab title not updating after forum rename on reload
document.title was only set inside updateForumName (the rename action).
On page reload the cached/loaded forumName never synced to the title, so
the tab stayed 'Forumlify' (server-rendered). Add a useEffect on
forumName that syncs document.title + <title> element, covering init,
DB load and rename paths.
2026-08-10 16:47:30 +08:00
lezi-fun ae8299820f feat: full-screen loading page with fade-in on init complete
- AppProvider: add 'ready' flag set after init (auth restore + settings)
- page.js: show LoadingScreen (spinner + forum name) until ready, then
  fade in main UI (.app-fade-in 0.4s) — no more unloaded UI flash
2026-08-10 16:44:21 +08:00
lezi-fun e50bb2ff3d feat: full-screen loading page with fade-in on init complete
- AppProvider: add 'ready' flag set after init (auth restore + settings)
- page.js: show LoadingScreen (spinner + forum name) until ready, then
  fade in main UI (.app-fade-in 0.4s) — no more unloaded UI flash
2026-08-10 16:43:56 +08:00
lezi-fun 599b6f3435 fix: post/reply avatars not updating after avatar change
Feed, PostDetail and ReplyList rendered ui-avatars fallback from
username only, ignoring avatar_url from the posts/replies API. Now
use p.avatar_url / r.avatar_url when present.
2026-08-10 15:23:05 +08:00
lezi-fun 4d4c227f58 docs: deploy button → dedicated template repo (forumlify-deploy)
Separate one-click deploy template repo with next as default branch,
so Vercel imports the Next.js version without branch selection.

# Conflicts:
#	README.md
2026-08-10 15:20:01 +08:00
lezi-fun d5e56c0a20 docs: deploy button → dedicated template repo (forumlify-deploy)
Separate one-click deploy template repo with next as default branch,
so Vercel imports the Next.js version without branch selection.
2026-08-10 15:13:09 +08:00
lezi-fun 9ffafc73b3 docs: point deploy button to fork with next as default branch
Vercel one-click deploy imports the repo's default branch with no way
to select a branch, so point the button at lezi-fun/forumlify whose
default branch is now 'next' (Next.js version).
2026-08-10 15:10:25 +08:00
lezi-fun 35a3fe0e8f docs: one-click Vercel deploy badge + clear env var table
- Add Deploy with Vercel button (auto-fills env var prompts)
- Environment variable reference table (required vs optional, with examples)
- Cloudflare Pages: explicit build settings and env config steps
2026-08-10 15:05:44 +08:00
lezi-fun b1dd75312f docs: one-click Vercel deploy badge + clear env var table
- Add Deploy with Vercel button (auto-fills env var prompts)
- Environment variable reference table (required vs optional, with examples)
- Cloudflare Pages: explicit build settings and env config steps
2026-08-10 15:05:19 +08:00
lezi-fun 3d2886ec07 sync upstream: sidebar admin layout, latest styles, clean install
- README: clone -b next for the Next.js branch (was cloning Express main)
- AdminPage: sidebar layout matching upstream main (admin-layout/sidebar/nav)
- globals.css: sync latest upstream style.css (1200 lines)
- Remove broken lockfiles (package-lock.json, bun.lock) that caused
  'Failed to patch lockfile' build warnings; clean npm/bun install verified
2026-08-10 14:56:38 +08:00
lezi-fun 3a9e2ec297 sync upstream: sidebar admin layout, latest styles, clean install
- README: clone -b next for the Next.js branch (was cloning Express main)
- AdminPage: sidebar layout matching upstream main (admin-layout/sidebar/nav)
- globals.css: sync latest upstream style.css (1200 lines)
- Remove broken lockfiles (package-lock.json, bun.lock) that caused
  'Failed to patch lockfile' build warnings; clean npm/bun install verified
2026-08-10 14:56:29 +08:00
lezi-fun 694fa2bfaf feat: user signature (设置页编辑 + 帖子底部显示)
- schema: users.signature column (upstream aligned)
- API: posts query JOIN signature, /auth/me returns signature, PUT /users/:id updates signature
- Settings: signature textarea (Markdown hint), saved with profile
- PostDetail: signature shown under post content with divider
- README: remove upstream DB schema note (fixed upstream)
2026-08-10 14:46:05 +08:00
lezi-fun 581925ad7d feat: user signature (设置页编辑 + 帖子底部显示)
- schema: users.signature column (upstream aligned)
- API: posts query JOIN signature, /auth/me returns signature, PUT /users/:id updates signature
- Settings: signature textarea (Markdown hint), saved with profile
- PostDetail: signature shown under post content with divider
- README: remove upstream DB schema note (fixed upstream)
2026-08-10 14:45:50 +08:00
lezi-fun c8dcf32dd4 fix: dropdown menu not opening on avatar click
React synthetic event stopPropagation doesn't stop native document
listeners (React 17+ attaches to root, document listener is separate).
The document click handler was closing the menu right after avatar
opened it. Now it checks if the click target is inside the dropdown
or on the avatar and skips closing.
2026-08-10 14:38:45 +08:00
lezi-fun c171efc1ec fix: dropdown menu not opening on avatar click
React synthetic event stopPropagation doesn't stop native document
listeners (React 17+ attaches to root, document listener is separate).
The document click handler was closing the menu right after avatar
opened it. Now it checks if the click target is inside the dropdown
or on the avatar and skips closing.
2026-08-10 14:38:30 +08:00
lezi-fun 89987c430c fix: post detail client error (hooks order), image viewer, messages vs DM split
- Fix critical bug: useState declared after conditional return in PostDetail
  caused 'Rendered more hooks than during previous render' client error
- Add image viewer (click post image to zoom, matching upstream openImageViewer)
- CSS upload warning confirm modal (matching upstream)
- Fix: navbar 消息 menu item now opens notifications page (messages), not DM
  list — DM stays on the ✉️ nav button (matches upstream structure)
2026-08-10 14:18:39 +08:00
lezi-fun 2a508d1b21 fix: post detail client error (hooks order), image viewer, messages vs DM split
- Fix critical bug: useState declared after conditional return in PostDetail
  caused 'Rendered more hooks than during previous render' client error
- Add image viewer (click post image to zoom, matching upstream openImageViewer)
- CSS upload warning confirm modal (matching upstream)
- Fix: navbar 消息 menu item now opens notifications page (messages), not DM
  list — DM stays on the ✉️ nav button (matches upstream structure)
2026-08-10 14:18:29 +08:00
lezi-fun 48372aa14f feat: align with upstream — pin posts, edit marker, custom CSS, UX fixes
- Pin/unpin posts (PUT /api/posts/:id/pin, admin) with notification to author
- is_pinned/pinned_at in schema; 📌 badge on feed + detail; admin pin button
- Edited marker (已编辑) on feed + detail; edit button + modal for authors
- Custom CSS: upload/delete API + admin tab + global loader (style.css override)
- Fix: duplicate post title on detail page (remove card title, keep header)
- Fix: forum name flicker on load (localStorage cache before fetch)
- Fix: dropdown menu closes on outside click (document listener)
- Fix: document.title + <title> sync on forum rename
2026-08-10 12:35:50 +08:00
lezi-fun 4ee38f6486 feat: align with upstream — pin posts, edit marker, custom CSS, UX fixes
- Pin/unpin posts (PUT /api/posts/:id/pin, admin) with notification to author
- is_pinned/pinned_at in schema; 📌 badge on feed + detail; admin pin button
- Edited marker (已编辑) on feed + detail; edit button + modal for authors
- Custom CSS: upload/delete API + admin tab + global loader (style.css override)
- Fix: duplicate post title on detail page (remove card title, keep header)
- Fix: forum name flicker on load (localStorage cache before fetch)
- Fix: dropdown menu closes on outside click (document listener)
- Fix: document.title + <title> sync on forum rename
2026-08-10 12:32:06 +08:00
lezi-fun 721e4bfe42 fix: 405 on write methods in Vercel (static GET optimization)
Route handlers with both GET and write methods get the GET statically
optimized on Vercel, which 405s POST/PUT/DELETE. Add
export const dynamic = 'force-dynamic' to all 7 affected routes
(settings, posts, custom-pages, event-logs, links, conversations, reports).
2026-08-10 11:08:10 +08:00
lezi-fun 7ce81969ac fix: 405 on write methods in Vercel (static GET optimization)
Route handlers with both GET and write methods get the GET statically
optimized on Vercel, which 405s POST/PUT/DELETE. Add
export const dynamic = 'force-dynamic' to all 7 affected routes
(settings, posts, custom-pages, event-logs, links, conversations, reports).
2026-08-10 11:02:11 +08:00
Furrium Network 8ee6cc07c9 Merge pull request #5 from lezi-fun/serverless-support
feat: support serverless deployment (Vercel / Cloudflare Pages)
2026-08-10 10:47:00 +08:00
lezi-fun d1c06741f6 fix: uploads route ignored by .gitignore, image 404s
.gitignore 'uploads/' pattern matched app/api/uploads/ too, so the
image-serving route handler was never committed. Anchor it to /uploads/
so only the runtime storage dir is ignored. Also add vercel.json.
2026-08-10 10:45:25 +08:00
lezi-fun ac6e2dab84 fix: chat input hidden on small viewports
- Chat modal fixed height 70vh, message list flex:1 with minHeight:0
- Input row flexShrink:0 so it's never compressed out of view
2026-08-10 10:38:30 +08:00
lezi-fun 5d90e5c415 fix: hide DM button when logged out 2026-08-10 10:21:26 +08:00
lezi-fun 1486d95f89 fix: no-cache HTML headers (dynamic forum content)
Next.js default s-maxage=31536000 caches HTML for a year at CDN level,
serving stale pages after deploys. Add Cache-Control: no-store for all
routes so CDN/browser always fetch fresh.
2026-08-10 10:15:16 +08:00
lezi-fun 60c21ae0a6 fix: navbar full-width layout
- Remove flex wrapper around Navbar that collapsed it to content width
- Move DM button inside Navbar nav-right, ChatManager renders modals only
- Navbar is a direct body child again, sticky + full width restored
2026-08-10 10:11:32 +08:00
lezi-fun ec50efea89 feat: support serverless deployment (Vercel / Cloudflare Pages)
- Replace bcrypt (native) with bcryptjs (pure JS) — no native build on serverless
- Storage abstraction (lib/storage.js): local uploads/ for traditional deploy, S3-compatible (R2/MinIO/S3 via aws4fetch) for serverless
- DB pool auto-adapts to serverless (single connection, rotation, timeouts)
- next.config.js: standalone output only when DOCKER=1 (serverless skips it)
- Docs: serverless deployment section in README, S3 env vars in .env.example
2026-08-10 09:55:18 +08:00
Furrium Network 83239d498e huh
feat: migrate to Next.js 14 (App Router + Route Handlers)
2026-08-10 09:40:41 +08:00
lezi-fun 95b0d63223 Merge remote-tracking branch 'origin/main' into nextjs-migration 2026-08-10 09:08:30 +08:00
lezi-fun 4732e7d61d feat: port upstream custom pages, notifications, recovery codes, account security
- schema: custom_pages, notifications, recovery_codes tables + UNIQUE(conversations) + posts.edited_at
- API: custom-pages CRUD (public + admin), notifications (list/read/read-all), recovery-codes (generate/count/reset-password), user avatar/password/email, post edit
- UI: custom page nav links + iframe rendering, admin custom pages tab with editor modal, messages page shows notifications, settings page gains avatar upload, password/email change, recovery codes manager
- Sync globals.css with upstream rewrite
2026-08-10 09:07:06 +08:00

2026-08-09

lezi-fun 9e72e4de8e chore: allow .env in repo, add .env.example template
- .gitignore: track .env, still ignore local overrides (.env.local)
- Add .env.example with DATABASE_URL / JWT_SECRET / PORT / HOST
2026-08-09 21:26:29 +08:00
lezi-fun 7d431a89a7 test: add API integration test suite (40 tests)
- node:test based, zero extra dependencies, npm test script
- api.test.js: auth, posts, pagination, replies, 404/401 handling
- admin.test.js: admin API, role management, settings, links, logs
- dm.test.js: private messaging, unread counts, read receipts, 403
- helpers.js: makeAdmin() to guarantee admin role in shared DB
- test/README.md: setup and run instructions
2026-08-09 21:26:03 +08:00
lezi-fun 02ac24ba88 feat: port pagination and drag-drop upload from upstream
- GET /api/posts now supports page/limit, returns {data, pagination}
- Feed: pagination controls (‹ page numbers ›), reset to page 1 on sort change
- NewPost: dashed drop zone with click/drag-drop image upload, 5MB limit
- UserProfile adapts to paginated response
2026-08-09 21:14:18 +08:00
lezi-fun 96c3ac3bb9 Merge remote-tracking branch 'origin/main' into nextjs-migration 2026-08-09 21:03:38 +08:00
lezi-fun 300ad5959c feat: port private messaging (私信) from upstream
- Add conversations/messages tables to schema.sql (upstream missed them)
- API: GET/POST /api/conversations, GET/POST /api/conversations/[id]/messages, PUT /api/messages/[id]/read
- Chat UI: conversation list modal, chat window with 3s polling, unread badge
- Navbar message entry opens DM list; user profile has 发私信 button
- Access control: only conversation participants (403 otherwise)
2026-08-09 21:01:55 +08:00
lezi-fun 5ef8d4b1ff feat: port user profile feature from upstream
- GET /api/users?username= filter (admin)
- GET /api/posts?user_id= filter
- Add UserProfile page (profile card + user's posts), reachable via ?user=<username>
- Clickable usernames on feed, post detail, replies
2026-08-09 18:30:49 +08:00
lezi-fun e6ba5507ae Merge remote-tracking branch 'origin/main' into nextjs-migration 2026-08-09 18:24:37 +08:00
lezi-fun e16887a4b3 chore: remove orphaned js/ modules from reverted upstream split 2026-08-09 18:17:53 +08:00
lezi-fun 70a198ae32 fix: restore original Feather icons across UI
- Add components/Icons.js with SVG paths extracted verbatim from the original index.html (14 unique icons)
- Restore icons on navbar menu, sidebar, feed actions, post/reply, modals, admin tabs and settings
- Replaces emoji placeholders from the initial migration
2026-08-09 18:12:46 +08:00
lezi-fun 3e9d004fb6 Merge remote-tracking branch 'origin/main' into nextjs-migration 2026-08-09 17:15:57 +08:00
lezi-fun 94cb0f50be docs: preserve upstream attribution note in README 2026-08-09 17:03:00 +08:00
lezi-fun 281460fb03 feat: migrate to Next.js 14 (App Router + Route Handlers)
- Replace Express server with Next.js Route Handlers (16 API routes)
- Rewrite index.html SPA as React components (feed, post, admin, modals)
- Move style.css to app/globals.css with dark/light themes intact
- Add lib/db.js, lib/auth.js (JWT), lib/api.js (client API wrapper)
- Server binds 0.0.0.0 by default; host/port configurable via config.js
- Uploads served via /api/uploads route (rewrite keeps /uploads/ URLs)
- Multi-stage dockerfile using standalone output
2026-08-09 17:02:11 +08:00
157 changed files with 19584 additions and 8894 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
NEXTJS_ENV=development
+13
View File
@@ -0,0 +1,13 @@
# Cloudflare Workers 环境变量示例
# 复制为 .dev.vars 用于本地 preview;远程部署请在 CF 面板配置为 Secrets
DATABASE_URL=postgresql://user:pass@host:5432/forumlify
JWT_SECRET=change-me-in-production
# 图片上传(S3 兼容,R2)
S3_ENDPOINT=https://<account_id>.r2.cloudflarestorage.com
S3_BUCKET=forum
S3_REGION=auto
S3_ACCESS_KEY_ID=your-r2-access-key
S3_SECRET_ACCESS_KEY=your-r2-secret-key
S3_PUBLIC_URL=https://your-public-domain.example
+7 -8
View File
@@ -1,10 +1,9 @@
.git
.github
.env
.env.*
!.env.example
node_modules node_modules
npm-debug.log* .next
uploads uploads
coverage .git
*.md *.log
.DS_Store
.vercel
.wrangler
.open-next
+20 -4
View File
@@ -1,4 +1,20 @@
# Copy to .env, then set both required secrets before running Docker Compose. # Forumlify 环境变量示例
POSTGRES_PASSWORD= # 复制为 .env 并按需修改
JWT_SECRET=
PORT=3000 # PostgreSQL 连接串(默认与 docker-compose.yml 一致)
DATABASE_URL=postgresql://forumlify:123456@localhost:5432/forumlify
# JWT 签名密钥(生产环境务必修改为随机长字符串)
JWT_SECRET=forumlify-secret-key-change-me-in-production
# 可选:监听端口/地址(也可在 config.js 中设置 SERVER_PORT / SERVER_HOST)
# PORT=3000
# HOST=0.0.0.0
# ===== Serverless / 对象存储(可选,仅 serverless 部署需要)=====
# S3_ENDPOINT=https://xxx.r2.cloudflarestorage.com
# S3_BUCKET=forumlify
# S3_REGION=auto
# S3_ACCESS_KEY_ID=
# S3_SECRET_ACCESS_KEY=
# S3_PUBLIC_URL=https://cdn.example.com
-90
View File
@@ -1,90 +0,0 @@
name: 🐛 Bug 报告 / Bug Report
description: 报告一个 Bug / Report a bug
title: "[Bug] "
labels: [bug]
body:
- type: markdown
attributes:
value: |
## 感谢你报告问题!/ Thanks for reporting an issue!
请填写以下信息,帮助我们快速定位问题。/ Please fill in the following information to help us locate the issue quickly.
- type: dropdown
id: branch
attributes:
label: 你使用的是哪个分支?/ Which branch are you using?
description: 请选择你所使用的分支。/ Please select the branch you are using.
options:
- Lite(原生单文件版 / Original single-file version)
- next(Next.js 16 版 / Next.js 16 version)
validations:
required: true
- type: input
id: version
attributes:
label: 后台版本号 / Backend version (管理员填写 / admins only)
description: |
如果你使用的是 next 分支且是管理员,请粘贴后台显示的版本号。其他情况请留空。
/ If you are using the next branch and are an administrator, please paste the version shown in the admin panel. Leave blank otherwise.
placeholder: "例如 / e.g. 2.0.0"
validations:
required: false
- type: textarea
id: description
attributes:
label: 问题描述 / Description
description: 请清晰描述你遇到的问题。/ Please clearly describe the issue you encountered.
validations:
required: true
- type: textarea
id: steps
attributes:
label: 复现步骤 / Steps to reproduce
description: 如何复现这个问题?/ How can this issue be reproduced?
placeholder: |
1. 打开... / Open ...
2. 点击... / Click ...
3. 看到错误... / See the error...
validations:
required: true
- type: textarea
id: expected
attributes:
label: 期望行为 / Expected behavior
description: 你期望发生什么?/ What did you expect to happen?
validations:
required: true
- type: textarea
id: actual
attributes:
label: 实际行为 / Actual behavior
description: 实际发生了什么?/ What actually happened?
validations:
required: true
- type: textarea
id: environment
attributes:
label: 环境信息 / Environment
description: 你的运行环境。/ Your running environment.
placeholder: |
- 操作系统 / OS:
- 浏览器 / Browser:
- Node.js 版本 / Node.js version:
- 部署方式 / Deployment method (Docker / 源码 / Source):
validations:
required: false
- type: textarea
id: logs
attributes:
label: 日志 / Logs
description: 如有报错日志,请粘贴于此。/ Paste any error logs here if available.
render: shell
validations:
required: false
-1
View File
@@ -1 +0,0 @@
blank_issues_enabled: false
@@ -1,65 +0,0 @@
name: ✨ 功能建议 / Feature Request
description: 提出一个新功能或改进建议 / Suggest an idea for this project
title: "[Feature] "
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
## 感谢你的建议!/ Thanks for your suggestion!
请填写以下信息,让我们了解你的想法。/ Please fill in the information below to help us understand your idea.
- type: dropdown
id: branch
attributes:
label: 这个功能针对哪个分支?/ Which branch is this feature for?
description: 请选择你所使用的分支。/ Please select the branch you are using.
options:
- Lite(原生单文件版 / Original single-file version)
- next(Next.js 16 版 / Next.js 16 version)
validations:
required: true
- type: input
id: version
attributes:
label: 后台版本号 / Backend version (管理员填写 / admins only)
description: |
如果你使用的是 next 分支且是管理员,请粘贴后台显示的版本号。其他情况请留空。
/ If you are using the next branch and are an administrator, please paste the version shown in the admin panel. Leave blank otherwise.
placeholder: "例如 / e.g. 2.0.0"
validations:
required: false
- type: textarea
id: problem
attributes:
label: 要解决的问题 / Problem to solve
description: 这个功能解决什么问题?/ What problem does this feature solve?
placeholder: "当我...时,我希望... / When I ..., I wish ..."
validations:
required: true
- type: textarea
id: solution
attributes:
label: 期望的解决方案 / Proposed solution
description: 你希望如何实现?/ How would you like it to work?
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: 替代方案 / Alternatives considered
description: 你考虑过其他方案吗?/ Have you considered any alternative approaches?
validations:
required: false
- type: textarea
id: additional
attributes:
label: 补充说明 / Additional context
description: 其他任何信息、截图或示例。/ Any other information, screenshots, or examples.
validations:
required: false
-52
View File
@@ -1,52 +0,0 @@
# 感谢你为 Forumlify 提交贡献!/ Thank you for contributing to Forumlify!
<!-- 请填写以下信息,帮助我们快速处理你的 PR。/ Please fill in the information below to help us process your PR quickly. -->
## 目标分支 / Target branch
**你提交的代码是基于哪个分支?/ Which branch is your code based on?**
- [ ] **Lite**(原生单文件版 / Original single-file version)
- [ ] **next**(Next.js 16 版 / Next.js 16 version)
> ⚠️ 请确保 PR 的 base 分支与你的代码来源分支一致。/ Please make sure the PR's base branch matches the branch your code comes from.
## 版本信息 / Version info
<!-- 仅当你选择 next 分支且为管理员时填写。/ Only fill in if you chose the next branch AND you are an administrator. -->
**后台版本号 / Backend version (admin only):**
```
(在此粘贴后台显示的版本号 / Paste the version shown in the admin panel here)
```
## 变更内容 / What does this PR do?
<!-- 简要描述你的改动。/ Briefly describe your changes. -->
-
## 动机 / Motivation
<!-- 为什么需要这个改动?/ Why is this change needed? -->
-
## 测试 / Testing
<!-- 你如何验证这些改动?/ How did you verify these changes? -->
- [ ] 本地构建通过 / Local build passes (`npm run build`,仅 next 分支 / next branch only)
- [ ] 相关功能已手动测试 / Related features manually tested
- [ ] 测试用例已更新 / Tests updated
## 截图 / Screenshots
<!-- 如有 UI 改动,请附截图。/ Attach screenshots if this changes the UI. -->
## 检查清单 / Checklist
- [ ] 我已阅读并遵循了贡献指南 / I have read and followed the contributing guidelines
- [ ] 我的代码遵循现有代码风格 / My code follows the existing code style
- [ ] 我已同步最新的上游分支 / I have synced with the latest upstream branch
- [ ] 本 PR 只包含必要的改动 / This PR contains only the necessary changes
+131
View File
@@ -0,0 +1,131 @@
name: Coverage
on:
push:
branches: [next]
pull_request:
branches: [next]
permissions:
contents: read
id-token: write
jobs:
test-and-upload:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15
env:
POSTGRES_USER: forumlify
POSTGRES_PASSWORD: 123456
POSTGRES_DB: forumlify
ports:
- 5433:5432
options: >-
--health-cmd "pg_isready -U forumlify -d forumlify"
--health-interval 10s
--health-timeout 5s
--health-retries 5
env:
DATABASE_URL: postgresql://forumlify:123456@localhost:5433/forumlify
JWT_SECRET: ci-test-secret
ENABLE_CAPTCHA: 'false'
PORT: 3100
BASE_URL: http://127.0.0.1:3100
NEXT_TELEMETRY_DISABLED: '1'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- uses: oven-sh/setup-bun@v2
- name: Install dependencies
run: npm ci
- name: Initialize test database
env:
PGPASSWORD: '123456'
run: psql -h localhost -p 5433 -U forumlify -d forumlify -f schema.sql
- name: Build application
run: npm run build
- name: Upload bundle analysis to Codecov
env:
CODECOV_BUNDLE_ANALYSIS: 'true'
run: npx next build --webpack
- name: Run integration tests with coverage
run: |
node node_modules/next/dist/bin/next start -H 127.0.0.1 -p "$PORT" > server.log 2>&1 &
server_pid=$!
cleanup() {
kill "$server_pid" 2>/dev/null || true
wait "$server_pid" 2>/dev/null || true
}
trap cleanup EXIT
for attempt in {1..30}; do
if curl --fail --silent --show-error "$BASE_URL/api/stats" >/dev/null; then
break
fi
if [ "$attempt" -eq 30 ]; then
cat server.log
exit 1
fi
sleep 1
done
node --test \
--test-concurrency=1 \
--test-reporter=spec \
--test-reporter=junit \
--test-reporter-destination=stdout \
--test-reporter-destination=test-results.xml \
test/*.test.js
cleanup
trap - EXIT
mkdir -p coverage
node --test \
--experimental-test-coverage \
--test-reporter=lcov \
--test-reporter-destination=coverage/lcov.info \
test/http-cache.test.js \
test/i18n-ui.test.js
test -s coverage/lcov.info
covered_lines=$(awk -F: '/^DA:/{split($2, data, ","); hits += data[2]} END {print hits + 0}' coverage/lcov.info)
test "$covered_lines" -gt 0
test -s test-results.xml
- name: Publish coverage report
uses: actions/upload-artifact@v4
with:
name: coverage-report
path: coverage/
if-no-files-found: error
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v5
with:
use_oidc: true
files: coverage/lcov.info
disable_search: true
fail_ci_if_error: true
verbose: true
- name: Upload test results to Codecov
uses: codecov/codecov-action@v5
with:
use_oidc: true
files: test-results.xml
report_type: test_results
disable_search: true
fail_ci_if_error: true
@@ -1,15 +1,13 @@
name: Build & Push Docker to GHCR (Lite) name: Build & Push Docker to GHCR
on: on:
push: push:
branches: [Lite] branches: [next, main]
tags: ['v*'] tags: ['v*']
workflow_dispatch: workflow_dispatch:
env: env:
REGISTRY: ghcr.io REGISTRY: ghcr.io
# 推仓库自己的 GHCR 包(github.repository = Furrium/forumlify)——
# 仓库 GITHUB_TOKEN 无权推跨仓库包(如 lezi-fun/forumlify-deploy)
IMAGE_NAME: ${{ github.repository }} IMAGE_NAME: ${{ github.repository }}
jobs: jobs:
@@ -38,9 +36,9 @@ jobs:
with: with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: | tags: |
# Lite 分支 → lite 标签(与 next 镜像隔离,避免覆盖) type=ref,event=branch
type=raw,value=lite,enable=${{ github.ref == 'refs/heads/Lite' }}
type=semver,pattern={{version}} type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha,prefix=git- type=sha,prefix=git-
- name: Build and push (linux/amd64 + linux/arm64) - name: Build and push (linux/amd64 + linux/arm64)
-83
View File
@@ -1,83 +0,0 @@
name: ghbot
on:
pull_request_target:
types:
- opened
- synchronize
- reopened
- ready_for_review
- edited
issues:
types:
- opened
- edited
- reopened
issue_comment:
types:
- created
pull_request_review:
types:
- submitted
permissions:
contents: write
pull-requests: write
checks: write
statuses: read
issues: write
jobs:
review:
if: |
github.event_name == 'pull_request_target' ||
github.event_name == 'issues' ||
(github.event_name == 'issue_comment' && github.event.issue.pull_request != null) ||
github.event_name == 'pull_request_review'
uses: lezi-fun/ghbot/.github/workflows/review-reusable.yml@main
secrets:
GOOSE_API_KEY: ${{ secrets.GOOSE_API_KEY || secrets.OPENCODE_API_KEY }}
GH_APP_ID: ${{ secrets.GH_APP_ID }}
GH_APP_PRIVATE_KEY: ${{ secrets.GH_APP_PRIVATE_KEY }}
GH_APP_INSTALLATION_ID: ${{ secrets.GH_APP_INSTALLATION_ID }}
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
with:
event_name: ${{ github.event_name }}
event_action: ${{ github.event.action }}
repository_owner: ${{ github.repository_owner }}
repository_name: ${{ github.event.repository.name }}
repository_id: ${{ github.repository_id }}
pull_number: ${{ github.event.pull_request.number || github.event.issue.number }}
pull_head_repository: ${{ github.event.pull_request.head.repo.full_name || '' }}
comment_id: ${{ github.event.comment.id || '' }}
commenter_login: ${{ github.event.comment.user.login || '' }}
comment_body: ${{ github.event.comment.body || '' }}
reviewer_login: ${{ github.event.review.user.login || '' }}
review_state: ${{ github.event.review.state || '' }}
review_commit_id: ${{ github.event.review.commit_id || '' }}
bot_name: ${{ vars.BOT_NAME || 'github-actions[bot]' }}
goose_base_url: ${{ vars.GOOSE_BASE_URL || vars.OPENCODE_BASE_URL || 'https://api.openai.com/v1' }}
goose_model: ${{ vars.GOOSE_MODEL || vars.OPENCODE_MODEL || 'gpt-5.4' }}
goose_thinking_effort: ${{ vars.GOOSE_THINKING_EFFORT || vars.OPENCODE_REASONING_EFFORT || 'high' }}
review_policy: ${{ vars.REVIEW_POLICY || 'allow' }}
review_strictness: ${{ vars.REVIEW_STRICTNESS || 'normal' }}
review_instructions: ${{ vars.REVIEW_INSTRUCTIONS || '' }}
review_branches: ${{ vars.REVIEW_BRANCHES || '' }}
repository_knowledge_enabled: ${{ vars.REPOSITORY_KNOWLEDGE_ENABLED || 'true' }}
repository_knowledge_write: ${{ vars.REPOSITORY_KNOWLEDGE_WRITE || 'false' }}
r2_endpoint: ${{ vars.R2_ENDPOINT || '' }}
r2_bucket_name: ${{ vars.R2_BUCKET_NAME || '' }}
r2_prefix: ${{ vars.R2_PREFIX || '' }}
triage_enabled: ${{ vars.TRIAGE_ENABLED || 'true' }}
triage_labels: ${{ vars.TRIAGE_LABELS || 'bug,enhancement,documentation,question' }}
triage_duplicate_label: ${{ vars.TRIAGE_DUPLICATE_LABEL || 'duplicate' }}
triage_candidate_limit: ${{ vars.TRIAGE_CANDIDATE_LIMIT || '50' }}
triage_instructions: ${{ vars.TRIAGE_INSTRUCTIONS || '' }}
auto_merge: ${{ vars.AUTO_MERGE || 'false' }}
auto_resolve_conflicts: ${{ vars.AUTO_RESOLVE_CONFLICTS || 'false' }}
conflict_test_command: ${{ vars.CONFLICT_TEST_COMMAND || '' }}
merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }}
max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }}
log_level: info
+22 -13
View File
@@ -1,15 +1,24 @@
node_modules/ node_modules/
uploads/
*.log
.DS_Store
.env
# Wrangler 本地状态
.wrangler/
# 构建产物
.open-next/
.vercel/
.next/ .next/
.wrangler/ out/
/uploads/
*.log
coverage/
.coverage-tmp/
test-results.xml
.DS_Store
# 环境变量:.env 是用户本地环境变量(不提交),模板 .env.example 进仓库
.env
.env.*
!.env.example
.vercel
# OpenNext
.open-next
# wrangler files
.wrangler
.dev.vars*
!.dev.vars.example
+74
View File
@@ -0,0 +1,74 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
# Forumlify repository guide
## Project scope
- This repository is the Forumlify NEXT edition: Next.js 16 App Router, React 19, PostgreSQL, and JavaScript.
- Normal development happens on the `next` branch and is pushed to `origin/next`. The `main` branch is the separate Lite/Express implementation; do not copy behavior from it blindly.
- Before changing code, run `git status --short --branch`. Preserve unrelated user changes and untracked files.
- Do not commit generated or local artifacts such as `.next/`, `.playwright-cli/`, uploaded files, logs, database data, or secrets.
## Commands and runtime
- Requires Node.js 20.9 or newer.
- Install dependencies with `npm install`.
- Start local development with `npm run dev`; it listens on `0.0.0.0` and normally uses port 3000.
- Create a production build with `npm run build`.
- Start a built server with `npm start`.
- Run tests with `npm test`. The test suite expects a running Forumlify instance and PostgreSQL; see `test/README.md`. Override the service URL with `BASE_URL` when needed.
- Always provide `DATABASE_URL` explicitly when the active PostgreSQL instance is not the default `localhost:5432/forumlify`. Inspect existing Docker containers before creating another database or changing ports.
- Never delete or recreate a database, volume, or upload directory merely to make a test pass.
## 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/: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.
- `locales/zh.json` and `locales/en.json` are the translation sources. User-facing text added or changed in an i18n-enabled area must be updated in both files.
- `lib/api.js` is the browser API wrapper, `lib/db.js` owns the PostgreSQL pool, and `lib/http-cache.js` provides ETag/304 helpers for cacheable JSON responses.
- `schema.sql` is shared with the Lite branch. Keep schema changes backward-compatible unless a migration and compatibility plan is explicitly requested.
## UI and interaction conventions
- Support both light and dark themes. Verify page backgrounds, cards, modals, settings/admin pages, borders, and text contrast in both modes.
- Do not use browser `alert`, `confirm`, or `prompt`. Use `useToast()` for timed success/warning/error notices and `confirmAction()` for decisions requiring user input.
- Use SVG icons through `components/Icons.js`; do not add emoji as interface icons. The existing empty-message greeting ending in `👋` is an intentional exception and must remain.
- Avoid hard-coded Chinese or English in newly touched UI when a translation key is appropriate. Date formatting must follow the selected language.
- Keep settings and administration layouts responsive: content should use the available right-side width, wrap long text, and must not become wider solely because English is selected.
- Preserve the current navigation bar during page transitions unless a task explicitly requires otherwise.
## View Transition rules
- `components/AppProvider.js` is the single coordination point for cross-page View Transitions. Do not start competing transitions from individual page components.
- Shared elements must exist in both the old and new DOM snapshots and must have exactly one matching `view-transition-name` per snapshot. Apply names only to the clicked card or target element to avoid duplicates.
- When the destination data is asynchronous, pass a preview object so the destination avatar, title, author, content, or other shared element renders in the first transition frame. Replace it with fetched data without remounting the shared element.
- Elements that exist only on the destination should reveal after shared geometry settles. Elements that exist only on the source should disappear before the destination content is revealed.
- Opening and returning animations should be visible inverses. On return, prefer the original `data-post-id` or stored source identity; if the target is unavailable, fall back to a simple fade instead of animating to the wrong element.
- Disable the default `.page-slide` animation on pages using a custom shared transition, otherwise the page will slide a second time after the transition completes.
- Respect `prefers-reduced-motion` and provide an immediate navigation fallback when `document.startViewTransition` is unavailable.
- For animation bugs, inspect intermediate frames and the trajectories of the outer card, lower edge, text, timestamps, badges, and background separately. Do not judge only the first and final screenshots.
## API, caching, and security
- Preserve conditional GET behavior for cacheable endpoints. Use `jsonWithEtag()` from `lib/http-cache.js` where appropriate so matching `If-None-Match` requests return 304 without a response body.
- Do not cache personalized, authenticated, rapidly changing, or mutation responses as public data.
- Never commit real JWT secrets, database credentials, cloud credentials, tokens, private keys, or local `.env` files. Example values belong only in example configuration.
- Validate and sanitize all user-controlled Markdown, uploads, identifiers, and custom content using the existing helpers and route patterns.
## Validation and Git
- For ordinary code changes, run `git diff --check` and `npm run build` at minimum.
- For API changes, run the focused `node:test` coverage and then `npm test` when the required database/service is available.
- For visual or animation changes, use Playwright against the local development server and check both themes and relevant viewport sizes. Keep Playwright artifacts untracked.
- Stage only files belonging to the task. Use concise commit messages that describe the outcome.
- When asked to push, fetch first if the remote has moved, rebase the scoped commit onto the latest `origin/next`, resolve conflicts without discarding remote work, and never force-push unless the user explicitly authorizes it.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
-19
View File
@@ -1,19 +0,0 @@
FROM node:22.23.2-bookworm-slim
ENV NODE_ENV=production
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --chown=node:node . .
RUN mkdir -p /app/uploads && chown node:node /app/uploads
RUN chmod +x /app/scripts/docker-entrypoint.sh
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD ["node", "scripts/healthcheck.js"]
ENTRYPOINT ["/app/scripts/docker-entrypoint.sh"]
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2026 Furrium Network Copyright (c) 2026 Furrium Network & lezi-fun
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
+176 -86
View File
@@ -1,13 +1,15 @@
# Forumlify NEXT Edition🌊
[![Codecov](https://codecov.io/gh/forumlify/public/branch/next/graph/badge.svg)](https://app.codecov.io/gh/forumlify/public/tree/next)
# Forumlify LITE Edition 🌊
> 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。 > 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。
官方演示地址:[Forumlify NEXT](https://next.forumlify.org)
## ✨ 特性 ## ✨ 特性
- 🎨 精致简约的界面设计,支持亮色/暗色模式 - 🎨 精致简约的界面设计,支持亮色/暗色模式
- ⚡️ 轻量快速,无需复杂配置 - ⚡️ 基于 Next.js 16 (App Router) + React 19,前后端一体化
- 🔐 自带用户认证(JWT) - 🔐 自带用户认证(JWT)
- 📝 发帖、回复、举报、管理后台 - 📝 发帖、回复、举报、管理后台
- 🐳 Docker 一键部署 - 🐳 Docker 一键部署
@@ -17,15 +19,15 @@
Forumlify 提供了两个不同架构的分支版本,以满足不同部署环境与开发需求的场景: Forumlify 提供了两个不同架构的分支版本,以满足不同部署环境与开发需求的场景:
* **Lite 版 (`lite` 分支)**:轻量单体架构,零构建步骤,资源占用极低,主要由Furrium维护。 * **Lite 版 (`main` 分支)**:轻量单体架构,零构建步骤,资源占用极低,主要由Furrium维护。
* **Next.js 版 (`next` 分支)**:现代全栈架构,组件化开发,支持云原生与 Serverless / 边缘部署,主要由lezi-fun维护。 * **Next.js 版 (`next` 分支)**:现代全栈架构,组件化开发,支持云原生与 Serverless / 边缘部署,主要由lezi-fun维护。
你可以根据以下维度选择最适合你当前需求的版本: 你可以根据以下维度选择最适合你当前需求的版本:
| 对比维度 | Forumlify (Lite 版 / `lite`) | Forumlify-Next (Next.js 版 / `next`) | 选择建议 | | 对比维度 | Forumlify (Lite 版 / `main`) | Forumlify-Next (Next.js 版 / `next`) | 选择建议 |
| :--- | :--- | :--- | :--- | | :--- | :--- | :--- | :--- |
| **上手速度与部署** | **极快**(零编译步骤,直接 `node server.js` 或 Docker 启动) | **中等**(需要经过 `next build` 编译打包,或配置 OpenNext) | 希望 1 分钟快速跑起来选 `lite` | | **上手速度与部署** | **极快**(零编译步骤,直接 `node server.js` 或 Docker 启动) | **中等**(需要经过 `next build` 编译打包,或配置 OpenNext) | 希望 1 分钟快速跑起来选 `main` |
| **VPS 最低配置要求** | **1 核 512MB RAM**(资源占用极低,适合低配小鸡) | **1 核 1GB RAM+**(主要在打包构建时需要较多内存) | 内存有限或低配 VPS 推荐 `lite` | | **VPS 最低配置要求** | **1 核 512MB RAM**(资源占用极低,适合低配小鸡) | **1 核 1GB RAM+**(主要在打包构建时需要较多内存) | 内存有限或低配 VPS 推荐 `main` |
| **存储扩展性** | 本地磁盘存储(`uploads/` 目录) | 支持 **Cloudflare R2 / S3 兼容对象存储** + 本地回退 | 需要接云存储或海量图片存储选 `next` | | **存储扩展性** | 本地磁盘存储(`uploads/` 目录) | 支持 **Cloudflare R2 / S3 兼容对象存储** + 本地回退 | 需要接云存储或海量图片存储选 `next` |
| **部署环境支持** | 传统 VPS / Docker 容器 | VPS / Docker / **Cloudflare Workers / Vercel** | 需要 Serverless / 边缘部署选 `next` | | **部署环境支持** | 传统 VPS / Docker 容器 | VPS / Docker / **Cloudflare Workers / Vercel** | 需要 Serverless / 边缘部署选 `next` |
| **技术栈与二次开发** | 原生 Vanilla JS + Express,无框架门槛 | React 19 + Next.js 16 + Tailwind,组件化程度高 | 熟悉 React 框架或需要团队协同选 `next` | | **技术栈与二次开发** | 原生 Vanilla JS + Express,无框架门槛 | React 19 + Next.js 16 + Tailwind,组件化程度高 | 熟悉 React 框架或需要团队协同选 `next` |
@@ -36,51 +38,27 @@ Forumlify 提供了两个不同架构的分支版本,以满足不同部署环
### Docker 部署(推荐) ### Docker 部署(推荐)
```
git clone https://github.com/forumlify/public.git
cd forumlify
cp .env.example .env
# 编辑 .env,为 POSTGRES_PASSWORD 和 JWT_SECRET 设置强随机值
docker compose up --build -d
```
旧版 Compose 也可以使用 `docker-compose up -d`。请妥善备份 `.env`;更换
`JWT_SECRET` 会使现有登录令牌失效。
应用默认运行在 `http://localhost:3000`。
容器启动时会自动执行 `migrations/` 中尚未应用的 SQL 文件。可使用以下命令检查状态:
```bash ```bash
docker compose ps # 本分支(NEXT 版);如要部署 LITE 版请 clone main 分支
docker compose logs -f app git clone -b next https://github.com/forumlify/public.git
curl http://localhost:3000/health/live cd public
curl http://localhost:3000/health/ready docker-compose up -d
``` ```
- `/health/live` 表示 Node.js 服务正在运行。 应用默认运行在 `http://localhost:3000`(监听 `0.0.0.0`,局域网可访问)。
- `/health/ready` 仅在 PostgreSQL 可用时返回成功。
- PostgreSQL 不再暴露到宿主机网络;应用通过 Compose 内部网络访问数据库。
- 应用收到 `SIGTERM`/`SIGINT` 后会停止接收新连接并关闭数据库连接池。
升级代码后执行 `docker compose up --build -d`,应用会在启动前自动应用新增迁移。 ##Docker更新
#### Docker 数据备份
数据库保存在 `db_data` 卷中,上传文件继续保存在宿主机的 `./uploads` 目录,以兼容旧版部署。升级或删除容器前请备份:
```bash
docker compose exec -T db pg_dump -U forumlify forumlify > forumlify.sql
tar czf forumlify-uploads.tar.gz uploads/
``` ```
# 拉取最新镜像
`docker compose down` 会保留数据卷;只有明确执行 `docker compose down -v` 才会删除数据。 docker pull ghcr.io/forumlify/public:next
# 重启
docker compose down && docker compose up -d
```
--- ---
> 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/forumlify/public/tree/next)。 > 以下内容需要一定的Nextjs开发技术!
--- ---
@@ -90,90 +68,202 @@ tar czf forumlify-uploads.tar.gz uploads/
#### 环境要求 #### 环境要求
- Node.js 20+ - Node.js 20.9+(Next.js 16 要求)
- PostgreSQL 13+ - PostgreSQL 13+(`schema.sql` 使用了内置的 `gen_random_uuid()`)
#### 步骤 #### 步骤
1. **克隆并安装依赖** 1. **克隆并安装依赖**
```bash ```bash
git clone https://github.com/forumlify/public.git # 克隆 next 分支(Next.js 版);main 分支是 Express 版
git clone -b next https://github.com/forumlify/public.git
cd public cd public
npm install npm install
``` ```
2. **准备数据库** 2. **准备数据库**(以本机 PostgreSQL 为例)
```bash ```bash
# 创建数据库和用户(与 docker-compose.yml 默认一致)
psql -U postgres -c "CREATE USER forumlify WITH PASSWORD '123456';" psql -U postgres -c "CREATE USER forumlify WITH PASSWORD '123456';"
psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;" psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;"
# 导入表结构
psql -U forumlify -d forumlify -f schema.sql psql -U forumlify -d forumlify -f schema.sql
``` ```
3. **配置环境变量** 3. **配置环境变量**(可选,均有默认值)
| 变量 | 默认值 | 说明 | | 变量 | 默认值 | 说明 |
|------|--------|------| |------|--------|------|
| `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 | | `DATABASE_URL` | `postgresql://forumlify:123456@localhost:5432/forumlify` | PostgreSQL 连接串 |
| `PORT` | `3000` | HTTP 监听端口 | | `JWT_SECRET` | `forumlify-secret-key-change-me-in-production` | JWT 签名密钥,**生产环境务必修改** |
| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;生产环境必须显式设置,建议至少 32 个字符。较短的旧密钥会产生警告但仍可启动,便于安排会话失效窗口后再轮换 |
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
| `PGHOST` / `PGPORT` / `PGUSER` / `PGPASSWORD` / `PGDATABASE` | PostgreSQL 客户端默认值 | 可替代 `DATABASE_URL`,Compose 使用这些变量避免密码 URL 编码问题 |
| `ADMIN_BOOTSTRAP_TOKEN` | 空 | 首次部署时设置强随机值;注册页填写相同值可创建唯一初始管理员,初始化后应删除该变量 |
4. **执行迁移并启动**
```bash ```bash
npm run migrate # 例如:
export DATABASE_URL=postgresql://forumlify:123456@localhost:5432/forumlify
export JWT_SECRET=your-own-secret-key
```
4. **构建并启动**
```bash
npm run build
npm start npm start
``` ```
应用运行在 `http://localhost:3000`,API 在 `http://localhost:3000/api`。 应用运行在 `http://localhost:3000`,API 在 `http://localhost:3000/api`。
#### 前端配置 开发模式(热更新):`npm run dev`。
前端页面为 `index.html`,相关行为可在 `config.js` 中调整: #### 服务端配置
监听端口与地址可在 `config.js` 中调整(服务端读取,浏览器端忽略):
| 配置项 | 默认值 | 说明 | | 配置项 | 默认值 | 说明 |
|--------|--------|------| |--------|--------|------|
| `FORUM_NAME` | `Forumlify` | 论坛名称(左上角显示) | | `SERVER_PORT` | `null` | 可选:监听端口。优先级:环境变量 `PORT` > `SERVER_PORT` > 默认 `3000` |
| `ENABLE_CAPTCHA` | `true` | 发帖/注册的人机验证(10 以内加减法) | | `SERVER_HOST` | `null` | 可选:监听地址。优先级:环境变量 `HOST` > `SERVER_HOST` > 默认 `0.0.0.0`(所有网卡)。设为 `127.0.0.1` 仅本机访问 |
| `SERVER_PORT` | `null` | 可选:服务端监听端口。优先级:环境变量 `PORT` > `SERVER_PORT` > 默认 `3000` |
#### 上传目录 #### 上传目录
帖子图片默认保存在 `uploads/` 目录,请确保该目录有写入权限: 帖子图片默认保存在 `uploads/` 目录(Docker 部署时通过 volume 挂载到 `/app/uploads`),源码部署时请确保该目录有写入权限:
```bash ```bash
mkdir -p uploads && chmod 755 uploads mkdir -p uploads && chmod 755 uploads
``` ```
## 📁 项目结构 ## ☁️ Serverless 部署(Vercel / Cloudflare Workers)
``` Forumlify 的 Next.js 版本天然支持 serverless 部署。与传统部署相比需要处理三件事:
forumlify/
├── index.html # 前端页面 1. **数据库**:使用外部 PostgreSQL(Neon / Supabase / RDS 等),设置 `DATABASE_URL` 环境变量。连接池会自动适配 serverless(单连接 + 定期轮换)。
├── style.css # 全局样式 2. **文件上传**:serverless 无持久磁盘,需要 S3 兼容对象存储(Cloudflare R2 / AWS S3 / MinIO)。设置 `S3_*` 环境变量后,上传自动切换到对象存储。
├── Dockerfile # Docker 镜像构建文件 3. **密码哈希**:已使用 `bcryptjs`(纯 JS),无原生编译依赖,各平台均可直接构建。
├── package-lock.json # 依赖锁定文件
├── server.js # 后端服务(Express) ### 环境变量说明
├── js/ # 前端 JS 模块
│ ├── app.js | 变量 | 必填 | 说明 |
│ ├── admin.js |------|------|------|
│ ├── api.js | `DATABASE_URL` | ✅ 必须 | PostgreSQL 连接串,如 `postgresql://user:pass@host:5432/dbname`(可用 [Neon](https://neon.tech) / [Supabase](https://supabase.com) 免费实例) |
│ ├── auth.js | `JWT_SECRET` | ✅ 必须 | JWT 签名密钥,任意长随机字符串(生产环境务必修改) |
│ ├── feed.js | `S3_ENDPOINT` | 上传图片时 | S3 兼容端点,如 R2 的 `https://<account_id>.r2.cloudflarestorage.com` |
│ ├── post.js | `S3_BUCKET` | 上传图片时 | 存储桶名 |
│ └── user.js | `S3_REGION` | 上传图片时 | 区域(R2 用 `auto`,AWS 用 `us-east-1` 等) |
├── schema.sql # 数据库表结构 | `S3_ACCESS_KEY_ID` | 上传图片时 | 对象存储 Access Key |
├── config.js # 配置文件 | `S3_SECRET_ACCESS_KEY` | 上传图片时 | 对象存储 Secret Key |
└── docker-compose.yml # Docker 编排 | `S3_PUBLIC_URL` | 上传图片时 | 公开访问前缀,如 `https://cdn.example.com`(图片 URL 将指向这里) |
> 只搭一个纯文字论坛、不上传图片的话,只需配置 `DATABASE_URL` 和 `JWT_SECRET` 两个变量。
### Vercel 部署(一键)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Flezi-fun%2Fforumlify-deploy&env=DATABASE_URL,JWT_SECRET,S3_ENDPOINT,S3_BUCKET,S3_REGION,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY,S3_PUBLIC_URL)
点击上方按钮,Vercel 会自动:
1. Fork 部署模板仓库([lezi-fun/forumlify-deploy](https://github.com/lezi-fun/forumlify-deploy),默认分支 `next`,即 Next.js 版,无需手动选分支)
2. 提示你填写环境变量(见上方表格,前两个必填,其余可跳过)
3. 自动完成构建并部署,完成后会给你一个 `https://xxx.vercel.app` 地址
也可以用 CLI 手动部署:
```bash
npm i -g vercel
vercel # 首次会要求登录并配置环境变量
``` ```
## 📝 License > 注意:不传图片的话 S3 变量可以留空;后续要传图时再到 Vercel 项目设置 → Environment Variables 补上即可,无需重新部署。
MIT ### Cloudflare Workers 部署(一键)
[![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https%3A%2F%2Fgithub.com%2Flezi-fun%2Fforumlify-deploy)
点击上方按钮,Cloudflare 会自动导入部署模板仓库([lezi-fun/forumlify-deploy](https://github.com/lezi-fun/forumlify-deploy),默认分支 `next`),在 Workers 面板确认后即完成部署。
#### 面板手动部署(Git 集成)
1. 打开 Cloudflare 控制台 → **Workers & Pages** → **Create** → **Connect to Git**
2. 选择 `lezi-fun/forumlify-deploy` 仓库(或你 fork 的副本),分支选 `next`
3. **构建设置**:
- Build command: `npx opennextjs-cloudflare build --dangerouslyUseUnsupportedNextVersion`
- 部署命令由 OpenNext 自动处理(`wrangler deploy`)
4. **环境变量**(Settings → Variables and Secrets,设为 **Secrets**):按上方表格配置 `DATABASE_URL`、`JWT_SECRET`、`S3_*`
5. 保存并部署。完成后会得到 `https://<name>.<subdomain>.workers.dev` 地址
#### 命令行部署
```bash
# 需要 Node.js 20+,安装依赖后:
npx opennextjs-cloudflare build --dangerouslyUseUnsupportedNextVersion
# 部署前先配置 wrangler 认证(三选一):
# wrangler login # 浏览器登录
# CLOUDFLARE_API_TOKEN=<token> # API Token
# CLOUDFLARE_API_KEY + CLOUDFLARE_API_EMAIL # Global API Key
export CLOUDFLARE_ACCOUNT_ID=<account_id>
# 设置环境变量(Secret)
echo 'postgresql://...' | npx wrangler secret put DATABASE_URL
echo 'your-jwt-secret' | npx wrangler secret put JWT_SECRET
# ... 其余 S3_* 同理
npx opennextjs-cloudflare deploy
```
> 注意:OpenNext 使用 R2 增量缓存,首次部署前需创建缓存桶:
> `npx wrangler r2 bucket create forumlify-opennext-cache`
>
> `--dangerouslyUseUnsupportedNextVersion` 用于跳过 Next.js 主版本支持期检查(如仍在使用旧主版本时)。
> 提示:`next.config.js` 中的 `output: 'standalone'` 仅在设置了 `DOCKER=1` 环境变量时启用,serverless 平台会自动跳过。
## 🔄 与 main 分支(Express 版)的对比
本分支(`next`)基于上游 `main` 的 Express 单文件架构全面重构为 Next.js 16(App Router)。两者功能一致,实现方式不同:
| 维度 | main 分支(Express) | next 分支(Next.js 16) |
|------|---------------------|------------------------|
| **前端** | 单个 1488 行 `index.html` + `js/` 原生 JS 模块(手写 DOM 操作) | React 19 组件(`components/`),状态由 `AppProvider` 管理 |
| **后端** | 单个 1000+ 行 `server.js`(Express 路由) | 36 个 Route Handlers(`app/api/**/route.js`),每个接口独立文件 |
| **模板渲染** | `innerHTML` 字符串拼接 + `onclick` 事件绑定 | JSX 声明式渲染 + React 事件 |
| **图片上传** | multer + `uploads/` 本地目录 | 存储抽象层(`lib/storage.js`):本地磁盘 或 S3 兼容对象存储(serverless) |
| **密码哈希** | `bcrypt`(原生编译) | `bcryptjs`(纯 JS,serverless 友好) |
| **数据库** | 共享同一套 PostgreSQL schema | **同一 `schema.sql`,与 main 完全兼容**(已实测互操作) |
| **部署** | Docker 或裸机 `node server.js` | Docker / 裸机 / **Vercel / Cloudflare Pages(serverless)** |
| **性能** | Express 同步渲染 | Next.js 增量静态生成 + 流式渲染 |
| **API 路径** | `/api/*` | `/api/*`(路径一致,前端兼容) |
### 数据库兼容性
两个分支使用**完全相同的 `schema.sql`**,共用同一个数据库实例(已验证:main 的 Express 代码与 next 的 Next.js 代码可同时连接同一 PostgreSQL 库,表结构、数据互不冲突)。
## 🏗️ 项目结构
```
app/
page.js # 主页(SPA 视图调度)
layout.js # 全局布局
globals.css # 全局样式(含亮/暗主题)
api/ # Route Handlers(API 后端)
auth/ posts/ replies/ users/ reports/ links/
stats/ event-logs/ settings/ upload/ uploads/
components/
AppProvider.js # 全局状态(用户/主题/路由)
Navbar.js Feed.js PostDetail.js ReplyList.js
NewPost.js AdminPage.js SettingsPage.js Modals.js
lib/
db.js # PostgreSQL 连接池
auth.js # JWT 认证工具
api.js # 前端 API 封装
scripts/
start.js # 启动入口(读取 config.js 监听配置)
schema.sql # 数据库表结构
config.js # 服务端配置(端口/地址)
```
## 📚 技术栈
- Next.js 16 (App Router) + React 19
- Express 风格 Route Handlers (Node.js Runtime)
- PostgreSQL + pg
- JWT 认证 + bcrypt 密码哈希
+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} />;
}
+64
View File
@@ -0,0 +1,64 @@
'use client';
// 主页客户端组件:SPA 视图调度 (feed/post/new/admin/settings/messages)
import { useState } from 'react';
import AppProvider, { useApp } from '@/components/AppProvider';
import Navbar from '@/components/Navbar';
import Sidebar from '@/components/Sidebar';
import Feed from '@/components/Feed';
import PostDetail from '@/components/PostDetail';
import NewPost from '@/components/NewPost';
import AdminPage from '@/components/AdminPage';
import SettingsPage from '@/components/SettingsPage';
import UserProfile from '@/components/UserProfile';
import CustomPage from '@/components/CustomPage';
import MessagesPage from '@/components/MessagesPage';
import ChatManager from '@/components/chat/ChatManager';
import Modals from '@/components/Modals';
import LoadingScreen from '@/components/LoadingScreen';
function HomeInner() {
const { view, currentPostId, currentPostPreview, currentUsername, currentUserPreview, currentUserPostsPreview, currentPageName, ready, forumName, forumNameLoaded } = useApp();
const [modal, setModal] = useState(null); // null | login | register | report
const [reportPostId, setReportPostId] = useState(null);
const openModal = (m) => setModal(m);
const openReport = (postId) => { setReportPostId(postId); setModal('report'); };
// 初始化未完成:显示全屏加载页,避免未加载完的界面闪烁
if (!ready) {
return <LoadingScreen forumName={forumName} forumNameLoaded={forumNameLoaded} />;
}
return (
<div className="app-fade-in">
<Navbar onOpenModal={openModal} />
<ChatManager />
<div id="app" style={{ display: view === 'feed' ? undefined : 'none' }}>
<Sidebar />
<Feed onOpenModal={openModal} onReport={openReport} />
</div>
{/* 独立页面 */}
<div style={{ display: view !== 'feed' ? 'block' : 'none' }}>
{view === 'post' && currentPostId && <PostDetail postId={currentPostId} initialPost={currentPostPreview} />}
{view === 'user' && currentUsername && <UserProfile username={currentUsername} initialUser={currentUserPreview} initialPosts={currentUserPostsPreview} />}
{view === 'custom' && currentPageName && <CustomPage pageName={currentPageName} />}
{view === 'new' && <NewPost />}
{view === 'admin' && <AdminPage />}
{view === 'settings' && <SettingsPage />}
{view === 'messages' && <MessagesPage />}
</div>
<Modals modal={modal} onClose={() => setModal(null)} reportPostId={reportPostId} />
</div>
);
}
export default function HomeClient({ cachedName = '' }) {
return (
<AppProvider cachedName={cachedName}>
<HomeInner />
</AppProvider>
);
}
+7
View File
@@ -0,0 +1,7 @@
import ForumPage from '../ForumPage';
export const dynamic = 'force-dynamic';
export default function NamedPage() {
return <ForumPage />;
}
+63
View File
@@ -0,0 +1,63 @@
// POST /api/admin/custom-css, DELETE /api/admin/custom-css — 管理自定义 CSS
import { writeFile, mkdir, unlink } from 'fs/promises';
import path from 'path';
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
export const runtime = 'nodejs';
// 上传 style.css(管理员)
export async function POST(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
const form = await req.formData();
const file = form.get('file');
if (!file || typeof file === 'string') {
return Response.json({ error: '请选择文件' }, { status: 400 });
}
if (file.name !== 'style.css') {
return Response.json({ error: '文件名必须是 style.css' }, { status: 400 });
}
if (file.size > 1024 * 1024) {
return Response.json({ error: 'CSS 文件不能超过 1MB' }, { status: 400 });
}
try {
const dir = path.join(process.cwd(), 'uploads', 'custom');
await mkdir(dir, { recursive: true });
const buffer = Buffer.from(await file.arrayBuffer());
await writeFile(path.join(dir, 'style.css'), buffer);
await pool.query(
`INSERT INTO settings (key, value) VALUES ($1, $2)
ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
['custom_css_enabled', 'true']
);
return Response.json({ success: true });
} catch {
return Response.json({ error: '上传失败,请稍后重试' }, { status: 500 });
}
}
// 删除自定义 CSS(管理员)
export async function DELETE(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
try {
const cssPath = path.join(process.cwd(), 'uploads', 'custom', 'style.css');
try { await unlink(cssPath); } catch { /* 不存在则忽略 */ }
await pool.query(
`INSERT INTO settings (key, value) VALUES ($1, $2)
ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
['custom_css_enabled', 'false']
);
return Response.json({ success: true });
} catch {
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
}
}
+48
View File
@@ -0,0 +1,48 @@
// PUT /api/admin/custom-pages/[id], DELETE /api/admin/custom-pages/[id]
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
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 });
}
const { title, content, enabled } = await req.json();
try {
const r = await pool.query(
`UPDATE custom_pages
SET title = $1, content = $2, enabled = $3, updated_at = NOW()
WHERE id = $4
RETURNING *`,
[title, content, enabled, (await params).id]
);
if (r.rows.length === 0) {
return Response.json({ error: '页面不存在' }, { status: 404 });
}
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '更新失败,请稍后重试' }, { status: 500 });
}
}
export async function DELETE(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 {
await pool.query('DELETE FROM custom_pages WHERE id = $1', [(await params).id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
}
}
+56
View File
@@ -0,0 +1,56 @@
// GET /api/admin/custom-pages, POST /api/admin/custom-pages — 管理 CRUD
import pool from '@/lib/db';
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);
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
try {
const r = await pool.query(
'SELECT id, name, title, content, enabled, created_at, updated_at FROM custom_pages ORDER BY created_at'
);
return Response.json(r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function POST(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
const { name, title, content } = await req.json();
if (!name || !title || !content) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
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)
VALUES ($1, $2, $3)
RETURNING *`,
[name, title, content]
);
return Response.json(r.rows[0]);
} catch (err) {
if (err.code === '23505') {
return Response.json({ error: '页面名称已存在' }, { status: 400 });
}
return Response.json({ error: '创建失败,请稍后重试' }, { status: 500 });
}
}
+43
View File
@@ -0,0 +1,43 @@
// POST /api/auth/login
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import pool from '@/lib/db';
import { JWT_SECRET } from '@/lib/auth';
import { logAudit } from '@/lib/audit';
export async function POST(req) {
const { email, password } = await req.json();
if (!email || !password) {
return Response.json({ error: '请填写邮箱和密码' }, { status: 400 });
}
try {
const r = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
const user = r.rows[0];
if (!user) {
return Response.json({ error: '邮箱或密码错误' }, { status: 401 });
}
const valid = await bcrypt.compare(password, user.password_hash);
if (!valid) {
return Response.json({ error: '邮箱或密码错误' }, { status: 401 });
}
const token = jwt.sign(
{ id: user.id, email: user.email, role: user.role },
JWT_SECRET,
{ expiresIn: '7d' }
);
// 服务端审计:登录成功
await logAudit(req, 'login', user.id);
return Response.json({
token,
user: {
id: user.id,
username: user.username,
avatar_url: user.avatar_url,
bio: user.bio,
role: user.role,
},
});
} catch {
return Response.json({ error: '登录失败,请稍后重试' }, { status: 500 });
}
}
+22
View File
@@ -0,0 +1,22 @@
// GET /api/auth/me
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function GET(req) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
try {
const r = await pool.query(
'SELECT id, username, avatar_url, bio, signature, role, created_at FROM users WHERE id = $1',
[user.id]
);
if (!r.rows[0]) {
return Response.json({ error: '用户不存在' }, { status: 404 });
}
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
@@ -0,0 +1,17 @@
// GET /api/auth/recovery-codes/count — 剩余恢复码数量
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function GET(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
try {
const r = await pool.query(
'SELECT COUNT(*) FROM recovery_codes WHERE user_id = $1 AND is_used = false',
[user.id]
);
return Response.json({ count: parseInt(r.rows[0].count) || 0 });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
@@ -0,0 +1,35 @@
// POST /api/auth/recovery-codes/generate — 生成 10 个恢复码
import bcrypt from 'bcryptjs';
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
function generateRecoveryCode() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let code = '';
for (let i = 0; i < 20; i++) {
code += chars[Math.floor(Math.random() * chars.length)];
if (i === 4 || i === 9 || i === 14) code += '-';
}
return code;
}
export async function POST(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
try {
await pool.query('DELETE FROM recovery_codes WHERE user_id = $1', [user.id]);
const codes = [];
for (let i = 0; i < 10; i++) {
const code = generateRecoveryCode();
codes.push(code);
const hash = await bcrypt.hash(code, 10);
await pool.query(
'INSERT INTO recovery_codes (user_id, code_hash) VALUES ($1, $2)',
[user.id, hash]
);
}
return Response.json({ success: true, codes });
} catch {
return Response.json({ error: '生成失败,请稍后重试' }, { status: 500 });
}
}
+46
View File
@@ -0,0 +1,46 @@
// POST /api/auth/register
import bcrypt from 'bcryptjs';
import pool from '@/lib/db';
import { verifyCaptcha } from '@/lib/captcha';
import { logAudit } from '@/lib/audit';
export async function POST(req) {
const { email, password, username, captcha_id, captcha_answer, captcha_sig } = await req.json();
if (!email || !password || !username) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
if (password.length < 6) {
return Response.json({ error: '密码至少6位' }, { status: 400 });
}
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
}
try {
const countResult = await pool.query('SELECT COUNT(*) FROM users');
const isFirstUser = parseInt(countResult.rows[0].count) === 0;
const hash = await bcrypt.hash(password, 10);
const avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64';
const role = isFirstUser ? 'admin' : 'user';
const r = await pool.query(
`INSERT INTO users (email, password_hash, username, avatar_url, role)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, username, avatar_url, role, created_at`,
[email, hash, username, avatar, role]
);
// 服务端审计:注册成功
await logAudit(req, 'register', r.rows[0].id);
return Response.json({
user: r.rows[0],
message: isFirstUser ? '你是第一个用户,已自动设为管理员!' : '注册成功',
});
} catch (err) {
if (err.code === '23505') {
return Response.json({ error: '邮箱或用户名已被注册' }, { status: 400 });
}
return Response.json({ error: '注册失败,请稍后重试' }, { status: 500 });
}
}
+38
View File
@@ -0,0 +1,38 @@
// POST /api/auth/reset-password — 用恢复码重置密码(公开)
import bcrypt from 'bcryptjs';
import pool from '@/lib/db';
export async function POST(req) {
const { email, recoveryCode, newPassword } = await req.json();
if (!email || !recoveryCode || !newPassword) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
if (newPassword.length < 6) {
return Response.json({ error: '密码至少6位' }, { status: 400 });
}
try {
const user = await pool.query('SELECT id FROM users WHERE email = $1', [email]);
if (user.rows.length === 0) {
return Response.json({ error: '用户不存在' }, { status: 404 });
}
const codes = await pool.query(
'SELECT id, code_hash FROM recovery_codes WHERE user_id = $1 AND is_used = false',
[user.rows[0].id]
);
let matched = false;
let matchedId = null;
for (const row of codes.rows) {
const valid = await bcrypt.compare(recoveryCode, row.code_hash);
if (valid) { matched = true; matchedId = row.id; break; }
}
if (!matched) {
return Response.json({ error: '恢复码无效或已使用' }, { status: 400 });
}
await pool.query('UPDATE recovery_codes SET is_used = true WHERE id = $1', [matchedId]);
const hash = await bcrypt.hash(newPassword, 10);
await pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, user.rows[0].id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '重置失败,请稍后重试' }, { status: 500 });
}
}
+7
View File
@@ -0,0 +1,7 @@
// GET /api/captcha — 服务端验证码挑战(HMAC 签名答案,防前端绕过)
import { generateCaptchaChallenge } from '@/lib/captcha';
export async function GET() {
const ch = generateCaptchaChallenge();
return Response.json({ id: ch.id, text: ch.text, sig: ch.sig });
}
@@ -0,0 +1,78 @@
// GET /api/conversations/[id]/messages, POST /api/conversations/[id]/messages
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export async function GET(req, { params }) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
if (!UUID_RE.test((await params).id)) {
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
}
try {
const check = await pool.query(`
SELECT id FROM conversations
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
`, [(await params).id, user.id]);
if (check.rows.length === 0) {
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
}
const r = await pool.query(`
SELECT
m.*,
u.username as sender_username,
u.avatar_url as sender_avatar_url
FROM messages m
JOIN users u ON m.sender_id = u.id
WHERE m.conversation_id = $1
ORDER BY m.created_at ASC
`, [(await params).id]);
await pool.query(`
UPDATE messages SET is_read = true
WHERE conversation_id = $1 AND sender_id != $2 AND is_read = false
`, [(await params).id, user.id]);
return Response.json(r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function POST(req, { params }) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
if (!UUID_RE.test((await params).id)) {
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
}
const { content } = await req.json();
if (!content || content.trim().length === 0) {
return Response.json({ error: '请填写消息内容' }, { status: 400 });
}
try {
const check = await pool.query(`
SELECT id FROM conversations
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
`, [(await params).id, user.id]);
if (check.rows.length === 0) {
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
}
const r = await pool.query(`
INSERT INTO messages (conversation_id, sender_id, content)
VALUES ($1, $2, $3)
RETURNING *
`, [(await params).id, user.id, content]);
await pool.query('UPDATE conversations SET last_message_at = NOW() WHERE id = $1', [(await params).id]);
const userInfo = await pool.query('SELECT username, avatar_url FROM users WHERE id = $1', [user.id]);
return Response.json({
...r.rows[0],
sender_username: userInfo.rows[0].username,
sender_avatar_url: userInfo.rows[0].avatar_url,
});
} catch {
return Response.json({ error: '发送失败,请稍后重试' }, { status: 500 });
}
}
+72
View File
@@ -0,0 +1,72 @@
// GET /api/conversations, POST /api/conversations
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
export const dynamic = 'force-dynamic';
export async function GET(req) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
try {
const r = await pool.query(`
SELECT
c.id,
c.user1_id,
c.user2_id,
c.last_message_at,
c.created_at,
u.id as other_user_id,
u.username as other_username,
u.avatar_url as other_avatar_url,
(SELECT COUNT(*) FROM messages WHERE conversation_id = c.id AND sender_id != $1 AND is_read = false) as unread_count,
(SELECT content FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_message,
(SELECT created_at FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_message_time
FROM conversations c
JOIN users u ON (u.id = c.user1_id OR u.id = c.user2_id) AND u.id != $1
WHERE c.user1_id = $1 OR c.user2_id = $1
ORDER BY c.last_message_at DESC
`, [user.id]);
return Response.json(r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function POST(req) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const { other_user_id } = await req.json();
if (!other_user_id) {
return Response.json({ error: '缺少对方用户ID' }, { status: 400 });
}
if (other_user_id === user.id) {
return Response.json({ error: '不能与自己私信' }, { status: 400 });
}
try {
const userCheck = await pool.query('SELECT id FROM users WHERE id = $1', [other_user_id]);
if (userCheck.rows.length === 0) {
return Response.json({ error: '用户不存在' }, { status: 404 });
}
const existing = await pool.query(`
SELECT id FROM conversations
WHERE (user1_id = $1 AND user2_id = $2) OR (user1_id = $2 AND user2_id = $1)
`, [user.id, other_user_id]);
if (existing.rows.length > 0) {
return Response.json({ id: existing.rows[0].id });
}
const r = await pool.query(`
INSERT INTO conversations (user1_id, user2_id)
VALUES ($1, $2)
RETURNING id
`, [user.id, other_user_id]);
return Response.json({ id: r.rows[0].id });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+15
View File
@@ -0,0 +1,15 @@
// GET /api/custom-css — 公开获取自定义 CSS
import { readFile } from 'fs/promises';
import path from 'path';
export const runtime = 'nodejs';
export async function GET() {
try {
const cssPath = path.join(process.cwd(), 'uploads', 'custom', 'style.css');
const css = await readFile(cssPath, 'utf-8');
return new Response(css, { headers: { 'Content-Type': 'text/css' } });
} catch {
return new Response('', { status: 404 });
}
}
+18
View File
@@ -0,0 +1,18 @@
// GET /api/custom-pages/[name] — 公开单个页面
import pool from '@/lib/db';
import { jsonWithEtag } from '@/lib/http-cache';
export async function GET(req, { params }) {
try {
const r = await pool.query(
'SELECT id, name, title, content FROM custom_pages WHERE name = $1 AND enabled = true',
[(await params).name]
);
if (r.rows.length === 0) {
return Response.json({ error: '页面不存在' }, { status: 404 });
}
return jsonWithEtag(req, r.rows[0]);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+14
View File
@@ -0,0 +1,14 @@
// GET /api/custom-pages — 公开页面列表
import pool from '@/lib/db';
import { jsonWithEtag } from '@/lib/http-cache';
export async function GET(req) {
try {
const r = await pool.query(
'SELECT id, name, title FROM custom_pages WHERE enabled = true ORDER BY created_at'
);
return jsonWithEtag(req, r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+31
View File
@@ -0,0 +1,31 @@
// GET /api/event-logs, POST /api/event-logs
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
export const dynamic = 'force-dynamic';
export async function GET(req) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
try {
const r = await pool.query(
`SELECT el.*, u.username
FROM event_logs el
LEFT JOIN users u ON el.user_id = u.id
ORDER BY el.created_at DESC
LIMIT 100`
);
return Response.json(r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
// 审计日志由服务端在关键操作后记录(对齐上游 PR #22)——
// 客户端上报端点已移除,防止伪造审计记录
+18
View File
@@ -0,0 +1,18 @@
// DELETE /api/links/[id]
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
export async function DELETE(req, { params }) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
try {
await pool.query('DELETE FROM friendly_links WHERE id = $1', [(await params).id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
}
}
+42
View File
@@ -0,0 +1,42 @@
// GET /api/links, POST /api/links
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
import { jsonWithEtag } from '@/lib/http-cache';
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
export const dynamic = 'force-dynamic';
export async function GET(req) {
try {
const r = await pool.query('SELECT * FROM friendly_links ORDER BY sort_order');
return jsonWithEtag(req, r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function POST(req) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
const { title, url } = await req.json();
if (!title || !url) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
try {
const r = await pool.query(
`INSERT INTO friendly_links (title, url)
VALUES ($1, $2)
RETURNING *`,
[title, url]
);
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '添加失败,请稍后重试' }, { status: 500 });
}
}
+24
View File
@@ -0,0 +1,24 @@
// PUT /api/messages/[id]/read — 标记消息已读
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
if (!UUID_RE.test((await params).id)) {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
try {
await pool.query(`
UPDATE messages SET is_read = true
WHERE id = $1 AND sender_id != $2
`, [(await params).id, user.id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+22
View File
@@ -0,0 +1,22 @@
// PUT /api/notifications/[id]/read — 标记单条已读
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
if (!UUID_RE.test((await params).id)) {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
try {
await pool.query(
'UPDATE notifications SET is_read = true WHERE id = $1 AND user_id = $2',
[(await params).id, user.id]
);
return Response.json({ success: true });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+14
View File
@@ -0,0 +1,14 @@
// PUT /api/notifications/read-all — 全部标记已读
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function PUT(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
try {
await pool.query('UPDATE notifications SET is_read = true WHERE user_id = $1', [user.id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+17
View File
@@ -0,0 +1,17 @@
// GET /api/notifications — 我的通知列表
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function GET(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
try {
const r = await pool.query(
'SELECT id, type, title, content, link, is_read, created_at FROM notifications WHERE user_id = $1 ORDER BY created_at DESC LIMIT 50',
[user.id]
);
return Response.json(r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+40
View File
@@ -0,0 +1,40 @@
// PUT /api/posts/[id]/pin — 置顶/取消置顶(管理员)
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
import { createNotification } from '@/lib/notify';
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;
try {
const reference = await resolvePostReference((await params).id);
if (!reference) {
return Response.json({ error: '帖子不存在' }, { status: 404 });
}
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, reference.id]
);
await createNotification(
post.rows[0].user_id,
'system',
isPinned ? '你的帖子已被取消置顶' : '你的帖子已被置顶',
isPinned ? '管理员取消了你的帖子置顶' : '管理员把你的帖子置顶了',
'/post/' + post.rows[0].post_number
);
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '操作失败,请稍后重试' }, { status: 500 });
}
}
+134
View File
@@ -0,0 +1,134 @@
// GET /api/posts/[id]/replies, POST /api/posts/[id]/replies
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
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) {
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
r.reply_to_id, u.username, u.avatar_url,
ru.username AS reply_to_username
FROM replies r
JOIN users u ON r.user_id = u.id
LEFT JOIN replies rt ON r.reply_to_id = rt.id
LEFT JOIN users ru ON rt.user_id = ru.id
WHERE r.post_id = $1
ORDER BY r.created_at ASC`;
}
if (capabilities.replyToUsername) {
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
NULL::uuid AS reply_to_id,
u.username, u.avatar_url,
r.reply_to_username
FROM replies r
JOIN users u ON r.user_id = u.id
WHERE r.post_id = $1
ORDER BY r.created_at ASC`;
}
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
NULL::uuid AS reply_to_id,
NULL::varchar AS reply_to_username,
u.username, u.avatar_url
FROM replies r
JOIN users u ON r.user_id = u.id
WHERE r.post_id = $1
ORDER BY r.created_at ASC`;
}
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), [reference.id]);
return jsonWithEtag(req, r.rows);
} catch (error) {
console.error('[replies] list failed:', error?.code || error?.message);
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function POST(req, { params }) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const { content, captcha_id, captcha_answer, captcha_sig, reply_to_id, reply_to_username } = await req.json();
if (!content || content.trim().length === 0) {
return Response.json({ error: '请填写回复内容' }, { status: 400 });
}
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
}
try {
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;
if (reply_to_id) {
const target = await pool.query(
`SELECT u.username
FROM replies r
JOIN users u ON u.id = r.user_id
WHERE r.id = $1 AND r.post_id = $2`,
[reply_to_id, postId]
);
if (!target.rows[0]) {
return Response.json({ error: '回复目标不存在' }, { status: 400 });
}
replyTargetUsername = target.rows[0].username;
} else if (reply_to_username && capabilities.replyToUsername) {
const target = await pool.query(
`SELECT u.username
FROM replies r
JOIN users u ON u.id = r.user_id
WHERE r.post_id = $1 AND u.username = $2
LIMIT 1`,
[postId, reply_to_username]
);
if (!target.rows[0]) {
return Response.json({ error: '回复目标不存在' }, { status: 400 });
}
replyTargetUsername = target.rows[0].username;
}
let r;
if (capabilities.replyToId) {
r = await pool.query(
`INSERT INTO replies (post_id, user_id, content, reply_to_id)
VALUES ($1, $2, $3, $4)
RETURNING *`,
[postId, user.id, content.trim(), reply_to_id || null]
);
} else if (capabilities.replyToUsername) {
r = await pool.query(
`INSERT INTO replies (post_id, user_id, content, reply_to_username)
VALUES ($1, $2, $3, $4)
RETURNING *, NULL::uuid AS reply_to_id`,
[postId, user.id, content.trim(), replyTargetUsername]
);
} else {
r = await pool.query(
`INSERT INTO replies (post_id, user_id, content)
VALUES ($1, $2, $3)
RETURNING *, NULL::uuid AS reply_to_id, NULL::varchar AS reply_to_username`,
[postId, user.id, content.trim()]
);
}
await logAudit(req, 'create_reply', user.id);
await pool.query('UPDATE posts SET updated_at = NOW() WHERE id = $1', [postId]);
return Response.json(r.rows[0]);
} catch (error) {
console.error('[replies] create failed:', error?.code || error?.message);
return Response.json({ error: '回复失败,请稍后重试' }, { status: 500 });
}
}
+80
View File
@@ -0,0 +1,80 @@
// GET /api/posts/[id], DELETE /api/posts/[id]
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
import { jsonWithEtag } from '@/lib/http-cache';
import { resolvePostReference } from '@/lib/post-reference';
function invalidId() {
return Response.json({ error: '帖子不存在' }, { status: 404 });
}
export async function GET(req, { params }) {
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`,
[reference.id]
);
if (r.rows.length === 0) {
return invalidId();
}
return jsonWithEtag(req, r.rows[0]);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const { title, content, images } = await req.json();
if (!content || content.trim().length === 0) {
return Response.json({ error: '请填写内容' }, { status: 400 });
}
try {
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 });
}
// 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 || [], reference.id]
);
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '编辑失败,请稍后重试' }, { status: 500 });
}
}
export async function DELETE(req, { params }) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
try {
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();
}
const u = await pool.query('SELECT role FROM users WHERE id = $1', [user.id]);
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', [reference.id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
}
}
+85
View File
@@ -0,0 +1,85 @@
// GET /api/posts, POST /api/posts — 支持 ?sort= & ?user_id= & 分页
import pool from '@/lib/db';
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';
export async function GET(req) {
const url = new URL(req.url);
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
const userId = url.searchParams.get('user_id');
const page = Math.max(1, parseInt(url.searchParams.get('page')) || 1);
// 分页边界:limit 封顶 50,page 封顶 10000(防深分页 DoS)
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit')) || 20));
const maxPage = Math.max(1, Math.ceil(200000 / limit));
const safePage = Math.min(page, maxPage);
const offset = (safePage - 1) * limit;
try {
await ensurePostNumberSchema();
const params = [];
let where = '';
if (userId) {
where = ' WHERE p.user_id = $1';
(await params).push(userId);
}
const countResult = await pool.query(`SELECT COUNT(*) as total FROM posts p${where}`, params);
const total = parseInt(countResult.rows[0]?.total || 0);
const r = await pool.query(`
SELECT
p.*,
u.username,
u.avatar_url,
u.signature,
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) as reply_count
FROM posts p
JOIN users u ON p.user_id = u.id
${where}
ORDER BY is_pinned DESC, pinned_at DESC NULLS LAST, ${sort} DESC
LIMIT $${(await params).length + 1} OFFSET $${(await params).length + 2}
`, [...params, limit, offset]);
return jsonWithEtag(req, {
data: r.rows,
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
});
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function POST(req) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const { title, content, images, captcha_id, captcha_answer, captcha_sig } = await req.json();
if (!content || content.trim().length === 0) {
return Response.json({ error: '请填写内容' }, { status: 400 });
}
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
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)
RETURNING *`,
[user.id, title || '无标题', content, images || []]
);
await logAudit(req, 'create_post', user.id);
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '发布失败,请稍后重试' }, { status: 500 });
}
}
+29
View File
@@ -0,0 +1,29 @@
// DELETE /api/replies/[id]
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export async function DELETE(req, { params }) {
if (!UUID_RE.test((await params).id)) {
return Response.json({ error: '回复不存在' }, { status: 404 });
}
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
try {
const reply = await pool.query('SELECT user_id FROM replies WHERE id = $1', [(await params).id]);
if (reply.rows.length === 0) {
return Response.json({ error: '回复不存在' }, { status: 404 });
}
const u = await pool.query('SELECT role FROM users WHERE id = $1', [user.id]);
if (reply.rows[0].user_id !== user.id && u.rows[0]?.role !== 'admin') {
return Response.json({ error: '无权限删除此回复' }, { status: 403 });
}
await pool.query('DELETE FROM replies WHERE id = $1', [(await params).id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
}
}
+33
View File
@@ -0,0 +1,33 @@
// PUT /api/reports/[id]
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export async function PUT(req, { params }) {
if (!UUID_RE.test((await params).id)) {
return Response.json({ error: '操作失败,请稍后重试' }, { status: 404 });
}
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
const { status, note } = await req.json();
if (!['pending', 'approved', 'rejected'].includes(status)) {
return Response.json({ error: '无效的状态' }, { status: 400 });
}
try {
await pool.query(
`UPDATE reports
SET status = $1, handled_at = NOW(), handler_id = $2, handler_note = $3
WHERE id = $4`,
[status, user.id, note || '', (await params).id]
);
return Response.json({ success: true });
} catch {
return Response.json({ error: '操作失败,请稍后重试' }, { status: 500 });
}
}
+62
View File
@@ -0,0 +1,62 @@
// 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';
export async function GET(req) {
const user = getUser(req);
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
try {
const r = await pool.query(`
SELECT
r.*,
reporter.username as reporter_name,
handler.username as handler_name,
p.title as post_title,
p.content as post_content
FROM reports r
JOIN users reporter ON r.reporter_id = reporter.id
LEFT JOIN users handler ON r.handler_id = handler.id
LEFT JOIN posts p ON r.post_id = p.id
ORDER BY r.created_at DESC
`);
return Response.json(r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function POST(req) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const { post_id, reason } = await req.json();
if (!post_id || !reason) {
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']
);
if (existing.rows.length > 0) {
return Response.json({ error: '你已经举报过此帖子,请等待处理' }, { status: 400 });
}
await pool.query(
`INSERT INTO reports (post_id, reporter_id, reason)
VALUES ($1, $2, $3)`,
[post.id, user.id, reason]
);
return Response.json({ success: true });
} catch {
return Response.json({ error: '举报失败,请稍后重试' }, { status: 500 });
}
}
+46
View File
@@ -0,0 +1,46 @@
// GET /api/settings, PUT /api/settings
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
import { jsonWithEtag } from '@/lib/http-cache';
// 避免 GET 被静态优化导致 PUT 405(动态接口,不能缓存)
export const dynamic = 'force-dynamic';
export async function GET(req) {
try {
// 确保 forum_name 始终存在(未设置过则初始化默认值),前端拿到后显示
await pool.query(
`INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
ON CONFLICT (key) DO NOTHING`
);
const r = await pool.query('SELECT key, value FROM settings ORDER BY key');
const settings = {};
r.rows.forEach((row) => { settings[row.key] = row.value; });
// 兜底:即使插入失败也保证返回 forum_name
if (!settings.forum_name) settings.forum_name = 'Forumlify';
return jsonWithEtag(req, settings);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function PUT(req) {
const user = getUser(req);
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
const { forum_name } = await req.json();
if (!forum_name || forum_name.trim().length === 0) {
return Response.json({ error: '论坛名称不能为空' }, { status: 400 });
}
try {
await pool.query(
`INSERT INTO settings (key, value) VALUES ($1, $2)
ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
['forum_name', forum_name.trim()]
);
return Response.json({ success: true });
} catch {
return Response.json({ error: '更新失败,请稍后重试' }, { status: 500 });
}
}
+19
View File
@@ -0,0 +1,19 @@
// GET /api/stats
import pool from '@/lib/db';
export async function GET() {
try {
const [postsRes, usersRes] = await Promise.all([
pool.query('SELECT COUNT(*) FROM posts'),
pool.query('SELECT COUNT(*) FROM users'),
]);
return Response.json({
posts: parseInt(postsRes.rows[0].count) || 0,
users: parseInt(usersRes.rows[0].count) || 0,
topics: parseInt(postsRes.rows[0].count) || 0,
online: Math.floor(Math.random() * 20) + 5,
});
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+54
View File
@@ -0,0 +1,54 @@
// POST /api/upload — 图片上传 (multipart/form-data)
// 安全:校验文件 magic bytes(不信任客户端 MIME/文件名),服务器生成 UUID 文件名
import path from 'path';
import { randomUUID } from 'crypto';
import { getUser } from '@/lib/auth';
import { saveObject } from '@/lib/storage';
const MAX_SIZE = 5 * 1024 * 1024;
// 从文件头字节嗅探真实图片类型(JPEG/PNG/GIF/WebP),拒绝伪造内容
function sniffImage(buf) {
if (buf.length < 12) return null;
// JPEG: FF D8 FF
if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return { ext: '.jpg', mime: 'image/jpeg' };
// PNG: 89 50 4E 47 0D 0A 1A 0A
if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 && buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) return { ext: '.png', mime: 'image/png' };
// GIF: "GIF8"
if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) return { ext: '.gif', mime: 'image/gif' };
// WebP: "RIFF" .... "WEBP"
if (buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) return { ext: '.webp', mime: 'image/webp' };
return null;
}
export const runtime = 'nodejs';
export async function POST(req) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const form = await req.formData();
const file = form.get('file');
if (!file || typeof file === 'string') {
return Response.json({ error: '请选择图片' }, { status: 400 });
}
if (file.size > MAX_SIZE) {
return Response.json({ error: '图片大小不能超过 5MB' }, { status: 400 });
}
try {
const buffer = Buffer.from(await file.arrayBuffer());
const sniff = sniffImage(buffer);
if (!sniff) {
return Response.json({ error: '不支持的图片格式' }, { status: 400 });
}
// 服务器生成 UUID 文件名 + 嗅探出的扩展名(不信任客户端文件名)
const name = randomUUID() + sniff.ext;
const { url } = await saveObject(name, buffer, sniff.mime);
return Response.json({ url });
} catch {
return Response.json({ error: '上传失败,请稍后重试' }, { status: 500 });
}
}
+37
View File
@@ -0,0 +1,37 @@
// GET /api/uploads/[name] — 提供上传的图片文件(本地存储模式)
// (next.config.js 中 rewrites 把 /uploads/* 指向这里,URL 保持 /uploads/... 不变)
// S3 模式下走 S3_PUBLIC_URL 直接访问,此路由不生效(rewrite 仍指向但返回 404 前可跳过)
import path from 'path';
import { getObject, STORAGE_TYPE } from '@/lib/storage';
export const runtime = 'nodejs';
const MIME = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
};
export async function GET(req, { params }) {
const name = (await params).name;
// 防止路径穿越
if (!/^[\w-]+\.\w+$/.test(name)) {
return new Response('Not Found', { status: 404 });
}
// S3 模式下文件不在本地,由 S3_PUBLIC_URL 提供
if (STORAGE_TYPE === 's3') {
return new Response('Not Found', { status: 404 });
}
try {
const data = await getObject(name);
if (!data) return new Response('Not Found', { status: 404 });
const ext = path.extname(name).toLowerCase();
return new Response(new Uint8Array(data), {
headers: { 'Content-Type': MIME[ext] || 'application/octet-stream' },
});
} catch {
return new Response('Not Found', { status: 404 });
}
}
+21
View File
@@ -0,0 +1,21 @@
// PUT /api/users/[id]/avatar — 修改头像
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
if ((await params).id !== user.id) {
return Response.json({ error: '无权限修改他人头像' }, { status: 403 });
}
const { avatar_url } = await req.json();
if (!avatar_url) {
return Response.json({ error: '请提供头像地址' }, { status: 400 });
}
try {
await pool.query('UPDATE users SET avatar_url = $1 WHERE id = $2', [avatar_url, (await params).id]);
return Response.json({ success: true, avatar_url });
} catch {
return Response.json({ error: '更新失败,请稍后重试' }, { status: 500 });
}
}
+34
View File
@@ -0,0 +1,34 @@
// PUT /api/users/[id]/email — 修改邮箱(需密码验证)
import bcrypt from 'bcryptjs';
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
if ((await params).id !== user.id) {
return Response.json({ error: '无权限' }, { status: 403 });
}
const { password, newEmail } = await req.json();
if (!password || !newEmail) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
try {
const u = await pool.query('SELECT password_hash FROM users WHERE id = $1', [(await params).id]);
if (u.rows.length === 0) {
return Response.json({ error: '用户不存在' }, { status: 404 });
}
const valid = await bcrypt.compare(password, u.rows[0].password_hash);
if (!valid) {
return Response.json({ error: '密码错误' }, { status: 400 });
}
const existing = await pool.query('SELECT id FROM users WHERE email = $1 AND id != $2', [newEmail, (await params).id]);
if (existing.rows.length > 0) {
return Response.json({ error: '邮箱已被占用' }, { status: 400 });
}
await pool.query('UPDATE users SET email = $1 WHERE id = $2', [newEmail, (await params).id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '修改失败,请稍后重试' }, { status: 500 });
}
}
+34
View File
@@ -0,0 +1,34 @@
// PUT /api/users/[id]/password — 修改密码
import bcrypt from 'bcryptjs';
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
if ((await params).id !== user.id) {
return Response.json({ error: '无权限' }, { status: 403 });
}
const { oldPassword, newPassword } = await req.json();
if (!oldPassword || !newPassword) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
if (newPassword.length < 6) {
return Response.json({ error: '新密码至少6位' }, { status: 400 });
}
try {
const u = await pool.query('SELECT password_hash FROM users WHERE id = $1', [(await params).id]);
if (u.rows.length === 0) {
return Response.json({ error: '用户不存在' }, { status: 404 });
}
const valid = await bcrypt.compare(oldPassword, u.rows[0].password_hash);
if (!valid) {
return Response.json({ error: '当前密码错误' }, { status: 400 });
}
const hash = await bcrypt.hash(newPassword, 10);
await pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, (await params).id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '修改失败,请稍后重试' }, { status: 500 });
}
}
+30
View File
@@ -0,0 +1,30 @@
// PUT /api/users/[id]/role (admin 改角色)
import pool from '@/lib/db';
import { getUser, isSuperAdmin, requireAdmin } from '@/lib/auth';
export async function PUT(req, { params }) {
const { id } = await params;
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
const { role } = await req.json();
if (!['user', 'admin'].includes(role)) {
return Response.json({ error: '无效的角色' }, { status: 400 });
}
if (id === user.id) {
return Response.json({ error: '不能修改自己的角色' }, { status: 400 });
}
try {
if (role !== 'admin' && await isSuperAdmin(id)) {
return Response.json({ error: '不能降级超级管理员' }, { status: 403 });
}
await pool.query('UPDATE users SET role = $1 WHERE id = $2', [role, id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+50
View File
@@ -0,0 +1,50 @@
// PUT /api/users/[id] (更新资料), PUT /api/users/[id]/role (改角色)
import pool from '@/lib/db';
import { getUser, isSuperAdmin, requireAdmin } from '@/lib/auth';
export async function PUT(req, { params }) {
const { id } = await params;
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const body = await req.json();
const { username, bio, signature, role } = body;
// 改角色:仅管理员
if (role !== undefined) {
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
if (!['user', 'admin'].includes(role)) {
return Response.json({ error: '无效的角色' }, { status: 400 });
}
if (id === user.id) {
return Response.json({ error: '不能修改自己的角色' }, { status: 400 });
}
// 超级管理员不能被降级(兼容旧的角色更新入口)
if (role !== 'admin' && await isSuperAdmin(id)) {
return Response.json({ error: '不能降级超级管理员' }, { status: 403 });
}
try {
await pool.query('UPDATE users SET role = $1 WHERE id = $2', [role, id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
// 更新资料:仅本人
if (id !== user.id) {
return Response.json({ error: '无权限修改他人资料' }, { status: 403 });
}
try {
await pool.query('UPDATE users SET username = $1, bio = $2, signature = $3 WHERE id = $4', [username, bio || '', signature || '', id]);
return Response.json({ success: true });
} catch (err) {
if (err.code === '23505') {
return Response.json({ error: '用户名已被占用' }, { status: 400 });
}
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+22
View File
@@ -0,0 +1,22 @@
// GET /api/users/profile/:username — 用户公开信息(无需登录,用于用户主页)
import pool from '@/lib/db';
import { jsonWithEtag } from '@/lib/http-cache';
export async function GET(req, { params }) {
const { username } = await params;
if (!username) {
return Response.json({ error: '缺少用户名' }, { status: 400 });
}
try {
const r = await pool.query(
'SELECT id, username, avatar_url, bio, role, signature, created_at FROM users WHERE username = $1',
[username]
);
if (r.rows.length === 0) {
return Response.json({ error: '用户不存在' }, { status: 404 });
}
return jsonWithEtag(req, r.rows[0]);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+31
View File
@@ -0,0 +1,31 @@
// GET /api/users (admin) — 支持 ?username= 按用户名查询
import pool from '@/lib/db';
import { getUser, getSuperAdminId, requireAdmin } from '@/lib/auth';
export async function GET(req) {
const user = getUser(req);
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
const url = new URL(req.url);
const username = url.searchParams.get('username');
try {
// 超级管理员 = 最早注册的 admin(对齐迁移:无 admin 时自动提升最早注册用户)
const superAdminId = await getSuperAdminId();
let query = 'SELECT id, username, avatar_url, bio, role, created_at FROM users';
const params = [];
if (username) {
query += ' WHERE username = $1';
(await params).push(username);
}
query += ' ORDER BY created_at DESC';
const r = await pool.query(query, params);
// 标记超级管理员(前端显示"超级管理员")
const rows = r.rows.map((u) => ({ ...u, is_super: u.id === superAdminId }));
return Response.json(rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
File diff suppressed because it is too large. Load diff
+59
View File
@@ -0,0 +1,59 @@
// 全局布局
import './globals.css';
import { cookies, headers } from 'next/headers';
import CustomCssLoader from '@/components/CustomCssLoader';
import { ToastProvider } from '@/components/Toast';
import I18nInit from '@/components/I18nInit';
export const metadata = {
// 初始标题用默认论坛名(AppProvider 加载期轮换 Loading.,完成后覆盖为真实名)。
// 注意:不能设 'Loading...' —— Next.js 客户端重渲染会重置 <title> 为 metadata 值,
// 导致加载完成后标题又变回 "Loading..."。
title: 'Forumlify',
description: 'Forumlify - 简洁优雅的现代社区系统',
};
// cookies()/headers() 是动态 API:禁止静态优化
export const dynamic = 'force-dynamic';
export default async function RootLayout({ children }) {
// 语言检测:用户配置 cookie 优先,否则按浏览器 Accept-Language
let lng = 'zh';
try {
const cookieStore = await cookies();
const saved = cookieStore.get('forumlify-lang')?.value;
if (saved === 'en' || saved === 'zh') {
lng = saved;
} else {
const hdrs = await headers();
const accept = (hdrs.get('accept-language') || '').toLowerCase();
if (accept.startsWith('en')) lng = 'en';
}
} catch (e) { /* 默认 zh */ }
return (
<html lang={lng === 'en' ? 'en' : 'zh-CN'} suppressHydrationWarning>
<head>
</head>
<body>
{/* 首帧初始化(主题防 FOUC + 论坛名首帧显示):
script 放 body 首个子元素(children 前),React 官方防 FOUC 模式 */}
<script dangerouslySetInnerHTML={{ __html: `(function(){
try {
var t = localStorage.getItem('forumlify-theme');
if (!t) { t = (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; }
document.documentElement.setAttribute('data-theme', t);
} catch (e) {}
try { var n = localStorage.getItem('forumlify-forum-name'); if (n) document.title = n; } catch (e) {}
// 加载页论坛名不再由脚本注入 DOM——由 Server Component 读 cookie 首帧输出,
// React 状态渲染,SSR/客户端一致,无 hydration mismatch
})();` }} />
<ToastProvider>
<I18nInit lng={lng} />
<CustomCssLoader />
{children}
</ToastProvider>
</body>
</html>
);
}
+9
View File
@@ -0,0 +1,9 @@
// 主页:Server Component,路径页面共用同一个客户端应用外壳。
import ForumPage from './ForumPage';
// cookies() 是动态 API:禁止静态优化,每次请求 SSR
export const dynamic = 'force-dynamic';
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 />;
}
+14
View File
@@ -0,0 +1,14 @@
coverage:
status:
project:
default:
target: auto
threshold: 1%
patch:
default:
target: auto
threshold: 1%
ignore:
- "test/**"
- "scripts/**"
+76
View File
@@ -0,0 +1,76 @@
'use client';
// 账户安全:修改密码 + 修改邮箱
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { useToast } from './Toast';
export default function AccountSecurity() {
const { currentUser } = useApp();
const { t } = useTranslation();
const { toast } = useToast();
const [oldPassword, setOldPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [pwStatus, setPwStatus] = useState(null);
const [emailPassword, setEmailPassword] = useState('');
const [newEmail, setNewEmail] = useState('');
const [emailStatus, setEmailStatus] = useState(null);
const changePassword = async () => {
if (!oldPassword || !newPassword) { toast(t('security.fillAll'), 'warning'); return; }
if (newPassword.length < 6) { toast(t('security.pwMin'), 'warning'); return; }
try {
await API.updatePassword(currentUser.id, oldPassword, newPassword);
setPwStatus({ ok: true, msg: t('security.pwChanged') });
setOldPassword('');
setNewPassword('');
} catch (err) {
setPwStatus({ ok: false, msg: err.message });
}
};
const changeEmail = async () => {
if (!emailPassword || !newEmail) { toast(t('security.fillAll'), 'warning'); return; }
try {
await API.updateEmail(currentUser.id, emailPassword, newEmail);
setEmailStatus({ ok: true, msg: t('security.emailChanged') });
setEmailPassword('');
setNewEmail('');
} catch (err) {
setEmailStatus({ ok: false, msg: err.message });
}
};
return (
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<h3 style={{ fontSize: 16, marginBottom: 12 }}><Icon name="lock" size={16} /> {t('security.title')}</h3>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>{t('security.currentPw')}</label>
<input type="password" value={oldPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setOldPassword(e.target.value)} />
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>{t('security.newPw')}</label>
<input type="password" value={newPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewPassword(e.target.value)} />
</div>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changePassword}>{t('security.changePw')}</button>
{pwStatus && <div style={{ fontSize: 13, marginTop: 6, color: pwStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={pwStatus.ok ? 'success' : 'error'} size={14} /> {pwStatus.msg}</div>}
<div style={{ borderTop: '1px solid var(--border)', margin: '16px 0' }}></div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>{t('security.currentPwVerify')}</label>
<input type="password" value={emailPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setEmailPassword(e.target.value)} />
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>{t('security.newEmail')}</label>
<input type="email" value={newEmail} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewEmail(e.target.value)} />
</div>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changeEmail}>{t('security.changeEmail')}</button>
{emailStatus && <div style={{ fontSize: 13, marginTop: 6, color: emailStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={emailStatus.ok ? 'success' : 'error'} size={14} /> {emailStatus.msg}</div>}
</div>
);
}
+63
View File
@@ -0,0 +1,63 @@
'use client';
// 管理后台:侧边栏布局(对齐上游 main 分支)
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Icon } from './Icons';
import AdminReports from './admin/AdminReports';
import AdminUsers from './admin/AdminUsers';
import AdminLogs from './admin/AdminLogs';
import AdminLinks from './admin/AdminLinks';
import AdminForumSettings from './admin/AdminForumSettings';
import AdminCustomPages from './admin/AdminCustomPages';
import AdminCustomCss from './admin/AdminCustomCss';
const NAV = [
{ key: 'reports', labelKey: 'admin.reports', icon: 'shieldAlert' },
{ key: 'users', labelKey: 'admin.users', icon: 'users' },
{ key: 'logs', labelKey: 'admin.logs', icon: 'file' },
{ key: 'links', labelKey: 'admin.links', icon: 'link' },
{ key: 'settings', labelKey: 'admin.forumSettings', icon: 'settings' },
{ key: 'custom', labelKey: 'admin.customPages', icon: 'file' },
{ key: 'css', labelKey: 'admin.customCss', icon: 'file' },
];
export default function AdminPage() {
const { t } = useTranslation();
const [tab, setTab] = useState('reports');
return (
<div className="page-slide active">
<div className="page-header" style={{ maxWidth: 1200, margin: '0 auto', width: '100%' }}>
<h2><Icon name="shieldAlert" size={20} /> {t('admin.title')}</h2>
</div>
<div className="admin-layout" style={{ maxWidth: 1200, margin: '0 auto', width: '100%' }}>
<aside className="admin-sidebar">
<nav className="admin-nav">
{NAV.map((n) => (
<a
key={n.key}
href="#"
className={'admin-nav-item' + (tab === n.key ? ' active' : '')}
data-tab={n.key}
onClick={(e) => { e.preventDefault(); setTab(n.key); }}
>
<span className="nav-icon"><Icon name={n.icon} size={18} /></span>
{t(n.labelKey)}
</a>
))}
</nav>
</aside>
<main className="admin-content" id="adminContent">
{tab === 'reports' && <AdminReports />}
{tab === 'users' && <AdminUsers />}
{tab === 'logs' && <AdminLogs />}
{tab === 'links' && <AdminLinks />}
{tab === 'custom' && <AdminCustomPages />}
{tab === 'css' && <AdminCustomCss />}
{tab === 'settings' && <AdminForumSettings />}
</main>
</div>
</div>
);
}
+912
View File
@@ -0,0 +1,912 @@
'use client';
// 全局状态 Provider:用户、主题、论坛名、当前视图(feed/post/new/admin/...)
import { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react';
import { flushSync } from 'react-dom';
import { API, getTheme, setToken, getToken } from '@/lib/api';
const AppContext = createContext(null);
const POST_TRANSITION_PARTS = [
['.post-avatar', 'post-avatar'],
['.post-username', 'post-author'],
['.post-title', 'post-heading'],
['.post-time', 'post-time'],
['.post-content', 'post-body'],
['.post-images', 'post-media'],
['.post-pin-state', 'post-pin-state'],
['.post-edited-label', 'post-edited-label'],
['.post-actions', 'post-feed-actions'],
];
function namePostTransitionParts(card) {
if (!card) return [];
return POST_TRANSITION_PARTS.flatMap(([selector, name]) => {
const element = card.querySelector(selector);
if (!element) return [];
element.style.viewTransitionName = name;
return [element];
});
}
function clearPostTransitionParts(elements) {
elements.forEach((element) => {
element.style.viewTransitionName = '';
});
}
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();
return new Promise((resolve) => {
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
clearTimeout(timeout);
resolve();
};
const timeout = setTimeout(finish, 1200);
Promise.all(images.map((image) => image.decode?.().catch(() => {}) || Promise.resolve())).then(finish);
});
}
function stageSharedGeometry(transition, {
name,
duration,
moveOffset,
moveEasing = 'cubic-bezier(0.16, 1, 0.3, 1)',
resizeEasing = 'cubic-bezier(0.4, 0, 0.2, 1)',
reverse = false,
}) {
transition.ready.then(() => {
const groupAnimation = document.getAnimations().find(
(animation) => animation.effect?.pseudoElement === `::view-transition-group(${name})`
);
const frames = groupAnimation?.effect?.getKeyframes();
if (!groupAnimation || !frames || frames.length < 2) return;
const start = frames[0];
const end = frames[frames.length - 1];
groupAnimation.effect.setKeyframes(reverse ? [
{
offset: 0,
width: start.width,
height: start.height,
transform: start.transform,
easing: resizeEasing,
},
{
offset: 1 - moveOffset,
width: start.width,
height: end.height,
transform: start.transform,
easing: moveEasing,
},
{
offset: 1,
width: end.width,
height: end.height,
transform: end.transform,
},
] : [
{
offset: 0,
width: start.width,
height: start.height,
transform: start.transform,
easing: moveEasing,
},
{
offset: moveOffset,
width: end.width,
height: start.height,
transform: end.transform,
easing: resizeEasing,
},
{
offset: 1,
width: end.width,
height: end.height,
transform: end.transform,
},
]);
groupAnimation.effect.updateTiming({ duration, easing: 'linear', fill: 'both' });
}).catch(() => {});
}
function stagePostBodyGeometry(transition, {
duration,
moveOffset,
moveEasing = 'cubic-bezier(0.42, 0, 0.58, 1)',
resizeEasing = 'cubic-bezier(0.42, 0, 0.58, 1)',
}) {
transition.ready.then(() => {
const animations = document.getAnimations();
const cardAnimation = animations.find(
(animation) => animation.effect?.pseudoElement === '::view-transition-group(post-expand)'
);
const bodyAnimation = animations.find(
(animation) => animation.effect?.pseudoElement === '::view-transition-group(post-body)'
);
const cardFrames = cardAnimation?.effect?.getKeyframes();
const bodyFrames = bodyAnimation?.effect?.getKeyframes();
if (!bodyAnimation || !cardFrames || cardFrames.length < 2 || !bodyFrames || bodyFrames.length < 2) return;
const cardStart = cardFrames[0];
const cardEnd = cardFrames[cardFrames.length - 1];
const bodyStart = bodyFrames[0];
const bodyEnd = bodyFrames[bodyFrames.length - 1];
const cardStartMatrix = new DOMMatrixReadOnly(cardStart.transform);
const cardEndMatrix = new DOMMatrixReadOnly(cardEnd.transform);
const bodyStartMatrix = new DOMMatrixReadOnly(bodyStart.transform);
const bodyEndMatrix = new DOMMatrixReadOnly(bodyEnd.transform);
const startCardWidth = Number.parseFloat(cardStart.width);
const endCardWidth = Number.parseFloat(cardEnd.width);
const startBodyWidth = Number.parseFloat(bodyStart.width);
if (![startCardWidth, endCardWidth, startBodyWidth].every(Number.isFinite)) return;
// 第一阶段让正文锁定在卡片内的原始位置;卡片停稳后,正文才调整到详情布局。
const leftInset = bodyStartMatrix.e - cardStartMatrix.e;
const topInset = bodyStartMatrix.f - cardStartMatrix.f;
const rightInset = startCardWidth - leftInset - startBodyWidth;
const midpointWidth = Math.max(0, endCardWidth - leftInset - rightInset);
const midpointTransform = new DOMMatrix([
bodyEndMatrix.a,
bodyEndMatrix.b,
bodyEndMatrix.c,
bodyEndMatrix.d,
cardEndMatrix.e + leftInset,
cardEndMatrix.f + topInset,
]).toString();
bodyAnimation.effect.setKeyframes([
{
offset: 0,
width: bodyStart.width,
height: bodyStart.height,
transform: bodyStart.transform,
easing: moveEasing,
},
{
offset: moveOffset,
width: `${midpointWidth}px`,
height: bodyStart.height,
transform: midpointTransform,
easing: resizeEasing,
},
{
offset: 1,
width: bodyEnd.width,
height: bodyEnd.height,
transform: bodyEnd.transform,
},
]);
bodyAnimation.effect.updateTiming({ duration, easing: 'linear', fill: 'both' });
}).catch(() => {});
}
export function useApp() {
return useContext(AppContext);
}
export default function AppProvider({ children, cachedName = '' }) {
const [currentUser, setCurrentUser] = useState(null);
// 论坛名初始值来自 cookie(SSR 首帧即输出,SSR/客户端一致 → 无 hydration mismatch)
const [forumName, setForumName] = useState(cachedName || 'Forumlify');
const [theme, setThemeState] = useState('light');
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom
const [currentPostId, setCurrentPostId] = useState(null);
const [currentPostPreview, setCurrentPostPreview] = useState(null);
const [currentPostOrigin, setCurrentPostOrigin] = useState(null);
const [currentUsername, setCurrentUsername] = useState(null);
const [currentUserPreview, setCurrentUserPreview] = useState(null);
const [currentUserPostsPreview, setCurrentUserPostsPreview] = useState(null);
const [currentPageName, setCurrentPageName] = useState(null);
const [sort, setSort] = useState('latest');
const [refreshKey, setRefreshKey] = useState(0);
const [ready, setReady] = useState(false); // 初始加载完成标记(控制加载页/淡入)
// 有 cookie 缓存名即视为已加载(SSR/客户端一致)
const [forumNameLoaded, setForumNameLoaded] = useState(!!cachedName);
const loadedRef = useRef(false);
const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);
// 论坛名写 cookie(SSR 可读 → 首帧输出,无需内联脚本注入 DOM)
const syncForumNameCookie = useCallback((name) => {
try {
document.cookie = 'forumlify-name=' + encodeURIComponent(name) + '; path=/; max-age=31536000';
} catch (e) {}
}, []);
// 主题
useEffect(() => {
const t = getTheme();
setThemeState(t);
document.documentElement.setAttribute('data-theme', t);
// 系统主题变化时跟随(仅当用户未手动设置过)
const mq = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
if (mq && mq.addEventListener) {
const onSysChange = () => {
if (!localStorage.getItem('forumlify-theme')) {
const next = mq.matches ? 'dark' : 'light';
setThemeState(next);
document.documentElement.setAttribute('data-theme', next);
}
};
mq.addEventListener('change', onSysChange);
return () => mq.removeEventListener('change', onSysChange);
}
}, []);
// 论坛名变化时同步浏览器标题(覆盖初始化/数据库加载/改名三条路径)
useEffect(() => {
document.title = forumName;
const titleEl = document.querySelector('title');
if (titleEl) titleEl.textContent = forumName;
}, [forumName]);
const toggleTheme = useCallback(() => {
setThemeState((prev) => {
const next = prev === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', next);
localStorage.setItem('forumlify-theme', next);
return next;
});
}, []);
// 初始化:读取缓存论坛名(立即显示),恢复登录、加载服务器论坛名
useEffect(() => {
// 缓存论坛名(hydrate 后立即生效;SSR 首帧已由 cookie 输出)
try {
const cached = localStorage.getItem('forumlify-forum-name');
if (cached) {
setForumName(cached);
setForumNameLoaded(true);
syncForumNameCookie(cached);
}
} catch (e) {}
if (loadedRef.current) return;
loadedRef.current = true;
async function init() {
const token = getToken();
if (token) {
try {
const user = await API.getMe();
setCurrentUser(user);
} catch {
setToken(null);
}
}
try {
const s = await API.getSettings();
if (s.forum_name) {
setForumName(s.forum_name);
localStorage.setItem('forumlify-forum-name', s.forum_name);
syncForumNameCookie(s.forum_name);
}
// 先标记论坛名已收到(加载页原地淡入名字),稍后切换主页
setForumNameLoaded(true);
setTimeout(() => setReady(true), 650);
} catch {
setForumNameLoaded(true);
setReady(true);
}
}
init();
}, []);
// 页面标题:初始化中轮换 Loading. → Loading.. → Loading...,收到论坛名/完成后显示论坛名
useEffect(() => {
// 尚未收到论坛名且未完成初始化:轮换 Loading.
if (!ready && !forumNameLoaded) {
const seq = ['Loading.', 'Loading..', 'Loading...'];
let i = 0;
document.title = seq[0];
const t = setInterval(() => {
i = (i + 1) % seq.length;
document.title = seq[i];
}, 1000);
return () => {
clearInterval(t);
};
}
// 已收到论坛名或初始化完成:标题显示论坛名(Next 重置 metadata 时也能恢复)
document.title = forumName;
const titleEl = document.querySelector('title');
if (titleEl) titleEl.textContent = forumName;
}, [ready, forumNameLoaded, forumName]);
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 = clearLegacyPageParams(new URL(window.location));
url.pathname = pathForPage(page);
const commitNavigation = (refreshFeed = true) => {
window.history.pushState({ page }, '', url);
setView(page);
setCurrentPostId(null);
setCurrentPostPreview(null);
setCurrentPostOrigin(null);
setCurrentUsername(null);
setCurrentUserPreview(null);
setCurrentUserPostsPreview(null);
if (refreshFeed) refresh();
};
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;
}
if (view === 'user') {
const root = document.documentElement;
const sourceAvatar = document.querySelector('#pageUser .user-profile-avatar');
const sourceName = document.querySelector('#pageUser .user-profile-name');
const findTargetCard = () => {
if (currentUserPreview?.sourcePostId) {
const exact = Array.from(document.querySelectorAll('[data-post-ref], [data-post-id]')).find(
(element) => postCardMatches(element, currentUserPreview.sourcePostId)
);
if (exact) return exact;
}
return Array.from(document.querySelectorAll('[data-username]')).find(
(element) => element.dataset.username === String(currentUsername || '')
) || null;
};
let targetCard = findTargetCard();
if (sourceAvatar && sourceName && targetCard) {
let targetAvatar = null;
let targetName = null;
root.classList.add('user-view-transition', 'returning-user-home');
const transition = document.startViewTransition(() => {
flushSync(() => commitNavigation(false));
targetCard = findTargetCard();
targetAvatar = targetCard?.querySelector('.post-avatar') || null;
targetName = targetCard?.querySelector('.post-username') || null;
if (targetAvatar) targetAvatar.style.viewTransitionName = 'user-avatar';
if (targetName) targetName.style.viewTransitionName = 'user-name';
});
const clearTargetNames = () => {
if (targetAvatar) targetAvatar.style.viewTransitionName = '';
if (targetName) targetName.style.viewTransitionName = '';
};
transition.ready.then(clearTargetNames, clearTargetNames);
transition.finished.finally(() => {
root.classList.remove('user-view-transition', 'returning-user-home');
refresh();
});
return;
}
}
let targetCard = 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');
if (targetCard) document.documentElement.classList.add('returning-home');
const transition = document.startViewTransition(() => {
flushSync(() => commitNavigation(false));
targetCard = 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);
});
stageSharedGeometry(transition, {
name: 'post-expand',
duration: 1100,
moveOffset: 0.73,
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
resizeEasing: 'cubic-bezier(0.16, 1, 0.3, 1)',
reverse: true,
});
stageSharedGeometry(transition, {
name: 'post-body',
duration: 1100,
moveOffset: 0.73,
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
resizeEasing: 'cubic-bezier(0.16, 1, 0.3, 1)',
reverse: true,
});
const clearTargetNames = () => {
if (targetCard) targetCard.style.viewTransitionName = '';
clearPostTransitionParts(targetParts);
};
transition.ready.then(clearTargetNames, clearTargetNames);
transition.finished.finally(() => {
document.documentElement.classList.remove('home-view-transition', 'returning-home');
refresh();
});
}, [currentPostId, currentUser, currentUsername, currentUserPreview, refresh, view]);
const openPost = useCallback((postId, sourceElement = null, preview = null, origin = null) => {
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: postRef, origin: historyOrigin }, '', url);
setView('post');
setCurrentPostId(postRef);
setCurrentPostPreview(preview);
setCurrentPostOrigin(resolvedOrigin);
setCurrentUserPreview(null);
setCurrentUserPostsPreview(null);
};
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
if (!sourceElement || !document.startViewTransition || reduceMotion) {
commitNavigation();
return;
}
document.documentElement.classList.remove('post-transition-settled');
sourceElement.style.viewTransitionName = 'post-expand';
const sourceParts = namePostTransitionParts(sourceElement);
document.documentElement.classList.add('post-view-transition');
const transition = document.startViewTransition(async () => {
flushSync(commitNavigation);
await waitForPostImages(document.querySelector('#pagePost .post-detail-card'));
});
stageSharedGeometry(transition, {
name: 'post-expand',
duration: 960,
moveOffset: 0.62,
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
resizeEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
});
stagePostBodyGeometry(transition, {
duration: 960,
moveOffset: 0.62,
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
resizeEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
});
const clearSourceNames = () => {
sourceElement.style.viewTransitionName = '';
clearPostTransitionParts(sourceParts);
};
transition.ready.then(clearSourceNames, clearSourceNames);
transition.finished.finally(() => {
const root = document.documentElement;
root.classList.remove('post-view-transition');
root.classList.add('post-transition-settled');
window.setTimeout(() => root.classList.remove('post-transition-settled'), 220);
});
}, [view]);
const returnFromPost = useCallback(() => {
if (currentPostOrigin?.view !== 'user' || !currentPostOrigin.username) {
navigate('feed');
return;
}
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');
setCurrentUsername(currentPostOrigin.username);
setCurrentUserPreview(currentPostOrigin.user || { username: currentPostOrigin.username });
setCurrentUserPostsPreview(currentPostOrigin.posts || []);
setCurrentPostId(null);
setCurrentPostPreview(null);
};
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
const sourceCard = document.querySelector('#pagePost .post-detail-card');
if (!sourceCard || !document.startViewTransition || reduceMotion) {
commitNavigation();
return;
}
const root = document.documentElement;
let targetCard = null;
let targetParts = [];
root.classList.add('home-view-transition', 'returning-home', 'returning-user-post');
const transition = document.startViewTransition(() => {
flushSync(commitNavigation);
const userPage = document.getElementById('pageUser');
if (userPage) userPage.scrollTop = currentPostOrigin.scrollTop || 0;
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);
});
stageSharedGeometry(transition, {
name: 'post-expand',
duration: 1100,
moveOffset: 0.73,
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
resizeEasing: 'cubic-bezier(0.16, 1, 0.3, 1)',
reverse: true,
});
stageSharedGeometry(transition, {
name: 'post-body',
duration: 1100,
moveOffset: 0.73,
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
resizeEasing: 'cubic-bezier(0.16, 1, 0.3, 1)',
reverse: true,
});
const clearTargetNames = () => {
if (targetCard) targetCard.style.viewTransitionName = '';
clearPostTransitionParts(targetParts);
};
transition.ready.then(clearTargetNames, clearTargetNames);
transition.finished.finally(() => {
root.classList.remove('home-view-transition', 'returning-home', 'returning-user-post');
setCurrentPostOrigin(null);
});
}, [currentPostId, currentPostOrigin, navigate]);
const openUser = useCallback((username, source = null, preview = null) => {
const url = clearLegacyPageParams(new URL(window.location));
url.pathname = pathForUser(username);
const commitNavigation = () => {
window.history.pushState({ page: 'user', username }, '', url);
setView('user');
setCurrentUsername(username);
setCurrentUserPreview(preview || { username });
setCurrentPostId(null);
setCurrentPostPreview(null);
setCurrentPostOrigin(null);
setCurrentUserPostsPreview(null);
};
const avatarElement = source?.avatarElement;
const nameElement = source?.nameElement;
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
if (!avatarElement || !nameElement || !document.startViewTransition || reduceMotion) {
commitNavigation();
return;
}
const root = document.documentElement;
root.classList.remove('user-transition-settled');
root.classList.add('user-view-transition');
avatarElement.style.viewTransitionName = 'user-avatar';
nameElement.style.viewTransitionName = 'user-name';
const transition = document.startViewTransition(() => {
flushSync(commitNavigation);
});
const clearSourceNames = () => {
avatarElement.style.viewTransitionName = '';
nameElement.style.viewTransitionName = '';
};
transition.ready.then(clearSourceNames, clearSourceNames);
transition.finished.finally(() => {
root.classList.remove('user-view-transition');
root.classList.add('user-transition-settled');
window.setTimeout(() => root.classList.remove('user-transition-settled'), 320);
});
}, []);
const openCustomPage = useCallback((pageName) => {
const url = clearLegacyPageParams(new URL(window.location));
url.pathname = pathForCustomPage(pageName);
window.history.pushState({ page: 'custom', pageName }, '', url);
setView('custom');
setCurrentPageName(pageName);
setCurrentUserPreview(null);
}, []);
// 浏览器前进后退
useEffect(() => {
const onPop = (e) => {
const state = e.state || {};
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);
if (result.user) {
setCurrentUser(result.user);
}
return result;
}, []);
const register = useCallback(async (email, password, username, captcha) => {
const result = await API.register(email, password, username, captcha);
const loginResult = await API.login(email, password);
if (loginResult.user) {
setCurrentUser(loginResult.user);
}
return result;
}, []);
const logout = useCallback(() => {
API.logout();
setCurrentUser(null);
navigate('feed');
}, [navigate]);
const updateForumName = useCallback((name) => {
setForumName(name);
localStorage.setItem('forumlify-forum-name', name);
syncForumNameCookie(name);
}, [syncForumNameCookie]);
const value = {
currentUser, setCurrentUser,
forumName, forumNameLoaded, updateForumName,
theme, toggleTheme,
view, navigate,
currentPostId, currentPostPreview, currentPostOrigin, openPost, returnFromPost,
currentUsername, currentUserPreview, currentUserPostsPreview, openUser,
currentPageName, openCustomPage,
sort, setSort,
refreshKey, refresh,
ready,
login, register, logout,
};
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
}
+68
View File
@@ -0,0 +1,68 @@
'use client';
// 图片验证码:用 canvas 绘制算式(带噪点/干扰线,挡一部分人机)
// 点击图片可刷新验证码
import { useEffect, useRef } from 'react';
export default function CaptchaImage({ captcha, onRefresh }) {
const canvasRef = useRef(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas || !captcha) return;
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
// 背景(半透明玻璃感)
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = 'rgba(91, 155, 213, 0.10)';
ctx.fillRect(0, 0, W, H);
// 干扰线
for (let i = 0; i < 4; i++) {
ctx.strokeStyle = `rgba(${80 + Math.random() * 120}, ${80 + Math.random() * 120}, 200, ${0.2 + Math.random() * 0.3})`;
ctx.lineWidth = 1 + Math.random();
ctx.beginPath();
ctx.moveTo(Math.random() * W, Math.random() * H);
ctx.lineTo(Math.random() * W, Math.random() * H);
ctx.stroke();
}
// 噪点
for (let i = 0; i < 30; i++) {
ctx.fillStyle = `rgba(${Math.random() * 200}, ${Math.random() * 200}, 220, ${0.3 + Math.random() * 0.5})`;
ctx.beginPath();
ctx.arc(Math.random() * W, Math.random() * H, 1 + Math.random() * 1.5, 0, Math.PI * 2);
ctx.fill();
}
// 算式文字(每个字符轻微旋转/位移,增加识别难度)
const text = (captcha.text || captcha.question || '').replace(' = ?', '');
const chars = text.split('');
const fontSize = Math.floor(H * 0.52);
const step = W / (chars.length + 1);
chars.forEach((ch, i) => {
ctx.save();
ctx.translate(step * (i + 1) + (Math.random() - 0.5) * 6, H / 2 + (Math.random() - 0.5) * 6);
ctx.rotate((Math.random() - 0.5) * 0.25);
ctx.font = `bold ${fontSize}px -apple-system, "SF Pro Display", "Segoe UI", Roboto, sans-serif`;
ctx.fillStyle = `rgba(${40 + Math.random() * 60}, ${50 + Math.random() * 50}, 90, 0.9)`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(ch, 0, 0);
ctx.restore();
});
}, [captcha]);
return (
<canvas
ref={canvasRef}
width={120}
height={40}
onClick={onRefresh}
title="看不清?点击刷新"
style={{ cursor: 'pointer', borderRadius: 6, border: '1px solid var(--glass-border)', verticalAlign: 'middle' }}
/>
);
}
+17
View File
@@ -0,0 +1,17 @@
'use client';
// 加载自定义 CSS(管理员上传的 style.css,覆盖默认样式)
import { useEffect } from 'react';
export default function CustomCssLoader() {
useEffect(() => {
// 尝试加载 /api/custom-css;404 表示未设置,静默跳过
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/api/custom-css';
link.id = 'custom-css-link';
document.head.appendChild(link);
}, []);
return null;
}
+61
View File
@@ -0,0 +1,61 @@
'use client';
// 自定义页面:以 iframe srcdoc 渲染 HTML 内容(与原版一致)
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
export default function CustomPage({ pageName }) {
const [html, setHtml] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
setHtml(null);
setError(null);
API.getCustomPage(pageName)
.then((page) => setHtml(page.content))
.catch((err) => setError(err.message));
}, [pageName]);
if (error) {
return (
<div style={{ padding: '84px 32px', textAlign: 'center', color: '#ef4444' }}>
页面加载失败:{error}
</div>
);
}
if (html === null) {
return <div style={{ padding: '84px 32px', textAlign: 'center', color: '#94a3b8' }}><span className="spinner-sm" />加载中...</div>;
}
const srcdoc = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
padding: 24px;
background: var(--bg, #f6f8fc);
color: var(--text, #0a0e1a);
}
@media (prefers-color-scheme: dark) {
body { background: #0f1117; color: #e8edf5; }
}
</style>
</head>
<body>${html}</body>
</html>`;
return (
<div className="custom-page-container" style={{ padding: '84px 32px 40px', background: 'var(--bg)', minHeight: '100vh' }}>
<iframe
style={{ width: '100%', minHeight: '70vh', border: 'none', borderRadius: 8, background: 'var(--surface)' }}
sandbox="allow-scripts allow-modals allow-same-origin"
srcDoc={srcdoc}
title={pageName}
/>
</div>
);
}
+277
View File
@@ -0,0 +1,277 @@
'use client';
// 信息流:帖子列表 + 排序 tab + 发布新帖按钮
import { useEffect, useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import ImageViewer from './ImageViewer';
import { renderMarkdown } from '@/lib/markdown';
import { useToast } from './Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
'&background=6366f1&color=fff&size=64';
}
export default function Feed({ onOpenModal, onReport }) {
const { currentUser, sort, setSort, openPost, openUser, navigate, refreshKey } = useApp();
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [posts, setPosts] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [viewerSrc, setViewerSrc] = useState(null);
const [selectedSort, setSelectedSort] = useState(sort);
const [drawerPhase, setDrawerPhase] = useState('closed');
const postListRef = useRef(null);
const sortTimerRef = useRef(null);
const pendingSortRef = useRef(null);
const initialDrawerOpenedRef = useRef(false);
const PAGE_SIZE = 20;
const load = useCallback(async (targetPage) => {
setError(null);
try {
const result = await API.getPosts(sort, null, targetPage, PAGE_SIZE);
setPosts(result.data || []);
setTotalPages(result.pagination?.totalPages || 1);
setPage(result.pagination?.page || 1);
} catch (err) {
setError(err.message);
setPosts([]);
} finally {
if (pendingSortRef.current === sort) {
requestAnimationFrame(() => {
setDrawerPhase('opening');
sortTimerRef.current = setTimeout(() => {
pendingSortRef.current = null;
setDrawerPhase('idle');
}, 360);
});
} else if (!initialDrawerOpenedRef.current) {
// 首次加载:先在收起状态完成列表渲染,再像排序切换一样抽屉式展开。
// Feed 在 SPA 视图间保持挂载,因此从帖子/用户页返回时不会重复播放。
initialDrawerOpenedRef.current = true;
requestAnimationFrame(() => {
setDrawerPhase('opening');
sortTimerRef.current = setTimeout(() => setDrawerPhase('idle'), 360);
});
}
}
}, [sort, refreshKey]);
useEffect(() => { load(page); }, [load]);
// 长帖内容:超过 3 行时加 .has-fade(底部渐变遮罩提示还有更多内容)
useEffect(() => {
if (!posts || posts.length === 0 || !postListRef.current) return;
const els = postListRef.current.querySelectorAll('.post-content');
els.forEach((el) => {
if (el.scrollHeight > el.clientHeight + 4) {
el.classList.add('has-fade');
} else {
el.classList.remove('has-fade');
}
});
}, [posts]);
// 排序切换时回第一页
useEffect(() => { setPage(1); }, [sort]);
useEffect(() => () => clearTimeout(sortTimerRef.current), []);
const handleSortChange = (nextSort) => {
if (nextSort === selectedSort) return;
setSelectedSort(nextSort);
clearTimeout(sortTimerRef.current);
// 快速切回当前排序时,直接重新展开尚未替换的列表。
if (nextSort === sort) {
pendingSortRef.current = null;
setDrawerPhase('opening');
sortTimerRef.current = setTimeout(() => setDrawerPhase('idle'), 360);
return;
}
setDrawerPhase('closing');
sortTimerRef.current = setTimeout(() => {
pendingSortRef.current = nextSort;
setDrawerPhase('closed');
setSort(nextSort);
}, 220);
};
const handleDelete = async (postId) => {
if (!await confirmAction(t('feed.confirmDelete'))) return;
try {
await API.deletePost(postId);
load(page);
} catch (err) {
toast(t('feed.deleteFailed', { msg: err.message }), 'error');
}
};
const handleOpenUser = (event, post) => {
event.stopPropagation();
const header = event.currentTarget.closest('.post-header');
openUser(
post.username,
{
avatarElement: header?.querySelector('.post-avatar'),
nameElement: header?.querySelector('.post-username'),
},
{
username: post.username,
avatar_url: post.avatar_url || avatar(post.username),
sourcePostId: post.id,
}
);
};
return (
<main id="feed">
<div className="feed-header">
<div className="feed-header-left">
<button className={'tab' + (selectedSort === 'latest' ? ' active' : '')} onClick={() => handleSortChange('latest')}>{t('feed.latest')}</button>
<button className={'tab' + (selectedSort === 'hot' ? ' active' : '')} onClick={() => handleSortChange('hot')}>{t('feed.hot')}</button>
</div>
<button
className="btn-primary fab-btn"
onClick={() => {
if (!currentUser) { toast(t('newPost.pleaseLogin'), 'warning'); return; }
navigate('new');
}}
>
<Icon name="plus" /> {t('feed.newPost')}
</button>
</div>
<div className={'feed-posts-drawer ' + drawerPhase}>
<div className="feed-posts-drawer-inner">
<div id="postList" ref={postListRef}>
{posts === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />{t('feed.loading')}</div>
) : error ? (
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>{t('feed.loadFailed', { msg: error })}</div>
) : posts.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>{t('feed.empty')}</div>
) : (
posts.map((p) => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
return (
<div key={p.id} className="post-card" data-post-id={p.id} 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>
)}
<div className="post-header">
<img
src={p.avatar_url || avatar(p.username)}
className="post-avatar"
alt={p.username || t('feed.anonymous')}
role="button"
tabIndex={0}
style={{ cursor: 'pointer' }}
onClick={(e) => handleOpenUser(e, p)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handleOpenUser(e, p);
}
}}
/>
<span
className="post-username"
style={{ cursor: 'pointer', color: 'var(--primary)' }}
onClick={(e) => handleOpenUser(e, p)}
>
{p.username || t('feed.anonymous')}
</span>
<span className="post-time">{time}</span>
{p.edited_at && (
<span className="post-edited-state" style={{ fontSize: 11, color: 'var(--text-light)', marginLeft: 6 }}>
<span className="post-edited-label">{t('feed.deleted')}</span>
</span>
)}
</div>
<div className="post-title">{p.title || t('feed.noTitle')}</div>
<div className="post-content" dangerouslySetInnerHTML={{ __html: renderMarkdown(p.content) }} />
{p.images && p.images.length > 0 && (
<div className="post-images">
{p.images.map((img, i) => (
<img key={i} src={img} className="post-image" alt="" style={{ cursor: 'pointer' }} onClick={(e) => { e.stopPropagation(); setViewerSrc(img); }} />
))}
</div>
)}
<div className="post-actions">
<span>
<Icon name="message" size={14} /> {p.reply_count || 0}
</span>
<button className="action-report" onClick={(e) => {
e.stopPropagation();
if (!currentUser) { toast(t('newPost.pleaseLogin'), 'warning'); return; }
onReport(p.id);
}}>
<Icon name="flag" size={14} /> {t('feed.report')}
</button>
{currentUser && (currentUser.id === p.user_id || currentUser.role === 'admin') && (
<button className="action-delete" onClick={(e) => {
e.stopPropagation();
handleDelete(p.id);
}}>
<Icon name="trash" size={14} /> {t('feed.delete')}
</button>
)}
</div>
</div>
);
})
)}
</div>
</div>
</div>
{totalPages > 1 && posts && posts.length > 0 && (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 6, padding: '16px 0', marginTop: 8, borderTop: '1px solid var(--border)', flexWrap: 'wrap' }}>
<button
className="page-btn"
disabled={page <= 1}
onClick={() => load(page - 1)}
style={{ padding: '6px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', color: 'var(--text)', cursor: page <= 1 ? 'not-allowed' : 'pointer', fontSize: 13, opacity: page <= 1 ? 0.4 : 1 }}
>
&laquo;
</button>
{Array.from({ length: totalPages }, (_, i) => i + 1).map((i) => (
<button
key={i}
className="page-btn"
disabled={i === page}
onClick={() => load(i)}
style={{
padding: '6px 10px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 13, minWidth: 32, textAlign: 'center',
background: i === page ? 'var(--primary)' : 'var(--surface)',
color: i === page ? '#fff' : 'var(--text)',
cursor: i === page ? 'default' : 'pointer',
borderColor: i === page ? 'var(--primary)' : 'var(--border)',
}}
>
{i}
</button>
))}
<button
className="page-btn"
disabled={page >= totalPages}
onClick={() => load(page + 1)}
style={{ padding: '6px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', color: 'var(--text)', cursor: page >= totalPages ? 'not-allowed' : 'pointer', fontSize: 13, opacity: page >= totalPages ? 0.4 : 1 }}
>
&raquo;
</button>
</div>
)}
{viewerSrc && <ImageViewer src={viewerSrc} onClose={() => setViewerSrc(null)} />}
</main>
);
}
+12
View File
@@ -0,0 +1,12 @@
'use client';
// i18n 客户端 Provider:在 children 渲染前同步初始化 i18n
// - lng 由 Server Component(layout)从 cookie / Accept-Language 推导传入
// - 同步 init(initImmediate:false)→ SSR 与客户端首次渲染语言一致,无 hydration mismatch
import { initI18n } from '@/lib/i18n';
export default function I18nProvider({ lng, children }) {
// 函数体在 children 渲染前执行:useTranslation 组件拿到已初始化的 i18n
initI18n(lng);
return <>{children}</>;
}
+200
View File
@@ -0,0 +1,200 @@
'use client';
// 图标库 — SVG 内容逐字符提取自旧版 index.html (Feather Icons),与原版一致
const S = {
xmlns: 'http://www.w3.org/2000/svg', width: 16, height: 16, viewBox: '0 0 24 24',
fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round',
style: { display: 'inline', verticalAlign: 'middle' },
};
export function Icon({ name, size = 16, ...rest }) {
return <svg {...S} width={size} height={size} {...rest}>{PATHS[name] || null}</svg>;
}
const PATHS = {
message: (
<>
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
</>
),
reply: (
<>
<path d="M9 14l-4-4 4-4"/><path d="M5 10h11a4 4 0 0 1 4 4v0"/>
</>
),
chevronDown: (
<>
<path d="M6 9l6 6 6-6"/>
</>
),
settings: (
<>
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>
</>
),
shieldAlert: (
<>
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/>
</>
),
user: (
<>
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
</>
),
lock: (
<>
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
</>
),
moon: (
<>
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
</>
),
sun: (
<>
<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
</>
),
logout: (
<>
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>
</>
),
book: (
<>
<path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><line x1="18" y1="12" x2="18" y2="12"/>
</>
),
link: (
<>
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
</>
),
plus: (
<>
<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
</>
),
shield: (
<>
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
</>
),
users: (
<>
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
</>
),
file: (
<>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/>
</>
),
plus2: (
<>
<path d="M12 5v14"/><path d="M5 12h14"/>
</>
),
back: (
<>
<polyline points="15 18 9 12 15 6"/>
</>
),
close: (
<>
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
</>
),
trash: (
<>
<polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
</>
),
success: (
<>
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>
</>
),
error: (
<>
<circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>
</>
),
warning: (
<>
<path d="M12 9v4"/><path d="M12 17h.01"/><circle cx="12" cy="12" r="10"/>
</>
),
pending: (
<>
<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
</>
),
edit: (
<>
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
</>
),
pin: (
<>
<path d="M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8.5"/><polyline points="16 2 22 8 16 8"/><line x1="10" y1="14" x2="18" y2="14"/><line x1="10" y1="18" x2="14" y2="18"/>
</>
),
camera: (
<>
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/>
</>
),
image: (
<>
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>
</>
),
key: (
<>
<path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>
</>
),
calendar: (
<>
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
</>
),
refresh: (
<>
<polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
</>
),
list: (
<>
<line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/>
</>
),
megaphone: (
<>
<path d="M17 18.5c0 1.5-1.5 3-3.5 3s-3.5-1.5-3.5-3c0-.5.5-1 1-1h5c.5 0 1 .5 1 1z"/><path d="M4 11h16v6H4z"/><path d="M8 17v3"/><path d="M16 17v3"/><path d="M9 11V7a3 3 0 0 1 6 0v4"/>
</>
),
code: (
<>
<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>
</>
),
upload: (
<>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>
</>
),
save: (
<>
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/>
</>
),
flag: (
<>
<path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/>
</>
),
};
+35
View File
@@ -0,0 +1,35 @@
'use client';
// 图片查看器(点击帖子图片放大)
import { useEffect } from 'react';
export default function ImageViewer({ src, onClose }) {
useEffect(() => {
const onKey = (e) => { if (e.key === 'Escape') onClose(); };
document.addEventListener('keydown', onKey);
return () => document.removeEventListener('keydown', onKey);
}, [onClose]);
return (
<div
className="modal active"
style={{
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.85)', zIndex: 9999,
display: 'flex', alignItems: 'center', justifyContent: 'center',
cursor: 'pointer', animation: 'fadeIn 0.2s ease-out',
}}
onClick={onClose}
>
<img
src={src}
alt=""
style={{
maxWidth: '90vw', maxHeight: '90vh', objectFit: 'contain',
borderRadius: 8, boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
cursor: 'default', userSelect: 'none',
}}
onClick={(e) => e.stopPropagation()}
/>
</div>
);
}
+19
View File
@@ -0,0 +1,19 @@
'use client';
// 全屏加载页:初始化未完成时显示转圈,加载完成后淡出
// 论坛名:容器由 React 渲染(SSR 即有),内联脚本在 DOMContentLoaded 时
// 填充缓存名 → 首帧显示;suppressHydrationWarning 让 React 跳过该元素
// 的文本检查(保留脚本填入的内容),hydrate 后由 AppProvider 状态接管。
export default function LoadingScreen({ forumName, forumNameLoaded }) {
return (
<div className="loading-screen">
<div className="loading-inner">
<div className="loading-spinner" />
<div className={'loading-title' + (forumNameLoaded ? ' loading-title-appear' : '')} id="loadingTitle" suppressHydrationWarning>
{forumNameLoaded && forumName}
</div>
<div className="loading-sub">加载中...</div>
</div>
</div>
);
}
+67
View File
@@ -0,0 +1,67 @@
'use client';
// 消息页:通知列表(回复/删除/举报处理/系统)
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
const TYPE_MAP = { reply: 'message', post_deleted: 'trash', report_handled: 'shield', system: 'megaphone' };
export default function MessagesPage() {
const { currentUser } = useApp();
const [notifications, setNotifications] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
if (!currentUser) return;
API.getNotifications()
.then((data) => {
setNotifications(data || []);
setError(null);
API.markAllNotificationsRead().catch(() => {});
})
.catch((e) => { setError(e.message); setNotifications([]); });
}, [currentUser]);
if (!currentUser) {
return <div className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>请先登录</div>;
}
return (
<div className="page-slide active">
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<h2><Icon name="message" size={20} /> 消息</h2>
</div>
<div style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
{error ? (
<div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>
) : notifications === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
) : notifications.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>
<Icon name="message" size={48} />
<p style={{ fontSize: 16 }}>暂无消息</p>
<p style={{ fontSize: 13 }}>当有人回复你的帖子或处理你的举报时,会在这里通知你</p>
</div>
) : (
notifications.map((n) => {
const icon = TYPE_MAP[n.type] || 'pin';
const time = n.created_at ? new Date(n.created_at).toLocaleString('zh-CN') : '';
return (
<div key={n.id} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px', borderBottom: '1px solid var(--border-light)', background: 'var(--surface)', borderRadius: 6, marginBottom: 6 }}>
<span style={{ color: 'var(--text-secondary)', paddingTop: 2 }}><Icon name={icon} size={20} /></span>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 14 }}>{n.title}</div>
<div style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 2 }}>{n.content}</div>
{n.link && <a href={n.link} style={{ color: 'var(--primary)', fontSize: 13, textDecoration: 'none', marginTop: 4, display: 'inline-block' }}>查看详情 →</a>}
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 4 }}>{time}</div>
</div>
</div>
);
})
)}
</div>
</div>
);
}
+237
View File
@@ -0,0 +1,237 @@
'use client';
// 登录/注册/举报 模态框
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import CaptchaImage from './CaptchaImage';
import { useToast } from './Toast';
export default function Modals({ modal, onClose, reportPostId }) {
const { login, register, currentUser, refresh } = useApp();
const { t } = useTranslation();
const { toast } = useToast();
// 登录表单
const [loginEmail, setLoginEmail] = useState('');
const [loginPassword, setLoginPassword] = useState('');
const [authMode, setAuthMode] = useState('login');
const [resetEmail, setResetEmail] = useState('');
const [resetRecoveryCode, setResetRecoveryCode] = useState('');
const [resetPassword, setResetPassword] = useState('');
const [resetPasswordConfirm, setResetPasswordConfirm] = useState('');
// 注册表单
const [regUsername, setRegUsername] = useState('');
const [regEmail, setRegEmail] = useState('');
const [regPassword, setRegPassword] = useState('');
const [regCaptcha, setRegCaptcha] = useState(null);
const [regCaptchaInput, setRegCaptchaInput] = useState('');
// 举报表单
const [reportReason, setReportReason] = useState('spam');
// 打开注册弹窗时从服务器获取验证码挑战(HMAC 签名)
useEffect(() => {
if (modal === 'register') {
API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {});
}
if (modal !== 'login') {
setAuthMode('login');
setResetEmail('');
setResetRecoveryCode('');
setResetPassword('');
setResetPasswordConfirm('');
}
}, [modal]);
if (!modal) return null;
const close = (e) => {
if (e && e.target !== e.currentTarget) return;
onClose();
};
const handleLogin = async () => {
if (!loginEmail.trim() || !loginPassword) { toast('请填写完整信息', 'warning'); return; }
try {
const result = await login(loginEmail.trim(), loginPassword);
if (result.user) {
onClose();
setLoginEmail('');
setLoginPassword('');
refresh();
}
} catch (err) {
toast('登录失败:' + err.message, 'error');
}
};
const handleResetPassword = async () => {
if (!resetEmail.trim() || !resetRecoveryCode.trim() || !resetPassword || !resetPasswordConfirm) {
toast(t('auth.resetFillAll'), 'warning');
return;
}
if (resetPassword.length < 6) {
toast(t('auth.passwordTooShort'), 'warning');
return;
}
if (resetPassword !== resetPasswordConfirm) {
toast(t('auth.passwordMismatch'), 'warning');
return;
}
try {
await API.resetPassword(resetEmail.trim(), resetRecoveryCode.trim(), resetPassword);
setAuthMode('login');
setLoginEmail(resetEmail.trim());
setLoginPassword('');
setResetEmail('');
setResetRecoveryCode('');
setResetPassword('');
setResetPasswordConfirm('');
toast(t('auth.resetSuccess'), 'success');
} catch (err) {
toast(t('auth.resetFailed', { msg: err.message }), 'error');
}
};
const returnToLogin = () => {
setAuthMode('login');
setResetEmail('');
setResetRecoveryCode('');
setResetPassword('');
setResetPasswordConfirm('');
};
const handleRegister = async () => {
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { toast('请填写完整信息', 'warning'); return; }
if (regPassword.length < 6) { toast('密码至少6位', 'warning'); return; }
if (!regCaptcha || !regCaptchaInput.trim()) {
toast('请填写验证码', 'warning');
return;
}
try {
// 答案由服务端 HMAC 校验,前端不对比答案
await register(regEmail.trim(), regPassword, regUsername.trim(), { id: regCaptcha.id, answer: regCaptchaInput.trim(), sig: regCaptcha.sig });
onClose();
setRegUsername('');
setRegEmail('');
setRegPassword('');
setRegCaptchaInput('');
toast('注册成功!', 'success');
refresh();
} catch (err) {
toast('注册失败:' + err.message, 'error');
// 失败后刷新验证码
API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {});
setRegCaptchaInput('');
}
};
const handleReport = async () => {
if (!reportPostId) return;
try {
await API.createReport(reportPostId, reportReason);
onClose();
toast('举报已提交,管理员将尽快处理', 'success');
} catch (err) {
toast('举报失败:' + err.message, 'error');
}
};
return (
<>
{modal === 'login' && authMode === 'login' && (
<div className="modal active" onClick={close}>
<div className="modal-content">
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}>{t('auth.login')}</h2>
<input type="email" placeholder={t('auth.email')} value={loginEmail} onChange={(e) => setLoginEmail(e.target.value)} />
<input type="password" placeholder={t('auth.password')} value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') handleLogin(); }} />
<button className="btn-primary" style={{ width: '100%' }} onClick={handleLogin}>{t('auth.login')}</button>
<button
type="button"
className="auth-forgot-link"
onClick={() => {
setResetEmail(loginEmail);
setAuthMode('forgot');
}}
>
{t('auth.forgotPassword')}
</button>
</div>
</div>
)}
{modal === 'login' && authMode === 'forgot' && (
<div className="modal active" onClick={close}>
<div className="modal-content">
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}>{t('auth.resetTitle')}</h2>
<p className="auth-reset-hint">{t('auth.resetHint')}</p>
<input type="email" placeholder={t('auth.email')} value={resetEmail} onChange={(e) => setResetEmail(e.target.value)} />
<input type="text" placeholder={t('auth.recoveryCode')} value={resetRecoveryCode} onChange={(e) => setResetRecoveryCode(e.target.value)} />
<input type="password" placeholder={t('auth.newPassword')} value={resetPassword} onChange={(e) => setResetPassword(e.target.value)} />
<input
type="password"
placeholder={t('auth.confirmPassword')}
value={resetPasswordConfirm}
onChange={(e) => setResetPasswordConfirm(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') handleResetPassword(); }}
/>
<button className="btn-primary" style={{ width: '100%' }} onClick={handleResetPassword}>{t('auth.resetPassword')}</button>
<button type="button" className="auth-forgot-link" onClick={returnToLogin}>
{t('auth.backToLogin')}
</button>
</div>
</div>
)}
{modal === 'register' && (
<div className="modal active" onClick={close}>
<div className="modal-content">
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}>{t('auth.register')}</h2>
<input type="text" placeholder={t('auth.username')} value={regUsername} onChange={(e) => setRegUsername(e.target.value)} />
<input type="email" placeholder={t('auth.email')} value={regEmail} onChange={(e) => setRegEmail(e.target.value)} />
<input type="password" placeholder={t('auth.passwordHint')} value={regPassword} onChange={(e) => setRegPassword(e.target.value)} />
<div className="captcha-row" style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '12px 0' }}>
{regCaptcha ? (
<CaptchaImage captcha={regCaptcha} onRefresh={() => { API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {}); setRegCaptchaInput(''); }} />
) : (
<span style={{ color: 'var(--text-light)' }}>{t('newPost.captchaLoading')}</span>
)}
<input type="text" placeholder="答案" style={{ width: 80, background: 'var(--bg)', color: 'var(--text)', border: '1px solid var(--border)', padding: '8px 12px', borderRadius: 4 }} value={regCaptchaInput} onChange={(e) => setRegCaptchaInput(e.target.value)} />
</div>
<button className="btn-primary" style={{ width: '100%' }} onClick={handleRegister}>{t('auth.register')}</button>
</div>
</div>
)}
{modal === 'report' && currentUser && (
<div className="modal active" onClick={close}>
<div className="modal-content">
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}><Icon name="shieldAlert" size={20} /> {t('post.reportTitle')}</h2>
<p style={{ fontSize: 14, color: '#64748b', marginBottom: 12 }}>{t('post.reportReason')}</p>
<select
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, marginBottom: 16, background: 'var(--bg)', color: 'var(--text)' }}
value={reportReason}
onChange={(e) => setReportReason(e.target.value)}
>
<option value="spam">{t('report.spam')}</option>
<option value="abuse">{t('report.abuse')}</option>
<option value="illegal">{t('report.illegal')}</option>
<option value="nsfw">{t('report.nsfw')}</option>
<option value="other">{t('report.other')}</option>
</select>
<button className="btn-primary" style={{ width: '100%' }} onClick={handleReport}>{t('post.submitReport')}</button>
</div>
</div>
)}
</>
);
}
+140
View File
@@ -0,0 +1,140 @@
'use client';
// 导航栏:论坛名、自定义页面链接、登录/注册、私信、用户菜单、主题切换
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { API } from '@/lib/api';
import { DMButton } from './chat/ChatManager';
import { useToast } from './Toast';
export default function Navbar({ onOpenModal }) {
const { currentUser, forumName, theme, toggleTheme, navigate, openCustomPage, logout } = useApp();
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [menuOpen, setMenuOpen] = useState(false);
const [customPages, setCustomPages] = useState([]);
useEffect(() => {
API.getCustomPages().then(setCustomPages).catch(() => {});
}, []);
// 点击菜单外部关闭下拉(检查目标是否在菜单/头像内,避免 React 合成事件与原生监听冲突)
useEffect(() => {
const closeMenu = (e) => {
const menu = document.getElementById('userDropdown');
const avatarEl = document.getElementById('userDropdown')?.querySelector('.avatar');
if (menu && menu.contains(e.target)) return;
if (avatarEl && avatarEl.contains(e.target)) return;
setMenuOpen(false);
};
document.addEventListener('click', closeMenu);
return () => document.removeEventListener('click', closeMenu);
}, []);
const avatarSrc = currentUser?.avatar_url ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') +
'&background=6366f1&color=fff';
const goPage = (page) => {
if (page === 'admin' && currentUser?.role !== 'admin') {
toast('无权限访问', 'warning');
return;
}
setMenuOpen(false);
navigate(page);
};
const openMessages = (e) => {
e.preventDefault();
setMenuOpen(false);
// 消息页展示通知列表,私信使用导航栏按钮。
navigate('messages');
};
return (
<nav id="navbar">
<div className="nav-left">
<span className="forum-name" onClick={() => navigate('feed')} style={{ cursor: 'pointer' }}>
{forumName}
</span>
<span id="customNavLinks" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginLeft: 16 }}>
{customPages.map((p) => (
<a
key={p.id}
href={'/' + encodeURIComponent(p.name)}
className="custom-page-nav-link"
data-custom={p.name}
onClick={(e) => { e.preventDefault(); openCustomPage(p.name); }}
style={{ color: 'var(--text-secondary)', textDecoration: 'none', fontSize: 14, padding: '4px 10px', borderRadius: 4, transition: 'color 0.15s' }}
onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--text)'; }}
onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--text-secondary)'; }}
>
{p.title}
</a>
))}
</span>
</div>
<div className="nav-right">
<DMButton />
<div id="userMenu">
{!currentUser ? (
<div id="authButtons">
<button className="btn-ghost" onClick={() => onOpenModal('login')}>{t('nav.login')}</button>
<button className="btn-primary" onClick={() => onOpenModal('register')}>{t('nav.register')}</button>
</div>
) : (
<div id="userDropdown" style={{ display: 'block' }}>
<img
className="avatar"
src={avatarSrc}
alt="avatar"
onClick={(e) => { e.stopPropagation(); setMenuOpen(!menuOpen); }}
/>
{menuOpen && (
<div className="dropdown-menu show" onClick={(e) => e.stopPropagation()}>
<a href="#" onClick={openMessages}>
<Icon name="message" /> {t('nav.messages')}
</a>
<a href="#" onClick={(e) => { e.preventDefault(); goPage('settings'); }}>
<Icon name="settings" /> {t('nav.settings')}
</a>
{currentUser.role === 'admin' && (
<a href="#" onClick={(e) => { e.preventDefault(); goPage('admin'); }}>
<Icon name="shieldAlert" /> {t('nav.admin')}
</a>
)}
<hr />
<a
href="#"
onClick={(e) => {
e.preventDefault();
toggleTheme();
setMenuOpen(false);
}}
>
<Icon name={theme === 'dark' ? 'sun' : 'moon'} /> {theme === 'dark' ? t('nav.lightMode') : t('nav.darkMode')}
</a>
<hr />
<a
href="#"
onClick={async (e) => {
e.preventDefault();
if (await confirmAction(t('nav.logoutConfirm'))) {
setMenuOpen(false);
logout();
}
}}
>
<Icon name="logout" /> {t('nav.logout')}
</a>
</div>
)}
</div>
)}
</div>
</div>
</nav>
);
}
+149
View File
@@ -0,0 +1,149 @@
'use client';
// 发帖页
import { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API, uploadImage } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { useToast } from './Toast';
import CaptchaImage from './CaptchaImage';
export default function NewPost() {
const { currentUser, navigate, refresh } = useApp();
const { t } = useTranslation();
const { toast } = useToast();
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [images, setImages] = useState([]); // 上传后的 URL 列表
const [previews, setPreviews] = useState([]); // 本地预览 dataURL
const [captcha, setCaptcha] = useState(null);
const [captchaInput, setCaptchaInput] = useState('');
const [uploading, setUploading] = useState(false);
useEffect(() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); }, []);
const handleFiles = async (files) => {
setUploading(true);
try {
const newPreviews = [];
for (const file of files) {
if (!file.type.startsWith('image/')) continue;
if (file.size > 5 * 1024 * 1024) {
toast('图片 ' + file.name + ' 超过 5MB,请压缩后上传', 'warning');
continue;
}
const dataUrl = await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.readAsDataURL(file);
});
newPreviews.push(dataUrl);
const url = await uploadImage(file);
setImages((prev) => [...prev, url]);
}
setPreviews((prev) => [...prev, ...newPreviews]);
} catch (err) {
toast('上传失败:' + err.message, 'error');
} finally {
setUploading(false);
}
};
// 拖拽上传
const [dragOver, setDragOver] = useState(false);
const fileInputRef = useRef(null);
const dropZoneStyle = {
border: '2px dashed ' + (dragOver ? 'var(--primary)' : 'var(--border)'),
borderRadius: 8, padding: 24, textAlign: 'center', cursor: 'pointer',
transition: 'all 0.3s', margin: '8px 0 12px',
background: dragOver ? 'var(--primary-bg)' : 'var(--bg)',
};
const handleSubmit = async () => {
if (!currentUser || !currentUser.id) {
toast('请先登录', 'error');
navigate('feed');
return;
}
if (!content.trim()) { toast('请填写内容', 'error'); return; }
if (!captcha || !captchaInput.trim()) { toast('请填写验证码', 'error'); return; }
try {
// 答案由服务端 HMAC 校验
await API.createPost(title.trim() || '无标题', content.trim(), images, { id: captcha.id, answer: captchaInput.trim(), sig: captcha.sig });
toast('发布成功', 'success');
navigate('feed');
refresh();
} catch (err) {
toast('发布失败:' + err.message, 'error');
}
};
return (
<div className="page-slide active">
<div className="page-header" style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
<h2><Icon name="plus" size={20} /> {t('newPost.title')}</h2>
</div>
<div style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
<input
type="text"
placeholder={t('newPost.title')}
style={{ width: '100%', padding: '10px 14px', border: '1.5px solid var(--border)', borderRadius: 6, fontSize: 15, fontWeight: 600, marginBottom: 12, fontFamily: 'inherit', background: 'var(--bg)', color: 'var(--text)' }}
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<textarea
rows={6}
placeholder={t('newPost.content')}
style={{ width: '100%', padding: 12, border: '1.5px solid var(--border)', borderRadius: 6, fontSize: 15, fontFamily: 'inherit', resize: 'vertical', background: 'var(--bg)', color: 'var(--text)' }}
value={content}
onChange={(e) => setContent(e.target.value)}
/>
<div id="imagePreview" style={{ display: 'flex', flexWrap: 'wrap', gap: 8, margin: '8px 0' }}>
{previews.map((src, i) => (
<img key={i} src={src} alt="" style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: 4, border: '1px solid var(--border)' }} />
))}
</div>
<div
id="dropZone"
style={dropZoneStyle}
onClick={() => fileInputRef.current?.click()}
onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
onDragLeave={(e) => { e.preventDefault(); setDragOver(false); }}
onDrop={(e) => { e.preventDefault(); setDragOver(false); if (e.dataTransfer.files) handleFiles(Array.from(e.dataTransfer.files)); }}
>
{!uploading && !dragOver && <Icon name="image" size={32} style={{ display: 'block', margin: '0 auto 8px', color: 'var(--text-secondary)' }} />}
<div style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
{uploading ? t('newPost.uploading') : (dragOver ? t('newPost.drop') : t('newPost.dropHint'))}
</div>
</div>
<input
type="file"
id="fileInput"
accept="image/*"
multiple
ref={fileInputRef}
style={{ display: 'none' }}
onChange={(e) => { if (e.target.files) handleFiles(Array.from(e.target.files)); }}
/>
<div className="captcha-row" style={{ margin: '12px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
{captcha ? (
<CaptchaImage captcha={captcha} onRefresh={() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); setCaptchaInput(''); }} />
) : (
<span style={{ color: 'var(--text-light)' }}>{t('newPost.captchaLoading')}</span>
)}
<input
type="text"
placeholder={t('newPost.answer')}
style={{ width: 80, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }}
value={captchaInput}
onChange={(e) => setCaptchaInput(e.target.value)}
/>
</div>
<button className="btn-primary" style={{ padding: '10px 32px', fontSize: 15 }} onClick={handleSubmit}>
{uploading ? t('newPost.uploading') : t('newPost.publish')}
</button>
</div>
</div>
);
}
+306
View File
@@ -0,0 +1,306 @@
'use client';
// 帖子详情页
import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
import { API, uploadImage } from '@/lib/api';
import { useApp } from './AppProvider';
import ReplyList from './ReplyList';
import Sidebar from './Sidebar';
import { Icon } from './Icons';
import ImageViewer from './ImageViewer';
import { renderMarkdown } from '@/lib/markdown';
import { useToast } from './Toast';
import { useTranslation } from 'react-i18next';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
'&background=6366f1&color=fff&size=64';
}
export default function PostDetail({ postId, initialPost = null }) {
const { currentUser, navigate, openUser, returnFromPost, refreshKey } = useApp();
const { t, i18n } = useTranslation();
const { toast, confirmAction } = useToast();
const [post, setPost] = useState(initialPost);
const [error, setError] = useState(null);
const [viewerSrc, setViewerSrc] = useState(null);
const [editing, setEditing] = useState(false);
const [editTitle, setEditTitle] = useState('');
const [editContent, setEditContent] = useState('');
const [editImages, setEditImages] = useState([]);
const [editUploading, setEditUploading] = useState(false);
const editImageInputRef = useRef(null);
// 评论抽屉:帖子加载完成后自动展开(动画完整播放)
const [repliesOpen, setRepliesOpen] = useState(false);
useEffect(() => {
if (post && !repliesOpen) {
// 延迟到帖子内容渲染后,让抽屉动画平滑播放
const t = setTimeout(() => setRepliesOpen(true), 60);
return () => clearTimeout(t);
}
}, [post]);
const load = useCallback(async () => {
setError(null);
try {
const data = await API.getPost(postId);
setPost(data);
} catch (err) {
setError(err.message);
}
}, [postId, refreshKey]);
const initialRefreshKey = useRef(refreshKey);
useEffect(() => {
const initialReference = initialPost?.post_number || initialPost?.id;
if (String(initialReference || '') === String(postId) && refreshKey === initialRefreshKey.current) return;
load();
}, [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]);
if (error) {
return (
<div id="pagePost" className="page-slide active" style={{ padding: '40px 0', textAlign: 'center', color: '#ef4444' }}>
加载失败:{error}
</div>
);
}
if (!post) {
return <div id="pagePost" className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8' }}><span className="spinner-sm" />加载中...</div>;
}
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
// 作者本人 或 管理员 可删除/编辑
const canDelete = currentUser && (currentUser.id === post.user_id || currentUser.role === 'admin');
const canEdit = currentUser && currentUser.id === post.user_id;
const handleDelete = async () => {
if (!await confirmAction('确定要删除这条帖子吗?')) return;
try {
await API.deletePost(postId);
toast('删除成功', 'success');
navigate('feed');
} catch (err) {
toast('删除失败:' + err.message, 'error');
}
};
const handleTogglePin = async () => {
if (!await confirmAction('确定要' + (post.is_pinned ? '取消' : '') + '置顶吗?', { danger: false })) return;
try {
await API.togglePinPost(postId);
load();
} catch (err) {
toast('操作失败:' + err.message, 'error');
}
};
const handleEdit = () => {
setEditTitle(post.title || '');
setEditContent(post.content || '');
setEditImages(post.images || []);
setEditing(true);
};
const handleSaveEdit = async () => {
if (!editContent.trim()) { toast('请填写内容', 'warning'); return; }
try {
await API.updatePost(postId, editTitle.trim() || '无标题', editContent.trim(), editImages);
setEditing(false);
load();
} catch (err) {
toast('编辑失败:' + err.message, 'error');
}
};
// 编辑时上传新图片
const handleEditUpload = async (file) => {
if (!file) return;
if (!file.type.startsWith('image/')) { toast('请选择图片文件', 'warning'); return; }
if (file.size > 5 * 1024 * 1024) { toast('图片不能超过 5MB', 'warning'); return; }
setEditUploading(true);
try {
const url = await uploadImage(file);
setEditImages((prev) => [...prev, url]);
} catch (err) {
toast('上传失败:' + err.message, 'error');
} finally {
setEditUploading(false);
}
};
// 编辑时删除图片
const handleEditRemoveImage = (url) => {
setEditImages((prev) => prev.filter((u) => u !== url));
};
const handleOpenUser = (event) => {
const header = event.currentTarget.closest('.post-header');
openUser(
post.username,
{
avatarElement: header?.querySelector('.post-avatar'),
nameElement: header?.querySelector('.post-username'),
},
{
username: post.username,
avatar_url: post.avatar_url || avatar(post.username),
sourcePostId: post.id,
}
);
};
return (
<div id="pagePost" className="page-slide active">
<div className="page-header post-page-header">
<button className="back-btn" onClick={returnFromPost}>
<Icon name="back" size={16} /> 返回
</button>
<h2>{post.title || '帖子详情'}</h2>
</div>
<div className="post-page-layout">
<Sidebar id="postSidebar" />
<div id="postDetailContent" className="post-page-main">
<div className="post-detail-card" data-username={post.username || ''}>
<div className="post-header">
<img
src={post.avatar_url || avatar(post.username)}
className="post-avatar"
alt={post.username || '匿名用户'}
role="button"
tabIndex={0}
style={{ cursor: 'pointer' }}
onClick={handleOpenUser}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
handleOpenUser(event);
}
}}
/>
<span
className="post-username"
style={{ cursor: 'pointer', color: 'var(--primary)' }}
onClick={handleOpenUser}
>
{post.username || '匿名用户'}
</span>
<span className="post-time">{time}</span>
{post.edited_at && (
<span className="post-edited-state" style={{ fontSize: 12, color: 'var(--text-light)', marginLeft: 8 }}>
<span className="post-edited-label">{t('feed.deleted')}</span>
<span className="post-edited-detail">
{' '}{new Date(post.edited_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN')}
</span>
</span>
)}
{post.is_pinned && (
<span className="post-pin-state" style={{ fontSize: 12, color: 'var(--primary)', marginLeft: 8, display: 'inline-flex', alignItems: 'center', gap: 3 }}><Icon name="pin" size={12} /> 置顶</span>
)}
<div className="post-detail-controls" style={{ display: 'flex', gap: 4, marginLeft: 'auto' }}>
{currentUser && currentUser.role === 'admin' && (
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleTogglePin}>
<Icon name="pin" size={12} /> {post.is_pinned ? '取消置顶' : '置顶'}
</button>
)}
{canEdit && (
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleEdit}>
<Icon name="edit" size={12} /> 编辑
</button>
)}
{canDelete && (
<button className="btn-sm btn-danger" style={{ padding: '4px 10px' }} onClick={handleDelete}>
<Icon name="trash" size={14} /> 删除
</button>
)}
</div>
</div>
<div className="post-content" dangerouslySetInnerHTML={{ __html: renderedContent }} />
{post.images && post.images.length > 0 && (
<div className="post-images">
{post.images.map((img, i) => (
<img key={i} src={img} className="post-image" alt="" style={{ cursor: 'pointer' }} onClick={() => setViewerSrc(img)} />
))}
</div>
)}
{post.signature && (
<div className="post-detail-signature" style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border-light)', fontSize: 12, color: 'var(--text-secondary)' }} dangerouslySetInnerHTML={{ __html: renderedSignature }} />
)}
</div>
<div style={{ maxWidth: 700, margin: '0 auto', width: '100%', marginTop: 16 }}>
{/* 评论抽屉:帖子加载完成后自动展开 */}
<div className={'replies-drawer' + (repliesOpen ? ' open' : '')}>
<div className="replies-drawer-inner">
<ReplyList postId={postId} onRefresh={load} />
</div>
</div>
</div>
</div>
</div>
{/* 编辑帖子 modal */}
{editing && (
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) setEditing(false); }}>
<div className="modal-content" style={{ maxWidth: 600, position: 'relative' }}>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={() => setEditing(false)}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}><Icon name="edit" size={20} /> 编辑帖子</h2>
<input
type="text"
placeholder="标题"
value={editTitle}
onChange={(e) => setEditTitle(e.target.value)}
style={{ width: '100%', padding: '10px 14px', border: '1px solid var(--border)', borderRadius: 6, fontSize: 15, fontWeight: 600, marginBottom: 12, background: 'var(--bg)', color: 'var(--text)' }}
/>
<textarea
rows={6}
placeholder="说点什么..."
value={editContent}
onChange={(e) => setEditContent(e.target.value)}
style={{ width: '100%', padding: 12, border: '1px solid var(--border)', borderRadius: 6, fontSize: 15, fontFamily: 'inherit', resize: 'vertical', background: 'var(--bg)', color: 'var(--text)' }}
/>
{/* 图片管理:查看/删除已有图片 + 上传新图片 */}
{editImages.length > 0 && (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 10 }}>
{editImages.map((img, i) => (
<div key={img + i} style={{ position: 'relative' }}>
<img src={img} alt="" style={{ width: 72, height: 72, objectFit: 'cover', borderRadius: 6, border: '1px solid var(--border)' }} />
<button
type="button"
title="删除图片"
onClick={() => handleEditRemoveImage(img)}
style={{ position: 'absolute', top: -6, right: -6, width: 20, height: 20, borderRadius: '50%', background: '#ef4444', color: '#fff', border: 'none', cursor: 'pointer', lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
><Icon name="close" size={12} /></button>
</div>
))}
</div>
)}
<div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
<button type="button" className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={() => editImageInputRef.current?.click()}>
{editUploading ? '上传中...' : <><Icon name="camera" size={14} /> 上传图片</>}
</button>
<input type="file" ref={editImageInputRef} accept="image/*" multiple style={{ display: 'none' }} onChange={(e) => { const files = e.target.files; if (files && files.length > 0) { [...files].forEach((f) => handleEditUpload(f)); e.target.value = ''; } }} />
</div>
<button className="btn-primary" style={{ padding: '10px 32px', fontSize: 15, marginTop: 12, width: '100%' }} onClick={handleSaveEdit}>保存</button>
</div>
</div>
)}
{/* 图片查看器 */}
{viewerSrc && <ImageViewer src={viewerSrc} onClose={() => setViewerSrc(null)} />}
</div>
);
}
+79
View File
@@ -0,0 +1,79 @@
'use client';
// 恢复码管理:查看 + 重新生成
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from './Icons';
import { useToast } from './Toast';
export default function RecoveryCodes() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [count, setCount] = useState(0);
const [modal, setModal] = useState(null); // null | {codes, isNew}
const [modalClosing, setModalClosing] = useState(false);
const closeModal = () => {
setModalClosing(true);
setTimeout(() => {
setModal(null);
setModalClosing(false);
}, 340);
};
const loadCount = () => {
API.getRecoveryCodeCount().then((d) => setCount(d.count || 0)).catch(() => {});
};
useEffect(loadCount, []);
const regenerate = async () => {
if (!await confirmAction(t('recovery.confirmRegenerate'))) return;
try {
const d = await API.generateRecoveryCodes();
setModal({ codes: d.codes || [], isNew: true });
loadCount();
} catch (err) {
toast(t('recovery.genFailed', { msg: err.message }), 'error');
}
};
const view = async () => {
try {
// 生成后直接展示;若已有恢复码则重新生成展示(与原版一致:查看即生成新码)
const d = await API.generateRecoveryCodes();
setModal({ codes: d.codes || [], isNew: false });
loadCount();
} catch (err) {
toast(t('recovery.fetchFailed', { msg: err.message }), 'error');
}
};
return (
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<h3 style={{ fontSize: 16, marginBottom: 8 }}><Icon name="key" size={16} /> {t('recovery.title')}</h3>
<p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>{t('recovery.desc')}</p>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={view}><Icon name="list" size={14} /> {t('recovery.view')}</button>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={regenerate}><Icon name="refresh" size={14} /> {t('recovery.regenerate')}</button>
</div>
<div id="recoveryCodesStatus" style={{ fontSize: 13, color: 'var(--text-light)', marginTop: 8 }}>{t('recovery.remaining', { count })}</div>
{modal && (
<div className={'modal active' + (modalClosing ? ' closing' : '')} style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) closeModal(); }}>
<div className="modal-content" style={{ maxWidth: 480, position: 'relative' }}>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={closeModal}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 12 }}>{modal.isNew ? t('recovery.newCodes') : t('recovery.title')}</h2>
<p style={{ fontSize: 13, color: '#ef4444', marginBottom: 12, display: 'flex', alignItems: 'flex-start', gap: 6 }}><Icon name="warning" size={14} /> {t('recovery.saveWarning')}</p>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
{modal.codes.map((c, i) => (
<code key={i} style={{ background: 'var(--bg)', padding: '8px 12px', borderRadius: 6, fontSize: 13, textAlign: 'center', userSelect: 'all' }}>{c}</code>
))}
</div>
<button className="btn-primary" style={{ width: '100%', padding: 10, marginTop: 16 }} onClick={closeModal}>{t('recovery.saved')}</button>
</div>
</div>
)}
</div>
);
}
+219
View File
@@ -0,0 +1,219 @@
'use client';
// 回复列表 + 发表回复表单
import { useEffect, useState, useCallback, useRef } from 'react';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { renderMarkdown } from '@/lib/markdown';
import CaptchaImage from './CaptchaImage';
import { useToast } from './Toast';
import { useTranslation } from 'react-i18next';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
'&background=6366f1&color=fff&size=64';
}
export default function ReplyList({ postId, onRefresh }) {
const { currentUser, openUser } = useApp();
const { toast, confirmAction } = useToast();
const { t } = useTranslation();
const [replies, setReplies] = useState(null);
const [loading, setLoading] = useState(true);
const [showLoading, setShowLoading] = useState(false);
const [content, setContent] = useState('');
const [captcha, setCaptcha] = useState(null);
const [captchaInput, setCaptchaInput] = useState('');
// 正在回复的用户(hover 回复按钮 → 回填到回复框)
const [replyTo, setReplyTo] = useState(null);
const replyAreaRef = useRef(null);
const replyInputRef = useRef(null);
const loadRequestRef = useRef(0);
// 点击"回复":记录目标回复 ID,滚动到回复框并聚焦
const startReply = (replyId) => {
setReplyTo(replyId);
setTimeout(() => {
replyAreaRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
replyInputRef.current?.focus();
}, 120);
};
const load = useCallback(async ({ reset = false } = {}) => {
const requestId = ++loadRequestRef.current;
if (reset) setReplies(null);
setLoading(true);
try {
const data = await API.getReplies(postId);
if (requestId !== loadRequestRef.current) return;
setReplies(data || []);
} catch {
if (requestId !== loadRequestRef.current) return;
setReplies([]);
} finally {
if (requestId === loadRequestRef.current) setLoading(false);
}
}, [postId]);
useEffect(() => {
load({ reset: true });
return () => { loadRequestRef.current += 1; };
}, [load]);
// 快请求不闪加载态;慢请求的加载动画由 CSS 等帖子 View Transition 结束后再淡入。
useEffect(() => {
if (!loading) {
setShowLoading(false);
return;
}
const timer = setTimeout(() => setShowLoading(true), 180);
return () => clearTimeout(timer);
}, [loading]);
useEffect(() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); }, [postId]);
const handleSubmit = async () => {
if (!currentUser) { toast('请先登录', 'warning'); return; }
if (!content.trim()) { toast('请填写回复内容', 'warning'); return; }
if (!captcha || !captchaInput.trim()) { toast('请填写验证码', 'warning'); return; }
try {
// 答案由服务端 HMAC 校验
await API.createReply(
postId,
content.trim(),
{ id: captcha.id, answer: captchaInput.trim(), sig: captcha.sig },
replyTo,
replyToObj?.username
);
setContent('');
setCaptchaInput('');
setReplyTo(null);
API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {});
load();
onRefresh();
} catch (err) {
toast('回复失败:' + err.message, 'error');
API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {});
setCaptchaInput('');
}
};
const handleDelete = async (replyId) => {
if (!await confirmAction('确定要删除这条回复吗?')) return;
try {
await API.deleteReply(replyId);
load();
} catch (err) {
toast('删除失败:' + err.message, 'error');
}
};
// 计算每条回复的嵌套深度(按 reply_to_id 精确追踪回复链)
const loadedReplies = replies || [];
const replyDepths = (() => {
const map = {};
const getDepth = (r) => {
if (map[r.id] !== undefined) return map[r.id];
if (!r.reply_to_id) { map[r.id] = 0; return 0; }
const parent = loadedReplies.find((x) => x.id === r.reply_to_id);
const d = parent ? getDepth(parent) + 1 : 0;
map[r.id] = d;
return d;
};
loadedReplies.forEach((r) => getDepth(r));
return map;
})();
// 正在回复的目标回复对象(用于显示 @用户名)
const replyToObj = replyTo ? loadedReplies.find((x) => x.id === replyTo) : null;
return (
<>
{loading && replies === null ? (
showLoading && (
<div className="reply-loading-state" role="status" aria-live="polite">
<span className="reply-loading-spinner" aria-hidden="true" />
<span>{t('reply.loading')}</span>
</div>
)
) : (
<>
<div className="post-reply-count" style={{ marginTop: 20, fontSize: 14, color: '#64748b' }}>
<Icon name="message" size={14} /> {loadedReplies.length} 条回复
</div>
<div style={{ marginTop: 12 }}>
{loadedReplies.length === 0 ? (
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}><Icon name="message" size={16} /> 还没有回复,快来发表第一条回复吧</div>
) : (
loadedReplies.map((r) => {
const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '';
const nestDepth = Math.min(replyDepths[r.id] || 0, 5);
return (
<div key={r.id} className="reply-item" data-username={r.username} data-reply-id={r.id} style={{ marginLeft: nestDepth ? nestDepth * 18 : 0 }}>
<div className="reply-header">
<img src={r.avatar_url || avatar(r.username)} className="reply-avatar" alt="" />
<span
className="reply-username"
style={{ cursor: 'pointer', color: 'var(--primary)' }}
onClick={() => openUser(r.username)}
>
{r.username || '匿名用户'}
</span>
<span className="reply-time">{rTime}</span>
<button className="reply-btn" onClick={() => startReply(r.id)} title="回复">
<Icon name="reply" size={13} />
</button>
{currentUser && (currentUser.id === r.user_id || currentUser.role === 'admin') && (
<button className="btn-sm btn-danger reply-delete-btn" onClick={() => handleDelete(r.id)}>
<Icon name="trash" size={12} /> 删除
</button>
)}
</div>
<div className="reply-content" dangerouslySetInnerHTML={{ __html: renderMarkdown(r.content) }} />
</div>
);
})
)}
</div>
</>
)}
<div id="replyArea" ref={replyAreaRef} style={{ marginTop: 24, borderTop: '1px solid var(--border)', paddingTop: 20 }}>
<h3 style={{ fontSize: 16, marginBottom: 12 }}><Icon name="message" size={16} /> 发表回复</h3>
{replyTo && replyToObj && (
<div className="reply-preview-bar">
<Icon name="reply" size={13} />
<span>回复</span>
<strong>@{replyToObj.username}</strong>
<button className="reply-preview-cancel" onClick={() => setReplyTo(null)}>取消</button>
</div>
)}
<textarea
ref={replyInputRef}
rows={3}
placeholder="写下你的回复..."
style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, fontFamily: 'inherit', resize: 'vertical', background: 'var(--bg)', color: 'var(--text)' }}
value={content}
onChange={(e) => setContent(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) handleSubmit(); }}
/>
<div className="captcha-row" style={{ margin: '10px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
{captcha ? (
<CaptchaImage captcha={captcha} onRefresh={() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); setCaptchaInput(''); }} />
) : (
<span style={{ color: 'var(--text-light)' }}>验证码加载中...</span>
)}
<input
type="text"
placeholder="答案"
style={{ width: 80, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }}
value={captchaInput}
onChange={(e) => setCaptchaInput(e.target.value)}
/>
</div>
<button className="btn-primary" style={{ padding: '8px 24px' }} onClick={handleSubmit}>提交回复</button>
</div>
</>
);
}
+98
View File
@@ -0,0 +1,98 @@
'use client';
// 个人设置页:侧边栏布局 + 上下滑动平滑切换
// - 三个面板纵向排列在滚动容器里,scroll-snap 每次滑动对齐一个面板
// - 点侧边栏导航 → 平滑滚动到对应面板;滚动结束 → 自动更新导航高亮
import { useState, useRef, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Icon } from './Icons';
import SettingsProfile from './SettingsProfile';
import AccountSecurity from './AccountSecurity';
import RecoveryCodes from './RecoveryCodes';
const NAV = [
{ key: 'profile', labelKey: 'settings.profile', icon: 'user' },
{ key: 'security', labelKey: 'settings.security', icon: 'shieldAlert' },
{ key: 'recovery', labelKey: 'settings.recovery', icon: 'lock' },
];
export default function SettingsPage() {
const { t } = useTranslation();
const [tab, setTab] = useState('profile');
const scrollRef = useRef(null);
const scrollTicking = useRef(false);
// 滚动结束(或对齐后)更新高亮
const handleScroll = useCallback(() => {
const el = scrollRef.current;
if (!el || scrollTicking.current) return;
scrollTicking.current = true;
requestAnimationFrame(() => {
scrollTicking.current = false;
const idx = Math.round(el.scrollTop / el.clientHeight);
const key = NAV[Math.min(Math.max(idx, 0), NAV.length - 1)]?.key;
if (key) setTab(key);
});
}, []);
// 点击导航 → 平滑滚动到对应面板
const goTo = (key, e) => {
if (e) e.preventDefault();
setTab(key);
const el = scrollRef.current;
if (!el) return;
const idx = NAV.findIndex((n) => n.key === key);
el.scrollTo({ top: idx * el.clientHeight, behavior: 'smooth' });
};
return (
<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>
<div className="settings-layout" style={{ width: '100%', display: 'flex', gap: 28, alignItems: 'flex-start', flex: 1, minHeight: 0 }}>
<aside className="settings-sidebar" style={{ width: 200, flexShrink: 0 }}>
<nav className="settings-nav">
{NAV.map((n) => (
<a
key={n.key}
href="#"
className={'settings-nav-item' + (tab === n.key ? ' active' : '')}
data-settings-tab={n.key}
onClick={(e) => goTo(n.key, e)}
>
<span className="nav-icon"><Icon name={n.icon} size={18} /></span>
{t(n.labelKey)}
</a>
))}
</nav>
</aside>
<main className="settings-content" id="settingsContent" style={{ overflow: 'hidden', padding: 0, alignSelf: 'stretch', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
<div
ref={scrollRef}
onScroll={handleScroll}
style={{
flex: 1,
minHeight: 0,
overflowY: 'auto',
scrollSnapType: 'y mandatory',
scrollBehavior: 'smooth',
scrollbarWidth: 'none',
msOverflowStyle: 'none',
}}
>
<div style={{ scrollSnapAlign: 'start', minHeight: '100%', padding: '20px 24px' }} data-panel="profile">
<SettingsProfile />
</div>
<div style={{ scrollSnapAlign: 'start', minHeight: '100%', padding: '20px 24px', borderTop: '1px solid var(--glass-border)' }} data-panel="security">
<AccountSecurity />
</div>
<div style={{ scrollSnapAlign: 'start', minHeight: '100%', padding: '20px 24px', borderTop: '1px solid var(--glass-border)' }} data-panel="recovery">
<RecoveryCodes />
</div>
</div>
</main>
</div>
</div>
);
}
+116
View File
@@ -0,0 +1,116 @@
'use client';
// 设置 - 个人资料(头像 + 用户名/简介/签名 + 语言)
import { useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API, uploadImage } from '@/lib/api';
import { useApp } from './AppProvider';
import { setAppLanguage } from '@/lib/i18n';
import { Icon } from './Icons';
import { useToast } from './Toast';
export default function SettingsProfile() {
const { currentUser, setCurrentUser } = useApp();
const { t, i18n } = useTranslation();
const { toast } = useToast();
const [username, setUsername] = useState(currentUser?.username || '');
const [bio, setBio] = useState(currentUser?.bio || '');
const [signature, setSignature] = useState(currentUser?.signature || '');
const [avatarUrl, setAvatarUrl] = useState(currentUser?.avatar_url || '');
const [avatarStatus, setAvatarStatus] = useState(null);
const avatarInputRef = useRef(null);
const handleAvatar = async (file) => {
if (!file) return;
if (!file.type.startsWith('image/')) { setAvatarStatus({ ok: false, msg: t('settings.avatarFileRequired') }); return; }
if (file.size > 5 * 1024 * 1024) { setAvatarStatus({ ok: false, msg: t('settings.avatarTooLarge') }); return; }
try {
const url = await uploadImage(file);
await API.updateAvatar(currentUser.id, url);
setAvatarUrl(url);
setCurrentUser({ ...currentUser, avatar_url: url });
setAvatarStatus({ ok: true, msg: t('settings.avatarUpdated') });
} catch (err) {
setAvatarStatus({ ok: false, msg: err.message });
}
};
const handleSave = async () => {
if (!currentUser) { toast(t('settings.pleaseLogin'), 'warning'); return; }
if (!username.trim()) { toast(t('settings.usernameRequired'), 'warning'); return; }
try {
const data = await API.updateProfile(currentUser.id, username.trim(), bio.trim(), signature.trim());
if (data.error) throw new Error(data.error);
setCurrentUser({ ...currentUser, username: username.trim(), bio: bio.trim(), signature: signature.trim() });
toast(t('settings.saved'), 'success');
} catch (err) {
toast(t('settings.saveFailed', { msg: err.message }), 'error');
}
};
const avatarSrc = avatarUrl ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') + '&background=6366f1&color=fff&size=128';
return (
<div>
{/* 头像 */}
<div style={{ textAlign: 'center', marginBottom: 24 }}>
<div style={{ position: 'relative', display: 'inline-block' }}>
<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()}
aria-label={t('settings.changeAvatar')}
title={t('settings.changeAvatar')}
>
<Icon name="camera" size={16} />
</button>
</div>
<input type="file" ref={avatarInputRef} accept="image/*" style={{ display: 'none' }} onChange={(e) => { if (e.target.files?.[0]) handleAvatar(e.target.files[0]); }} />
<h2 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>
)}
</div>
{/* 基本资料 */}
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<div style={{ marginBottom: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.username')}</label>
<input type="text" value={username} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setUsername(e.target.value)} />
</div>
<div style={{ marginBottom: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.bio')}</label>
<textarea rows={3} value={bio} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }} onChange={(e) => setBio(e.target.value)} />
</div>
<div style={{ marginBottom: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.signature')} <span style={{ color: 'var(--text-light)', fontWeight: 400 }}>({t('settings.signatureHint')})</span></label>
<textarea rows={2} value={signature} placeholder={t('settings.signaturePlaceholder')} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical', fontFamily: 'inherit' }} onChange={(e) => setSignature(e.target.value)} />
</div>
<button className="btn-primary" style={{ width: '100%', padding: 10 }} onClick={handleSave}>{t('settings.save')}</button>
</div>
{/* 语言设置 */}
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20, marginTop: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 8 }}>{t('settings.language')}</label>
<div className="feed-header-left language-toggle" style={{ display: 'inline-flex' }}>
<button
className={'tab' + (i18n.language.startsWith('zh') ? ' active' : '')}
aria-pressed={i18n.language.startsWith('zh')}
onClick={() => setAppLanguage('zh')}
>
{t('settings.languageZh')}
</button>
<button
className={'tab' + (i18n.language.startsWith('en') ? ' active' : '')}
aria-pressed={i18n.language.startsWith('en')}
onClick={() => setAppLanguage('en')}
>
{t('settings.languageEn')}
</button>
</div>
</div>
</div>
);
}
+58
View File
@@ -0,0 +1,58 @@
'use client';
// 侧边栏:社区统计 + 友情链接
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import { Icon } from './Icons';
const emptyStats = { posts: 0, users: 0, topics: 0, online: 0 };
let cachedStats = null;
let cachedLinks = null;
export default function Sidebar({ id = 'sidebar' }) {
const [stats, setStats] = useState(() => cachedStats || emptyStats);
const [links, setLinks] = useState(() => cachedLinks || []);
useEffect(() => {
if (!cachedStats) {
API.getStats().then((nextStats) => {
cachedStats = nextStats;
setStats(nextStats);
}).catch(() => {});
}
if (!cachedLinks) {
API.getLinks().then((nextLinks) => {
cachedLinks = nextLinks;
setLinks(nextLinks);
}).catch(() => {});
}
}, []);
return (
<aside id={id} className="sidebar">
<div className="stats-box">
<h4>
<Icon name="book" size={14} /> 社区统计
</h4>
<div className="stat-item"><span>主题</span><span>{stats.topics || 0}</span></div>
<div className="stat-item"><span>帖子</span><span>{stats.posts || 0}</span></div>
<div className="stat-item"><span>用户</span><span>{stats.users || 0}</span></div>
<div className="stat-item"><span>在线</span><span>{stats.online || 0}</span></div>
</div>
<div className="links-box">
<h4>
<Icon name="link" size={14} /> 友情链接
</h4>
<ul id={id === 'sidebar' ? 'friendlyLinks' : undefined} className="friendly-links">
{links.length === 0 ? (
<li style={{ color: '#94a3b8', fontSize: 13 }}>暂无链接</li>
) : (
links.map((l) => (
<li key={l.id}><a href={l.url} target="_blank" rel="noreferrer">{l.title}</a></li>
))
)}
</ul>
</div>
</aside>
);
}
+101
View File
@@ -0,0 +1,101 @@
'use client';
// Toast 通知系统:右上角弹出,自动消失(替代 alert)
// 用法:const { toast } = useToast(); toast('发布成功', 'success');
// 注意:不用 createPortal(SSR 时 document 不存在会造成 hydration mismatch,
// 导致整树重建)。toast-container 是 position:fixed,渲染位置不影响视觉。
import { createContext, useContext, useState, useCallback, useRef, useEffect } from 'react';
import { Icon } from './Icons';
const ToastContext = createContext(null);
export function useToast() {
return useContext(ToastContext);
}
let idCounter = 0;
export function ToastProvider({ children }) {
const [toasts, setToasts] = useState([]);
const [dialog, setDialog] = useState(null);
const timersRef = useRef({});
const dialogTimerRef = useRef(null);
const dialogResolverRef = useRef(null);
const removeToast = useCallback((id) => {
setToasts((prev) => prev.filter((item) => item.id !== id));
delete timersRef.current[id];
}, []);
const dismiss = useCallback((id) => {
if (timersRef.current[id]) clearTimeout(timersRef.current[id]);
setToasts((prev) => prev.map((item) => item.id === id ? { ...item, closing: true } : item));
timersRef.current[id] = setTimeout(() => removeToast(id), 220);
}, [removeToast]);
const toast = useCallback((message, type = 'success', duration = 3000) => {
const id = ++idCounter;
setToasts((prev) => [...prev, { id, message, type, closing: false }]);
if (timersRef.current[id]) clearTimeout(timersRef.current[id]);
timersRef.current[id] = setTimeout(() => dismiss(id), duration);
}, [dismiss]);
const confirmAction = useCallback((message, options = {}) => {
if (dialogResolverRef.current) dialogResolverRef.current(false);
const isEnglish = localStorage.getItem('forumlify-lang') === 'en';
setDialog({
message,
title: options.title || (isEnglish ? 'Confirm action' : '确认操作'),
confirmLabel: options.confirmLabel || (isEnglish ? 'Confirm' : '确定'),
cancelLabel: options.cancelLabel || (isEnglish ? 'Cancel' : '取消'),
danger: options.danger !== false,
closing: false,
});
return new Promise((resolve) => {
dialogResolverRef.current = resolve;
});
}, []);
const closeDialog = useCallback((result) => {
setDialog((current) => current ? { ...current, closing: true } : current);
if (dialogTimerRef.current) clearTimeout(dialogTimerRef.current);
dialogTimerRef.current = setTimeout(() => {
setDialog(null);
const resolve = dialogResolverRef.current;
dialogResolverRef.current = null;
if (resolve) resolve(result);
}, 340);
}, []);
useEffect(() => () => {
Object.values(timersRef.current).forEach(clearTimeout);
if (dialogTimerRef.current) clearTimeout(dialogTimerRef.current);
if (dialogResolverRef.current) dialogResolverRef.current(false);
}, []);
return (
<ToastContext.Provider value={{ toast, confirmAction }}>
{children}
<div className="toast-container">
{toasts.map((t) => (
<div key={t.id} className={'toast toast-' + t.type + (t.closing ? ' closing' : '')} onClick={() => dismiss(t.id)} role="status">
<Icon name={t.type === 'error' ? 'error' : t.type === 'warning' ? 'warning' : 'success'} size={16} />
<span>{t.message}</span>
</div>
))}
</div>
{dialog && (
<div className={'modal active feedback-confirm' + (dialog.closing ? ' closing' : '')} onClick={(e) => { if (e.target === e.currentTarget) closeDialog(false); }}>
<div className="modal-content" role="alertdialog" aria-modal="true" aria-labelledby="feedbackConfirmTitle" aria-describedby="feedbackConfirmMessage">
<h2 id="feedbackConfirmTitle"><Icon name="warning" size={20} /> {dialog.title}</h2>
<p id="feedbackConfirmMessage">{dialog.message}</p>
<div className="feedback-confirm-actions">
<button className={dialog.danger ? 'btn-danger' : 'btn-primary'} onClick={() => closeDialog(true)}>{dialog.confirmLabel}</button>
<button className="btn-secondary" onClick={() => closeDialog(false)}>{dialog.cancelLabel}</button>
</div>
</div>
</div>
)}
</ToastContext.Provider>
);
}
+155
View File
@@ -0,0 +1,155 @@
'use client';
// 用户主页:资料卡 + 该用户的帖子列表
import { useEffect, useState, useCallback, useRef } from 'react';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { useOpenPrivateChat } from './chat/ChatManager';
import { renderMarkdown } from '@/lib/markdown';
import { useTranslation } from 'react-i18next';
function avatar(username, size = 128) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
'&background=6366f1&color=fff&size=' + size;
}
export default function UserProfile({ username, initialUser = null, initialPosts = null }) {
const { currentUser, openPost } = useApp();
const { t, i18n } = useTranslation();
const openPrivateChat = useOpenPrivateChat();
const [user, setUser] = useState(initialUser);
const [posts, setPosts] = useState(initialPosts || []);
const [error, setError] = useState(null);
const postsRef = useRef(null);
const load = useCallback(async () => {
setError(null);
try {
const u = await API.getUserProfile(username);
if (u.error || !u.id) {
setError(u.error || '用户不存在');
return;
}
setUser(u);
const result = await API.getPosts('latest', u.id);
setPosts(result.data || []);
} catch (err) {
setError(err.message || '加载失败');
}
}, [username]);
useEffect(() => {
setUser(initialUser);
setPosts(initialPosts || []);
load();
}, [initialPosts, initialUser, load]);
useEffect(() => {
const contents = postsRef.current?.querySelectorAll('.user-post-preview') || [];
contents.forEach((element) => {
element.classList.toggle('has-fade', element.scrollHeight > element.clientHeight + 4);
});
}, [posts]);
if (error) {
return (
<div id="pageUser" className="page-slide active">
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>加载失败:{error}</div>
</div>
);
}
if (!user) {
return <div id="pageUser" className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div>;
}
return (
<div id="pageUser" className="page-slide active">
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<h2><Icon name="users" size={20} /> 用户主页</h2>
</div>
<div id="userProfileContent" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<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 && (
<div className="user-profile-details">
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
{currentUser && currentUser.username !== user.username && (
<button
className="btn-primary"
style={{ marginTop: 12, padding: '8px 20px' }}
onClick={() => openPrivateChat(user.id, user.username)}
>
<Icon name="message" size={14} /> 发私信
</button>
)}
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
<span><Icon name="calendar" size={14} /> 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span><Icon name="file" size={14} /> 发了 {posts.length} 个帖子</span>
{user.role === 'admin' && <span style={{ color: 'var(--primary)', fontWeight: 600 }}><Icon name="shield" size={14} /> 管理员</span>}
</div>
</div>
)}
</div>
{user.id && (
<div className="user-profile-posts" ref={postsRef}>
<h3 style={{ margin: '24px 0 16px', fontSize: 18 }}><Icon name="file" size={18} /> 发布的帖子</h3>
{posts.length === 0 ? (
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有发帖</div>
) : (
posts.map((p) => {
const time = p.created_at ? new Date(p.created_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : '';
return (
<div
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.post_number || p.id, event.currentTarget, p, {
view: 'user',
username: user.username,
user,
posts,
scrollTop: document.getElementById('pageUser')?.scrollTop || 0,
})}
>
{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>
)}
<div className="post-header">
<img src={p.avatar_url || user.avatar_url || avatar(user.username, 64)} className="post-avatar" alt="" />
<span className="post-username" style={{ color: 'var(--primary)' }}>{user.username}</span>
<span className="post-time">{time}</span>
{p.edited_at && (
<span className="post-edited-state" style={{ fontSize: 11, color: 'var(--text-light)', marginLeft: 6 }}>
<span className="post-edited-label">{t('feed.deleted')}</span>
</span>
)}
</div>
<div className="post-title">{p.title || t('feed.noTitle')}</div>
<div className="post-content user-post-preview" dangerouslySetInnerHTML={{ __html: renderMarkdown(p.content) }} />
{p.images && p.images.length > 0 && (
<div className="post-images">
{p.images.map((image, index) => (
<img key={image + index} src={image} className="post-image" alt="" />
))}
</div>
)}
<div className="post-actions">
<span><Icon name="message" size={14} /> {p.reply_count || 0}</span>
</div>
</div>
);
})
)}
</div>
)}
</div>
</div>
);
}
+113
View File
@@ -0,0 +1,113 @@
'use client';
// 管理后台 - 自定义 CSS(上传 style.css 覆盖默认样式)
import { useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function AdminCustomCss() {
const { t } = useTranslation();
const { confirmAction } = useToast();
const [status, setStatus] = useState(null);
const [dragOver, setDragOver] = useState(false);
const [pendingFile, setPendingFile] = useState(null); // 待确认的 CSS 文件
const fileInputRef = useRef(null);
const handleFile = async (file) => {
if (!file) return;
if (file.name !== 'style.css') {
setStatus({ ok: false, msg: t('admin.css.filenameInvalid') });
return;
}
if (file.size > 1024 * 1024) {
setStatus({ ok: false, msg: t('admin.css.sizeInvalid') });
return;
}
// 上传前警告确认(与原版一致)
setPendingFile(file);
};
const doUpload = async () => {
try {
await API.uploadCustomCss(pendingFile);
setStatus({ ok: true, msg: t('admin.css.active') });
const link = document.getElementById('custom-css-link');
if (link) link.href = '/api/custom-css?t=' + Date.now();
} catch (err) {
setStatus({ ok: false, msg: err.message });
} finally {
setPendingFile(null);
}
};
const handleDelete = async () => {
if (!await confirmAction(t('admin.css.confirmDelete'))) return;
try {
await API.deleteCustomCss();
setStatus({ ok: true, msg: t('admin.css.deleted') });
const link = document.getElementById('custom-css-link');
if (link) link.remove();
} catch (err) {
setStatus({ ok: false, msg: err.message });
}
};
return (
<>
<h3 style={{ marginBottom: 16 }}><Icon name="code" size={16} /> {t('admin.css.title')}</h3>
<p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>
{t('admin.css.description')}
</p>
<div
style={{
border: '2px dashed ' + (dragOver ? 'var(--primary)' : 'var(--border)'),
borderRadius: 8, padding: 32, textAlign: 'center', cursor: 'pointer',
transition: 'all 0.3s', background: dragOver ? 'var(--primary-bg)' : 'var(--bg)',
}}
onClick={() => fileInputRef.current?.click()}
onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
onDragLeave={() => setDragOver(false)}
onDrop={(e) => { e.preventDefault(); setDragOver(false); if (e.dataTransfer.files?.[0]) handleFile(e.dataTransfer.files[0]); }}
>
<span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
<Icon name="upload" size={14} /> {dragOver ? t('admin.css.releaseUpload') : t('admin.css.uploadHint')}
</span>
</div>
<input
type="file"
ref={fileInputRef}
accept=".css"
style={{ display: 'none' }}
onChange={(e) => { if (e.target.files?.[0]) handleFile(e.target.files[0]); }}
/>
{status && (
<div style={{ fontSize: 13, marginTop: 8, color: status.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={status.ok ? 'success' : 'error'} size={14} /> {status.msg}</div>
)}
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
<button className="btn-primary" style={{ padding: '8px 20px' }} onClick={() => fileInputRef.current?.click()}><Icon name="save" size={14} /> {t('admin.css.save')}</button>
<button className="btn-secondary" style={{ padding: '8px 20px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={handleDelete}><Icon name="trash" size={14} /> {t('admin.css.delete')}</button>
</div>
{/* 上传前警告确认 */}
{pendingFile && (
<div className="modal active" style={{ display: 'flex' }} onClick={() => setPendingFile(null)}>
<div className="modal-content" style={{ maxWidth: 420 }} onClick={(e) => e.stopPropagation()}>
<h2 style={{ marginBottom: 12 }}><Icon name="warning" size={20} /> {t('admin.css.warningTitle')}</h2>
<p style={{ fontSize: 14, color: 'var(--text-secondary)', marginBottom: 16 }}>
{t('admin.css.warningBody')}
</p>
<p style={{ fontSize: 13, color: 'var(--text-light)', marginBottom: 20 }}>
{t('admin.css.warningHelp')}
</p>
<div style={{ display: 'flex', gap: 8 }}>
<button className="btn-primary" style={{ padding: '8px 24px' }} onClick={doUpload}><Icon name="upload" size={14} /> {t('admin.css.continueUpload')}</button>
<button className="btn-secondary" style={{ padding: '8px 24px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={() => setPendingFile(null)}>{t('admin.common.cancel')}</button>
</div>
</div>
</div>
)}
</>
);
}
+91
View File
@@ -0,0 +1,91 @@
'use client';
// 管理后台 - 自定义页面管理(列表)
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import CustomPageEditor from './CustomPageEditor';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function AdminCustomPages() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [pages, setPages] = useState(null);
const [error, setError] = useState(null);
const [editing, setEditing] = useState(null); // null | 'new' | page对象
const load = () => {
API.adminGetCustomPages()
.then((data) => { setPages(data || []); setError(null); })
.catch((e) => { setError(e.message); setPages([]); });
};
useEffect(load, []);
const handleDelete = async (p) => {
if (!await confirmAction(t('admin.page.confirmDelete'))) return;
try {
await API.adminDeleteCustomPage(p.id);
load();
} catch (err) {
toast(t('admin.common.deleteFailed', { msg: err.message }), 'error');
}
};
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
return (
<>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
<h3 style={{ margin: 0 }}><Icon name="file" size={16} /> {t('admin.page.title')}</h3>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={() => setEditing('new')}><Icon name="plus" size={14} /> {t('admin.page.add')}</button>
</div>
<div id="customPageList">
{pages === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>
) : pages.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>{t('admin.page.empty')}</div>
) : (
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
<thead>
<tr style={{ textAlign: 'left', borderBottom: '2px solid var(--border)' }}>
<th style={{ padding: '8px 12px' }}>{t('admin.page.name')}</th>
<th style={{ padding: '8px 12px' }}>{t('admin.page.columnTitle')}</th>
<th style={{ padding: '8px 12px' }}>{t('admin.page.url')}</th>
<th style={{ padding: '8px 12px' }}>{t('admin.common.status')}</th>
<th style={{ padding: '8px 12px', textAlign: 'center' }}>{t('admin.common.actions')}</th>
</tr>
</thead>
<tbody>
{pages.map((p) => (
<tr key={p.id} style={{ borderBottom: '1px solid var(--border-light)' }}>
<td style={{ padding: '8px 12px' }}><code style={{ background: 'var(--bg)', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>{p.name}</code></td>
<td style={{ padding: '8px 12px' }}>{p.title}</td>
<td style={{ padding: '8px 12px' }}><code style={{ background: 'var(--bg)', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>?custom={p.name}</code></td>
<td style={{ padding: '8px 12px' }}>
<span style={{ color: p.enabled ? '#22c55e' : '#ef4444', display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name={p.enabled ? 'success' : 'error'} size={13} /> {p.enabled ? t('admin.common.enabled') : t('admin.common.disabled')}</span>
</td>
<td style={{ padding: '8px 12px', textAlign: 'center', display: 'flex', gap: 6, justifyContent: 'center' }}>
<button className="btn-sm btn-secondary" title={t('admin.page.edit')} aria-label={t('admin.page.edit')} onClick={() => setEditing(p)}><Icon name="edit" size={13} /></button>
<button className="btn-sm btn-danger" title={t('admin.page.delete')} aria-label={t('admin.page.delete')} onClick={() => handleDelete(p)}><Icon name="trash" size={13} /></button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{editing && (
<CustomPageEditor
page={editing === 'new' ? null : editing}
onClose={() => setEditing(null)}
onSaved={() => { setEditing(null); load(); }}
/>
)}
</>
);
}
+54
View File
@@ -0,0 +1,54 @@
'use client';
// 管理后台 - 论坛设置
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import { useApp } from '../AppProvider';
import { Icon } from '../Icons';
import { useTranslation } from 'react-i18next';
import { useToast } from '../Toast';
export default function AdminForumSettings() {
const { updateForumName } = useApp();
const { t } = useTranslation();
const { toast } = useToast();
// 初始为空:收到服务器返回的论坛名后才显示,避免默认名一闪而过
const [name, setName] = useState('');
const [result, setResult] = useState(null); // {ok, msg}
useEffect(() => {
API.getSettings()
.then((data) => { if (data.forum_name) setName(data.forum_name); })
.catch(() => {});
}, []);
const handleSave = async () => {
if (!name.trim()) { toast(t('admin.forum.nameRequired'), 'warning'); return; }
try {
await API.updateSettings(name.trim());
updateForumName(name.trim());
setResult({ ok: true, msg: t('admin.forum.saved') });
} catch {
setResult({ ok: false, msg: t('admin.forum.saveFailed') });
}
};
return (
<>
<h3 style={{ marginBottom: 16 }}><Icon name="settings" size={16} /> {t('admin.forum.title')}</h3>
<div style={{ maxWidth: 400 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 6 }}>{t('admin.forum.nameLabel')}</label>
<input
type="text"
style={{ width: '100%', padding: '10px 14px', border: '1.5px solid var(--border)', borderRadius: 6, fontSize: 15, marginBottom: 12, fontFamily: 'inherit', background: 'var(--bg)', color: 'var(--text)' }}
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button className="btn-primary" style={{ padding: '10px 24px' }} onClick={handleSave}><Icon name="save" size={14} /> {t('admin.forum.save')}</button>
{result && (
<span style={{ marginLeft: 12, fontSize: 14, color: result.ok ? '#22c55e' : '#ef4444' }}><Icon name={result.ok ? 'success' : 'error'} size={14} /> {result.msg}</span>
)}
</div>
</>
);
}
+73
View File
@@ -0,0 +1,73 @@
'use client';
// 管理后台 - 友情链接管理
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function AdminLinks() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [links, setLinks] = useState([]);
const [title, setTitle] = useState('');
const [url, setUrl] = useState('');
const load = () => { API.getLinks().then(setLinks).catch(() => {}); };
useEffect(load, []);
const handleAdd = async () => {
if (!title.trim() || !url.trim()) { toast(t('admin.link.incomplete'), 'warning'); return; }
try {
await API.addLink(title.trim(), url.trim());
setTitle('');
setUrl('');
load();
} catch (err) {
toast(t('admin.link.addFailed', { msg: err.message }), 'error');
}
};
const handleDelete = async (id) => {
if (!await confirmAction(t('admin.link.confirmDelete'))) return;
try {
await API.deleteLink(id);
load();
} catch (err) {
toast(t('admin.common.deleteFailed', { msg: err.message }), 'error');
}
};
return (
<>
<div style={{ marginBottom: 16, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<input
type="text" placeholder={t('admin.link.namePlaceholder')}
style={{ flex: 1, minWidth: 120, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)' }}
value={title} onChange={(e) => setTitle(e.target.value)}
/>
<input
type="url" placeholder={t('admin.link.urlPlaceholder')}
style={{ flex: 2, minWidth: 160, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)' }}
value={url} onChange={(e) => setUrl(e.target.value)}
/>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={handleAdd}>{t('admin.link.add')}</button>
</div>
<div id="linkList">
{links.length === 0 ? (
<div style={{ color: '#94a3b8', fontSize: 13 }}>{t('admin.link.empty')}</div>
) : (
links.map((l) => (
<div key={l.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: '1px solid var(--border)' }}>
<span><a href={l.url} target="_blank" rel="noreferrer" style={{ color: '#6366f1', textDecoration: 'none' }}>{l.title}</a></span>
<button className="btn-sm btn-danger" onClick={() => handleDelete(l.id)}>
<Icon name="trash" size={12} /> {t('admin.common.delete')}
</button>
</div>
))
)}
</div>
</>
);
}
+45
View File
@@ -0,0 +1,45 @@
'use client';
// 管理后台 - 事件日志
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
export default function AdminLogs() {
const { t, i18n } = useTranslation();
const [logs, setLogs] = useState(null);
const [error, setError] = useState(null);
const load = () => {
API.getEventLogs()
.then((data) => { setLogs(data || []); setError(null); })
.catch((e) => { setError(e.message); setLogs([]); });
};
useEffect(load, []);
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
if (!logs) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
if (logs.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>{t('admin.log.empty')}</div>;
const dateLocale = i18n.resolvedLanguage === 'en' ? 'en-US' : 'zh-CN';
return (
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
<thead>
<tr style={{ textAlign: 'left', borderBottom: '1px solid var(--border)' }}>
<th>{t('admin.log.time')}</th><th>{t('admin.log.user')}</th><th>{t('admin.log.action')}</th>
</tr>
</thead>
<tbody>
{logs.map((l) => (
<tr key={l.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
<td style={{ padding: '6px 0' }}>{new Date(l.created_at).toLocaleString(dateLocale)}</td>
<td style={{ padding: '6px 0' }}>{l.username || t('admin.log.system')}</td>
<td style={{ padding: '6px 0' }}>{l.action}</td>
</tr>
))}
</tbody>
</table>
);
}
+80
View File
@@ -0,0 +1,80 @@
'use client';
// 管理后台 - 举报处理
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function AdminReports() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [reports, setReports] = useState(null);
const [error, setError] = useState(null);
const load = () => {
API.getReports()
.then((data) => { setReports(data || []); setError(null); })
.catch((e) => { setError(e.message); setReports([]); });
};
useEffect(load, []);
const handleAction = async (r, action) => {
const status = action === 'approve' ? 'approved' : 'rejected';
const note = action === 'approve' ? t('admin.report.approvedNote') : t('admin.report.rejectedNote');
if (action === 'approve' && !await confirmAction(t('admin.report.confirmApprove'))) return;
try {
await API.updateReport(r.id, status, note);
if (action === 'approve' && r.post_id) {
API.deletePost(r.post_id).catch(() => {});
}
load();
} catch (err) {
toast(t('admin.common.operationFailed', { msg: err.message }), 'error');
}
};
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
if (!reports) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
if (reports.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}><Icon name="success" size={16} /> {t('admin.report.empty')}</div>;
const statusLabels = {
pending: t('admin.report.statusPending'),
approved: t('admin.report.statusApproved'),
rejected: t('admin.report.statusRejected'),
};
const statusIcons = { pending: 'pending', approved: 'success', rejected: 'error' };
return reports.map((r) => (
<div key={r.id} className="report-item">
<div>{t('admin.report.reportedPost', { name: r.reporter_name || t('admin.report.anonymous') })}</div>
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>{t('admin.report.reason', { reason: r.reason })}</div>
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>
{t('admin.report.post', {
title: r.post_title || t('admin.report.untitled'),
content: (r.post_content || '').substring(0, 30) + ((r.post_content || '').length > 30 ? '...' : ''),
})}
</div>
<div style={{ fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
{statusIcons[r.status] && <Icon name={statusIcons[r.status]} size={13} />} {t('admin.common.status')}: {statusLabels[r.status] || r.status}
</div>
{r.handler_name && (
<div style={{ fontSize: 12, color: '#94a3b8' }}>
{t('admin.report.handler', { name: r.handler_name })}{r.handler_note ? ' (' + r.handler_note + ')' : ''}
</div>
)}
{r.status === 'pending' && (
<div className="report-actions">
<button className="btn-sm btn-danger" onClick={() => handleAction(r, 'approve')}>
<Icon name="trash" size={12} /> {t('admin.report.deletePost')}
</button>
<button className="btn-sm btn-secondary" onClick={() => handleAction(r, 'reject')}>
<Icon name="close" size={12} /> {t('admin.report.reject')}
</button>
</div>
)}
</div>
));
}
+102
View File
@@ -0,0 +1,102 @@
'use client';
// 管理后台 - 用户管理
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { useApp } from '../AppProvider';
import { useToast } from '../Toast';
export default function AdminUsers() {
const { currentUser } = useApp();
const { t, i18n } = useTranslation();
const { toast, confirmAction } = useToast();
const [users, setUsers] = useState(null);
const [error, setError] = useState(null);
const load = () => {
API.getUsers()
.then((data) => { setUsers(data || []); setError(null); })
.catch((e) => { setError(e.message); setUsers([]); });
};
useEffect(load, []);
const handleRole = async (u, role) => {
const roleName = role === 'admin' ? t('admin.user.roleAdmin') : t('admin.user.roleUser');
if (!await confirmAction(t('admin.user.confirmRole', { role: roleName }), { danger: false })) return;
try {
await API.updateUserRole(u.id, role);
load();
} catch (err) {
toast(t('admin.common.operationFailed', { msg: err.message }), 'error');
}
};
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
if (!users) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
const dateLocale = i18n.resolvedLanguage === 'en' ? 'en-US' : 'zh-CN';
return (
<>
<div style={{ marginBottom: 12, fontSize: 13, color: '#94a3b8' }}>{t('admin.user.count', { count: users.length })}</div>
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
<thead>
<tr style={{ textAlign: 'left', borderBottom: '2px solid var(--border)' }}>
<th style={{ padding: '10px 12px' }}>{t('admin.user.user')}</th>
<th style={{ padding: '10px 12px' }}>{t('admin.user.role')}</th>
<th style={{ padding: '10px 12px' }}>{t('admin.user.registeredAt')}</th>
<th style={{ padding: '10px 12px', textAlign: 'center' }}>{t('admin.common.actions')}</th>
</tr>
</thead>
<tbody>
{users.map((u) => {
const isAdmin = u.role === 'admin';
const isCurrent = currentUser && currentUser.id === u.id;
return (
<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 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>
<td style={{ padding: '10px 12px' }}>
<span style={{
display: 'inline-block', padding: '2px 10px', borderRadius: 4, fontSize: 12, fontWeight: 500,
...(isAdmin ? { background: '#6366f1', color: '#fff' } : { background: 'var(--border)', color: 'var(--text-secondary)' }),
}}>
{isAdmin ? (u.is_super ? t('admin.user.roleSuper') : t('admin.user.roleAdmin')) : t('admin.user.roleUser')}
</span>
</td>
<td style={{ padding: '10px 12px', color: '#94a3b8', fontSize: 13 }}>
{u.created_at ? new Date(u.created_at).toLocaleDateString(dateLocale) : '—'}
</td>
<td style={{ padding: '10px 12px', textAlign: 'center' }}>
{u.is_super ? (
<span style={{ fontSize: 12, color: '#94a3b8' }}>{t('admin.user.cannotSuper')}</span>
) : isCurrent ? (
<span style={{ fontSize: 12, color: '#94a3b8' }}>{t('admin.user.cannotSelf')}</span>
) : isAdmin ? (
<button className="btn-sm btn-secondary" style={{ padding: '4px 12px' }} onClick={() => handleRole(u, 'user')}>{t('admin.user.makeUser')}</button>
) : (
<button className="btn-sm btn-primary" style={{ padding: '4px 12px', background: '#6366f1', color: '#fff', border: 'none', borderRadius: 4, cursor: 'pointer' }} onClick={() => handleRole(u, 'admin')}>{t('admin.user.makeAdmin')}</button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</>
);
}
+93
View File
@@ -0,0 +1,93 @@
'use client';
// 管理后台 - 自定义页面编辑器(modal)
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function CustomPageEditor({ page, onClose, onSaved }) {
const { t } = useTranslation();
const { toast } = useToast();
const isEdit = !!page;
const [name, setName] = useState(page?.name || '');
const [title, setTitle] = useState(page?.title || '');
const [content, setContent] = useState(page?.content || '');
const [enabled, setEnabled] = useState(page?.enabled !== false);
const handleSave = async () => {
if (!name.trim()) { toast(t('admin.page.nameRequired'), 'warning'); return; }
if (!title.trim()) { toast(t('admin.page.titleRequired'), 'warning'); return; }
if (!content.trim()) { toast(t('admin.page.contentRequired'), 'warning'); return; }
if (!/^[a-zA-Z0-9\-_]+$/.test(name.trim())) {
toast(t('admin.page.nameInvalid'), 'warning');
return;
}
try {
if (isEdit) {
await API.adminUpdateCustomPage(page.id, title.trim(), content.trim(), enabled);
} else {
await API.adminCreateCustomPage(name.trim(), title.trim(), content.trim());
}
onSaved();
} catch (err) {
toast(t('admin.common.saveFailed', { msg: err.message }), 'error');
}
};
return (
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
<div className="modal-content" style={{ maxWidth: 600, maxHeight: '90vh', overflowY: 'auto', position: 'relative' }}>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={onClose}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}><Icon name={isEdit ? 'edit' : 'file'} size={20} /> {isEdit ? t('admin.page.editTitle') : t('admin.page.addTitle')}</h2>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.nameLabel')}</label>
<input
type="text"
value={name}
readOnly={isEdit}
placeholder={t('admin.page.namePlaceholder')}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: isEdit ? 'var(--border-light)' : 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setName(e.target.value)}
/>
{isEdit
? <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}><Icon name="warning" size={12} /> {t('admin.page.nameLocked')}</div>
: <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>{t('admin.page.nameHint')}</div>}
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.navTitleLabel')}</label>
<input
type="text"
value={title}
placeholder={t('admin.page.navTitlePlaceholder')}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.common.status')}</label>
<select
value={String(enabled)}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setEnabled(e.target.value === 'true')}
>
<option value="true">{t('admin.common.enabled')}</option>
<option value="false">{t('admin.common.disabled')}</option>
</select>
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.contentLabel')}</label>
<textarea
rows={12}
value={content}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 13, fontFamily: 'monospace', background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }}
onChange={(e) => setContent(e.target.value)}
/>
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>{t('admin.page.contentHelp')}</div>
</div>
<button className="btn-primary" style={{ padding: '10px 24px', width: '100%' }} onClick={handleSave}>{t('admin.common.save')}</button>
</div>
</div>
);
}
+118
View File
@@ -0,0 +1,118 @@
'use client';
// 私信管理器:会话列表 modal + 聊天窗口 modal + 未读 badge
import { useState, useEffect, useCallback } from 'react';
import { API } from '@/lib/api';
import { useApp } from '../AppProvider';
import { Icon } from '../Icons';
import ConversationList from './ConversationList';
import ChatWindow from './ChatWindow';
import { useToast } from '../Toast';
// 私信按钮(含未读 badge),渲染在导航栏内
export function DMButton() {
const { currentUser } = useApp();
const [unread, setUnread] = useState(0);
useEffect(() => {
if (!currentUser) { setUnread(0); return; }
const update = () => {
API.getConversations()
.then((cs) => setUnread((cs || []).reduce((s, c) => s + (c.unread_count || 0), 0)))
.catch(() => {});
};
update();
const t = setInterval(update, 30000);
return () => clearInterval(t);
}, [currentUser]);
if (!currentUser) return null; // 未登录不显示私信按钮
return (
<button
className="nav-icon-btn"
title="私信"
style={{ position: 'relative', padding: '6px 8px', background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-secondary)', borderRadius: 4, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}
onClick={() => window.dispatchEvent(new CustomEvent('forumlify-open-messages'))}
>
<Icon name="message" size={20} />
{unread > 0 && (
<span style={{ position: 'absolute', top: -2, right: -2, background: '#ef4444', color: '#fff', borderRadius: '50%', padding: '2px 6px', fontSize: 10, fontWeight: 600, minWidth: 18, textAlign: 'center', lineHeight: 1.4 }}>
{unread > 99 ? '99+' : unread}
</span>
)}
</button>
);
}
// 私信 modals 容器(会话列表 + 聊天窗口)
export default function ChatManager() {
const [listOpen, setListOpen] = useState(false);
const [chat, setChat] = useState(null); // {conversationId, otherUserId, otherUsername}
const [refreshKey, setRefreshKey] = useState(0);
const refreshList = useCallback(() => setRefreshKey((k) => k + 1), []);
// 监听事件:打开会话列表 / 打开聊天
useEffect(() => {
const handler = (e) => {
setChat(e.detail);
setListOpen(false);
};
const openList = () => setListOpen(true);
window.addEventListener('forumlify-open-chat', handler);
window.addEventListener('forumlify-open-messages', openList);
return () => {
window.removeEventListener('forumlify-open-chat', handler);
window.removeEventListener('forumlify-open-messages', openList);
};
}, []);
const openChat = (conversationId, otherUserId, otherUsername) => {
setChat({ conversationId, otherUserId, otherUsername });
setListOpen(false);
};
const closeChat = () => {
setChat(null);
refreshList();
};
return (
<>
{listOpen && (
<ConversationList
onOpenChat={openChat}
onClose={() => setListOpen(false)}
/>
)}
{chat && (
<ChatWindow
conversationId={chat.conversationId}
otherUserId={chat.otherUserId}
otherUsername={chat.otherUsername}
onClose={closeChat}
onRefreshList={refreshList}
/>
)}
</>
);
}
// 供其他组件调用的打开私信(通过自定义事件桥接)
export function useOpenPrivateChat() {
const { currentUser } = useApp();
const { toast } = useToast();
const open = async (otherUserId, otherUsername) => {
if (!currentUser) { toast('请先登录', 'warning'); return; }
try {
const result = await API.getOrCreateConversation(otherUserId);
window.dispatchEvent(new CustomEvent('forumlify-open-chat', {
detail: { conversationId: result.id, otherUserId, otherUsername },
}));
} catch (err) {
toast('打开私信失败:' + err.message, 'error');
}
};
return open;
}
+112
View File
@@ -0,0 +1,112 @@
'use client';
// 私信 - 聊天窗口(3 秒轮询新消息)
import { useEffect, useState, useRef, useCallback } from 'react';
import { API } from '@/lib/api';
import { useApp } from '../AppProvider';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
'&background=6366f1&color=fff&size=64';
}
export default function ChatWindow({ conversationId, otherUserId, otherUsername, onClose, onRefreshList }) {
const { currentUser } = useApp();
const { toast } = useToast();
const [messages, setMessages] = useState(null);
const [content, setContent] = useState('');
const containerRef = useRef(null);
const load = useCallback(async (silent = false) => {
if (!silent) setMessages(null);
try {
const data = await API.getMessages(conversationId);
setMessages(data || []);
} catch {
if (!silent) setMessages([]);
}
}, [conversationId]);
useEffect(() => { load(); }, [load]);
// 3 秒轮询
useEffect(() => {
const t = setInterval(() => load(true), 3000);
return () => clearInterval(t);
}, [load]);
// 自动滚动到底部
useEffect(() => {
if (containerRef.current) containerRef.current.scrollTop = containerRef.current.scrollHeight;
}, [messages]);
const send = async () => {
if (!content.trim()) return;
try {
await API.sendMessage(conversationId, content.trim());
setContent('');
load();
onRefreshList();
} catch (err) {
toast('发送失败:' + err.message, 'error');
}
};
return (
<div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', height: '70vh', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
<span id="chatTitle" style={{ fontWeight: 600, fontSize: 16 }}>{otherUsername}</span>
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
</div>
<div id="chatMessages" ref={containerRef} style={{ flex: 1, overflowY: 'auto', padding: 16, minHeight: 0 }}>
{messages === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div>
) : messages.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>还没有消息,打个招呼吧 👋</div>
) : (
messages.map((m) => {
const isMine = m.sender_id === currentUser?.id;
const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : '';
return (
<div key={m.id} style={{ display: 'flex', justifyContent: isMine ? 'flex-end' : 'flex-start', marginBottom: 12 }}>
{!isMine && (
<img src={m.sender_avatar_url || avatar(m.sender_username)} style={{ width: 32, height: 32, borderRadius: '50%', objectFit: 'cover', marginRight: 8, flexShrink: 0 }} alt="" />
)}
<div style={{ maxWidth: '70%' }}>
<div style={{
background: isMine ? 'var(--primary)' : 'var(--surface)',
color: isMine ? '#fff' : 'var(--text)',
padding: '10px 14px', borderRadius: 12,
border: isMine ? 'none' : '1px solid var(--border)',
wordBreak: 'break-word',
}}>
{m.content}
</div>
<div style={{ fontSize: 11, color: 'var(--text-light)', marginTop: 4, textAlign: isMine ? 'right' : 'left' }}>
{time} {isMine && <Icon name="success" size={10} aria-label={m.is_read ? '已读' : '已发送'} />}
</div>
</div>
</div>
);
})
)}
</div>
<div style={{ display: 'flex', gap: 8, padding: '12px 16px', borderTop: '1px solid var(--border)', flexShrink: 0 }}>
<input
type="text"
id="chatInput"
placeholder="输入消息..."
style={{ flex: 1, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 6, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }}
value={content}
onChange={(e) => setContent(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
/>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={send}>发送</button>
</div>
</div>
</div>
);
}
+69
View File
@@ -0,0 +1,69 @@
'use client';
// 私信 - 会话列表
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
'&background=6366f1&color=fff&size=64';
}
export default function ConversationList({ onOpenChat, onClose }) {
const [conversations, setConversations] = useState(null);
const load = () => {
API.getConversations()
.then((data) => setConversations(data || []))
.catch(() => setConversations([]));
};
useEffect(load, []);
return (
<div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', height: '70vh', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
<h2 style={{ fontSize: 18, margin: 0 }}><Icon name="message" size={18} style={{ verticalAlign: -3, marginRight: 6 }} /> 私信</h2>
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
</div>
<div id="messageListContent" style={{ flex: 1, overflowY: 'auto', padding: 0 }}>
{conversations === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div>
) : conversations.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>暂无私信</div>
) : (
conversations.map((c) => {
const unread = c.unread_count || 0;
const lastMsg = c.last_message || '暂无消息';
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : '';
return (
<div
key={c.id}
className="message-list-item"
style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', borderBottom: '1px solid var(--border)', cursor: 'pointer', transition: 'background 0.15s' }}
onClick={() => onOpenChat(c.id, c.other_user_id, c.other_username)}
>
<img src={c.other_avatar_url || avatar(c.other_username)} style={{ width: 40, height: 40, borderRadius: '50%', objectFit: 'cover' }} alt="" />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span style={{ fontWeight: 600 }}>{c.other_username}</span>
<span style={{ fontSize: 12, color: 'var(--text-light)' }}>{time}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span style={{ fontSize: 13, color: 'var(--text-secondary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 200 }}>{lastMsg}</span>
{unread > 0 && (
<span style={{ background: '#ef4444', color: '#fff', borderRadius: '50%', padding: '2px 8px', fontSize: 11, fontWeight: 600 }}>{unread}</span>
)}
</div>
</div>
</div>
);
})
)}
</div>
</div>
</div>
);
}
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff. Show more