Compare commits
32 Commits
rebuild/gi
...
v1.1.6
| Author | SHA1 | Date | |
|---|---|---|---|
| 2e9c42a34c | |||
| dff60dde6a | |||
| ea9e0058d4 | |||
| d5aa36416c | |||
| 2159280af5 | |||
| bc9a031890 | |||
| 0d81787125 | |||
| 68713c053b | |||
| 94823c0821 | |||
| b608ec85ba | |||
| 6048d71759 | |||
| 37d14a22d5 | |||
| a02d103cfe | |||
| 21c6233fc0 | |||
| 4ca5c17e2e | |||
| cf7a37eccc | |||
| 44eed97fe0 | |||
| 9e134916a4 | |||
| ba60a9b1c4 | |||
| 132ca5c82c | |||
| 185649db7c | |||
| 9d926750b2 | |||
| a91d917fa9 | |||
| 34f3d088ad | |||
| c6ce44f8b4 | |||
| 429956c594 | |||
| 16b6a18096 | |||
| 95c2154087 | |||
| 0abfb32194 | |||
| bcfd306643 | |||
| 335b708b04 | |||
| a83f8bd670 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -23,3 +23,6 @@ tmp-cookie.txt
|
||||
*.swp
|
||||
Thumbs.db
|
||||
.DS_Store
|
||||
|
||||
# Lucide path <20><>ȡ<EFBFBD><C8A1>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD>
|
||||
frontend/tmp-lucide-paths.json
|
||||
|
||||
2
Makefile
2
Makefile
@@ -5,7 +5,7 @@ APP_NAME := jiang13
|
||||
MAIN_PKG := ./cmd/jiang13
|
||||
BUILD_DIR := dist
|
||||
DEV_DATA_DIR := dist/data
|
||||
VERSION := 1.0.0
|
||||
VERSION := 1.1.6
|
||||
LDFLAGS := -s -w -X main.version=$(VERSION)
|
||||
REGISTRY_IMAGE := hangzhang714128/jiang13-forum
|
||||
|
||||
|
||||
45
README.md
45
README.md
@@ -20,6 +20,7 @@
|
||||
[快速开始](#-快速开始) ·
|
||||
[界面预览](#-界面预览) ·
|
||||
[功能亮点](#-功能亮点) ·
|
||||
[更新日志](docs/site-posts/changelog.md) ·
|
||||
[路线图](ROADMAP.md) ·
|
||||
[参与贡献](CONTRIBUTING.md)
|
||||
|
||||
@@ -172,6 +173,11 @@ make compose-up
|
||||
|
||||
浏览器打开 `http://localhost:3000/register` 注册;**首个用户自动成为管理员**。
|
||||
|
||||
版本变更与升级说明见 **[更新日志](docs/site-posts/changelog.md)**。Docker 与 Windows / Linux 单文件共用同一版本号。
|
||||
|
||||
- Docker 标签:[hub.docker.com/r/hangzhang714128/jiang13-forum/tags](https://hub.docker.com/r/hangzhang714128/jiang13-forum/tags)
|
||||
- 预编译包:[Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases)
|
||||
|
||||
**拉取已构建镜像(Docker Hub):**
|
||||
|
||||
```bash
|
||||
@@ -196,6 +202,7 @@ docker run -d --name jiang13 \
|
||||
| `JIANG13_JWT_SECRET` | JWT 密钥(留空则自动生成并写入 `/data/.jwt_secret`) |
|
||||
| `JIANG13_CONFIG` | 配置文件路径 |
|
||||
| `JIANG13_WORK_PATH` | 工作目录 |
|
||||
| `JIANG13_COMMUNITY_HUB` | 维护者选项:设为 `1` 时本站作为社区枢纽收报。官方站 `bbs.iioio.com` 会按域名自动成为枢纽,无需此变量;仅非官网的枢纽镜像 / 预发需要显式开启(见 `app.ini.example`) |
|
||||
|
||||
**健康检查:** `GET /health` 返回 `{"status":"ok"}`,供 Docker / 负载均衡探活。
|
||||
|
||||
@@ -205,15 +212,15 @@ docker run -d --name jiang13 \
|
||||
docker login
|
||||
.\build.bat -Target docker # Windows
|
||||
# make docker # Linux/macOS
|
||||
docker push hangzhang714128/jiang13-forum:1.0.0
|
||||
docker push hangzhang714128/jiang13-forum:1.1.6
|
||||
docker push hangzhang714128/jiang13-forum:latest
|
||||
```
|
||||
|
||||
或直接构建:
|
||||
|
||||
```bash
|
||||
docker build --build-arg VERSION=1.0.0 -t hangzhang714128/jiang13-forum:1.0.0 -t hangzhang714128/jiang13-forum:latest .
|
||||
docker push hangzhang714128/jiang13-forum:1.0.0
|
||||
docker build --build-arg VERSION=1.1.6 -t hangzhang714128/jiang13-forum:1.1.6 -t hangzhang714128/jiang13-forum:latest .
|
||||
docker push hangzhang714128/jiang13-forum:1.1.6
|
||||
docker push hangzhang714128/jiang13-forum:latest
|
||||
```
|
||||
|
||||
@@ -238,7 +245,29 @@ docker push hangzhang714128/jiang13-forum:latest
|
||||
|
||||
### 3. 直接启动(二进制)
|
||||
|
||||
把二进制放到目标目录后直接运行(首次会在同目录生成 `app.ini`):
|
||||
不想自己编译时,从 [Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases) 下载与 Docker 同版本号的文件即可:
|
||||
|
||||
| 文件 | 平台 |
|
||||
|------|------|
|
||||
| `jiang13-*-windows-amd64.exe` | Windows x64 |
|
||||
| `jiang13-*-linux-amd64` | Linux x64 |
|
||||
|
||||
当前 **1.1.6:** [Windows](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-windows-amd64.exe) · [Linux](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-linux-amd64)
|
||||
|
||||
把文件放到目标目录后直接运行(首次会在同目录生成 `app.ini`):
|
||||
|
||||
```bash
|
||||
# Windows
|
||||
.\jiang13-1.1.6-windows-amd64.exe
|
||||
# 或改名为 jiang13.exe 后:
|
||||
.\jiang13.exe
|
||||
|
||||
# Linux
|
||||
chmod +x jiang13-1.1.6-linux-amd64
|
||||
./jiang13-1.1.6-linux-amd64
|
||||
```
|
||||
|
||||
本地刚编译的产物在 `dist/`:
|
||||
|
||||
```bash
|
||||
# Windows
|
||||
@@ -292,7 +321,7 @@ JWT_SECRET =
|
||||
| `--jwt-secret` | 自动生成 | JWT 签名密钥(留空则持久化到 `data/.jwt_secret`) |
|
||||
| `--service` | (空) | `install` / `uninstall` / `start` / `stop` / `restart` / `status` |
|
||||
|
||||
**环境变量(容器 / 编排,优先级低于命令行):** `JIANG13_HTTP_PORT`、`JIANG13_DATA`、`JIANG13_JWT_SECRET`、`JIANG13_CONFIG`、`JIANG13_WORK_PATH`
|
||||
**环境变量(容器 / 编排,优先级低于命令行):** `JIANG13_HTTP_PORT`、`JIANG13_DATA`、`JIANG13_JWT_SECRET`、`JIANG13_CONFIG`、`JIANG13_WORK_PATH`、`JIANG13_COMMUNITY_HUB`(非官网枢纽镜像用;`bbs.iioio.com` 按域名自动为枢纽,见上表)
|
||||
|
||||
### 5. 注册为系统服务(可选)
|
||||
|
||||
@@ -405,13 +434,15 @@ jiang13-forum/
|
||||
|
||||
```
|
||||
data/
|
||||
├── jiang13.db # SQLite 主数据库
|
||||
├── jiang13.db # SQLite 主数据库(不含浏览量)
|
||||
├── monitor.db # 网站监控 page_views
|
||||
├── jiang13.log # 运行日志
|
||||
├── filter_words.txt # 敏感词配置
|
||||
├── .jwt_secret # JWT 密钥(自动生成)
|
||||
├── logs/access/ # 网站监控请求日志(按日 jsonl)
|
||||
├── uploads/avatars/ # 用户头像
|
||||
├── uploads/posts/ # 帖子正文图片
|
||||
└── jiang13_backup_*.db # 后台导出的备份
|
||||
└── jiang13_backup_*.db # 后台导出的主库备份
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -13,3 +13,13 @@ DATA = data
|
||||
[security]
|
||||
; 留空则自动生成并持久化到 data/.jwt_secret(勿把生产密钥提交到仓库)
|
||||
JWT_SECRET =
|
||||
|
||||
; ---------------------------------------------------------------------------
|
||||
; 维护者选项(默认关闭;普通自托管无需开启)
|
||||
; 开启后本站可接收其它实例「自愿向官方演示站」的心跳,并在后台「公网实例」展示。
|
||||
; 官方演示站 bbs.iioio.com 会按域名自动识别为枢纽,无需开启本项。
|
||||
; 本开关仅用于非 bbs.iioio.com 的枢纽镜像 / 预发环境。
|
||||
; 等价环境变量:JIANG13_COMMUNITY_HUB=1
|
||||
; ---------------------------------------------------------------------------
|
||||
; [community]
|
||||
; HUB = false
|
||||
|
||||
@@ -12,7 +12,7 @@ $AppName = 'jiang13'
|
||||
$MainPkg = './cmd/jiang13'
|
||||
$BuildDir = 'dist'
|
||||
$DevDataDir = 'dist/data'
|
||||
$Version = '1.0.0'
|
||||
$Version = '1.1.6'
|
||||
$RegistryImage = 'hangzhang714128/jiang13-forum'
|
||||
$Ldlags = "-s -w -X main.version=$Version"
|
||||
|
||||
|
||||
@@ -8,12 +8,14 @@ import (
|
||||
"github.com/kardianos/service"
|
||||
|
||||
"git.iioio.com/freefire/jiang13-forum/config"
|
||||
appsvc "git.iioio.com/freefire/jiang13-forum/service"
|
||||
)
|
||||
|
||||
// version 由构建脚本通过 -ldflags "-X main.version=..." 注入
|
||||
var version = "dev"
|
||||
|
||||
func main() {
|
||||
appsvc.SetAppVersion(version)
|
||||
cfg, err := config.Parse()
|
||||
if err != nil {
|
||||
log.Fatalf("配置解析失败: %v", err)
|
||||
|
||||
@@ -78,6 +78,9 @@ func (p *program) setup() error {
|
||||
if err := model.InitDB(cfg.DBPath()); err != nil {
|
||||
return fmt.Errorf("数据库初始化失败: %w", err)
|
||||
}
|
||||
if err := model.InitMonitorDB(cfg.MonitorDBPath()); err != nil {
|
||||
return fmt.Errorf("监控库初始化失败: %w", err)
|
||||
}
|
||||
|
||||
engine, err := router.Setup(cfg)
|
||||
if err != nil {
|
||||
|
||||
410
cmd/monitor-geo-check/main.go
Normal file
410
cmd/monitor-geo-check/main.go
Normal file
@@ -0,0 +1,410 @@
|
||||
// 只读诊断:检查 Geo 库与 page_views 地理字段,或对指定 IP 试查中文映射结果。
|
||||
//
|
||||
// go run ./cmd/monitor-geo-check -db data/monitor.db
|
||||
// go run ./cmd/monitor-geo-check -db data/monitor.db -ip 14.109.35.246
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.iioio.com/freefire/jiang13-forum/service"
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func main() {
|
||||
dbPath := flag.String("db", filepath.Join("data", "monitor.db"), "含 page_views 的 SQLite(默认 data/monitor.db)")
|
||||
ipLookup := flag.String("ip", "", "对指定 IP 试查 BIN+ASN(不写库)")
|
||||
flag.Parse()
|
||||
|
||||
abs, err := filepath.Abs(*dbPath)
|
||||
if err != nil {
|
||||
fatalf("解析路径失败: %v", err)
|
||||
}
|
||||
dataDir := filepath.Dir(abs)
|
||||
|
||||
if *ipLookup == "" {
|
||||
if st, err := os.Stat(abs); err != nil || st.IsDir() {
|
||||
fatalf("数据库不存在: %s", abs)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("数据库: %s\n", abs)
|
||||
fmt.Printf("数据目录: %s\n\n", dataDir)
|
||||
|
||||
suite := service.NewGeoIPService(dataDir)
|
||||
defer suite.Close()
|
||||
printGeoFiles(dataDir, suite)
|
||||
|
||||
if ip := strings.TrimSpace(*ipLookup); ip != "" {
|
||||
lookupIP(suite, ip)
|
||||
fmt.Println()
|
||||
if _, err := os.Stat(abs); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
db, err := gorm.Open(sqlite.Open(abs), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
fatalf("打开数据库失败: %v", err)
|
||||
}
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
fatalf("获取连接失败: %v", err)
|
||||
}
|
||||
defer sqlDB.Close()
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
|
||||
if !tableExists(db, "page_views") {
|
||||
fatalf("表 page_views 不存在(请确认指向 data/monitor.db,或尚未写入过浏览量)")
|
||||
}
|
||||
|
||||
have := columnSet(db)
|
||||
printColumnPresence(have)
|
||||
|
||||
since := time.Now().AddDate(0, 0, -30)
|
||||
var total, recentNonBot, withCountry, withRegion, withCity, withASN int64
|
||||
_ = db.Table("page_views").Count(&total).Error
|
||||
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ?", since, false).Count(&recentNonBot).Error
|
||||
|
||||
fmt.Println("=== page_views 统计(近 30 日非 bot)===")
|
||||
fmt.Printf("总量: %d\n", total)
|
||||
fmt.Printf("近 30 日非 bot: %d\n", recentNonBot)
|
||||
|
||||
if have["country"] {
|
||||
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ? AND country <> ''", since, false).Count(&withCountry).Error
|
||||
fmt.Printf("有国家: %d\n", withCountry)
|
||||
} else {
|
||||
fmt.Println("有国家: (列缺失)")
|
||||
}
|
||||
if have["region"] || have["region_iso"] {
|
||||
cond := "created_at >= ? AND is_bot = ?"
|
||||
parts := []string{}
|
||||
if have["region"] {
|
||||
parts = append(parts, "region <> ''")
|
||||
}
|
||||
if have["region_iso"] {
|
||||
parts = append(parts, "region_iso <> ''")
|
||||
}
|
||||
_ = db.Table("page_views").
|
||||
Where(cond+" AND ("+strings.Join(parts, " OR ")+")", since, false).
|
||||
Count(&withRegion).Error
|
||||
fmt.Printf("有省字段: %d\n", withRegion)
|
||||
} else {
|
||||
fmt.Println("有省字段: (列缺失)")
|
||||
}
|
||||
if have["city"] {
|
||||
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ? AND city <> ''", since, false).Count(&withCity).Error
|
||||
fmt.Printf("有城市: %d\n", withCity)
|
||||
} else {
|
||||
fmt.Println("有城市: (列缺失)")
|
||||
}
|
||||
if have["asn"] {
|
||||
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ? AND asn > 0", since, false).Count(&withASN).Error
|
||||
fmt.Printf("有 ASN: %d\n", withASN)
|
||||
} else {
|
||||
fmt.Println("有 ASN: (列缺失)")
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
fmt.Println("=== 近 30 日省级 Top(country / region / region_iso)===")
|
||||
if !(have["region"] || have["region_iso"]) {
|
||||
fmt.Println("(省列尚未迁移,跳过)")
|
||||
} else {
|
||||
type regionRow struct {
|
||||
Country string
|
||||
Region string
|
||||
RegionISO string `gorm:"column:region_iso"`
|
||||
Count int64
|
||||
}
|
||||
parts := []string{}
|
||||
if have["region"] {
|
||||
parts = append(parts, "region <> ''")
|
||||
}
|
||||
if have["region_iso"] {
|
||||
parts = append(parts, "region_iso <> ''")
|
||||
}
|
||||
selParts := []string{}
|
||||
groupParts := []string{}
|
||||
if have["country"] {
|
||||
selParts = append(selParts, "country")
|
||||
groupParts = append(groupParts, "country")
|
||||
} else {
|
||||
selParts = append(selParts, "'' as country")
|
||||
}
|
||||
if have["region"] {
|
||||
selParts = append(selParts, "region")
|
||||
groupParts = append(groupParts, "region")
|
||||
} else {
|
||||
selParts = append(selParts, "'' as region")
|
||||
}
|
||||
if have["region_iso"] {
|
||||
selParts = append(selParts, "region_iso")
|
||||
groupParts = append(groupParts, "region_iso")
|
||||
} else {
|
||||
selParts = append(selParts, "'' as region_iso")
|
||||
}
|
||||
selParts = append(selParts, "COUNT(*) as count")
|
||||
var regions []regionRow
|
||||
_ = db.Table("page_views").
|
||||
Select(strings.Join(selParts, ", ")).
|
||||
Where("created_at >= ? AND is_bot = ? AND ("+strings.Join(parts, " OR ")+")", since, false).
|
||||
Group(strings.Join(groupParts, ", ")).
|
||||
Order("count DESC").
|
||||
Limit(20).
|
||||
Scan(®ions).Error
|
||||
if len(regions) == 0 {
|
||||
fmt.Println("(空)")
|
||||
} else {
|
||||
for i, r := range regions {
|
||||
fmt.Printf("%2d. %s | %s | %s | %d\n", i+1, r.Country, r.Region, r.RegionISO, r.Count)
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
fmt.Println("=== 对账抽样(近 30 日非 bot)===")
|
||||
printGeoReconcileSamples(db, have, since)
|
||||
fmt.Println()
|
||||
|
||||
fmt.Println("=== 样例行(近 30 日,最多 10 条)===")
|
||||
cols := []string{"id", "created_at", "path", "is_bot"}
|
||||
for _, c := range []string{"ip", "country", "region", "region_iso", "city", "asn", "as_org"} {
|
||||
if have[c] {
|
||||
cols = append(cols, c)
|
||||
}
|
||||
}
|
||||
type sample struct {
|
||||
ID uint
|
||||
CreatedAt time.Time
|
||||
IP string
|
||||
Country string
|
||||
Region string
|
||||
RegionISO string `gorm:"column:region_iso"`
|
||||
City string
|
||||
ASN uint
|
||||
ASOrg string `gorm:"column:as_org"`
|
||||
Path string
|
||||
IsBot bool
|
||||
}
|
||||
var samples []sample
|
||||
_ = db.Table("page_views").
|
||||
Select(strings.Join(cols, ", ")).
|
||||
Where("created_at >= ?", since).
|
||||
Order("id DESC").
|
||||
Limit(10).
|
||||
Scan(&samples).Error
|
||||
if len(samples) == 0 {
|
||||
fmt.Println("(无近 30 日 pageview)")
|
||||
} else {
|
||||
for _, s := range samples {
|
||||
fmt.Printf("#%d %s ip=%s country=%q region=%q iso=%q city=%q asn=%d org=%q bot=%v path=%s\n",
|
||||
s.ID, s.CreatedAt.Format("2006-01-02 15:04:05"), s.IP,
|
||||
s.Country, s.Region, s.RegionISO, s.City, s.ASN, s.ASOrg, s.IsBot, s.Path)
|
||||
}
|
||||
}
|
||||
|
||||
regionReady := have["region"] || have["region_iso"]
|
||||
if !regionReady || withRegion == 0 {
|
||||
fmt.Fprintln(os.Stderr, "")
|
||||
fmt.Fprintln(os.Stderr, "提示: 近 30 日无省级字段。中国地图「暂无省级访问数据」属预期。")
|
||||
if !regionReady {
|
||||
fmt.Fprintln(os.Stderr, "当前库缺 region/region_iso 列:请先启动一次主程序以完成 AutoMigrate。")
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, "请确认数据目录已放置 IP2LOCATION-LITE-DB3.BIN 与 GeoLite2-ASN.mmdb,且有公网访问产生的 pageview。")
|
||||
fmt.Fprintln(os.Stderr, "本机/私网 IP 通常解不出省,属正常。")
|
||||
fmt.Fprintln(os.Stderr, "注意: 请求日志有地理 ≠ 概览地图/排行有数据(后者只读 page_views)。")
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
func printGeoReconcileSamples(db *gorm.DB, have map[string]bool, since time.Time) {
|
||||
type sample struct {
|
||||
ID uint
|
||||
CreatedAt time.Time
|
||||
IP string
|
||||
Country string
|
||||
Region string
|
||||
RegionISO string `gorm:"column:region_iso"`
|
||||
City string
|
||||
ASN uint
|
||||
ASOrg string `gorm:"column:as_org"`
|
||||
Path string
|
||||
}
|
||||
selCols := []string{"id", "created_at", "path"}
|
||||
for _, c := range []string{"ip", "country", "region", "region_iso", "city", "asn", "as_org"} {
|
||||
if have[c] {
|
||||
selCols = append(selCols, c)
|
||||
}
|
||||
}
|
||||
sel := strings.Join(selCols, ", ")
|
||||
|
||||
printBlock := func(title string, n int64, rows []sample) {
|
||||
fmt.Printf("%s: %d\n", title, n)
|
||||
if len(rows) == 0 {
|
||||
return
|
||||
}
|
||||
for _, s := range rows {
|
||||
fmt.Printf(" #%d %s ip=%s country=%q region=%q iso=%q city=%q asn=%d org=%q path=%s\n",
|
||||
s.ID, s.CreatedAt.Format("2006-01-02 15:04:05"), s.IP,
|
||||
s.Country, s.Region, s.RegionISO, s.City, s.ASN, s.ASOrg, s.Path)
|
||||
}
|
||||
}
|
||||
|
||||
if have["city"] {
|
||||
var n int64
|
||||
_ = db.Table("page_views").
|
||||
Where("created_at >= ? AND is_bot = ? AND city <> '' AND city GLOB '[A-Za-z]*'", since, false).
|
||||
Count(&n).Error
|
||||
var rows []sample
|
||||
_ = db.Table("page_views").
|
||||
Select(sel).
|
||||
Where("created_at >= ? AND is_bot = ? AND city <> '' AND city GLOB '[A-Za-z]*'", since, false).
|
||||
Order("id DESC").
|
||||
Limit(5).
|
||||
Scan(&rows).Error
|
||||
printBlock("英文城市名(可能未中文化)", n, rows)
|
||||
} else {
|
||||
fmt.Println("英文城市名: (city 列缺失)")
|
||||
}
|
||||
|
||||
if have["region"] || have["region_iso"] {
|
||||
cond := "created_at >= ? AND is_bot = ? AND country <> ''"
|
||||
emptyParts := []string{}
|
||||
if have["region"] {
|
||||
emptyParts = append(emptyParts, "(region = '' OR region IS NULL OR region = '-')")
|
||||
}
|
||||
if have["region_iso"] {
|
||||
emptyParts = append(emptyParts, "(region_iso = '' OR region_iso IS NULL)")
|
||||
}
|
||||
where := cond + " AND (" + strings.Join(emptyParts, " AND ") + ")"
|
||||
var n int64
|
||||
_ = db.Table("page_views").Where(where, since, false).Count(&n).Error
|
||||
var rows []sample
|
||||
_ = db.Table("page_views").
|
||||
Select(sel).
|
||||
Where(where, since, false).
|
||||
Order("id DESC").
|
||||
Limit(5).
|
||||
Scan(&rows).Error
|
||||
printBlock("有国家但省为空", n, rows)
|
||||
} else {
|
||||
fmt.Println("有国家但省为空: (省列缺失)")
|
||||
}
|
||||
|
||||
if have["asn"] {
|
||||
var n int64
|
||||
_ = db.Table("page_views").
|
||||
Where("created_at >= ? AND is_bot = ? AND (asn = 0 OR asn IS NULL)", since, false).
|
||||
Count(&n).Error
|
||||
var rows []sample
|
||||
_ = db.Table("page_views").
|
||||
Select(sel).
|
||||
Where("created_at >= ? AND is_bot = ? AND (asn = 0 OR asn IS NULL)", since, false).
|
||||
Order("id DESC").
|
||||
Limit(5).
|
||||
Scan(&rows).Error
|
||||
printBlock("asn=0(无运营商)", n, rows)
|
||||
} else {
|
||||
fmt.Println("asn=0: (asn 列缺失)")
|
||||
}
|
||||
}
|
||||
|
||||
func printGeoFiles(dataDir string, suite *service.GeoIPService) {
|
||||
fmt.Println("=== Geo 数据文件 ===")
|
||||
v4, v6, asn, country := suite.Paths()
|
||||
for _, item := range []struct {
|
||||
name string
|
||||
path string
|
||||
ok bool
|
||||
}{
|
||||
{"IP2LOCATION-LITE-DB3.BIN", v4, suite.BINV4Available()},
|
||||
{"IP2LOCATION-LITE-DB3.IPV6.BIN", v6, suite.BINV6Available()},
|
||||
{"GeoLite2-ASN.mmdb", asn, suite.ASNAvailable()},
|
||||
{"GeoLite2-Country.mmdb", country, suite.CountryAvailable()},
|
||||
} {
|
||||
st, err := os.Stat(item.path)
|
||||
if err != nil {
|
||||
fmt.Printf("%s: 不存在\n", item.name)
|
||||
continue
|
||||
}
|
||||
loaded := "未加载"
|
||||
if item.ok {
|
||||
loaded = "已加载"
|
||||
}
|
||||
fmt.Printf("%s: 存在 (%d bytes, mtime %s) · %s\n", item.name, st.Size(), st.ModTime().Format(time.RFC3339), loaded)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func lookupIP(suite *service.GeoIPService, ipStr string) {
|
||||
fmt.Printf("=== IP 试查 %s(中文映射后)===\n", ipStr)
|
||||
info := suite.Lookup(ipStr)
|
||||
if info.Country == "" && info.Region == "" && info.City == "" && info.ASN == 0 {
|
||||
fmt.Println("未解析到地理信息(请确认 BIN/ASN 文件存在且 IP 为公网地址)")
|
||||
return
|
||||
}
|
||||
fmt.Printf("国家 ISO: %s (%s)\n", info.Country, service.CountryLabelZh(info.Country))
|
||||
if info.Region != "" || info.RegionISO != "" {
|
||||
fmt.Printf("省/州: %s / %s\n", info.Region, info.RegionISO)
|
||||
}
|
||||
if info.City != "" {
|
||||
fmt.Printf("城市: %s\n", info.City)
|
||||
}
|
||||
if info.ASN > 0 || info.ASOrg != "" {
|
||||
fmt.Printf("ASN: AS%d %s\n", info.ASN, info.ASOrg)
|
||||
}
|
||||
}
|
||||
|
||||
func tableExists(db *gorm.DB, name string) bool {
|
||||
var n int
|
||||
err := db.Raw(
|
||||
`SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?`, name,
|
||||
).Scan(&n).Error
|
||||
return err == nil && n > 0
|
||||
}
|
||||
|
||||
func columnSet(db *gorm.DB) map[string]bool {
|
||||
type colRow struct {
|
||||
Name string `gorm:"column:name"`
|
||||
}
|
||||
var cols []colRow
|
||||
_ = db.Raw(`PRAGMA table_info(page_views)`).Scan(&cols).Error
|
||||
have := map[string]bool{}
|
||||
for _, c := range cols {
|
||||
have[c.Name] = true
|
||||
}
|
||||
return have
|
||||
}
|
||||
|
||||
func printColumnPresence(have map[string]bool) {
|
||||
need := []string{"ip", "country", "region", "region_iso", "city", "asn", "as_org"}
|
||||
fmt.Println("=== page_views 列 ===")
|
||||
missing := false
|
||||
for _, n := range need {
|
||||
if have[n] {
|
||||
fmt.Printf("%s: 有\n", n)
|
||||
} else {
|
||||
fmt.Printf("%s: 缺失\n", n)
|
||||
missing = true
|
||||
}
|
||||
}
|
||||
fmt.Println()
|
||||
if missing {
|
||||
fmt.Fprintln(os.Stderr, "提示: 缺列时请先启动一次主程序以完成监控库 AutoMigrate。")
|
||||
fmt.Fprintln(os.Stderr, "")
|
||||
}
|
||||
}
|
||||
|
||||
func fatalf(format string, args ...any) {
|
||||
fmt.Fprintf(os.Stderr, format+"\n", args...)
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -32,6 +32,9 @@ type Config struct {
|
||||
ServiceAction string
|
||||
// 开发模式:后端代理前端请求到 Vite 开发服务器(非内嵌静态资源)
|
||||
DevMode bool
|
||||
// CommunityHub 维护者选项:开启后本站接收其它实例自愿上报(默认关闭)。
|
||||
// 官方站 bbs.iioio.com 会按域名自动识别为枢纽,无需开启;本项仅给非官网枢纽镜像。
|
||||
CommunityHub bool
|
||||
}
|
||||
|
||||
// Parse 解析命令行、环境变量与 app.ini,并初始化数据目录
|
||||
@@ -108,6 +111,11 @@ func Parse() (*Config, error) {
|
||||
jwtSecret = strings.TrimSpace(*jwtFlag)
|
||||
}
|
||||
|
||||
communityHub := fileCfg.CommunityHub
|
||||
if v := envBoolOrNil(envCommunityHub); v != nil {
|
||||
communityHub = *v
|
||||
}
|
||||
|
||||
cfg := &Config{
|
||||
WorkPath: workPath,
|
||||
ConfigFile: configFile,
|
||||
@@ -117,6 +125,7 @@ func Parse() (*Config, error) {
|
||||
LogFile: filepath.Join(absData, "jiang13.log"),
|
||||
ServiceAction: action,
|
||||
DevMode: *devFlag,
|
||||
CommunityHub: communityHub,
|
||||
}
|
||||
|
||||
needDirs := action == "" || action == "install"
|
||||
@@ -184,6 +193,7 @@ func ensureDataDirs(dataDir string) error {
|
||||
filepath.Join(dataDir, "uploads", "avatars"),
|
||||
filepath.Join(dataDir, "uploads", "posts"),
|
||||
filepath.Join(dataDir, "uploads", "site"),
|
||||
filepath.Join(dataDir, "logs", "access"),
|
||||
} {
|
||||
if err := os.MkdirAll(sub, 0755); err != nil {
|
||||
return fmt.Errorf("创建上传目录失败: %w", err)
|
||||
@@ -218,11 +228,16 @@ func validServiceAction(action string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// DBPath 返回 SQLite 数据库文件路径
|
||||
// DBPath 返回主库 SQLite 路径
|
||||
func (c *Config) DBPath() string {
|
||||
return filepath.Join(c.DataDir, "jiang13.db")
|
||||
}
|
||||
|
||||
// MonitorDBPath 返回监控独立库路径(page_views)
|
||||
func (c *Config) MonitorDBPath() string {
|
||||
return filepath.Join(c.DataDir, "monitor.db")
|
||||
}
|
||||
|
||||
// AvatarUploadDir 返回头像上传目录
|
||||
func (c *Config) AvatarUploadDir() string {
|
||||
return filepath.Join(c.DataDir, "uploads", "avatars")
|
||||
|
||||
@@ -8,11 +8,12 @@ import (
|
||||
|
||||
// 容器 / 编排常用环境变量(优先级:命令行 > 环境变量 > app.ini > 内置默认)
|
||||
const (
|
||||
envWorkPath = "JIANG13_WORK_PATH"
|
||||
envConfig = "JIANG13_CONFIG"
|
||||
envHTTPPort = "JIANG13_HTTP_PORT"
|
||||
envData = "JIANG13_DATA"
|
||||
envJWTSecret = "JIANG13_JWT_SECRET"
|
||||
envWorkPath = "JIANG13_WORK_PATH"
|
||||
envConfig = "JIANG13_CONFIG"
|
||||
envHTTPPort = "JIANG13_HTTP_PORT"
|
||||
envData = "JIANG13_DATA"
|
||||
envJWTSecret = "JIANG13_JWT_SECRET"
|
||||
envCommunityHub = "JIANG13_COMMUNITY_HUB"
|
||||
)
|
||||
|
||||
func envOrDefault(key string) string {
|
||||
@@ -30,3 +31,21 @@ func envIntOrZero(key string) int {
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// envBoolOrNil 解析布尔环境变量;未设置返回 nil
|
||||
func envBoolOrNil(key string) *bool {
|
||||
v := strings.ToLower(envOrDefault(key))
|
||||
if v == "" {
|
||||
return nil
|
||||
}
|
||||
switch v {
|
||||
case "1", "true", "yes", "on":
|
||||
t := true
|
||||
return &t
|
||||
case "0", "false", "no", "off":
|
||||
f := false
|
||||
return &f
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,9 +18,10 @@ const (
|
||||
|
||||
// fileSettings 从 app.ini 读出的原始值(尚未解析为绝对路径)
|
||||
type fileSettings struct {
|
||||
Port int
|
||||
DataRel string
|
||||
JWTSecret string
|
||||
Port int
|
||||
DataRel string
|
||||
JWTSecret string
|
||||
CommunityHub bool // 维护者选项:是否作为社区枢纽收报
|
||||
}
|
||||
|
||||
func defaultFileSettings() fileSettings {
|
||||
@@ -62,6 +63,12 @@ func loadAppINI(path string) (fileSettings, error) {
|
||||
out.JWTSecret = strings.TrimSpace(sec.Key("JWT_SECRET").String())
|
||||
}
|
||||
|
||||
if sec, err := cfg.GetSection("community"); err == nil {
|
||||
if k := sec.Key("HUB"); k.String() != "" {
|
||||
out.CommunityHub = k.MustBool(false)
|
||||
}
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
|
||||
105
docs/docker-data.md
Normal file
105
docs/docker-data.md
Normal file
@@ -0,0 +1,105 @@
|
||||
# Docker 数据持久化说明
|
||||
|
||||
Docker 部署时**默认只挂载一个目录**,不是分别映射「数据库文件夹」和「附件文件夹」两个卷。
|
||||
|
||||
## 挂载对应关系
|
||||
|
||||
| 宿主机 | 容器内 |
|
||||
|--------|--------|
|
||||
| 任意目录或 named volume(如 `jiang13-data`) | **`/data`** |
|
||||
|
||||
**示例:**
|
||||
|
||||
```bash
|
||||
docker run -d --name jiang13 \
|
||||
-p 3000:3000 \
|
||||
-v /你的路径/jiang13-data:/data \
|
||||
--restart unless-stopped \
|
||||
hangzhang714128/jiang13-forum:latest
|
||||
```
|
||||
|
||||
或在 `docker-compose.yml` 中:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- jiang13-data:/data
|
||||
# 或绑定宿主机目录:
|
||||
# - ./data:/data
|
||||
```
|
||||
|
||||
## `/data` 目录结构
|
||||
|
||||
数据库与附件都在同一个 `/data` 挂载内:
|
||||
|
||||
```
|
||||
/data/
|
||||
├── jiang13.db # SQLite 主数据库(不含浏览量)
|
||||
├── monitor.db # 网站监控 page_views
|
||||
├── uploads/ # 附件根目录
|
||||
│ ├── avatars/ # 用户头像
|
||||
│ └── posts/ # 帖子图片等
|
||||
├── logs/
|
||||
│ └── access/ # 网站监控请求日志(按日 jsonl)
|
||||
│ └── YYYY-MM-DD.jsonl
|
||||
├── IP2LOCATION-LITE-DB3.BIN # 可选:IPv4 城市库(监控)
|
||||
├── IP2LOCATION-LITE-DB3.IPV6.BIN # 可选:IPv6 城市库
|
||||
├── GeoLite2-ASN.mmdb # 可选:ASN/运营商
|
||||
├── GeoLite2-Country.mmdb # 可选:国家兜底
|
||||
├── .jwt_secret # JWT 密钥(自动生成)
|
||||
├── filter_words.txt # 敏感词配置
|
||||
└── jiang13.log # 运行日志(若启用)
|
||||
```
|
||||
|
||||
| 用途 | 路径 |
|
||||
|------|------|
|
||||
| 主数据库 | `/data/jiang13.db` |
|
||||
| 监控浏览量 | `/data/monitor.db` |
|
||||
| 附件 | `/data/uploads/` |
|
||||
| 请求日志(监控) | `/data/logs/access/` |
|
||||
| 地理库(可选) | `/data/IP2LOCATION-LITE-DB3*.BIN`、`GeoLite2-ASN.mmdb` 等 |
|
||||
|
||||
官方镜像不要求拆成两个 volume;挂好 `/data` 即可同时持久化 SQLite、上传文件与监控日志。
|
||||
|
||||
地理库与 BIN **不内置**于 Docker 镜像。详见 [网站监控设计](monitor.md)。管理端展示完整客户端 IP(不做脱敏)。
|
||||
|
||||
## 设计说明:为何只挂一个 `/data`
|
||||
|
||||
对本项目(单容器、SQLite、默认可本地存附件)而言,**一个数据卷是合理默认**:
|
||||
|
||||
- 部署成本最低,不易漏挂导致「重启丢图 / 丢库」
|
||||
- 备份、迁移时拷贝或快照整个 `/data` 即可恢复站点状态
|
||||
- 密钥(`.jwt_secret`)、敏感词与库同目录,避免「库还在、登录全失效」这类半残状态
|
||||
|
||||
若你习惯「数据库文件夹 / 附件文件夹」分开填写:在本镜像中它们分别是 **`/data` 下的文件与子目录**,不是两个独立容器路径。
|
||||
|
||||
附件特别大、希望对象存储时:优先使用管理后台的 **S3 兼容存储**,而不是拆 Docker 卷。
|
||||
|
||||
## 后续计划(可选增强,非必须)
|
||||
|
||||
按优先级,仅在有明确需求时做:
|
||||
|
||||
1. **文档与面板提示(优先)**
|
||||
- README / 1Panel 说明中固定话术:「只需挂载 `/data`;数据库=`jiang13.db`,监控=`monitor.db`,附件=`uploads/`」。
|
||||
- 本页保持为权威说明,避免用户误以为漏了一个卷。
|
||||
|
||||
2. **进阶:同一 DataDir 下拆挂子路径(文档级,无需改代码)**
|
||||
若必须把库与附件分到不同宿主机磁盘,可在仍使用容器 `/data` 的前提下分别绑定,例如:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
# 推荐:父目录一次挂载
|
||||
- /ssd/jiang13:/data
|
||||
# 或仅把附件分到大容量盘(需保证 /data 下其余文件仍可写)
|
||||
- /ssd/jiang13:/data
|
||||
- /hdd/jiang13-uploads:/data/uploads
|
||||
```
|
||||
|
||||
拆挂时仍要保证 `/data` 下 `.jwt_secret` 等文件可写;不熟悉 Docker 时请继续只用单个 `/data` 挂载。
|
||||
|
||||
3. **产品级:可配置上传根目录(中期)**
|
||||
- 环境变量或 `app.ini` 支持 `upload_dir` 与 `data_dir` 分离。
|
||||
- Docker 示例改为可选双卷;**默认仍单卷**,避免破坏现有部署。
|
||||
|
||||
4. **不做的事**
|
||||
- 不为「看起来像 WordPress」而强制双卷。
|
||||
- 不在未支持分离配置前,在 UI 里假装有两个独立数据根。
|
||||
79
docs/monitor.md
Normal file
79
docs/monitor.md
Normal file
@@ -0,0 +1,79 @@
|
||||
# 网站监控设计说明
|
||||
|
||||
管理端「网站监控」:轻量自建访问统计,对标 1Panel 思路——**请求流水写文件、访客地理写独立库**,开启后不拖慢前台读帖。
|
||||
|
||||
## 双通道数据
|
||||
|
||||
| 数据 | 存储 | 用途 |
|
||||
|------|------|------|
|
||||
| 请求日志 | `{DataDir}/logs/access/YYYY-MM-DD.jsonl` | 请求日志页、请求数/流量/4xx·5xx、实时曲线 |
|
||||
| page_views | `{DataDir}/monitor.db`(SQLite) | 浏览量/访客、国家/省/城市/运营商排行与地图 |
|
||||
|
||||
请求日志**只写 jsonl**,不进 SQLite。删除过期 `.jsonl` 即释放磁盘。
|
||||
|
||||
`page_views` **不进主库** `jiang13.db`。后台「导出备份」只含主库,不含浏览量。
|
||||
|
||||
### 文件行格式(JSONL)
|
||||
|
||||
每行一条 JSON,字段包括:`t`(RFC3339)、`method`、`path`、`status`、`bytes`、`duration_ms`、`ip`、`ua`、`referer`、`country`、`region`、`region_iso`、`city`、`asn`、`as_org`、`is_bot`。
|
||||
|
||||
### 保留天数
|
||||
|
||||
- `monitor_retention_days`:仅 **page_views**(默认 30)
|
||||
- `monitor_access_log_retention_days`:请求日志文件(默认 7)
|
||||
|
||||
## 地理数据文件
|
||||
|
||||
放在数据目录(与 `jiang13.db` 同级),有则加载、无则静默降级:
|
||||
|
||||
| 文件 | 用途 |
|
||||
|------|------|
|
||||
| `IP2LOCATION-LITE-DB3.BIN` | IPv4 国家/省/城市 |
|
||||
| `IP2LOCATION-LITE-DB3.IPV6.BIN` | IPv6 国家/省/城市 |
|
||||
| `GeoLite2-ASN.mmdb` | ASN / 运营商 |
|
||||
| `GeoLite2-Country.mmdb` | 可选:BIN 未命中时国家兜底 |
|
||||
|
||||
CDN 头(如 `CF-IPCountry`)仅在本地库无国家码时补全。不落 Lat/Lon/Zip/TimeZone。管理端展示**完整客户端 IP**。
|
||||
|
||||
写入时做本地中文映射(省 / 中国城市按 IP2Location 英文名 / 运营商);同音城市(如苏州/宿州)按省份歧义。`country` 存 ISO2,展示用中文名。历史 `page_views` / 请求日志不会回写,仅影响新写入。
|
||||
|
||||
**口径提示:** 访客地图与城市/运营商排行只聚合 `page_views`(前台浏览);请求日志里的地理来自 access JSONL。仅有请求日志、没有前台浏览时,地图与排行可为空——属预期。
|
||||
|
||||
## 写入路径(性能)
|
||||
|
||||
1. 中间件:监控关闭或命中排除规则则直接放行;否则 `c.Next()` 后**仅入队**轻量字段(不查 BIN/ASN、不写盘)。
|
||||
2. 后台 flush:出队 → Geo + 中文映射 → append 当日 jsonl + 更新内存实时环。
|
||||
3. 队列上限 8192,满则丢弃新日志(保护内存与磁盘)。
|
||||
4. pageview 信标 QPS 低,可在写入时同步 Geo 后写独立 `monitor.db`(不占用主库连接)。
|
||||
|
||||
**热路径零 Geo、零写库、零写文件。**
|
||||
|
||||
## 请求日志口径(排除规则)
|
||||
|
||||
默认只关心**前台访客**,排除管理员刷后台产生的壳请求:
|
||||
|
||||
- `/admin`、`/api/admin/`
|
||||
- `/api/me`、`/api/site-branding`
|
||||
- `/health`、`/uploads/`、`/media/`、静态后缀、`/api/monitor/pageview` 等
|
||||
|
||||
设置页可「恢复推荐排除规则」。不强制覆盖用户已保存的自定义列表。
|
||||
|
||||
浏览量/访客仍来自前台路由 pageview(后台路径本身不上报)。
|
||||
|
||||
## 实时与聚合
|
||||
|
||||
- 近 1 分钟 / 近 1 小时:内存环(flush 时更新),避免扫全文件。
|
||||
- 今日请求数等:内存日累加器(进程内;重启后自新流量累积,论坛量级可接受)。
|
||||
- 地理排行:仅 `page_views`。
|
||||
|
||||
## 诊断
|
||||
|
||||
```bash
|
||||
go run ./cmd/monitor-geo-check -db data/monitor.db -ip 14.109.35.246
|
||||
```
|
||||
|
||||
会输出 Geo 文件状态、近 30 日省级 Top,以及对账抽样(英文城市名、有国家但省为空、`asn=0`)。
|
||||
## 明确不做
|
||||
|
||||
- 不用 CIDR;不把请求日志写入 SQLite;不把 page_views 写入主库
|
||||
- 不做街道级地图;Docker 镜像不内置 BIN/MMDB
|
||||
@@ -18,6 +18,16 @@
|
||||
|
||||
把原先分篇的「上手 / 功能 / 部署」三帖 **删除**,避免与长文重复。
|
||||
|
||||
## 自定义单页(推荐)
|
||||
|
||||
站务帖之外,建议在后台 **单页管理** 发一篇更新日志,方便 Docker / Windows 用户对照版本:
|
||||
|
||||
| 文件 | 标题 | slug | 操作 |
|
||||
| --- | --- | --- | --- |
|
||||
| [changelog.md](./changelog.md) | 更新日志 | `changelog` | 发布;页脚展示(可选侧栏导航) |
|
||||
|
||||
访问路径:`/page/changelog`。
|
||||
|
||||
## 可选短文
|
||||
|
||||
若站务区希望不止一篇,见 [optional.md](./optional.md):
|
||||
|
||||
145
docs/site-posts/changelog.md
Normal file
145
docs/site-posts/changelog.md
Normal file
@@ -0,0 +1,145 @@
|
||||
# 更新日志
|
||||
|
||||
> 建议标题:更新日志
|
||||
> 建议 slug:`changelog`
|
||||
> 建议路径:`/page/changelog`
|
||||
> 建议操作:后台「单页管理」新建并发布;勾选「页脚展示」(可选「侧栏导航」)
|
||||
> 复制正文时:从下方第一个 `---` **之后**开始粘贴(Markdown 模式)
|
||||
|
||||
---
|
||||
|
||||
Docker 镜像、Windows exe、Linux 单文件 **共用同一版本号**。有新版本时,以本页为准。
|
||||
|
||||
**当前版本:1.1.6**(2026-09-01)
|
||||
|
||||
## 去哪看新版本
|
||||
|
||||
| 渠道 | 看什么 | 地址 |
|
||||
| --- | --- | --- |
|
||||
| 本页 | 版本号、变更说明、升级注意 | 本站 `/page/changelog` |
|
||||
| Docker | 镜像标签(`latest` 与 `1.1.x`) | [Docker Hub · Tags](https://hub.docker.com/r/hangzhang714128/jiang13-forum/tags) |
|
||||
| Windows / Linux | 预编译单文件(与 Docker 同版本) | [Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases) |
|
||||
| 源码 | 提交记录与自行编译 | [Gitea 仓库](https://git.iioio.com/freefire/jiang13-forum) |
|
||||
|
||||
**1.1.6 直接下载:**
|
||||
|
||||
- Windows x64:[jiang13-1.1.6-windows-amd64.exe](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-windows-amd64.exe)
|
||||
- Linux x64:[jiang13-1.1.6-linux-amd64](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-linux-amd64)
|
||||
- 校验文件:[SHA256SUMS.txt](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/SHA256SUMS.txt)
|
||||
|
||||
拉取指定版本镜像:
|
||||
|
||||
```bash
|
||||
docker pull hangzhang714128/jiang13-forum:1.1.6
|
||||
# 或始终跟随最新
|
||||
docker pull hangzhang714128/jiang13-forum:latest
|
||||
```
|
||||
|
||||
Windows:停掉正在跑的进程或服务,用新下载的 exe 覆盖原文件(可改名为 `jiang13.exe`),**不要动**旁边的 `data/` 与 `app.ini`,再启动即可。
|
||||
|
||||
Linux:赋予执行权限后放到原目录覆盖,同样保留 `data/` 与 `app.ini`。
|
||||
|
||||
## 升级注意
|
||||
|
||||
- 一般只需换镜像或换 exe,数据目录向后兼容。
|
||||
- Docker 请继续挂载原来的 `/data` 卷,切勿新建空目录当「升级」。
|
||||
- 升级后若页面样式异常,强制刷新浏览器(Ctrl+F5)。程序也会在前端资源失效时自动硬刷新。
|
||||
|
||||
---
|
||||
|
||||
## 1.1.6 — 2026-09-01
|
||||
|
||||
编辑器插入体验与首页默认 Feed 排序更合理。
|
||||
|
||||
**新增 / 调整**
|
||||
|
||||
- 链接对话框支持网址、链接文字与站内帖子/单页搜索;站内搜索收进「高级选项」,点选同步链接文字
|
||||
- 文章与评论共用统一图片插入选择器(上传 / 链接 / 已上传)
|
||||
- 链接是否新标签打开交由全站设置,对话框不再单独开关
|
||||
- 首页默认「最新」按发帖与最后评论的较晚时间混排,零回复新帖不再沉底
|
||||
- 单页详情右侧栏与帖子共用目录布局;三栏主滚动区统一细绿色滚动条
|
||||
|
||||
**修复**
|
||||
|
||||
- 帖子目录从正文同步派生,避免预取缓存竞态导致空树
|
||||
|
||||
## 1.1.5 — 2026-09-01
|
||||
|
||||
首页首屏与交互更稳,Feed 排序语义更清楚。
|
||||
本版起同时提供 **Docker 镜像** 与 **Windows / Linux 预编译单文件**(Gitea Release `v1.1.5`)。
|
||||
|
||||
**新增 / 调整**
|
||||
|
||||
- 首页改为 Go SSR 与 React hydrate(注水)同构,打开首页不再先闪一层空壳再跳内容
|
||||
- Feed 排序改为:**新评论 / 新帖子 / 推荐帖**;推荐帖只出精华(featured)
|
||||
- 点击排序会强制刷新列表;软刷新时同步站点限额与品牌文案
|
||||
- 返回列表用缓存恢复滚动位置,不再重复请求
|
||||
|
||||
**修复**
|
||||
|
||||
- 发版后软刷新会检测入口壳;chunk(代码分片)404 时自动硬刷新,避免卡在旧页面
|
||||
- 软刷新齐套前保留旧画面,避免一点击就把内容卸光
|
||||
- 补齐 `/favicon.ico` 与页面 head 图标;拆除爬虫专用 HTML
|
||||
- 桌面端隐藏多余的导航汉堡按钮
|
||||
- 帖行评论数、列表「共 N 条」右对齐;排序栏数字紧跟标签
|
||||
- 手机端 SSR 顶栏 / 页脚与 React 一致,减少闪动
|
||||
|
||||
## 1.1.4 — 2026-08-31
|
||||
|
||||
网站监控的地理信息与口径更准确。
|
||||
|
||||
- 补全 IP2Location(IP 地理位置库)中国城市中文名,同名城市按省消歧
|
||||
- 对齐监控概览「双通道」口径文案与诊断抽样说明
|
||||
|
||||
## 1.1.3 — 2026-08-31
|
||||
|
||||
管理后台可看站点访问情况。
|
||||
|
||||
- 新增管理端 **网站监控**:浏览量写入独立 `monitor.db`,与主库分开
|
||||
|
||||
## 1.1.2 — 2026-08-31
|
||||
|
||||
可选接入官方社区展柜。
|
||||
|
||||
- 可选社区上报,以及官方精选展柜(自建站可出现在官方社区列表中)
|
||||
|
||||
## 1.1.1 — 2026-08-31
|
||||
|
||||
- 评论管理操作收进「更多」菜单,管理员界面更干净
|
||||
|
||||
## 1.1.0 — 2026-08-30
|
||||
|
||||
一批社区功能与界面整理,版本号从 1.0 跨到 1.1。
|
||||
|
||||
**新增**
|
||||
|
||||
- 友链申请、独立友链页;页脚左右区域可分别开关
|
||||
- 自定义单页(后台「单页管理」,如本页)
|
||||
- 投票帖、悬赏帖、抽奖帖
|
||||
- 侧栏签到;右侧栏「最新注册」
|
||||
- 搜索重设计:筛选面板、结果页 chips(筛选标签)
|
||||
- 帖子管理收进右上角菜单;手机端评论输入默认折叠
|
||||
|
||||
**优化**
|
||||
|
||||
- 首页帖子列表密度与标题样式
|
||||
- 开源码桶展示加强,去掉 Feed 顶栏统计
|
||||
- 单页编辑、列表留白与友链申请体验
|
||||
- 开发与发行版共用 `dist/data` 数据目录,避免两套数据打架
|
||||
|
||||
**修复**
|
||||
|
||||
- 手机端搜索入口与底部 Sheet(抽屉面板)
|
||||
- 占位头像对比度;无头像用户不再误用游客灰底
|
||||
- 页面双指缩放锁死,正文原图与灯箱仍可 pinch(捏合)放大
|
||||
- 单页正文排版与帖子详情对齐
|
||||
|
||||
## 1.0.0 — 2026-08-23
|
||||
|
||||
首次发布 Docker 镜像 `hangzhang714128/jiang13-forum:1.0.0`。
|
||||
|
||||
当时已包含论坛核心能力:板块与发帖、楼层评论、点赞收藏、私信、TipTap 富文本、贴纸、修订历史、管理后台、OIDC(开放身份连接)/ SSO(单点登录)、邮件验证码、Gitea 仓库同步、SQLite 单二进制部署,以及 Docker 一键运行。
|
||||
|
||||
---
|
||||
|
||||
之后发版时:Docker 推 `x.y.z` + `latest`,Gitea 打 tag `vx.y.z` 并挂上对应 exe / linux 文件,再把新版本写到本页最上方。
|
||||
@@ -14,9 +14,10 @@ import (
|
||||
var staticFS embed.FS
|
||||
|
||||
var (
|
||||
spaTitleRe = regexp.MustCompile(`(?s)<title>.*?</title>`)
|
||||
spaBrandTitleFn func() string
|
||||
spaBrandJSONFn func() []byte // 站点品牌 JSON,注入 window.__J13_BRANDING__
|
||||
spaTitleRe = regexp.MustCompile(`(?s)<title>.*?</title>`)
|
||||
spaBrandTitleFn func() string
|
||||
spaBrandJSONFn func() []byte // 站点品牌 JSON,注入 window.__J13_BRANDING__
|
||||
spaBrandFaviconFn func() string // 站点 Favicon URL,注入 <link rel="icon">
|
||||
)
|
||||
|
||||
// SetSPADocumentTitle 注册站点标题提供者,ServeSPA 会注入到入口 HTML,避免刷新闪烁
|
||||
@@ -29,13 +30,19 @@ func SetSPABrandingJSON(fn func() []byte) {
|
||||
spaBrandJSONFn = fn
|
||||
}
|
||||
|
||||
// SetSPAFaviconURL 注册 Favicon URL 提供者,注入到入口 HTML 的 <link rel="icon">
|
||||
func SetSPAFaviconURL(fn func() string) {
|
||||
spaBrandFaviconFn = fn
|
||||
}
|
||||
|
||||
// SetupEmbed 配置内嵌资源:React SPA 静态资源
|
||||
func SetupEmbed(r *gin.Engine) error {
|
||||
if sub, err := fs.Sub(staticFS, "static/spa/assets"); err == nil {
|
||||
fileServer := http.StripPrefix("/assets", http.FileServer(http.FS(sub)))
|
||||
r.GET("/assets/*filepath", func(c *gin.Context) {
|
||||
// hashed 资源可长期缓存;发版后文件名变更,旧 URL 自然 404
|
||||
c.Header("Cache-Control", "public, max-age=31536000, immutable")
|
||||
// 仅 200 写 immutable,避免中间层把旧 chunk 的 404 长期缓存
|
||||
w := &cacheOnOKWriter{ResponseWriter: c.Writer, cacheControl: "public, max-age=31536000, immutable"}
|
||||
c.Writer = w
|
||||
fileServer.ServeHTTP(c.Writer, c.Request)
|
||||
})
|
||||
}
|
||||
@@ -51,6 +58,30 @@ func SetupEmbed(r *gin.Engine) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// cacheOnOKWriter 仅在最终状态码为 200 时写入长期 Cache-Control
|
||||
type cacheOnOKWriter struct {
|
||||
gin.ResponseWriter
|
||||
cacheControl string
|
||||
wroteHeader bool
|
||||
}
|
||||
|
||||
func (w *cacheOnOKWriter) WriteHeader(code int) {
|
||||
if !w.wroteHeader {
|
||||
w.wroteHeader = true
|
||||
if code == http.StatusOK {
|
||||
w.Header().Set("Cache-Control", w.cacheControl)
|
||||
}
|
||||
}
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (w *cacheOnOKWriter) Write(b []byte) (int, error) {
|
||||
if !w.wroteHeader {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
return w.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
// ServeSPA 返回 React SPA 入口(仅注入站点默认标题)
|
||||
func ServeSPA(c *gin.Context) {
|
||||
ServeSPAWithMeta(c, nil)
|
||||
|
||||
@@ -5,12 +5,16 @@ import (
|
||||
"encoding/json"
|
||||
"html"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// SPAPageMeta 注入到 SPA 入口 HTML 的 SEO / 社交预览元数据(仅 <head>,不写 #root,避免刷新闪屏)
|
||||
var spaRootEmptyRe = regexp.MustCompile(`(?s)<div id="root">\s*</div>`)
|
||||
|
||||
// SPAPageMeta 注入到 SPA 入口 HTML 的 SEO / 社交预览元数据。
|
||||
// 默认不写 #root;首页/板块文档 SSR 可填 RootHTML / BootJSON。
|
||||
type SPAPageMeta struct {
|
||||
Title string // 完整 <title>
|
||||
Description string
|
||||
@@ -23,6 +27,8 @@ type SPAPageMeta struct {
|
||||
Robots string // 如 noindex,nofollow
|
||||
JSONLD string // 已序列化的 JSON-LD 对象(不含 script 标签)
|
||||
Status int // HTTP 状态码,0 视为 200
|
||||
RootHTML string // 可选:写入 #root 的首屏 HTML(首页文档 SSR)
|
||||
BootJSON []byte // 可选:window.__J13_HOME_BOOT__ 合法 JSON
|
||||
}
|
||||
|
||||
// ServeSPAWithMeta 返回带页面级 meta / JSON-LD 的干净 SPA 入口
|
||||
@@ -37,8 +43,9 @@ func ServeSPAWithMeta(c *gin.Context, meta *SPAPageMeta) {
|
||||
return
|
||||
}
|
||||
data = applySPAPageMeta(data, meta)
|
||||
// 入口 HTML 禁止长期缓存,否则发版后仍引用旧 chunk 哈希
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
// 入口 HTML 禁止缓存,否则发版后仍引用旧 chunk 哈希(部分反代对 no-cache 仍会存)
|
||||
c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
c.Header("Pragma", "no-cache")
|
||||
c.Data(status, "text/html; charset=utf-8", data)
|
||||
}
|
||||
|
||||
@@ -56,15 +63,20 @@ func applySPAPageMeta(data []byte, meta *SPAPageMeta) []byte {
|
||||
data = spaTitleRe.ReplaceAll(data, []byte("<title>"+escaped+"</title>"))
|
||||
}
|
||||
|
||||
var head strings.Builder
|
||||
writeMeta(&head, "description", meta.Description)
|
||||
writeMeta(&head, "keywords", meta.Keywords)
|
||||
// —— 静态 SEO HTML(meta / OG / JSON-LD / favicon),紧跟 </title>,不经 JS ——
|
||||
var seo strings.Builder
|
||||
writeMeta(&seo, "description", meta.Description)
|
||||
writeMeta(&seo, "keywords", meta.Keywords)
|
||||
if canonical := strings.TrimSpace(meta.Canonical); canonical != "" {
|
||||
head.WriteString(`<link rel="canonical" href="` + html.EscapeString(canonical) + `"/>`)
|
||||
seo.WriteString(`<link rel="canonical" href="` + html.EscapeString(canonical) + `"/>`)
|
||||
}
|
||||
if favicon := spaFaviconHref(); favicon != "" {
|
||||
seo.WriteString(`<link rel="icon" href="` + html.EscapeString(favicon) + `"/>`)
|
||||
seo.WriteString(`<link rel="shortcut icon" href="` + html.EscapeString(favicon) + `"/>`)
|
||||
}
|
||||
robots := strings.TrimSpace(meta.Robots)
|
||||
if robots != "" {
|
||||
writeMeta(&head, "robots", robots)
|
||||
writeMeta(&seo, "robots", robots)
|
||||
}
|
||||
|
||||
ogType := strings.TrimSpace(meta.OGType)
|
||||
@@ -75,36 +87,63 @@ func applySPAPageMeta(data []byte, meta *SPAPageMeta) []byte {
|
||||
if locale == "" {
|
||||
locale = "zh_CN"
|
||||
}
|
||||
writeProp(&head, "og:type", ogType)
|
||||
writeProp(&head, "og:site_name", meta.SiteName)
|
||||
writeProp(&head, "og:locale", locale)
|
||||
writeProp(&head, "og:title", firstNonEmpty(meta.Title, title))
|
||||
writeProp(&head, "og:description", meta.Description)
|
||||
writeProp(&head, "og:url", meta.Canonical)
|
||||
writeProp(&head, "og:image", meta.OGImage)
|
||||
writeMetaName(&head, "twitter:card", twitterCard(meta.OGImage))
|
||||
writeMetaName(&head, "twitter:title", firstNonEmpty(meta.Title, title))
|
||||
writeMetaName(&head, "twitter:description", meta.Description)
|
||||
writeMetaName(&head, "twitter:image", meta.OGImage)
|
||||
writeProp(&seo, "og:type", ogType)
|
||||
writeProp(&seo, "og:site_name", meta.SiteName)
|
||||
writeProp(&seo, "og:locale", locale)
|
||||
writeProp(&seo, "og:title", firstNonEmpty(meta.Title, title))
|
||||
writeProp(&seo, "og:description", meta.Description)
|
||||
writeProp(&seo, "og:url", meta.Canonical)
|
||||
writeProp(&seo, "og:image", meta.OGImage)
|
||||
writeMetaName(&seo, "twitter:card", twitterCard(meta.OGImage))
|
||||
writeMetaName(&seo, "twitter:title", firstNonEmpty(meta.Title, title))
|
||||
writeMetaName(&seo, "twitter:description", meta.Description)
|
||||
writeMetaName(&seo, "twitter:image", meta.OGImage)
|
||||
|
||||
if jsonld := strings.TrimSpace(meta.JSONLD); jsonld != "" {
|
||||
head.WriteString(`<script type="application/ld+json">`)
|
||||
head.WriteString(jsonld)
|
||||
head.WriteString(`</script>`)
|
||||
// 常规 HTML 节点;仅转义 < 防止提前闭合,不是用 JS 写入
|
||||
seo.WriteString(`<script type="application/ld+json">`)
|
||||
seo.WriteString(string(bytes.ReplaceAll([]byte(jsonld), []byte("<"), []byte(`\u003c`))))
|
||||
seo.WriteString(`</script>`)
|
||||
}
|
||||
|
||||
// 同步注入品牌配置,避免 React 首屏用默认名闪一下
|
||||
if boot := spaBrandingBootScript(); boot != "" {
|
||||
head.WriteString(boot)
|
||||
if seo.Len() > 0 {
|
||||
data = bytes.Replace(data, []byte("</title>"), []byte("</title>\n"+seo.String()), 1)
|
||||
}
|
||||
|
||||
if head.Len() > 0 {
|
||||
data = bytes.Replace(data, []byte("</head>"), []byte(head.String()+"</head>"), 1)
|
||||
// —— 可执行 boot 脚本仍放在 </head> 前 ——
|
||||
var boot strings.Builder
|
||||
if s := spaBrandingBootScript(); s != "" {
|
||||
boot.WriteString(s)
|
||||
}
|
||||
if s := spaHomeBootScript(meta.BootJSON); s != "" {
|
||||
boot.WriteString(s)
|
||||
}
|
||||
if boot.Len() > 0 {
|
||||
data = bytes.Replace(data, []byte("</head>"), []byte(boot.String()+"</head>"), 1)
|
||||
}
|
||||
|
||||
if root := strings.TrimSpace(meta.RootHTML); root != "" {
|
||||
data = injectSPARootHTML(data, root)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
// spaHomeBootScript 生成 window.__J13_HOME_BOOT__=...; 内联脚本(前端灌缓存,非 SEO)
|
||||
func spaHomeBootScript(raw []byte) string {
|
||||
raw = bytes.TrimSpace(raw)
|
||||
if len(raw) == 0 || !json.Valid(raw) {
|
||||
return ""
|
||||
}
|
||||
safe := bytes.ReplaceAll(raw, []byte("<"), []byte(`\u003c`))
|
||||
return "<script>window.__J13_HOME_BOOT__=" + string(safe) + ";</script>"
|
||||
}
|
||||
|
||||
// injectSPARootHTML 将首屏 HTML 写入 #root(允许空白)
|
||||
func injectSPARootHTML(data []byte, rootHTML string) []byte {
|
||||
return spaRootEmptyRe.ReplaceAll(data, []byte(`<div id="root">`+rootHTML+`</div>`))
|
||||
}
|
||||
|
||||
// spaBrandingBootScript 生成 window.__J13_BRANDING__=...; 内联脚本
|
||||
func spaBrandingBootScript() string {
|
||||
if spaBrandJSONFn == nil {
|
||||
@@ -114,7 +153,6 @@ func spaBrandingBootScript() string {
|
||||
if len(raw) == 0 || !json.Valid(raw) {
|
||||
return ""
|
||||
}
|
||||
// 防止 JSON 字符串中的 </script> 提前闭合标签
|
||||
safe := bytes.ReplaceAll(raw, []byte("<"), []byte(`\u003c`))
|
||||
return "<script>window.__J13_BRANDING__=" + string(safe) + ";</script>"
|
||||
}
|
||||
@@ -154,3 +192,11 @@ func firstNonEmpty(vals ...string) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// spaFaviconHref 当前站点配置的 Favicon(相对或绝对 URL)
|
||||
func spaFaviconHref() string {
|
||||
if spaBrandFaviconFn == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(spaBrandFaviconFn())
|
||||
}
|
||||
|
||||
@@ -5,23 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<meta name="description" content="拾三一隅,自在交流" />
|
||||
<title>姜十三论坛 - 拾三一隅,自在交流</title>
|
||||
<style>
|
||||
/* 关键布局样式:在 JS/CSS 包加载前即固定三栏结构,避免刷新时组件错位 */
|
||||
html { scrollbar-gutter: stable; }
|
||||
html, body, #root { height: 100%; margin: 0; touch-action: pan-x pan-y; }
|
||||
body { overflow: hidden; font-size: 14px; line-height: 1.5; }
|
||||
.app-shell { height: 100%; max-height: 100dvh; display: flex; flex-direction: column; overflow: hidden; touch-action: pan-x pan-y; }
|
||||
.app-frame { flex: 1; min-height: 0; height: 100%; max-width: 1400px; width: 100%; margin: 0 auto; display: flex; flex-direction: column; overflow: hidden; touch-action: pan-x pan-y; }
|
||||
.app-header { height: 56px; flex-shrink: 0; }
|
||||
.site-footer { flex-shrink: 0; }
|
||||
.app-body { flex: 1; display: flex; min-height: 0; width: 100%; overflow: hidden; touch-action: pan-x pan-y; }
|
||||
.content-workspace { flex: 1; display: flex; min-width: 0; min-height: 0; overflow: hidden; touch-action: pan-x pan-y; }
|
||||
.sidebar { width: 210px; flex-shrink: 0; }
|
||||
.main-content { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; touch-action: pan-x pan-y; }
|
||||
.aside-panel { width: 280px; flex-shrink: 0; }
|
||||
@media (max-width: 1100px) { .aside-panel { display: none; } }
|
||||
@media (max-width: 768px) { .sidebar { display: none; } }
|
||||
</style>
|
||||
<!-- 样式由 Vite 构建注入外链 CSS,不在此内联 style -->
|
||||
<script>
|
||||
(function () {
|
||||
var theme = localStorage.getItem('j13-theme') || 'light';
|
||||
|
||||
45
frontend/package-lock.json
generated
45
frontend/package-lock.json
generated
@@ -18,6 +18,8 @@
|
||||
"@radix-ui/react-label": "^2.1.9",
|
||||
"@radix-ui/react-slot": "^1.2.5",
|
||||
"@radix-ui/react-switch": "^1.3.0",
|
||||
"@svg-maps/china": "^2.0.0",
|
||||
"@svg-maps/world": "^2.0.0",
|
||||
"@tanstack/react-virtual": "^3.11.2",
|
||||
"@tiptap/core": "^3.26.1",
|
||||
"@tiptap/extension-code-block": "^3.26.1",
|
||||
@@ -49,7 +51,8 @@
|
||||
"tailwindcss": "^3.4.19",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"turndown": "^7.2.4",
|
||||
"zod": "^4.4.3"
|
||||
"zod": "^4.4.3",
|
||||
"zustand": "^4.5.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.9.3",
|
||||
@@ -1971,6 +1974,18 @@
|
||||
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@svg-maps/china": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@svg-maps/china/-/china-2.0.0.tgz",
|
||||
"integrity": "sha512-/B0a4hYJHRtfcUG+x6BudQFWhLQyPoaN2WbqfdEeWeXnwef6oXaE93Msrq2odu72c09vE+G4Ds9+n60Qsr4p1g==",
|
||||
"license": "CC-BY-4.0"
|
||||
},
|
||||
"node_modules/@svg-maps/world": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@svg-maps/world/-/world-2.0.0.tgz",
|
||||
"integrity": "sha512-VmYYnyygJ5Zhr48xPqukFBoq4aCBgVNIjBzqBnWKXSdHhrRK3pntdvbCa8lMsxwVCFzEw9a+smIMEGI2sC1xcQ==",
|
||||
"license": "CC-BY-4.0"
|
||||
},
|
||||
"node_modules/@tanstack/react-virtual": {
|
||||
"version": "3.14.2",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.14.2.tgz",
|
||||
@@ -4466,6 +4481,34 @@
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
},
|
||||
"node_modules/zustand": {
|
||||
"version": "4.5.7",
|
||||
"resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",
|
||||
"integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"use-sync-external-store": "^1.2.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.7.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=16.8",
|
||||
"immer": ">=9.0.6",
|
||||
"react": ">=16.8"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"immer": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
"@radix-ui/react-label": "^2.1.9",
|
||||
"@radix-ui/react-slot": "^1.2.5",
|
||||
"@radix-ui/react-switch": "^1.3.0",
|
||||
"@svg-maps/china": "^2.0.0",
|
||||
"@svg-maps/world": "^2.0.0",
|
||||
"@tanstack/react-virtual": "^3.11.2",
|
||||
"@tiptap/core": "^3.26.1",
|
||||
"@tiptap/extension-code-block": "^3.26.1",
|
||||
@@ -50,7 +52,8 @@
|
||||
"tailwindcss": "^3.4.19",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"turndown": "^7.2.4",
|
||||
"zod": "^4.4.3"
|
||||
"zod": "^4.4.3",
|
||||
"zustand": "^4.5.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.9.3",
|
||||
|
||||
60
frontend/scripts/extract-lucide-paths.mjs
Normal file
60
frontend/scripts/extract-lucide-paths.mjs
Normal file
@@ -0,0 +1,60 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const iconsDir = path.join('node_modules/lucide-react/dist/esm/icons');
|
||||
const names = [
|
||||
'search', 'house', 'star', 'folder-git-2', 'link-2', 'earth', 'file-text',
|
||||
'message-circle', 'tags', 'moon', 'clock', 'badge-check', 'sliders-horizontal',
|
||||
'plus', 'sun', 'mail', 'calendar-check', 'check', 'gift', 'panel-right',
|
||||
'user-plus', 'layout-dashboard',
|
||||
'code-2', 'coffee', 'help-circle', 'message-square', 'lightbulb', 'book-open',
|
||||
'gamepad-2', 'palette', 'music', 'camera', 'heart', 'zap', 'globe', 'users',
|
||||
'briefcase', 'graduation-cap', 'shopping-bag', 'map-pin', 'megaphone', 'flame',
|
||||
'folder', 'wrench', 'cpu',
|
||||
];
|
||||
|
||||
function esc(v) {
|
||||
return String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
|
||||
}
|
||||
|
||||
function nodeToInner(nodes) {
|
||||
return nodes.map(([tag, attrs]) => {
|
||||
let s = `<${tag}`;
|
||||
for (const [k, v] of Object.entries(attrs)) {
|
||||
if (k === 'key') continue;
|
||||
s += ` ${k}="${esc(v)}"`;
|
||||
}
|
||||
return `${s}/>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function resolveIconFile(name) {
|
||||
let f = path.join(iconsDir, `${name}.mjs`);
|
||||
let src = fs.readFileSync(f, 'utf8');
|
||||
const re = src.match(/export \{ default \} from '\.\/([^']+)';/);
|
||||
if (re) {
|
||||
f = path.join(iconsDir, re[1]);
|
||||
src = fs.readFileSync(f, 'utf8');
|
||||
}
|
||||
return { f, src };
|
||||
}
|
||||
|
||||
const out = {};
|
||||
for (const n of names) {
|
||||
try {
|
||||
const { src } = resolveIconFile(n);
|
||||
const m = src.match(/const __iconNode = (\[[\s\S]*?\]);/);
|
||||
if (!m) {
|
||||
console.error('no node', n);
|
||||
continue;
|
||||
}
|
||||
// eslint-disable-next-line no-eval
|
||||
const nodes = eval(m[1]);
|
||||
out[n] = nodeToInner(nodes);
|
||||
} catch (e) {
|
||||
console.error('fail', n, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
fs.writeFileSync('tmp-lucide-paths.json', JSON.stringify(out, null, 2));
|
||||
console.log('wrote', Object.keys(out).length, 'icons');
|
||||
168
frontend/scripts/gen-ssr-icons.mjs
Normal file
168
frontend/scripts/gen-ssr-icons.mjs
Normal file
@@ -0,0 +1,168 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const paths = JSON.parse(fs.readFileSync('tmp-lucide-paths.json', 'utf8'));
|
||||
|
||||
function splitInner(inner) {
|
||||
const tags = [];
|
||||
const re = /<([a-z]+)([^>]*)\/>/g;
|
||||
let m;
|
||||
while ((m = re.exec(inner))) {
|
||||
tags.push(`<${m[1]}${m[2]}/>`);
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
function goFunc(name, size, key, className = '') {
|
||||
const tags = splitInner(paths[key]);
|
||||
const lines = tags.map((t) => `\t\t\`${t}\`,`).join('\n');
|
||||
if (className) {
|
||||
return `func ${name}() string {\n\treturn ssrSVGWithClass(${size}, "${className}",\n${lines}\n\t)\n}\n\n`;
|
||||
}
|
||||
return `func ${name}() string {\n\treturn ssrSVG(${size},\n${lines}\n\t)\n}\n\n`;
|
||||
}
|
||||
|
||||
const boardKeys = [
|
||||
'code-2', 'coffee', 'help-circle', 'message-square', 'lightbulb', 'book-open',
|
||||
'gamepad-2', 'palette', 'music', 'camera', 'heart', 'zap', 'globe', 'users',
|
||||
'briefcase', 'graduation-cap', 'shopping-bag', 'map-pin', 'megaphone', 'flame',
|
||||
'star', 'folder', 'wrench', 'cpu',
|
||||
];
|
||||
const defaults = [
|
||||
'code-2', 'coffee', 'help-circle', 'message-square',
|
||||
'lightbulb', 'book-open', 'gamepad-2', 'palette',
|
||||
];
|
||||
|
||||
let out = `package handler
|
||||
|
||||
import (
|
||||
\t"strconv"
|
||||
\t"strings"
|
||||
\t"time"
|
||||
)
|
||||
|
||||
// 内联 SVG:path 对齐 lucide-react@1.18(由 scripts/extract-lucide-paths.mjs 抽取)
|
||||
|
||||
func ssrSVG(size int, paths ...string) string {
|
||||
\treturn ssrSVGWithClass(size, "", paths...)
|
||||
}
|
||||
|
||||
func ssrSVGWithClass(size int, className string, paths ...string) string {
|
||||
\tvar b strings.Builder
|
||||
\tb.WriteString(\`<svg xmlns="http://www.w3.org/2000/svg" width="\`)
|
||||
\tb.WriteString(strconv.Itoa(size))
|
||||
\tb.WriteString(\`" height="\`)
|
||||
\tb.WriteString(strconv.Itoa(size))
|
||||
\tb.WriteString(\`" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"\`)
|
||||
\tif className != "" {
|
||||
\t\tb.WriteString(\` class="\`)
|
||||
\t\tb.WriteString(className)
|
||||
\t\tb.WriteString(\`"\`)
|
||||
\t}
|
||||
\tb.WriteString(\` aria-hidden="true">\`)
|
||||
\tfor _, p := range paths {
|
||||
\t\tb.WriteString(p)
|
||||
\t}
|
||||
\tb.WriteString(\`</svg>\`)
|
||||
\treturn b.String()
|
||||
}
|
||||
|
||||
`;
|
||||
|
||||
out += goFunc('ssrIconSearch', 16, 'search', 'header-search-icon');
|
||||
out += goFunc('ssrIconSliders', 15, 'sliders-horizontal');
|
||||
out += goFunc('ssrIconPlus', 16, 'plus');
|
||||
out += goFunc('ssrIconMoon', 18, 'moon');
|
||||
out += goFunc('ssrIconSun', 18, 'sun');
|
||||
out += goFunc('ssrIconMail', 18, 'mail');
|
||||
out += goFunc('ssrIconHome', 18, 'house');
|
||||
out += goFunc('ssrIconStar', 18, 'star');
|
||||
out += goFunc('ssrIconFolderGit', 18, 'folder-git-2');
|
||||
out += goFunc('ssrIconLink2', 18, 'link-2');
|
||||
out += goFunc('ssrIconEarth', 18, 'earth');
|
||||
out += goFunc('ssrIconFileText', 18, 'file-text');
|
||||
out += goFunc('ssrIconLayoutDashboard', 18, 'layout-dashboard');
|
||||
out += goFunc('ssrIconMessageCircle', 16, 'message-circle');
|
||||
out += goFunc('ssrIconClock', 16, 'clock');
|
||||
out += goFunc('ssrIconBadgeCheck', 16, 'badge-check');
|
||||
out += goFunc('ssrIconTags', 16, 'tags');
|
||||
out += goFunc('ssrIconUserPlus', 16, 'user-plus');
|
||||
out += goFunc('ssrIconCalendarCheck', 18, 'calendar-check');
|
||||
out += goFunc('ssrIconCheck', 18, 'check');
|
||||
out += goFunc('ssrIconGift', 15, 'gift');
|
||||
out += goFunc('ssrIconPanelRight', 18, 'panel-right');
|
||||
|
||||
out += '// 板块图标 path(key 对齐 BOARD_ICON_OPTIONS / AllowedBoardIcons)\nvar ssrBoardIconInner = map[string]string{\n';
|
||||
for (const k of boardKeys) {
|
||||
out += `\t"${k}": \`${paths[k]}\`,\n`;
|
||||
}
|
||||
out += '}\n\n';
|
||||
|
||||
out += '// 与前端 DEFAULT_ICONS 顺序一致(按 themeIndex 回退)\nvar ssrBoardDefaultIcons = []string{\n';
|
||||
for (const k of defaults) {
|
||||
out += `\t"${k}",\n`;
|
||||
}
|
||||
out += '}\n\n';
|
||||
|
||||
out += `// ssrBoardIconSVG 输出板块 Lucide 图标;class 打在 svg 上(与 React BoardIconDisplay 一致)
|
||||
func ssrBoardIconSVG(icon string, themeIndex int, className string) string {
|
||||
\tkey := strings.TrimSpace(strings.ToLower(icon))
|
||||
\tinner, ok := ssrBoardIconInner[key]
|
||||
\tif !ok || inner == "" {
|
||||
\t\tif themeIndex < 0 {
|
||||
\t\t\tthemeIndex = 0
|
||||
\t\t}
|
||||
\t\tkey = ssrBoardDefaultIcons[themeIndex%len(ssrBoardDefaultIcons)]
|
||||
\t\tinner = ssrBoardIconInner[key]
|
||||
\t}
|
||||
\treturn ssrSVGWithClass(18, className, inner)
|
||||
}
|
||||
|
||||
// formatSSRRelativeTime 与前端 formatTime 同规则
|
||||
func formatSSRRelativeTime(t time.Time) string {
|
||||
\tif t.IsZero() {
|
||||
\t\treturn ""
|
||||
\t}
|
||||
\tnow := time.Now()
|
||||
\tdiffSec := now.Sub(t).Seconds()
|
||||
\tif diffSec < 0 {
|
||||
\t\tdiffSec = 0
|
||||
\t}
|
||||
\tif diffSec < 60 {
|
||||
\t\treturn "刚刚"
|
||||
\t}
|
||||
\tif diffSec < 3600 {
|
||||
\t\treturn strconv.Itoa(int(diffSec/60)) + "分钟前"
|
||||
\t}
|
||||
\tif diffSec < 86400 {
|
||||
\t\treturn strconv.Itoa(int(diffSec/3600)) + "小时前"
|
||||
\t}
|
||||
\tdiffDay := int(diffSec / 86400)
|
||||
\tif diffDay < 30 {
|
||||
\t\treturn strconv.Itoa(diffDay) + "天前"
|
||||
\t}
|
||||
\tif t.Year() == now.Year() {
|
||||
\t\treturn strconv.Itoa(int(t.Month())) + "月" + strconv.Itoa(t.Day()) + "日"
|
||||
\t}
|
||||
\treturn strconv.Itoa(t.Year()) + "年" + strconv.Itoa(int(t.Month())) + "月" + strconv.Itoa(t.Day()) + "日"
|
||||
}
|
||||
|
||||
// formatSSRShortDateTime 与前端 formatShortDateTime 同规则(MM-DD HH:mm)
|
||||
func formatSSRShortDateTime(t time.Time) string {
|
||||
\tif t.IsZero() {
|
||||
\t\treturn ""
|
||||
\t}
|
||||
\tlocal := t.Local()
|
||||
\tpad := func(n int) string {
|
||||
\t\tif n < 10 {
|
||||
\t\t\treturn "0" + strconv.Itoa(n)
|
||||
\t\t}
|
||||
\t\treturn strconv.Itoa(n)
|
||||
\t}
|
||||
\treturn pad(int(local.Month())) + "-" + pad(local.Day()) + " " + pad(local.Hour()) + ":" + pad(local.Minute())
|
||||
}
|
||||
`;
|
||||
|
||||
const outPath = path.join('..', 'handler', 'ssr_icons.go');
|
||||
fs.writeFileSync(outPath, out);
|
||||
console.log('wrote', outPath, Object.keys(paths).length, 'icons');
|
||||
@@ -17,6 +17,7 @@ import PageLoader from './components/PageLoader';
|
||||
import AuthPageFallback from './components/AuthPageFallback';
|
||||
import { Toaster } from './components/ui/sonner';
|
||||
import PullToRefresh from './components/PullToRefresh';
|
||||
import TopProgressBar from './components/TopProgressBar';
|
||||
import { lazyWithRetry } from './utils/lazyWithRetry';
|
||||
|
||||
const HomePage = lazyWithRetry(() => import('./pages/HomePage'));
|
||||
@@ -32,6 +33,7 @@ const FavoritesPage = lazyWithRetry(() => import('./pages/FavoritesPage'));
|
||||
const MessagesPage = lazyWithRetry(() => import('./pages/MessagesPage'));
|
||||
const ProjectsPage = lazyWithRetry(() => import('./pages/ProjectsPage'));
|
||||
const LinksPage = lazyWithRetry(() => import('./pages/LinksPage'));
|
||||
const ShowcasePage = lazyWithRetry(() => import('./pages/ShowcasePage'));
|
||||
const AdminDashboardPage = lazyWithRetry(() => import('./pages/admin/AdminDashboardPage'));
|
||||
const AdminPostsPage = lazyWithRetry(() => import('./pages/admin/AdminPostsPage'));
|
||||
const AdminCommentsPage = lazyWithRetry(() => import('./pages/admin/AdminCommentsPage'));
|
||||
@@ -39,11 +41,13 @@ const AdminReportsPage = lazyWithRetry(() => import('./pages/admin/AdminReportsP
|
||||
const AdminUsersPage = lazyWithRetry(() => import('./pages/admin/AdminUsersPage'));
|
||||
const AdminBadgesPage = lazyWithRetry(() => import('./pages/admin/AdminBadgesPage'));
|
||||
const AdminMediaPage = lazyWithRetry(() => import('./pages/admin/AdminMediaPage'));
|
||||
const AdminMonitorPage = lazyWithRetry(() => import('./pages/admin/AdminMonitorPage'));
|
||||
const AdminPagesPage = lazyWithRetry(() => import('./pages/admin/AdminPagesPage'));
|
||||
const AdminSitePageEditPage = lazyWithRetry(() => import('./pages/admin/AdminSitePageEditPage'));
|
||||
const AdminLinksPage = lazyWithRetry(() => import('./pages/admin/AdminLinksPage'));
|
||||
const SitePageView = lazyWithRetry(() => import('./pages/SitePageView'));
|
||||
const AdminSettingsPage = lazyWithRetry(() => import('./pages/admin/AdminSettingsPage'));
|
||||
const AdminCommunityPage = lazyWithRetry(() => import('./pages/admin/AdminCommunityPage'));
|
||||
const NotFoundPage = lazyWithRetry(() => import('./pages/NotFoundPage'));
|
||||
|
||||
const router = createBrowserRouter(
|
||||
@@ -61,12 +65,14 @@ const router = createBrowserRouter(
|
||||
<Route path="pages/:id/edit" element={<Suspense fallback={<PageLoader />}><AdminSitePageEditPage /></Suspense>} />
|
||||
<Route path="pages" element={<Suspense fallback={<PageLoader />}><AdminPagesPage /></Suspense>} />
|
||||
<Route path="links" element={<Suspense fallback={<PageLoader />}><AdminLinksPage /></Suspense>} />
|
||||
<Route path="community" element={<Suspense fallback={<PageLoader />}><AdminCommunityPage /></Suspense>} />
|
||||
<Route path="posts" element={<Suspense fallback={<PageLoader />}><AdminPostsPage /></Suspense>} />
|
||||
<Route path="comments" element={<Suspense fallback={<PageLoader />}><AdminCommentsPage /></Suspense>} />
|
||||
<Route path="reports" element={<Suspense fallback={<PageLoader />}><AdminReportsPage /></Suspense>} />
|
||||
<Route path="users" element={<Suspense fallback={<PageLoader />}><AdminUsersPage /></Suspense>} />
|
||||
<Route path="badges" element={<Suspense fallback={<PageLoader />}><AdminBadgesPage /></Suspense>} />
|
||||
<Route path="media" element={<Suspense fallback={<PageLoader />}><AdminMediaPage /></Suspense>} />
|
||||
<Route path="monitor" element={<Suspense fallback={<PageLoader />}><AdminMonitorPage /></Suspense>} />
|
||||
<Route path="settings" element={<Suspense fallback={<PageLoader />}><AdminSettingsPage /></Suspense>} />
|
||||
<Route path="*" element={<Suspense fallback={<PageLoader />}><NotFoundPage title="后台页面不存在" /></Suspense>} />
|
||||
</Route>
|
||||
@@ -82,9 +88,10 @@ const router = createBrowserRouter(
|
||||
<Route path="/favorites" element={<FavoritesPage />} />
|
||||
<Route path="/projects" element={<ProjectsPage />} />
|
||||
<Route path="/links" element={<LinksPage />} />
|
||||
<Route path="/showcase" element={<Suspense fallback={null}><ShowcasePage /></Suspense>} />
|
||||
<Route path="/messages" element={<MessagesPage />} />
|
||||
<Route path="/page/:slug" element={<Suspense fallback={<PageLoader />}><SitePageView /></Suspense>} />
|
||||
<Route path="*" element={<Suspense fallback={<PageLoader />}><NotFoundPage /></Suspense>} />
|
||||
<Route path="/page/:slug" element={<Suspense fallback={null}><SitePageView /></Suspense>} />
|
||||
<Route path="*" element={<Suspense fallback={null}><NotFoundPage /></Suspense>} />
|
||||
</Route>
|
||||
<Route path="*" element={<Suspense fallback={<PageLoader fullScreen />}><NotFoundPage standalone /></Suspense>} />
|
||||
</Route>,
|
||||
@@ -97,6 +104,7 @@ export default function App() {
|
||||
<AuthProvider>
|
||||
<ErrorBoundary>
|
||||
<RouterProvider router={router} />
|
||||
<TopProgressBar />
|
||||
<PullToRefresh />
|
||||
<Toaster />
|
||||
</ErrorBoundary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { User, UserPublic, UserActivityStats, Board, PostItem, Comment, RecentComment, RecentUser, ForumStats, TagCount, AdminDashboard, AdminSettings, ForumLimits, ForumLimitsPublic, PostDetailResponse, PostRevision, CommentRevision, MailConfig, OIDCConfig, OAuthClient, OAuthClientInput, GiteaProject, GiteaSyncConfig, StorageConfig, MediaListResult, SiteBranding, RegisterConfig, PrivateMessage, MessageConversation, PostReport, ReportReason, ReportStatus, BadgeDef, PointLedger, CheckInStatus, LotteryStatus, SitePage, SitePageSummary, PollView, PostLotteryView, FriendLinkApply } from './types';
|
||||
import type { User, UserPublic, UserActivityStats, Board, PostItem, Comment, RecentComment, RecentUser, ForumStats, TagCount, AdminDashboard, AdminSettings, ForumLimits, ForumLimitsPublic, PostDetailResponse, PostRevision, CommentRevision, MailConfig, OIDCConfig, OAuthClient, OAuthClientInput, GiteaProject, GiteaSyncConfig, StorageConfig, MediaListResult, SiteBranding, RegisterConfig, PrivateMessage, MessageConversation, PostReport, ReportReason, ReportStatus, BadgeDef, PointLedger, CheckInStatus, LotteryStatus, SitePage, SitePageSummary, PollView, PostLotteryView, FriendLinkApply, CommunityConfig, CommunityInstance, CommunityShowcaseItem, MonitorConfig, MonitorOverview, MonitorGeoResult, MonitorStatItem, MonitorRealtime, MonitorLogItem } from './types';
|
||||
|
||||
const BASE = '';
|
||||
|
||||
@@ -25,6 +25,27 @@ export const api = {
|
||||
me: () => request<{ user: User | null }>('/api/me'),
|
||||
stats: () => request<ForumStats>('/api/stats'),
|
||||
forumLimits: () => request<ForumLimitsPublic>('/api/forum-limits'),
|
||||
/** 前台路由 pageview;失败静默(204 无 body) */
|
||||
monitorPageview: (body: { path: string; referrer?: string }) => {
|
||||
const payload = JSON.stringify(body);
|
||||
try {
|
||||
if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
|
||||
const blob = new Blob([payload], { type: 'application/json' });
|
||||
if (navigator.sendBeacon('/api/monitor/pageview', blob)) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* 回退 fetch */
|
||||
}
|
||||
return fetch('/api/monitor/pageview', {
|
||||
method: 'POST',
|
||||
credentials: 'omit',
|
||||
keepalive: true,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: payload,
|
||||
}).then(() => undefined).catch(() => undefined);
|
||||
},
|
||||
siteBranding: () => request<SiteBranding>('/api/site-branding'),
|
||||
pages: () => request<{ pages: SitePageSummary[] }>('/api/pages'),
|
||||
page: (slug: string) => request<{ page: SitePage }>(`/api/pages/${encodeURIComponent(slug)}`),
|
||||
@@ -63,6 +84,59 @@ export const api = {
|
||||
// 管理后台 API
|
||||
adminDashboard: () => request<AdminDashboard>('/api/admin/dashboard'),
|
||||
adminSettings: () => request<AdminSettings>('/api/admin/settings'),
|
||||
adminUpdateCommunitySettings: (body: CommunityConfig) =>
|
||||
request<{ message: string; community: CommunityConfig; heartbeat_error?: string }>('/api/admin/settings/community', {
|
||||
method: 'PUT', body: JSON.stringify(body),
|
||||
}),
|
||||
adminMonitorSettings: () => request<MonitorConfig>('/api/admin/settings/monitor'),
|
||||
adminUpdateMonitorSettings: (body: MonitorConfig) =>
|
||||
request<{ message: string; monitor: MonitorConfig }>('/api/admin/settings/monitor', {
|
||||
method: 'PUT', body: JSON.stringify(body),
|
||||
}),
|
||||
adminMonitorOverview: () => request<MonitorOverview>('/api/admin/monitor/overview'),
|
||||
adminMonitorGeo: (range = '30d') =>
|
||||
request<MonitorGeoResult>(`/api/admin/monitor/geo?range=${encodeURIComponent(range)}`),
|
||||
adminMonitorStats: (dim: string, range = '30d') =>
|
||||
request<{ dim: string; range: string; items: MonitorStatItem[] }>(
|
||||
`/api/admin/monitor/stats?dim=${encodeURIComponent(dim)}&range=${encodeURIComponent(range)}`,
|
||||
),
|
||||
adminMonitorLogs: (params: { page?: number; size?: number; method?: string; path?: string; status?: string; ip?: string }) => {
|
||||
const q = new URLSearchParams();
|
||||
if (params.page) q.set('page', String(params.page));
|
||||
if (params.size) q.set('size', String(params.size));
|
||||
if (params.method) q.set('method', params.method);
|
||||
if (params.path) q.set('path', params.path);
|
||||
if (params.status) q.set('status', params.status);
|
||||
if (params.ip) q.set('ip', params.ip);
|
||||
const qs = q.toString();
|
||||
return request<{ items: MonitorLogItem[]; total: number; page: number; size: number }>(
|
||||
`/api/admin/monitor/logs${qs ? `?${qs}` : ''}`,
|
||||
);
|
||||
},
|
||||
adminMonitorRealtime: () => request<MonitorRealtime>('/api/admin/monitor/realtime'),
|
||||
adminCommunityInstances: () =>
|
||||
request<{ hub_enabled: boolean; instances: CommunityInstance[] }>('/api/admin/community/instances'),
|
||||
adminFeatureCommunityInstance: (instanceId: string, body: { featured: boolean; featured_note?: string }) =>
|
||||
request<{ message: string; instance: CommunityInstance }>(
|
||||
`/api/admin/community/instances/${encodeURIComponent(instanceId)}/feature`,
|
||||
{ method: 'PUT', body: JSON.stringify(body) },
|
||||
),
|
||||
adminUpdateShowcaseEntry: (body: {
|
||||
nav_show_showcase?: boolean;
|
||||
footer_show_showcase?: boolean;
|
||||
aside_show_showcase?: boolean;
|
||||
}) =>
|
||||
request<{
|
||||
message: string;
|
||||
nav_show_showcase: boolean;
|
||||
footer_show_showcase: boolean;
|
||||
aside_show_showcase: boolean;
|
||||
}>('/api/admin/community/showcase-entry', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
communityShowcase: () =>
|
||||
request<{ items: CommunityShowcaseItem[] }>('/api/community/showcase'),
|
||||
adminPosts: (params: { page?: number; keyword?: string; status?: string }) => {
|
||||
const q = new URLSearchParams();
|
||||
if (params.page) q.set('page', String(params.page));
|
||||
@@ -345,6 +419,14 @@ export const api = {
|
||||
fd.append('image', file);
|
||||
return request<{ url: string }>('/api/uploads/image', { method: 'POST', body: fd, headers: {} });
|
||||
},
|
||||
/** 当前用户历史上传的帖子图片 */
|
||||
myPostImages: (params?: { page?: number; size?: number }) => {
|
||||
const q = new URLSearchParams();
|
||||
if (params?.page) q.set('page', String(params.page));
|
||||
if (params?.size) q.set('size', String(params.size));
|
||||
const qs = q.toString();
|
||||
return request<MediaListResult>(`/api/uploads/images${qs ? `?${qs}` : ''}`);
|
||||
},
|
||||
createPost: (data: {
|
||||
board_id: string; title: string; content: string; tags?: string; post_type?: string;
|
||||
poll_options?: string; bounty_points?: number; lottery_winner_count?: number;
|
||||
|
||||
@@ -179,6 +179,14 @@ export interface Comment {
|
||||
reply_target?: Comment;
|
||||
}
|
||||
|
||||
export interface AdminDashboardTraffic {
|
||||
enabled: boolean;
|
||||
today_pv: number;
|
||||
today_uv: number;
|
||||
yesterday_pv: number;
|
||||
total_pv: number;
|
||||
}
|
||||
|
||||
export interface AdminDashboard {
|
||||
users: number;
|
||||
posts: number;
|
||||
@@ -189,9 +197,10 @@ export interface AdminDashboard {
|
||||
pending_reports?: number;
|
||||
pending_friend_links?: number;
|
||||
recent_posts: PostItem[];
|
||||
traffic?: AdminDashboardTraffic;
|
||||
}
|
||||
|
||||
export type AsideWidgetId = 'tag_cloud' | 'recent_comments' | 'recent_users' | 'friend_links';
|
||||
export type AsideWidgetId = 'tag_cloud' | 'recent_comments' | 'recent_users' | 'friend_links' | 'showcase';
|
||||
|
||||
export interface AsideWidget {
|
||||
id: AsideWidgetId;
|
||||
@@ -203,6 +212,21 @@ export const DEFAULT_ASIDE_WIDGETS: AsideWidget[] = [
|
||||
{ id: 'recent_comments', enabled: false },
|
||||
{ id: 'recent_users', enabled: false },
|
||||
{ id: 'friend_links', enabled: true },
|
||||
{ id: 'showcase', enabled: false },
|
||||
];
|
||||
|
||||
export type FeedSortId = 'reply' | 'latest' | 'hot';
|
||||
|
||||
export interface FeedSortTab {
|
||||
id: FeedSortId;
|
||||
label: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_FEED_SORT_TABS: FeedSortTab[] = [
|
||||
{ id: 'reply', label: '最新', enabled: true },
|
||||
{ id: 'latest', label: '新帖子', enabled: true },
|
||||
{ id: 'hot', label: '推荐帖', enabled: true },
|
||||
];
|
||||
|
||||
export interface ForumLimits {
|
||||
@@ -231,14 +255,22 @@ export interface ForumLimits {
|
||||
aside_show_recent_comments: boolean;
|
||||
/** 右侧栏友情链接 */
|
||||
aside_show_friend_links: boolean;
|
||||
/** 右侧栏开源展柜 */
|
||||
aside_show_showcase: boolean;
|
||||
/** 右侧栏可选组件顺序与开关 */
|
||||
aside_widgets: AsideWidget[];
|
||||
/** 左侧栏「站点」展示友情链接入口 */
|
||||
nav_show_friend_links: boolean;
|
||||
/** 页脚展示友情链接入口 */
|
||||
footer_show_friend_links: boolean;
|
||||
/** 左侧栏「站点」展示开源展柜入口 */
|
||||
nav_show_showcase: boolean;
|
||||
/** 页脚展示开源展柜入口 */
|
||||
footer_show_showcase: boolean;
|
||||
/** 首页列表样式:title 仅标题 / thumbnail 缩略图 */
|
||||
feed_list_style: 'title' | 'excerpt' | 'thumbnail';
|
||||
/** 首页排序标签:名称、顺序、启停 */
|
||||
feed_sort_tabs: FeedSortTab[];
|
||||
/** 伪静态(固定链接)开关 */
|
||||
permalink_enabled: boolean;
|
||||
/** 伪静态后缀,不含点,如 html / htm */
|
||||
@@ -262,12 +294,18 @@ export interface ForumLimitsPublic {
|
||||
aside_show_tag_cloud: boolean;
|
||||
aside_show_recent_comments: boolean;
|
||||
aside_show_friend_links: boolean;
|
||||
aside_show_showcase: boolean;
|
||||
aside_widgets: AsideWidget[];
|
||||
nav_show_friend_links: boolean;
|
||||
footer_show_friend_links: boolean;
|
||||
nav_show_showcase: boolean;
|
||||
footer_show_showcase: boolean;
|
||||
feed_list_style: 'title' | 'excerpt' | 'thumbnail';
|
||||
feed_sort_tabs: FeedSortTab[];
|
||||
permalink_enabled: boolean;
|
||||
permalink_ext: string;
|
||||
/** 是否上报前台路由 pageview(与后台监控采集开关同步) */
|
||||
monitor_pageview: boolean;
|
||||
}
|
||||
|
||||
export interface FriendLink {
|
||||
@@ -376,10 +414,148 @@ export interface AdminSettings {
|
||||
gitea?: GiteaSyncConfig;
|
||||
storage?: StorageConfig;
|
||||
branding?: SiteBranding;
|
||||
community?: CommunityConfig;
|
||||
filter_words: string;
|
||||
filter_word_count: number;
|
||||
}
|
||||
|
||||
/** 社区上报配置(hub_url / site_url 只读) */
|
||||
export interface CommunityConfig {
|
||||
report_enabled: boolean;
|
||||
/** 只读:是否作为社区枢纽 */
|
||||
hub_enabled: boolean;
|
||||
/** 只读:固定为官方演示站 */
|
||||
hub_url: string;
|
||||
/** 只读:服务端自动推断的本站地址 */
|
||||
site_url: string;
|
||||
instance_id: string;
|
||||
}
|
||||
|
||||
/** 网站监控设置 */
|
||||
export interface MonitorConfig {
|
||||
enabled: boolean;
|
||||
retention_days: number;
|
||||
access_log_retention_days: number;
|
||||
exclude_rules: string[];
|
||||
default_exclude_rules?: string[];
|
||||
trust_proxy: boolean;
|
||||
access_log_dir?: string;
|
||||
ip2location_v4_path?: string;
|
||||
ip2location_v6_path?: string;
|
||||
ip2location_v4_available?: boolean;
|
||||
ip2location_v6_available?: boolean;
|
||||
geoip_available: boolean;
|
||||
geoip_country_path?: string;
|
||||
geoip_asn_path?: string;
|
||||
geoip_country_available?: boolean;
|
||||
geoip_asn_available?: boolean;
|
||||
}
|
||||
|
||||
export interface MonitorOverview {
|
||||
enabled: boolean;
|
||||
pageviews: number;
|
||||
visitors: number;
|
||||
unique_ips: number;
|
||||
traffic: number;
|
||||
bots: number;
|
||||
requests: number;
|
||||
status_4xx: number;
|
||||
status_5xx: number;
|
||||
}
|
||||
|
||||
export interface MonitorGeoItem {
|
||||
country: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface MonitorRegionItem {
|
||||
country: string;
|
||||
region: string;
|
||||
region_iso: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface MonitorCityItem {
|
||||
country: string;
|
||||
region: string;
|
||||
city: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface MonitorASNItem {
|
||||
asn: number;
|
||||
as_org: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface MonitorGeoResult {
|
||||
range: string;
|
||||
countries: MonitorGeoItem[];
|
||||
regions: MonitorRegionItem[];
|
||||
cities: MonitorCityItem[];
|
||||
asns: MonitorASNItem[];
|
||||
has_data: boolean;
|
||||
}
|
||||
|
||||
export interface MonitorStatItem {
|
||||
key: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface MonitorRealtimePoint {
|
||||
minute: string;
|
||||
count: number;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface MonitorRealtime {
|
||||
enabled: boolean;
|
||||
requests_1m: number;
|
||||
traffic_1m: number;
|
||||
hourly_series: MonitorRealtimePoint[];
|
||||
}
|
||||
|
||||
export interface MonitorLogItem {
|
||||
id: number;
|
||||
created_at: string;
|
||||
method: string;
|
||||
path: string;
|
||||
status: number;
|
||||
bytes: number;
|
||||
duration_ms: number;
|
||||
ip: string;
|
||||
ua: string;
|
||||
referer: string;
|
||||
country: string;
|
||||
region?: string;
|
||||
city?: string;
|
||||
asn?: number;
|
||||
as_org?: string;
|
||||
is_bot: boolean;
|
||||
}
|
||||
|
||||
export interface CommunityInstance {
|
||||
instance_id: string;
|
||||
site_url: string;
|
||||
site_name: string;
|
||||
version: string;
|
||||
users: number;
|
||||
posts: number;
|
||||
first_seen_at: string;
|
||||
last_seen_at: string;
|
||||
online: boolean;
|
||||
featured: boolean;
|
||||
featured_note: string;
|
||||
}
|
||||
|
||||
/** 公开展柜条目 */
|
||||
export interface CommunityShowcaseItem {
|
||||
site_url: string;
|
||||
site_name: string;
|
||||
version: string;
|
||||
featured_note?: string;
|
||||
}
|
||||
|
||||
export interface StorageConfig {
|
||||
type: 'local' | 's3';
|
||||
endpoint: string;
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
insertMarkdownLink,
|
||||
} from '../utils/markdownFormat';
|
||||
import { countWords } from '../utils/text';
|
||||
import { api } from '../api/client';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { MembersOnly } from './editor/MembersOnlyExtension';
|
||||
import { ReplyOnly } from './editor/ReplyOnlyExtension';
|
||||
@@ -40,7 +39,8 @@ import { TabIndent } from './editor/TabIndentExtension';
|
||||
import { ArticleImage, type ImageDisplay } from './editor/ArticleImageExtension';
|
||||
import { ImageGroup, suggestImageGroupLayout } from './editor/ImageGroupExtension';
|
||||
import { ClearFloatParagraph, ClearFloatSync } from './editor/ClearFloatParagraph';
|
||||
import { ArticleLinkDialog } from './editor/ArticleLinkDialog';
|
||||
import { ArticleLinkDialog, type ArticleLinkConfirm } from './editor/ArticleLinkDialog';
|
||||
import { ArticleImagePickerDialog } from './editor/ArticleImagePickerDialog';
|
||||
import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
|
||||
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
|
||||
import {
|
||||
@@ -73,6 +73,7 @@ interface Props {
|
||||
|
||||
type EditorMode = 'rich' | 'markdown';
|
||||
type LinkTarget = 'rich' | 'markdown';
|
||||
type ImagePickerTarget = 'rich' | 'markdown';
|
||||
type CodeBlockTarget = 'rich' | 'markdown';
|
||||
type TableTarget = 'rich' | 'markdown';
|
||||
|
||||
@@ -167,34 +168,6 @@ function cycleHeading(editor: Editor) {
|
||||
editor.chain().focus().toggleHeading({ level: 2 }).run();
|
||||
}
|
||||
|
||||
/** 触发图片文件选择并上传(支持多选) */
|
||||
async function uploadPostImageFiles(multiple = true): Promise<string[]> {
|
||||
return new Promise(resolve => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/jpeg,image/png,image/gif,image/webp';
|
||||
input.multiple = multiple;
|
||||
input.onchange = async () => {
|
||||
const files = [...(input.files ?? [])];
|
||||
if (!files.length) {
|
||||
resolve([]);
|
||||
return;
|
||||
}
|
||||
const urls: string[] = [];
|
||||
for (const file of files) {
|
||||
try {
|
||||
const { url } = await api.uploadPostImage(file);
|
||||
urls.push(url);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '图片上传失败');
|
||||
}
|
||||
}
|
||||
resolve(urls);
|
||||
};
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
/** 渲染工具栏按钮列表 */
|
||||
function renderToolButtons(tools: ToolBtn[]) {
|
||||
return tools.map((t, i) => (
|
||||
@@ -228,7 +201,11 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
const [markdownSource, setMarkdownSource] = useState('');
|
||||
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
|
||||
const [linkDialogUrl, setLinkDialogUrl] = useState('');
|
||||
const [linkDialogText, setLinkDialogText] = useState('');
|
||||
const [linkDialogEditing, setLinkDialogEditing] = useState(false);
|
||||
const [linkTarget, setLinkTarget] = useState<LinkTarget>('rich');
|
||||
const [imagePickerOpen, setImagePickerOpen] = useState(false);
|
||||
const [imagePickerTarget, setImagePickerTarget] = useState<ImagePickerTarget>('rich');
|
||||
const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
|
||||
const [codeBlockTarget, setCodeBlockTarget] = useState<CodeBlockTarget>('rich');
|
||||
const [codeBlockEditing, setCodeBlockEditing] = useState(false);
|
||||
@@ -262,6 +239,11 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
openOnClick: false,
|
||||
autolink: true,
|
||||
defaultProtocol: 'https',
|
||||
// 新标签由全站设置在展示层处理,编辑器不写 target/rel
|
||||
HTMLAttributes: {
|
||||
target: null,
|
||||
rel: null,
|
||||
},
|
||||
}),
|
||||
ArticleImage.configure({ inline: false, allowBase64: false }),
|
||||
ImageGroup,
|
||||
@@ -393,14 +375,33 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
const openLinkDialog = useCallback((target: LinkTarget) => {
|
||||
if (target === 'rich') {
|
||||
if (!editor) return;
|
||||
const prev = editor.getAttributes('link').href as string | undefined;
|
||||
setLinkDialogUrl(prev ?? '');
|
||||
const { from, to, empty } = editor.state.selection;
|
||||
let text = empty ? '' : editor.state.doc.textBetween(from, to, '');
|
||||
let href = '';
|
||||
let editing = false;
|
||||
if (editor.isActive('link')) {
|
||||
const attrs = editor.getAttributes('link');
|
||||
href = (attrs.href as string) || '';
|
||||
editing = Boolean(href);
|
||||
editor.chain().focus().extendMarkRange('link').run();
|
||||
const sel = editor.state.selection;
|
||||
text = editor.state.doc.textBetween(sel.from, sel.to, '') || text;
|
||||
}
|
||||
setLinkDialogUrl(href);
|
||||
setLinkDialogText(text);
|
||||
setLinkDialogEditing(editing);
|
||||
} else {
|
||||
const textarea = markdownRef.current;
|
||||
const selected = textarea
|
||||
? markdownSource.slice(textarea.selectionStart, textarea.selectionEnd)
|
||||
: '';
|
||||
setLinkDialogUrl('');
|
||||
setLinkDialogText(selected);
|
||||
setLinkDialogEditing(false);
|
||||
}
|
||||
setLinkTarget(target);
|
||||
setLinkDialogOpen(true);
|
||||
}, [editor]);
|
||||
}, [editor, markdownSource]);
|
||||
|
||||
const openCodeBlockDialog = useCallback((target: CodeBlockTarget) => {
|
||||
setCodeBlockTarget(target);
|
||||
@@ -477,11 +478,12 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
}
|
||||
}, [editor]);
|
||||
|
||||
const applyLink = useCallback((url: string) => {
|
||||
const applyLink = useCallback((payload: ArticleLinkConfirm) => {
|
||||
const { url, text } = payload;
|
||||
if (linkTarget === 'markdown') {
|
||||
const textarea = markdownRef.current;
|
||||
if (!textarea || !url) return;
|
||||
insertMarkdownLink(textarea, markdownSource, url, handleMarkdownChange);
|
||||
insertMarkdownLink(textarea, markdownSource, url, handleMarkdownChange, { text });
|
||||
return;
|
||||
}
|
||||
if (!editor) return;
|
||||
@@ -489,7 +491,31 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
|
||||
// 新标签行为由全站 open_content_links_in_new_tab 在展示层处理
|
||||
const linkAttrs = { href: url };
|
||||
const { empty } = editor.state.selection;
|
||||
const hasLink = editor.isActive('link');
|
||||
if (!empty || hasLink) {
|
||||
editor.chain().focus().extendMarkRange('link').setLink(linkAttrs).run();
|
||||
const { from, to } = editor.state.selection;
|
||||
const current = editor.state.doc.textBetween(from, to, '');
|
||||
if (text && current !== text) {
|
||||
editor.chain().focus().insertContentAt(
|
||||
{ from, to },
|
||||
{
|
||||
type: 'text',
|
||||
text,
|
||||
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||
},
|
||||
).run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().insertContent({
|
||||
type: 'text',
|
||||
text: text || '链接文字',
|
||||
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||
}).run();
|
||||
}, [editor, linkTarget, markdownSource, handleMarkdownChange]);
|
||||
|
||||
const removeLink = useCallback(() => {
|
||||
@@ -497,16 +523,33 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||
}, [editor]);
|
||||
|
||||
const setImage = useCallback(async () => {
|
||||
if (!editor) return;
|
||||
const urls = await uploadPostImageFiles(true);
|
||||
const openImagePicker = useCallback((target: ImagePickerTarget) => {
|
||||
setImagePickerTarget(target);
|
||||
setImagePickerOpen(true);
|
||||
}, []);
|
||||
|
||||
const applyImageUrls = useCallback((urls: string[]) => {
|
||||
if (!urls.length) return;
|
||||
if (imagePickerTarget === 'markdown') {
|
||||
const textarea = markdownRef.current;
|
||||
if (!textarea) return;
|
||||
if (urls.length === 1) {
|
||||
insertAtCursor(textarea, markdownSource, `\n\n\n\n`, handleMarkdownChange);
|
||||
return;
|
||||
}
|
||||
const layout = suggestImageGroupLayout(urls.length);
|
||||
const imgs = urls.map(u => `<img src="${u}" alt="">`).join('');
|
||||
const block = `\n\n<div data-image-group data-layout="${layout}" class="image-group image-group--${layout}">${imgs}</div>\n\n`;
|
||||
insertAtCursor(textarea, markdownSource, block, handleMarkdownChange);
|
||||
return;
|
||||
}
|
||||
if (!editor) return;
|
||||
if (urls.length === 1) {
|
||||
editor.chain().focus().setImage({ src: urls[0] }).run();
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().insertImageGroup(urls, suggestImageGroupLayout(urls.length)).run();
|
||||
}, [editor]);
|
||||
}, [editor, imagePickerTarget, markdownSource, handleMarkdownChange]);
|
||||
|
||||
const setImageDisplay = useCallback((display: ImageDisplay) => {
|
||||
if (!editor) return;
|
||||
@@ -596,21 +639,6 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
fn(textarea, markdownSource, handleMarkdownChange);
|
||||
}, [markdownSource, handleMarkdownChange]);
|
||||
|
||||
const insertMarkdownImage = useCallback(async () => {
|
||||
const textarea = markdownRef.current;
|
||||
if (!textarea) return;
|
||||
const urls = await uploadPostImageFiles(true);
|
||||
if (!urls.length) return;
|
||||
if (urls.length === 1) {
|
||||
insertAtCursor(textarea, markdownSource, `\n\n\n\n`, handleMarkdownChange);
|
||||
return;
|
||||
}
|
||||
const layout = suggestImageGroupLayout(urls.length);
|
||||
const imgs = urls.map(u => `<img src="${u}" alt="">`).join('');
|
||||
const block = `\n\n<div data-image-group data-layout="${layout}" class="image-group image-group--${layout}">${imgs}</div>\n\n`;
|
||||
insertAtCursor(textarea, markdownSource, block, handleMarkdownChange);
|
||||
}, [markdownSource, handleMarkdownChange]);
|
||||
|
||||
const markdownPreviewHtml = useMemo(
|
||||
() => sanitizeHtml(markdownToHtml(markdownSource)),
|
||||
[markdownSource],
|
||||
@@ -637,9 +665,9 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: () => openLinkDialog('rich') },
|
||||
{
|
||||
icon: <ImageIcon size={15} />,
|
||||
title: '上传图片',
|
||||
hint: '可多选;多张自动并排成图组',
|
||||
action: setImage,
|
||||
title: '图片',
|
||||
hint: '上传、链接或从已上传中选择',
|
||||
action: () => openImagePicker('rich'),
|
||||
},
|
||||
{
|
||||
icon: <Columns2 size={15} />,
|
||||
@@ -732,7 +760,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
}
|
||||
|
||||
return tools;
|
||||
}, [editor, enableContentGates, openLinkDialog, openCodeBlockDialog, openTableDialog, setImage, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]);
|
||||
}, [editor, enableContentGates, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]);
|
||||
|
||||
const buildMarkdownTools = useCallback((): ToolBtn[] => {
|
||||
const tools: ToolBtn[] = [
|
||||
@@ -748,7 +776,12 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
{ icon: <Code size={15} />, title: '代码块', hint: '语言、行号与折叠', action: () => openCodeBlockDialog('markdown') },
|
||||
{ icon: <TableIcon size={15} />, title: '表格', hint: '插入 GFM 管道表', action: () => openTableDialog('markdown') },
|
||||
{ icon: <LinkIcon size={15} />, title: '链接', action: () => openLinkDialog('markdown') },
|
||||
{ icon: <ImageIcon size={15} />, title: '上传图片', action: insertMarkdownImage },
|
||||
{
|
||||
icon: <ImageIcon size={15} />,
|
||||
title: '图片',
|
||||
hint: '上传、链接或从已上传中选择',
|
||||
action: () => openImagePicker('markdown'),
|
||||
},
|
||||
];
|
||||
if (enableContentGates) {
|
||||
tools.push(
|
||||
@@ -776,7 +809,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
);
|
||||
}
|
||||
return tools;
|
||||
}, [enableContentGates, withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, insertMarkdownImage]);
|
||||
}, [enableContentGates, withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker]);
|
||||
|
||||
const tools = mode === 'rich' ? buildRichTools() : buildMarkdownTools();
|
||||
const words = mode === 'markdown'
|
||||
@@ -897,8 +930,15 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
open={linkDialogOpen}
|
||||
onOpenChange={setLinkDialogOpen}
|
||||
initialUrl={linkDialogUrl}
|
||||
initialText={linkDialogText}
|
||||
editing={linkDialogEditing}
|
||||
onConfirm={applyLink}
|
||||
onRemove={linkTarget === 'rich' && linkDialogUrl ? removeLink : undefined}
|
||||
onRemove={linkTarget === 'rich' && linkDialogEditing ? removeLink : undefined}
|
||||
/>
|
||||
<ArticleImagePickerDialog
|
||||
open={imagePickerOpen}
|
||||
onOpenChange={setImagePickerOpen}
|
||||
onInsert={applyImageUrls}
|
||||
/>
|
||||
<ArticleCodeBlockDialog
|
||||
open={codeBlockDialogOpen}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { CalendarCheck, Check, Gift, Loader2 } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { useCheckIn } from '../hooks/useCheckIn';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { loginPath } from '../utils/authRedirect';
|
||||
@@ -8,8 +7,14 @@ import { loginPath } from '../utils/authRedirect';
|
||||
/** 右侧栏首块底部:每日签到 */
|
||||
export default function AsideCheckInStrip() {
|
||||
const nav = useNavigate();
|
||||
const { user } = useAuth();
|
||||
const { status, loading, busy, doCheckIn } = useCheckIn();
|
||||
const { user, loading: authLoading } = useAuth();
|
||||
const { status, loading, busy, doCheckIn } = useCheckIn(!!user && !authLoading);
|
||||
|
||||
// 鉴权未完成且无种子:空白,避免访客签到卡闪一下再消失
|
||||
// 有 SSR boot 时 loading 一开始就是 false
|
||||
if (authLoading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
@@ -37,17 +42,14 @@ export default function AsideCheckInStrip() {
|
||||
);
|
||||
}
|
||||
|
||||
if (loading && !status) {
|
||||
return (
|
||||
<div className="widget-checkin" aria-busy="true" aria-label="签到加载中">
|
||||
<Skeleton className="widget-checkin-skeleton" />
|
||||
</div>
|
||||
);
|
||||
// 登录用户:status 未到齐前不渲染最终态
|
||||
if (loading || !status) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const checkedIn = !!status?.checked_in;
|
||||
const streak = status?.streak ?? 0;
|
||||
const todayPoints = status?.today_points ?? 5;
|
||||
const checkedIn = !!status.checked_in;
|
||||
const streak = status.streak ?? 0;
|
||||
const todayPoints = status.today_points ?? 5;
|
||||
|
||||
const meta = checkedIn
|
||||
? (streak > 0 ? `连续 ${streak} 天 · 今日已获得 ${todayPoints} 积分` : `今日已获得 ${todayPoints} 积分`)
|
||||
|
||||
@@ -12,11 +12,11 @@ import {
|
||||
List, ListOrdered, Code, Link as LinkIcon, Image as ImageIcon,
|
||||
} from 'lucide-react';
|
||||
import { POST_CONTENT_PURIFY_CONFIG } from '../utils/postContent';
|
||||
import { api } from '../api/client';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
|
||||
import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
|
||||
import { ArticleImage } from './editor/ArticleImageExtension';
|
||||
import { ArticleImagePickerDialog } from './editor/ArticleImagePickerDialog';
|
||||
import { ArticleLinkDialog, type ArticleLinkConfirm } from './editor/ArticleLinkDialog';
|
||||
import { TabIndent } from './editor/TabIndentExtension';
|
||||
import type { CodeBlockInsertOptions } from '../utils/codeBlockOptions';
|
||||
import { Tooltip } from './ui/Tooltip';
|
||||
@@ -49,28 +49,6 @@ function isEditorEmpty(editor: Editor): boolean {
|
||||
return !hasImage;
|
||||
}
|
||||
|
||||
/** 触发图片文件选择并上传 */
|
||||
async function uploadImageFiles(): Promise<string[]> {
|
||||
return new Promise(resolve => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/jpeg,image/png,image/gif,image/webp';
|
||||
input.multiple = false;
|
||||
input.onchange = async () => {
|
||||
const files = [...(input.files ?? [])];
|
||||
if (!files.length) { resolve([]); return; }
|
||||
try {
|
||||
const { url } = await api.uploadPostImage(files[0]);
|
||||
resolve([url]);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '图片上传失败');
|
||||
resolve([]);
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEditor(
|
||||
{ value, onChange, placeholder = '说点什么吧…' },
|
||||
ref,
|
||||
@@ -79,6 +57,11 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
const lastValueRef = useRef(value);
|
||||
const [, setTick] = useState(0);
|
||||
const [showSticker, setShowSticker] = useState(false);
|
||||
const [imagePickerOpen, setImagePickerOpen] = useState(false);
|
||||
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
|
||||
const [linkDialogUrl, setLinkDialogUrl] = useState('');
|
||||
const [linkDialogText, setLinkDialogText] = useState('');
|
||||
const [linkDialogEditing, setLinkDialogEditing] = useState(false);
|
||||
const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
|
||||
const [codeBlockEditing, setCodeBlockEditing] = useState(false);
|
||||
const [codeBlockInitial, setCodeBlockInitial] = useState<CodeBlockInsertOptions | null>(null);
|
||||
@@ -99,6 +82,11 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
openOnClick: false,
|
||||
autolink: true,
|
||||
defaultProtocol: 'https',
|
||||
// 新标签由全站设置在展示层处理,编辑器不写 target/rel
|
||||
HTMLAttributes: {
|
||||
target: null,
|
||||
rel: null,
|
||||
},
|
||||
}),
|
||||
ArticleImage.configure({ inline: true, allowBase64: true }),
|
||||
Placeholder.configure({ placeholder }),
|
||||
@@ -179,11 +167,14 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
setShowSticker(false);
|
||||
}, [editor]);
|
||||
|
||||
const setImage = useCallback(async () => {
|
||||
if (!editor) return;
|
||||
const urls = await uploadImageFiles();
|
||||
if (!urls.length) return;
|
||||
editor.chain().focus().setImage({ src: urls[0] }).run();
|
||||
const applyImageUrls = useCallback((urls: string[]) => {
|
||||
if (!editor || !urls.length) return;
|
||||
// 评论为 inline 图,无图组:逐张插入并跟空格,便于光标落在右侧
|
||||
const nodes = urls.flatMap(src => [
|
||||
{ type: 'image' as const, attrs: { src } },
|
||||
{ type: 'text' as const, text: ' ' },
|
||||
]);
|
||||
editor.chain().focus().insertContent(nodes).run();
|
||||
}, [editor]);
|
||||
|
||||
const openCodeBlockDialog = useCallback(() => {
|
||||
@@ -213,23 +204,70 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
}).run();
|
||||
}, [editor]);
|
||||
|
||||
const setLink = useCallback(() => {
|
||||
const openLinkDialog = useCallback(() => {
|
||||
if (!editor) return;
|
||||
const prev = editor.getAttributes('link').href as string | undefined;
|
||||
const url = window.prompt('链接地址', prev ?? 'https://');
|
||||
if (url === null) return;
|
||||
const { from, to, empty } = editor.state.selection;
|
||||
let text = empty ? '' : editor.state.doc.textBetween(from, to, '');
|
||||
let href = '';
|
||||
let editing = false;
|
||||
if (editor.isActive('link')) {
|
||||
const attrs = editor.getAttributes('link');
|
||||
href = (attrs.href as string) || '';
|
||||
editing = Boolean(href);
|
||||
editor.chain().focus().extendMarkRange('link').run();
|
||||
const sel = editor.state.selection;
|
||||
text = editor.state.doc.textBetween(sel.from, sel.to, '') || text;
|
||||
}
|
||||
setLinkDialogUrl(href);
|
||||
setLinkDialogText(text);
|
||||
setLinkDialogEditing(editing);
|
||||
setLinkDialogOpen(true);
|
||||
}, [editor]);
|
||||
|
||||
const applyLink = useCallback((payload: ArticleLinkConfirm) => {
|
||||
if (!editor) return;
|
||||
const { url, text } = payload;
|
||||
if (!url) {
|
||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
|
||||
// 新标签行为由全站 open_content_links_in_new_tab 在展示层处理
|
||||
const linkAttrs = { href: url };
|
||||
const { empty } = editor.state.selection;
|
||||
const hasLink = editor.isActive('link');
|
||||
if (!empty || hasLink) {
|
||||
editor.chain().focus().extendMarkRange('link').setLink(linkAttrs).run();
|
||||
const { from, to } = editor.state.selection;
|
||||
const current = editor.state.doc.textBetween(from, to, '');
|
||||
if (text && current !== text) {
|
||||
editor.chain().focus().insertContentAt(
|
||||
{ from, to },
|
||||
{
|
||||
type: 'text',
|
||||
text,
|
||||
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||
},
|
||||
).run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().insertContent({
|
||||
type: 'text',
|
||||
text: text || '链接文字',
|
||||
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||
}).run();
|
||||
}, [editor]);
|
||||
|
||||
const removeLink = useCallback(() => {
|
||||
if (!editor) return;
|
||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||
}, [editor]);
|
||||
|
||||
if (!editor) {
|
||||
return <div className="comment-editor"><div className="article-editor-bar" /><div className="article-editor-body" /></div>;
|
||||
}
|
||||
|
||||
const tools: { icon: React.ReactNode; title: string; active?: boolean; action: () => void; className?: string }[] = [
|
||||
const tools: { icon: React.ReactNode; title: string; hint?: string; active?: boolean; action: () => void; className?: string }[] = [
|
||||
{ icon: <Bold size={15} />, title: '加粗', active: editor.isActive('bold'), action: () => editor.chain().focus().toggleBold().run() },
|
||||
{ icon: <Italic size={15} />, title: '斜体', active: editor.isActive('italic'), action: () => editor.chain().focus().toggleItalic().run() },
|
||||
{ icon: <UnderlineIcon size={15} />, title: '下划线', active: editor.isActive('underline'), action: () => editor.chain().focus().toggleUnderline().run() },
|
||||
@@ -237,8 +275,13 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
{ icon: <List size={15} />, title: '无序列表', active: editor.isActive('bulletList'), action: () => editor.chain().focus().toggleBulletList().run() },
|
||||
{ icon: <ListOrdered size={15} />, title: '有序列表', active: editor.isActive('orderedList'), action: () => editor.chain().focus().toggleOrderedList().run() },
|
||||
{ icon: <Code size={15} />, title: '代码块', active: editor.isActive('codeBlock'), action: openCodeBlockDialog },
|
||||
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: setLink },
|
||||
{ icon: <ImageIcon size={15} />, title: '上传图片', action: setImage },
|
||||
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: openLinkDialog },
|
||||
{
|
||||
icon: <ImageIcon size={15} />,
|
||||
title: '图片',
|
||||
hint: '上传、链接或从已上传中选择',
|
||||
action: () => setImagePickerOpen(true),
|
||||
},
|
||||
{ icon: <span className="article-tool-btn__owo">OwO</span>, title: '表情 OwO', active: showSticker, action: () => setShowSticker(v => !v), className: 'article-tool-btn--owo' },
|
||||
];
|
||||
|
||||
@@ -247,14 +290,14 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
<div className="article-editor-bar">
|
||||
<div className="article-editor-tools">
|
||||
{tools.map((t, i) => (
|
||||
<Tooltip key={i} content={t.title} side="bottom">
|
||||
<Tooltip key={i} content={t.title} hint={t.hint} side="bottom">
|
||||
<button
|
||||
ref={i === tools.length - 1 ? stickerBtnRef : undefined}
|
||||
type="button"
|
||||
className={`article-tool-btn${t.active ? ' active' : ''}${t.className ? ` ${t.className}` : ''}`}
|
||||
onMouseDown={e => e.preventDefault()}
|
||||
onClick={t.action}
|
||||
aria-label={t.title}
|
||||
aria-label={t.hint ? `${t.title},${t.hint}` : t.title}
|
||||
>
|
||||
{t.icon}
|
||||
</button>
|
||||
@@ -268,6 +311,20 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
</div>
|
||||
</div>
|
||||
{showSticker && <StickerPicker onSelect={insertSticker} />}
|
||||
<ArticleLinkDialog
|
||||
open={linkDialogOpen}
|
||||
onOpenChange={setLinkDialogOpen}
|
||||
initialUrl={linkDialogUrl}
|
||||
initialText={linkDialogText}
|
||||
editing={linkDialogEditing}
|
||||
onConfirm={applyLink}
|
||||
onRemove={linkDialogEditing ? removeLink : undefined}
|
||||
/>
|
||||
<ArticleImagePickerDialog
|
||||
open={imagePickerOpen}
|
||||
onOpenChange={setImagePickerOpen}
|
||||
onInsert={applyImageUrls}
|
||||
/>
|
||||
<ArticleCodeBlockDialog
|
||||
open={codeBlockDialogOpen}
|
||||
onOpenChange={setCodeBlockDialogOpen}
|
||||
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import {
|
||||
Dialog,
|
||||
@@ -32,6 +31,8 @@ import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -144,6 +145,11 @@ function CommentItem({
|
||||
&& !!onApprove;
|
||||
const showEdited = !hidden && !!c.updated_at && isTimeDiffSignificant(c.created_at, c.updated_at);
|
||||
const canReport = !hidden && !isEditing && !isCommentAuthor(c, currentUser);
|
||||
const showHistory = isAdmin && showEdited;
|
||||
const showManageMenu = !hidden && !isEditing && (
|
||||
canApprove || canEdit || showHistory || canDelete || canReport
|
||||
);
|
||||
const showManageGroup = canApprove || canEdit || showHistory || canDelete;
|
||||
const [editText, setEditText] = useState(c.content);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
@@ -152,6 +158,7 @@ function CommentItem({
|
||||
const [liked, setLiked] = useState(!!c.liked);
|
||||
const [likeCount, setLikeCount] = useState(c.like_count ?? 0);
|
||||
const [revOpen, setRevOpen] = useState(false);
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
const [reportOpen, setReportOpen] = useState(false);
|
||||
const [reportReason, setReportReason] = useState<ReportReason>('spam');
|
||||
const [reportDetail, setReportDetail] = useState('');
|
||||
@@ -333,24 +340,6 @@ function CommentItem({
|
||||
{c.reply_target && (
|
||||
<span className="waline-reply-at">@{commentNick(c.reply_target)}</span>
|
||||
)}
|
||||
{!hidden && !isEditing && canApprove && (
|
||||
<button
|
||||
type="button"
|
||||
className="waline-comment-reply-btn waline-comment-approve-btn"
|
||||
disabled={approving}
|
||||
onClick={async () => {
|
||||
setApproving(true);
|
||||
try {
|
||||
await onApprove?.(c);
|
||||
} finally {
|
||||
setApproving(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Check size={14} />
|
||||
{approving ? '通过中…' : '通过'}
|
||||
</button>
|
||||
)}
|
||||
{!hidden && !isEditing && !!renderReplyBox && (
|
||||
isReplying ? (
|
||||
<button type="button" className="waline-comment-reply-btn cancel" onClick={onCancelReply}>
|
||||
@@ -366,12 +355,6 @@ function CommentItem({
|
||||
</Tooltip>
|
||||
)
|
||||
)}
|
||||
{!hidden && !isEditing && canEdit && (
|
||||
<button type="button" className="waline-comment-reply-btn" onClick={() => onStartEdit(c)}>
|
||||
<Pencil size={14} />
|
||||
编辑
|
||||
</button>
|
||||
)}
|
||||
{bountyAward?.open && bountyAward.canAward && c.user_id !== bountyAward.postAuthorId
|
||||
&& c.status === 'published' && !hidden && (
|
||||
<button
|
||||
@@ -383,46 +366,7 @@ function CommentItem({
|
||||
采纳
|
||||
</button>
|
||||
)}
|
||||
{!hidden && !isEditing && isAdmin && showEdited && (
|
||||
<button type="button" className="waline-comment-reply-btn" onClick={() => setRevOpen(true)}>
|
||||
<History size={14} />
|
||||
编辑记录
|
||||
</button>
|
||||
)}
|
||||
{!hidden && !isEditing && canDelete && (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<button type="button" className="waline-comment-reply-btn cancel" disabled={deleting}>
|
||||
<Trash2 size={14} />
|
||||
删除
|
||||
</button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确定删除该评论?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
将同时移入回收站其下所有回复,可在后台恢复或永久删除。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={async () => {
|
||||
setDeleting(true);
|
||||
try {
|
||||
await onDelete(c);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
删除
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
{canReport && (
|
||||
{showManageMenu && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
@@ -433,19 +377,98 @@ function CommentItem({
|
||||
<MoreHorizontal size={14} />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="center" className="report-more-menu">
|
||||
<DropdownMenuItem
|
||||
className="report-more-menu__item"
|
||||
onSelect={openReport}
|
||||
>
|
||||
<Flag size={14} />
|
||||
举报
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuContent align="end" className="comment-manage-menu">
|
||||
{showManageGroup && (
|
||||
<>
|
||||
<DropdownMenuLabel>管理</DropdownMenuLabel>
|
||||
{canApprove && (
|
||||
<DropdownMenuItem
|
||||
disabled={approving}
|
||||
onSelect={() => {
|
||||
void (async () => {
|
||||
setApproving(true);
|
||||
try {
|
||||
await onApprove?.(c);
|
||||
} finally {
|
||||
setApproving(false);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
<Check size={14} aria-hidden />
|
||||
{approving ? '通过中…' : '通过审核'}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canEdit && (
|
||||
<DropdownMenuItem onSelect={() => onStartEdit(c)}>
|
||||
<Pencil size={14} aria-hidden />
|
||||
编辑
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{showHistory && (
|
||||
<DropdownMenuItem onSelect={() => setRevOpen(true)}>
|
||||
<History size={14} aria-hidden />
|
||||
编辑记录
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canDelete && (
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
disabled={deleting}
|
||||
onSelect={() => setDeleteOpen(true)}
|
||||
>
|
||||
<Trash2 size={14} aria-hidden />
|
||||
删除
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canReport && <DropdownMenuSeparator />}
|
||||
</>
|
||||
)}
|
||||
{canReport && (
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onSelect={openReport}
|
||||
>
|
||||
<Flag size={14} aria-hidden />
|
||||
举报
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确定删除该评论?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
将同时移入回收站其下所有回复,可在后台恢复或永久删除。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleting}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
disabled={deleting}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
void (async () => {
|
||||
setDeleting(true);
|
||||
try {
|
||||
await onDelete(c);
|
||||
setDeleteOpen(false);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
删除
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{isAdmin && (
|
||||
<CommentRevisionDialog open={revOpen} onOpenChange={setRevOpen} comment={c} />
|
||||
)}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Sparkles } from 'lucide-react';
|
||||
import { BadgeCheck } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface Props {
|
||||
@@ -6,13 +6,13 @@ interface Props {
|
||||
size?: number;
|
||||
}
|
||||
|
||||
/** 精华帖标识 */
|
||||
/** 推荐帖标识 */
|
||||
export default function FeaturedIcon({ className, size = 16 }: Props) {
|
||||
return (
|
||||
<Sparkles
|
||||
<BadgeCheck
|
||||
className={cn('post-featured-icon', className)}
|
||||
size={size}
|
||||
aria-label="精华"
|
||||
aria-label="推荐"
|
||||
role="img"
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import PostListSkeleton from './PostListSkeleton';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
|
||||
/** 首页 Feed 初始骨架(排序栏 + 列表) */
|
||||
export default function FeedPageSkeleton() {
|
||||
const { limits } = useForumLimits();
|
||||
|
||||
return (
|
||||
<div className="page-wrap page-wrap--feed" aria-busy="true" aria-label="内容加载中">
|
||||
<div className="feed-panel">
|
||||
<div className="feed-top">
|
||||
<div className="feed-top__bar">
|
||||
<div className="feed-toolbar feed-toolbar--skeleton" aria-hidden>
|
||||
<Skeleton className="skeleton--sort-tab" />
|
||||
<Skeleton className="skeleton--sort-tab" />
|
||||
<Skeleton className="skeleton--sort-tab" />
|
||||
<span className="feed-toolbar__spacer" />
|
||||
<Skeleton className="skeleton--count" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="post-list-scroll">
|
||||
<PostListSkeleton listStyle={limits.feed_list_style ?? 'title'} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,39 +1,56 @@
|
||||
import { useRef } from 'react';
|
||||
import { boardPath, type PermalinkOpts } from '../utils/permalink';
|
||||
import { getCachedForumLimits } from '../hooks/useForumLimits';
|
||||
import { Clock, MessageCircle, Flame } from 'lucide-react';
|
||||
import { useMemo, useRef } from 'react';
|
||||
import { useParams, useSearchParams } from 'react-router-dom';
|
||||
import { boardPath, parsePermalinkID, type PermalinkOpts } from '../utils/permalink';
|
||||
import { getCachedForumLimits, useForumLimits } from '../hooks/useForumLimits';
|
||||
import { Clock, MessageCircle, BadgeCheck, Loader2 } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { moveTabIndex } from '../hooks/useOverlayA11y';
|
||||
import {
|
||||
enabledFeedSortTabs,
|
||||
getDefaultFeedSort,
|
||||
normalizeFeedSortTabs,
|
||||
} from '../utils/feedSortTabs';
|
||||
import type { FeedSortTab } from '../api/types';
|
||||
|
||||
export type FeedSort = 'latest' | 'reply' | 'hot';
|
||||
|
||||
const SORT_OPTIONS: {
|
||||
key: FeedSort;
|
||||
label: string;
|
||||
hint: string;
|
||||
icon: typeof Clock;
|
||||
}[] = [
|
||||
{ key: 'latest', label: '最新发帖', hint: '按发布时间', icon: Clock },
|
||||
{ key: 'reply', label: '最新回复', hint: '最近有人回复', icon: MessageCircle },
|
||||
{ key: 'hot', label: '热门讨论', hint: '按互动热度', icon: Flame },
|
||||
];
|
||||
const SORT_META: Record<FeedSort, { hint: string; icon: typeof Clock }> = {
|
||||
reply: { hint: '按最近活动(发帖或评论)', icon: MessageCircle },
|
||||
latest: { hint: '按发帖时间', icon: Clock },
|
||||
hot: { hint: '仅展示推荐帖', icon: BadgeCheck },
|
||||
};
|
||||
|
||||
interface Props {
|
||||
value: FeedSort;
|
||||
onChange: (sort: FeedSort) => void;
|
||||
postTotal?: number;
|
||||
/** 正在加载、尚未提交到画面的目标排序 */
|
||||
pendingValue?: FeedSort | null;
|
||||
}
|
||||
|
||||
export function parseFeedSort(raw: string | null): FeedSort {
|
||||
if (raw === 'reply' || raw === 'hot') return raw;
|
||||
return 'latest';
|
||||
/** 当前配置下的默认排序(读缓存,供非 hook 路径) */
|
||||
export function getDefaultFeedSortFromCache(): FeedSort {
|
||||
return getDefaultFeedSort(getCachedForumLimits().feed_sort_tabs);
|
||||
}
|
||||
|
||||
/** 解析 URL sort;未启用或不合法时回落默认 */
|
||||
export function parseFeedSort(raw: string | null, tabs?: FeedSortTab[] | null): FeedSort {
|
||||
const list = tabs ?? getCachedForumLimits().feed_sort_tabs;
|
||||
const def = getDefaultFeedSort(list);
|
||||
if (raw === 'latest' || raw === 'hot' || raw === 'reply') {
|
||||
const enabled = enabledFeedSortTabs(list).some(t => t.id === raw);
|
||||
if (enabled) return raw;
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
export function buildHomeUrl(
|
||||
boardId: number,
|
||||
sort: FeedSort = 'latest',
|
||||
sort?: FeedSort,
|
||||
opts?: { keyword?: string; tag?: string; author?: string; titleOnly?: boolean; permalink?: PermalinkOpts },
|
||||
) {
|
||||
const def = getDefaultFeedSortFromCache();
|
||||
const effective = sort ?? def;
|
||||
const p = new URLSearchParams();
|
||||
const tag = opts?.tag?.trim();
|
||||
const keyword = opts?.keyword?.trim();
|
||||
@@ -47,7 +64,8 @@ export function buildHomeUrl(
|
||||
} else if (author) {
|
||||
p.set('author', author);
|
||||
}
|
||||
if (sort !== 'latest') p.set('sort', sort);
|
||||
// 默认排序不写进 URL
|
||||
if (effective !== def) p.set('sort', effective);
|
||||
const qs = p.toString();
|
||||
|
||||
if (boardId) {
|
||||
@@ -57,25 +75,65 @@ export function buildHomeUrl(
|
||||
return qs ? `/?${qs}` : '/';
|
||||
}
|
||||
|
||||
export function feedSortLabel(sort: FeedSort): string {
|
||||
return SORT_OPTIONS.find(o => o.key === sort)?.label ?? '帖子列表';
|
||||
export function feedSortLabel(sort: FeedSort, tabs?: FeedSortTab[] | null): string {
|
||||
const list = normalizeFeedSortTabs(tabs ?? getCachedForumLimits().feed_sort_tabs);
|
||||
return list.find(t => t.id === sort)?.label ?? '帖子列表';
|
||||
}
|
||||
|
||||
export default function FeedSortBar({ value, onChange, postTotal }: Props) {
|
||||
export default function FeedSortBar({
|
||||
value,
|
||||
onChange,
|
||||
postTotal,
|
||||
pendingValue,
|
||||
}: Props) {
|
||||
const { limits } = useForumLimits();
|
||||
const { id: boardRouteId } = useParams();
|
||||
const [params] = useSearchParams();
|
||||
// 与 SSR href / HomePage 一致:从路由与查询串解析板块与筛选
|
||||
const boardId = boardRouteId
|
||||
? (() => {
|
||||
const id = parsePermalinkID(boardRouteId);
|
||||
return Number.isFinite(id) && id > 0 ? id : 0;
|
||||
})()
|
||||
: (Number(params.get('board')) || 0);
|
||||
const keyword = params.get('keyword') || '';
|
||||
const tag = params.get('tag') || '';
|
||||
const author = params.get('author') || '';
|
||||
const titleOnly = params.get('title_only') === '1';
|
||||
|
||||
const options = useMemo(
|
||||
() => enabledFeedSortTabs(limits.feed_sort_tabs).map(t => ({
|
||||
key: t.id as FeedSort,
|
||||
label: t.label,
|
||||
hint: SORT_META[t.id]?.hint ?? '',
|
||||
icon: SORT_META[t.id]?.icon ?? Clock,
|
||||
href: buildHomeUrl(boardId, t.id as FeedSort, {
|
||||
keyword,
|
||||
tag,
|
||||
author,
|
||||
titleOnly,
|
||||
permalink: limits,
|
||||
}),
|
||||
})),
|
||||
[limits, boardId, keyword, tag, author, titleOnly],
|
||||
);
|
||||
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const activeIndex = Math.max(0, SORT_OPTIONS.findIndex(o => o.key === value));
|
||||
const activeIndex = Math.max(0, options.findIndex(o => o.key === value));
|
||||
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
const next = moveTabIndex(e.key, activeIndex, SORT_OPTIONS.length);
|
||||
const next = moveTabIndex(e.key, activeIndex, options.length);
|
||||
if (next == null) return;
|
||||
e.preventDefault();
|
||||
onChange(SORT_OPTIONS[next].key);
|
||||
onChange(options[next].key);
|
||||
requestAnimationFrame(() => {
|
||||
const tabs = listRef.current?.querySelectorAll<HTMLElement>('[role="tab"]');
|
||||
tabs?.[next]?.focus();
|
||||
});
|
||||
};
|
||||
|
||||
if (options.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="feed-toolbar">
|
||||
<div
|
||||
@@ -85,21 +143,30 @@ export default function FeedSortBar({ value, onChange, postTotal }: Props) {
|
||||
aria-label="帖子排序"
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{SORT_OPTIONS.map(({ key, label, hint, icon: Icon }, i) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
role="tab"
|
||||
tabIndex={activeIndex === i ? 0 : -1}
|
||||
aria-selected={value === key}
|
||||
title={`${label} · ${hint}`}
|
||||
className={cn('feed-sort-tab', value === key && 'active')}
|
||||
onClick={() => onChange(key)}
|
||||
>
|
||||
<Icon aria-hidden />
|
||||
<span className="feed-sort-tab__label">{label}</span>
|
||||
</button>
|
||||
))}
|
||||
{options.map(({ key, label, hint, icon: Icon, href }, i) => {
|
||||
const pending = pendingValue === key;
|
||||
return (
|
||||
<a
|
||||
key={key}
|
||||
href={href}
|
||||
role="tab"
|
||||
tabIndex={activeIndex === i ? 0 : -1}
|
||||
aria-selected={value === key}
|
||||
aria-busy={pending || undefined}
|
||||
title={`${label} · ${hint}`}
|
||||
className={cn('feed-sort-tab', value === key && 'active', pending && 'is-pending')}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
onChange(key);
|
||||
}}
|
||||
>
|
||||
{pending
|
||||
? <Loader2 className="feed-sort-tab__spin" aria-hidden />
|
||||
: <Icon aria-hidden />}
|
||||
<span className="feed-sort-tab__label">{label}</span>
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{postTotal != null && (
|
||||
<span className="feed-toolbar__count">共 {postTotal} 条</span>
|
||||
|
||||
@@ -6,7 +6,7 @@ type PageLoaderProps = {
|
||||
fullScreen?: boolean;
|
||||
};
|
||||
|
||||
/** 通用路由懒加载占位;首页请用 FeedPageSkeleton,避免非 Feed 页闪出鱼骨骨架 */
|
||||
/** 通用路由懒加载占位(后台 / 全屏独立页);前台 MainLayout 用顶栏进度条 + 空白 */
|
||||
export default function PageLoader({ fullScreen = false }: PageLoaderProps) {
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useMemo, useCallback, useEffect, useState } from 'react';
|
||||
import { useMemo, useCallback, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { renderPostContentHtml } from '../utils/postContent';
|
||||
import { extractHeadingsFromHtml, type PostHeading } from '../utils/postHeadings';
|
||||
import { loginPath, registerPath } from '../utils/authRedirect';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import { notify } from '@/lib/notify';
|
||||
@@ -12,8 +11,6 @@ interface Props {
|
||||
html: string;
|
||||
isLoggedIn: boolean;
|
||||
className?: string;
|
||||
/** 正文标题树变化时回调(用于侧栏目录) */
|
||||
onHeadingsChange?: (headings: PostHeading[]) => void;
|
||||
/** 点击「回复可见」门控的「去回复」 */
|
||||
onRequestReply?: () => void;
|
||||
/** 积分解锁成功后刷新正文 */
|
||||
@@ -26,7 +23,6 @@ export default function PostContent({
|
||||
html,
|
||||
isLoggedIn,
|
||||
className = 'post-detail-content',
|
||||
onHeadingsChange,
|
||||
onRequestReply,
|
||||
onUnlocked,
|
||||
postId: postIdProp,
|
||||
@@ -39,19 +35,12 @@ export default function PostContent({
|
||||
const [lightboxAlt, setLightboxAlt] = useState('');
|
||||
const [unlocking, setUnlocking] = useState(false);
|
||||
|
||||
const prepared = useMemo(() => {
|
||||
const rendered = renderPostContentHtml(html, isLoggedIn, {
|
||||
const preparedHtml = useMemo(
|
||||
() => renderPostContentHtml(html, isLoggedIn, {
|
||||
openLinksInNewTab: limits.open_content_links_in_new_tab,
|
||||
});
|
||||
return {
|
||||
html: rendered,
|
||||
headings: extractHeadingsFromHtml(rendered),
|
||||
};
|
||||
}, [html, isLoggedIn, limits.open_content_links_in_new_tab]);
|
||||
|
||||
useEffect(() => {
|
||||
onHeadingsChange?.(prepared.headings);
|
||||
}, [prepared.headings, onHeadingsChange]);
|
||||
}),
|
||||
[html, isLoggedIn, limits.open_content_links_in_new_tab],
|
||||
);
|
||||
|
||||
const openLightbox = useCallback((img: HTMLImageElement) => {
|
||||
const full = img.getAttribute('data-full') || img.currentSrc || img.src;
|
||||
@@ -167,7 +156,7 @@ export default function PostContent({
|
||||
className={className}
|
||||
onClick={handleClick}
|
||||
onKeyDown={handleKeyDown}
|
||||
dangerouslySetInnerHTML={{ __html: prepared.html }}
|
||||
dangerouslySetInnerHTML={{ __html: preparedHtml }}
|
||||
/>
|
||||
<ImageLightbox
|
||||
src={lightboxSrc}
|
||||
|
||||
@@ -61,6 +61,14 @@ function PostListItem({ post, sort = 'latest', boardId = 0, onSelect }: Props) {
|
||||
openPost();
|
||||
};
|
||||
|
||||
const hasTypeBadge = post.post_type === 'question'
|
||||
|| post.post_type === 'poll'
|
||||
|| post.post_type === 'lottery'
|
||||
|| (post.post_type === 'bounty' && (
|
||||
(post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0)
|
||||
|| post.bounty_status === 'awarded'
|
||||
));
|
||||
|
||||
const titleRow = (
|
||||
<div className="post-title-row">
|
||||
{post.pinned && (
|
||||
@@ -70,9 +78,9 @@ function PostListItem({ post, sort = 'latest', boardId = 0, onSelect }: Props) {
|
||||
<span className="post-pin-badge post-pin-badge--board" title="板块置顶">板块置顶</span>
|
||||
)}
|
||||
{post.featured && (
|
||||
<span className="post-feature-badge" title="精华">
|
||||
<span className="post-feature-badge" title="推荐">
|
||||
<FeaturedIcon size={12} />
|
||||
精华
|
||||
推荐
|
||||
</span>
|
||||
)}
|
||||
{post.status === 'pending' && (
|
||||
@@ -81,31 +89,36 @@ function PostListItem({ post, sort = 'latest', boardId = 0, onSelect }: Props) {
|
||||
{post.status === 'rejected' && (
|
||||
<span className="post-status-badge post-status-badge--rejected" title="未通过">未通过</span>
|
||||
)}
|
||||
{post.post_type === 'question' && (
|
||||
<span
|
||||
className={`post-qa-badge${post.question_resolved ? ' post-qa-badge--resolved' : ' post-qa-badge--open'}`}
|
||||
title={post.question_resolved ? '已解决' : '未解决'}
|
||||
>
|
||||
{post.question_resolved ? '已解决' : '未解决'}
|
||||
</span>
|
||||
)}
|
||||
{post.post_type === 'poll' && (
|
||||
<span className="post-type-badge post-type-badge--poll" title="投票">投票</span>
|
||||
)}
|
||||
{post.post_type === 'bounty' && post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0 && (
|
||||
<span className="post-bounty-badge post-bounty-badge--open" title="悬赏">悬赏 {post.bounty_points}</span>
|
||||
)}
|
||||
{post.post_type === 'bounty' && post.bounty_status === 'awarded' && (
|
||||
<span className="post-bounty-badge post-bounty-badge--awarded" title="已采纳">已采纳</span>
|
||||
)}
|
||||
{post.post_type === 'lottery' && (
|
||||
<span className="post-type-badge post-type-badge--lottery" title="抽奖">
|
||||
{post.lottery_status === 'drawn' ? '已开奖' : '抽奖'}
|
||||
</span>
|
||||
)}
|
||||
<a href={href} className="post-title" onClick={onTitleClick}>
|
||||
{post.title}
|
||||
</a>
|
||||
{/* 类型徽章放标题后:flex 自动扣宽,长标题省略号紧挨徽章左侧 */}
|
||||
{hasTypeBadge && (
|
||||
<span className="post-title-type-badges">
|
||||
{post.post_type === 'question' && (
|
||||
<span
|
||||
className={`post-qa-badge${post.question_resolved ? ' post-qa-badge--resolved' : ' post-qa-badge--open'}`}
|
||||
title={post.question_resolved ? '已解决' : '未解决'}
|
||||
>
|
||||
{post.question_resolved ? '已解决' : '未解决'}
|
||||
</span>
|
||||
)}
|
||||
{post.post_type === 'poll' && (
|
||||
<span className="post-type-badge post-type-badge--poll" title="投票">投票</span>
|
||||
)}
|
||||
{post.post_type === 'bounty' && post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0 && (
|
||||
<span className="post-bounty-badge post-bounty-badge--open" title="悬赏">悬赏 {post.bounty_points}</span>
|
||||
)}
|
||||
{post.post_type === 'bounty' && post.bounty_status === 'awarded' && (
|
||||
<span className="post-bounty-badge post-bounty-badge--awarded" title="已采纳">已采纳</span>
|
||||
)}
|
||||
{post.post_type === 'lottery' && (
|
||||
<span className="post-type-badge post-type-badge--lottery" title="抽奖">
|
||||
{post.lottery_status === 'drawn' ? '已开奖' : '抽奖'}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import type { ForumLimitsPublic } from '../api/types';
|
||||
|
||||
export type FeedListStyle = ForumLimitsPublic['feed_list_style'];
|
||||
@@ -11,69 +10,3 @@ export function feedListRowEstimate(style: FeedListStyle): number {
|
||||
default: return 64;
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
count?: number;
|
||||
listStyle?: FeedListStyle;
|
||||
}
|
||||
|
||||
/** 帖子列表加载骨架屏(对齐 v2 紧凑列表) */
|
||||
export default function PostListSkeleton({ count = 8, listStyle = 'title' }: Props) {
|
||||
const showExcerpt = listStyle === 'excerpt' || listStyle === 'thumbnail';
|
||||
const showThumb = listStyle === 'thumbnail';
|
||||
const titleOnly = listStyle === 'title';
|
||||
|
||||
return (
|
||||
<div className="post-list-skeleton" aria-busy="true" aria-label="加载中">
|
||||
{Array.from({ length: count }, (_, i) => {
|
||||
const hasThumb = showThumb && i % 3 === 0;
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
className={`post-row post-row--v2 post-row--skeleton${titleOnly ? ' post-row--title-only' : ''}${hasThumb ? ' post-row--has-thumb' : ''}`}
|
||||
>
|
||||
<Skeleton className="skeleton--avatar skeleton--avatar-v2" />
|
||||
{hasThumb ? (
|
||||
<div className="post-main post-main--with-thumb">
|
||||
<div className="post-content">
|
||||
<Skeleton className="skeleton--title skeleton--title-v2" style={{ width: `${58 + (i % 4) * 9}%` }} />
|
||||
{showExcerpt && (
|
||||
<Skeleton className="skeleton--excerpt skeleton--excerpt-v2" style={{ width: `${72 + (i % 3) * 8}%` }} />
|
||||
)}
|
||||
<div className="post-meta-left post-meta-left--skeleton">
|
||||
<Skeleton className="skeleton--board-badge" />
|
||||
<Skeleton className="skeleton--meta-line" style={{ width: `${45 + (i % 3) * 10}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="post-aside">
|
||||
<Skeleton className="skeleton--thumb skeleton--thumb-tall" />
|
||||
<div className="post-stats">
|
||||
<Skeleton className="skeleton--stat" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="post-main">
|
||||
<div className="post-text">
|
||||
<Skeleton className="skeleton--title skeleton--title-v2" style={{ width: `${58 + (i % 4) * 9}%` }} />
|
||||
{showExcerpt && (
|
||||
<Skeleton className="skeleton--excerpt skeleton--excerpt-v2" style={{ width: `${72 + (i % 3) * 8}%` }} />
|
||||
)}
|
||||
</div>
|
||||
<div className="post-meta">
|
||||
<div className="post-meta-left post-meta-left--skeleton">
|
||||
<Skeleton className="skeleton--board-badge" />
|
||||
<Skeleton className="skeleton--meta-line" style={{ width: `${45 + (i % 3) * 10}%` }} />
|
||||
</div>
|
||||
<div className="post-stats">
|
||||
<Skeleton className="skeleton--stat" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
189
frontend/src/components/PostManageMenu.tsx
Normal file
189
frontend/src/components/PostManageMenu.tsx
Normal file
@@ -0,0 +1,189 @@
|
||||
import {
|
||||
Ban,
|
||||
CircleCheck,
|
||||
CircleHelp,
|
||||
EllipsisVertical,
|
||||
History,
|
||||
Lock,
|
||||
LockOpen,
|
||||
MessageSquareOff,
|
||||
Pencil,
|
||||
Pin,
|
||||
Sparkles,
|
||||
Trash2,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import type { PostItem } from '../api/types';
|
||||
|
||||
export interface PostManageMenuProps {
|
||||
post: PostItem;
|
||||
isAdmin: boolean;
|
||||
isOwnerOrAdmin: boolean;
|
||||
canEdit: boolean;
|
||||
isEdited: boolean;
|
||||
isMobile?: boolean;
|
||||
editRemaining?: string;
|
||||
editBlockReason?: string;
|
||||
deleting?: boolean;
|
||||
onEdit: () => void;
|
||||
onShowRevisions: () => void;
|
||||
onToggleResolved: () => void;
|
||||
onApprove: () => void;
|
||||
onReject: () => void;
|
||||
onFeature: () => void;
|
||||
onPin: () => void;
|
||||
onBoardPin: () => void;
|
||||
onLock: () => void;
|
||||
onCommentsLock: () => void;
|
||||
onDelete: () => void;
|
||||
}
|
||||
|
||||
/** 帖子右上角管理菜单:编辑、审核、置顶、锁定、删除等 */
|
||||
export default function PostManageMenu({
|
||||
post,
|
||||
isAdmin,
|
||||
isOwnerOrAdmin,
|
||||
canEdit,
|
||||
isEdited,
|
||||
isMobile,
|
||||
editRemaining,
|
||||
editBlockReason,
|
||||
deleting,
|
||||
onEdit,
|
||||
onShowRevisions,
|
||||
onToggleResolved,
|
||||
onApprove,
|
||||
onReject,
|
||||
onFeature,
|
||||
onPin,
|
||||
onBoardPin,
|
||||
onLock,
|
||||
onCommentsLock,
|
||||
onDelete,
|
||||
}: PostManageMenuProps) {
|
||||
const showContent =
|
||||
canEdit
|
||||
|| (isOwnerOrAdmin && isEdited)
|
||||
|| (isOwnerOrAdmin && post.post_type === 'question');
|
||||
const hint = editRemaining || (!canEdit && isOwnerOrAdmin ? editBlockReason : '') || '';
|
||||
|
||||
if (!showContent && !isAdmin && !hint) return null;
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="post-manage-menu-trigger"
|
||||
aria-label="管理帖子"
|
||||
>
|
||||
{!isMobile && <span>管理</span>}
|
||||
<EllipsisVertical size={16} aria-hidden />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="post-manage-menu">
|
||||
{hint && (
|
||||
<>
|
||||
<DropdownMenuLabel className="post-manage-menu-hint">
|
||||
{hint}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
|
||||
{showContent && (
|
||||
<>
|
||||
<DropdownMenuLabel>内容</DropdownMenuLabel>
|
||||
{canEdit && (
|
||||
<DropdownMenuItem onSelect={onEdit}>
|
||||
<Pencil size={14} aria-hidden />
|
||||
编辑
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{isOwnerOrAdmin && isEdited && (
|
||||
<DropdownMenuItem onSelect={onShowRevisions}>
|
||||
<History size={14} aria-hidden />
|
||||
编辑历史
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{isOwnerOrAdmin && post.post_type === 'question' && (
|
||||
<DropdownMenuItem onSelect={onToggleResolved}>
|
||||
{post.question_resolved
|
||||
? <CircleHelp size={14} aria-hidden />
|
||||
: <CircleCheck size={14} aria-hidden />}
|
||||
{post.question_resolved ? '标为未解决' : '标为已解决'}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{isAdmin && <DropdownMenuSeparator />}
|
||||
</>
|
||||
)}
|
||||
|
||||
{isAdmin && (
|
||||
<>
|
||||
<DropdownMenuLabel>审核</DropdownMenuLabel>
|
||||
{(post.status === 'pending' || post.status === 'rejected') && (
|
||||
<DropdownMenuItem onSelect={onApprove}>
|
||||
<CircleCheck size={14} aria-hidden />
|
||||
通过审核
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{post.status !== 'rejected' && (
|
||||
<DropdownMenuItem onSelect={onReject}>
|
||||
<Ban size={14} aria-hidden />
|
||||
拒绝并通知
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<DropdownMenuLabel>展示</DropdownMenuLabel>
|
||||
<DropdownMenuItem onSelect={onFeature}>
|
||||
<Sparkles size={14} aria-hidden />
|
||||
{post.featured ? '取消推荐' : '设为推荐'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={onPin}>
|
||||
<Pin size={14} aria-hidden />
|
||||
{post.pinned ? '取消全局置顶' : '全局置顶'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={onBoardPin}>
|
||||
<Pin size={14} aria-hidden />
|
||||
{post.board_pinned ? '取消板块置顶' : '板块置顶'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<DropdownMenuLabel>讨论</DropdownMenuLabel>
|
||||
<DropdownMenuItem onSelect={onLock}>
|
||||
<Lock size={14} aria-hidden />
|
||||
{post.edit_locked ? '解锁编辑' : '锁定编辑'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={onCommentsLock}>
|
||||
{post.comments_locked
|
||||
? <LockOpen size={14} aria-hidden />
|
||||
: <MessageSquareOff size={14} aria-hidden />}
|
||||
{post.comments_locked ? '开放讨论' : '锁定讨论'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<DropdownMenuLabel>危险</DropdownMenuLabel>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
disabled={deleting}
|
||||
onSelect={onDelete}
|
||||
>
|
||||
<Trash2 size={14} aria-hidden />
|
||||
删除
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Loader2, ArrowDown } from 'lucide-react';
|
||||
import { softRefreshCurrentPage } from '../utils/softRefresh';
|
||||
|
||||
/** 触发刷新的下拉距离(px) */
|
||||
const REFRESH_THRESHOLD = 68;
|
||||
@@ -30,6 +31,9 @@ function pickScrollEl(): HTMLElement | null {
|
||||
const page = document.querySelector<HTMLElement>('.page-wrap:not(.page-wrap--feed)');
|
||||
if (page) return page;
|
||||
|
||||
const showcase = document.querySelector<HTMLElement>('.showcase-page');
|
||||
if (showcase) return showcase.closest<HTMLElement>('.main-content') ?? showcase;
|
||||
|
||||
const admin = document.querySelector<HTMLElement>('.admin-main');
|
||||
if (admin) return admin;
|
||||
|
||||
@@ -76,7 +80,7 @@ function isNestedScrollBlocking(target: EventTarget | null, bound: HTMLElement):
|
||||
}
|
||||
|
||||
/**
|
||||
* 手机端下拉刷新:在内部滚动容器顶部下拉后整页重载。
|
||||
* 手机端下拉刷新:在内部滚动容器顶部下拉后强制刷新当前页。
|
||||
* (浏览器原生 PTR 依赖 document 滚动,与本站 app-shell 布局不兼容。)
|
||||
*
|
||||
* 挂在 Router 外,故用 MutationObserver 在路由切换后重绑滚动容器。
|
||||
@@ -167,7 +171,22 @@ export default function PullToRefresh() {
|
||||
setSettling(true);
|
||||
setPull(REFRESH_THRESHOLD * 0.7);
|
||||
window.setTimeout(() => {
|
||||
window.location.reload();
|
||||
// 后台 / 登录页:整页 reload;前台:静默软刷新(无进度条,齐套后一次覆盖)
|
||||
const isAdminOrAuth = !!(
|
||||
document.querySelector('.admin-main')
|
||||
|| document.querySelector('.auth-page')
|
||||
);
|
||||
if (isAdminOrAuth) {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
void softRefreshCurrentPage()
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
setRefreshing(false);
|
||||
setSettling(true);
|
||||
setPull(0);
|
||||
});
|
||||
}, 180);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { ListTree, MessageCircle, Tags, Link2, UserPlus } from 'lucide-react';
|
||||
import { useLocation, useSearchParams, useNavigate } from 'react-router-dom';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { AsideWidget, RecentComment, RecentUser, TagCount, User, ForumStats, FriendLink } from '../api/types';
|
||||
import type { PostHeading } from '../utils/postHeadings';
|
||||
import { useSiteBranding } from '../hooks/useSiteBranding';
|
||||
@@ -13,6 +11,7 @@ import UserLink from './UserLink';
|
||||
import ArticleOutline from './ArticleOutline';
|
||||
import PostAuthorCard from './PostAuthorCard';
|
||||
import AsideCheckInStrip from './AsideCheckInStrip';
|
||||
import ShowcaseAsideWidget from './ShowcaseAsideWidget';
|
||||
|
||||
export type PostDetailAside = {
|
||||
author?: User | null;
|
||||
@@ -30,7 +29,7 @@ interface Props {
|
||||
tagsLoading?: boolean;
|
||||
stats?: ForumStats | null;
|
||||
onPostClick: (id: number, opts?: { floor?: number }) => void;
|
||||
/** 首次拉取中,显示骨架避免空态闪烁 */
|
||||
/** 首次拉取中:不渲染该块内容(由冷启动门闩保证首屏已齐或空白) */
|
||||
loading?: boolean;
|
||||
/** 右侧栏可选组件顺序与开关 */
|
||||
asideWidgets: AsideWidget[];
|
||||
@@ -38,35 +37,6 @@ interface Props {
|
||||
postDetail?: PostDetailAside | null;
|
||||
}
|
||||
|
||||
function CommentSkeleton() {
|
||||
return (
|
||||
<div className="widget-skeleton" aria-busy="true" aria-label="评论加载中">
|
||||
{Array.from({ length: 5 }, (_, i) => (
|
||||
<div key={i} className="widget-item widget-item--comment widget-item--skeleton">
|
||||
<Skeleton className="skeleton--widget-avatar" />
|
||||
<div className="widget-item-comment-main">
|
||||
<Skeleton className="skeleton--widget-title" style={{ width: `${72 + (i % 3) * 8}%` }} />
|
||||
<Skeleton className="skeleton--widget-meta" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UserSkeleton() {
|
||||
return (
|
||||
<div className="widget-recent-users-grid" aria-busy="true" aria-label="用户加载中">
|
||||
{Array.from({ length: 8 }, (_, i) => (
|
||||
<div key={i} className="widget-recent-user-cell widget-recent-user-cell--skeleton">
|
||||
<Skeleton className="skeleton--recent-user-avatar" />
|
||||
<Skeleton className="skeleton--recent-user-name" style={{ width: `${48 + (i % 3) * 10}%` }} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RightPanel({
|
||||
recentComments,
|
||||
recentUsers,
|
||||
@@ -108,12 +78,10 @@ export default function RightPanel({
|
||||
[asideWidgets],
|
||||
);
|
||||
|
||||
const handleApplyClick = () => {
|
||||
nav('/links?apply=1');
|
||||
};
|
||||
|
||||
const renderWidget = (widget: AsideWidget) => {
|
||||
switch (widget.id) {
|
||||
case 'showcase':
|
||||
return <ShowcaseAsideWidget key="showcase" />;
|
||||
case 'friend_links':
|
||||
return (
|
||||
<div key="friend_links" className="widget-card widget-card--friend-links">
|
||||
@@ -124,15 +92,9 @@ export default function RightPanel({
|
||||
友情链接
|
||||
</button>
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="widget-friend-links-apply"
|
||||
onClick={handleApplyClick}
|
||||
>
|
||||
<a href="/links?apply=1" className="widget-friend-links-apply">
|
||||
申请
|
||||
</Button>
|
||||
</a>
|
||||
</div>
|
||||
<div className="widget-card-body widget-card-body--friend-links">
|
||||
{friendLinks.length === 0 ? (
|
||||
@@ -178,9 +140,7 @@ export default function RightPanel({
|
||||
最新评论
|
||||
</div>
|
||||
<div className="widget-card-body">
|
||||
{loading && commentList.length === 0 ? (
|
||||
<CommentSkeleton />
|
||||
) : commentList.length === 0 ? (
|
||||
{loading && commentList.length === 0 ? null : commentList.length === 0 ? (
|
||||
<div className="widget-empty">暂无评论</div>
|
||||
) : commentList.map(item => (
|
||||
<div
|
||||
@@ -238,9 +198,7 @@ export default function RightPanel({
|
||||
最新注册
|
||||
</div>
|
||||
<div className="widget-card-body widget-card-body--users">
|
||||
{loading && userList.length === 0 ? (
|
||||
<UserSkeleton />
|
||||
) : userList.length === 0 ? (
|
||||
{loading && userList.length === 0 ? null : userList.length === 0 ? (
|
||||
<div className="widget-empty">暂无用户</div>
|
||||
) : (
|
||||
<div className="widget-recent-users-grid">
|
||||
@@ -274,11 +232,13 @@ export default function RightPanel({
|
||||
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
|
||||
{isPostDetail && (
|
||||
<>
|
||||
<PostAuthorCard
|
||||
author={postDetail.author}
|
||||
publishedAt={postDetail.publishedAt}
|
||||
viewCount={postDetail.viewCount}
|
||||
/>
|
||||
{postDetail.author?.id ? (
|
||||
<PostAuthorCard
|
||||
author={postDetail.author}
|
||||
publishedAt={postDetail.publishedAt}
|
||||
viewCount={postDetail.viewCount}
|
||||
/>
|
||||
) : null}
|
||||
<div className="widget-card widget-card--outline">
|
||||
<div className="widget-card-head">
|
||||
<ListTree className="widget-card-icon widget-card-icon--outline" aria-hidden />
|
||||
|
||||
128
frontend/src/components/ShowcaseAsideWidget.tsx
Normal file
128
frontend/src/components/ShowcaseAsideWidget.tsx
Normal file
@@ -0,0 +1,128 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Globe2 } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { api } from '../api/client';
|
||||
import type { CommunityShowcaseItem } from '../api/types';
|
||||
import { getSessionSnapshot, setSessionSnapshot } from '../utils/sessionPageCache';
|
||||
import { PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
|
||||
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
|
||||
|
||||
const SHOWCASE_KEY = 'showcase';
|
||||
|
||||
/** 右侧栏:开源展柜精简列表 */
|
||||
export default function ShowcaseAsideWidget() {
|
||||
const nav = useNavigate();
|
||||
const cached = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
|
||||
const [items, setItems] = useState<CommunityShowcaseItem[]>(() => cached ?? []);
|
||||
const [loading, setLoading] = useState(() => cached === undefined);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
|
||||
if (hit !== undefined) {
|
||||
setItems(hit);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
api.communityShowcase()
|
||||
.then((r) => {
|
||||
if (cancelled) return;
|
||||
const next = Array.isArray(r.items) ? r.items : [];
|
||||
setSessionSnapshot(SHOWCASE_KEY, next);
|
||||
setItems(next);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) {
|
||||
setSessionSnapshot(SHOWCASE_KEY, []);
|
||||
setItems([]);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchShowcase = (opts: { showLoading: boolean }) => {
|
||||
if (opts.showLoading) setLoading(true);
|
||||
api.communityShowcase()
|
||||
.then((r) => {
|
||||
const next = Array.isArray(r.items) ? r.items : [];
|
||||
setSessionSnapshot(SHOWCASE_KEY, next);
|
||||
setItems(next);
|
||||
})
|
||||
.catch(() => {
|
||||
if (opts.showLoading) {
|
||||
setSessionSnapshot(SHOWCASE_KEY, []);
|
||||
setItems([]);
|
||||
}
|
||||
// 软刷新失败:保持旧 UI
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
const applyHitOrReload = (showLoading: boolean) => {
|
||||
const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
|
||||
if (hit !== undefined) {
|
||||
setItems(hit);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
fetchShowcase({ showLoading });
|
||||
};
|
||||
const onForce = () => applyHitOrReload(true);
|
||||
const onCommit = () => applyHitOrReload(false);
|
||||
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||
return () => {
|
||||
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="widget-card widget-card--showcase">
|
||||
<div className="widget-card-head widget-card-head--split">
|
||||
<span className="widget-card-head-main">
|
||||
<Globe2 className="widget-card-icon widget-card-icon--showcase" aria-hidden />
|
||||
<button type="button" className="widget-friend-links-title" onClick={() => nav('/showcase')}>
|
||||
开源展柜
|
||||
</button>
|
||||
</span>
|
||||
<button type="button" className="widget-friend-links-more" onClick={() => nav('/showcase')}>
|
||||
全部
|
||||
</button>
|
||||
</div>
|
||||
<div className="widget-card-body widget-card-body--friend-links">
|
||||
{loading ? (
|
||||
<div className="widget-empty">加载中…</div>
|
||||
) : items.length === 0 ? (
|
||||
<div className="widget-empty">
|
||||
暂无精选实例
|
||||
<button type="button" className="widget-friend-links-more" onClick={() => nav('/showcase')}>
|
||||
查看展柜
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<ul className="widget-friend-links-list">
|
||||
{items.slice(0, 8).map((item) => (
|
||||
<li key={item.site_url}>
|
||||
<a href={item.site_url} target="_blank" rel="noopener noreferrer" title={item.site_name || item.site_url}>
|
||||
{item.site_name || '未命名站点'}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{items.length > 8 && (
|
||||
<button type="button" className="widget-friend-links-more" onClick={() => nav('/showcase')}>
|
||||
查看全部 {items.length} 个
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
import {
|
||||
Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft, FileText, Link2,
|
||||
Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft, FileText, Link2, Globe2,
|
||||
} from 'lucide-react';
|
||||
import { useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom';
|
||||
import type { Board } from '../api/types';
|
||||
import type { PostHeading } from '../utils/postHeadings';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { buildHomeUrl, parseFeedSort } from './FeedSortBar';
|
||||
import { navigateFeed } from '../utils/feedCache';
|
||||
import { transitionTo } from '../utils/spaTransition';
|
||||
import BoardIconDisplay from './BoardIconDisplay';
|
||||
import { getBoardThemeIndex } from '../utils/boardTheme';
|
||||
import ArticleOutline from './ArticleOutline';
|
||||
@@ -30,6 +30,7 @@ function resolveMenuKey(pathname: string, activeBoard: number, keyword = ''): st
|
||||
if (pathname.startsWith('/favorites')) return 'favorites';
|
||||
if (pathname.startsWith('/projects')) return 'projects';
|
||||
if (pathname.startsWith('/links')) return 'links';
|
||||
if (pathname.startsWith('/showcase')) return 'showcase';
|
||||
if (pathname.startsWith('/page/')) return 'pages';
|
||||
if (pathname.startsWith('/admin')) return 'admin';
|
||||
return activeBoard === 0 ? 'all' : String(activeBoard);
|
||||
@@ -61,13 +62,14 @@ export default function Sidebar({
|
||||
const nav = useNavigate();
|
||||
const loc = useLocation();
|
||||
const [params] = useSearchParams();
|
||||
const sort = parseFeedSort(params.get('sort'));
|
||||
const { user } = useAuth();
|
||||
const isAdmin = user?.role === 'admin';
|
||||
const { navPages } = useSitePages();
|
||||
const { limits } = useForumLimits();
|
||||
const sort = parseFeedSort(params.get('sort'), limits.feed_sort_tabs);
|
||||
const showFriendLinksNav = limits.nav_show_friend_links !== false;
|
||||
const showSiteSection = navPages.length > 0 || showFriendLinksNav;
|
||||
const showShowcaseNav = !!limits.nav_show_showcase;
|
||||
const showSiteSection = navPages.length > 0 || showFriendLinksNav || showShowcaseNav;
|
||||
|
||||
const keyword = params.get('keyword') || '';
|
||||
const menuKey = resolveMenuKey(loc.pathname, activeBoard, keyword);
|
||||
@@ -135,22 +137,12 @@ export default function Sidebar({
|
||||
<div className="sidebar-section">浏览</div>
|
||||
<nav className="sidebar-nav">
|
||||
{feedNavLink('all', buildHomeUrl(0, sort, permalinkOpts), '全部帖子', <Home aria-hidden />, 0)}
|
||||
{user && navItem('favorites', '我的收藏', <Star aria-hidden />, () => nav('/favorites'))}
|
||||
{navItem('projects', '开源码桶', <FolderGit2 aria-hidden />, () => nav('/projects'))}
|
||||
{user && navItem('favorites', '我的收藏', <Star aria-hidden />, () => void transitionTo(nav, '/favorites'))}
|
||||
{navItem('projects', '开源码桶', <FolderGit2 aria-hidden />, () => void transitionTo(nav, '/projects'))}
|
||||
</nav>
|
||||
|
||||
{(boardsLoading && boards.length === 0) ? (
|
||||
<>
|
||||
<div className="sidebar-section sidebar-section--boards">板块</div>
|
||||
<nav className="sidebar-nav sidebar-nav--skeleton" aria-busy="true" aria-label="板块加载中">
|
||||
{Array.from({ length: 4 }, (_, i) => (
|
||||
<div key={i} className="sidebar-nav-item sidebar-nav-item--skeleton">
|
||||
<Skeleton className="skeleton--sidebar-icon" />
|
||||
<Skeleton className="skeleton--sidebar-label" style={{ width: `${58 + (i % 3) * 12}%` }} />
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
</>
|
||||
<div className="sidebar-section sidebar-section--boards">板块</div>
|
||||
) : boards.length > 0 ? (
|
||||
<>
|
||||
<div className="sidebar-section sidebar-section--boards">板块</div>
|
||||
@@ -196,9 +188,10 @@ export default function Sidebar({
|
||||
<>
|
||||
<div className="sidebar-section sidebar-section--spaced">站点</div>
|
||||
<nav className="sidebar-nav">
|
||||
{showFriendLinksNav && navItem('links', '友情链接', <Link2 aria-hidden />, () => nav('/links'))}
|
||||
{showFriendLinksNav && navItem('links', '友情链接', <Link2 aria-hidden />, () => void transitionTo(nav, '/links'))}
|
||||
{showShowcaseNav && navItem('showcase', '开源展柜', <Globe2 aria-hidden />, () => void transitionTo(nav, '/showcase'))}
|
||||
{navPages.map(p => (
|
||||
navItem(`page-${p.slug}`, p.title, <FileText aria-hidden />, () => nav(pagePath(p.slug, limits)))
|
||||
navItem(`page-${p.slug}`, p.title, <FileText aria-hidden />, () => void transitionTo(nav, pagePath(p.slug, limits)))
|
||||
))}
|
||||
</nav>
|
||||
</>
|
||||
|
||||
@@ -9,7 +9,7 @@ function FooterSep() {
|
||||
return <span className="site-footer__sep" aria-hidden>·</span>;
|
||||
}
|
||||
|
||||
/** 站点页脚:版权、Sitemap、备案号 */
|
||||
/** 站点页脚:版权、友链/展柜入口、单页、备案号(结构与 Go writeSSRFooter 对齐) */
|
||||
export default function SiteFooter() {
|
||||
const { branding } = useSiteBranding();
|
||||
const { footerPages } = useSitePages();
|
||||
@@ -17,6 +17,44 @@ export default function SiteFooter() {
|
||||
const year = new Date().getFullYear();
|
||||
const icp = branding.icp_beian?.trim() || '';
|
||||
const icpURL = branding.icp_beian_url?.trim() || 'https://beian.miit.gov.cn/';
|
||||
const showFriendLinks = limits.footer_show_friend_links !== false;
|
||||
const showShowcase = !!limits.footer_show_showcase;
|
||||
|
||||
const navItems: React.ReactNode[] = [];
|
||||
if (showFriendLinks) {
|
||||
navItems.push(
|
||||
<span key="links" className="site-footer__friend">
|
||||
<Link to="/links">友情链接</Link>
|
||||
</span>,
|
||||
);
|
||||
}
|
||||
if (showShowcase) {
|
||||
navItems.push(
|
||||
<span key="showcase" className="site-footer__friend">
|
||||
<Link to="/showcase">开源展柜</Link>
|
||||
</span>,
|
||||
);
|
||||
}
|
||||
for (const p of footerPages) {
|
||||
navItems.push(
|
||||
<span key={p.slug} className="site-footer__friend">
|
||||
<Link to={pagePath(p.slug, limits)}>{p.title}</Link>
|
||||
</span>,
|
||||
);
|
||||
}
|
||||
if (icp) {
|
||||
navItems.push(
|
||||
<a
|
||||
key="icp"
|
||||
href={icpURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="site-footer__icp"
|
||||
>
|
||||
{icp}
|
||||
</a>,
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<footer className="site-footer">
|
||||
@@ -34,29 +72,8 @@ export default function SiteFooter() {
|
||||
</div>
|
||||
|
||||
<nav className="site-footer__nav" aria-label="站点链接">
|
||||
{limits.footer_show_friend_links !== false && (
|
||||
<span className="site-footer__friend">
|
||||
<Link to="/links">友情链接</Link>
|
||||
</span>
|
||||
)}
|
||||
{footerPages.map((p, i) => (
|
||||
<span key={p.slug} className="site-footer__friend">
|
||||
{(limits.footer_show_friend_links !== false || i > 0) && <FooterSep />}
|
||||
<Link to={pagePath(p.slug, limits)}>{p.title}</Link>
|
||||
</span>
|
||||
))}
|
||||
{icp && (
|
||||
<>
|
||||
{(limits.footer_show_friend_links !== false || footerPages.length > 0) && <FooterSep />}
|
||||
<a
|
||||
href={icpURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="site-footer__icp"
|
||||
>
|
||||
{icp}
|
||||
</a>
|
||||
</>
|
||||
{navItems.flatMap((node, i) =>
|
||||
i === 0 ? [node] : [<FooterSep key={`sep-${i}`} />, node],
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
227
frontend/src/components/StaticFeedList.tsx
Normal file
227
frontend/src/components/StaticFeedList.tsx
Normal file
@@ -0,0 +1,227 @@
|
||||
import type { PostItem } from '../api/types';
|
||||
import type { FeedSort } from './FeedSortBar';
|
||||
import { getBoardThemeIndex } from '../utils/boardTheme';
|
||||
import { postPath } from '../utils/permalink';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
|
||||
import { formatTime } from '../utils/content';
|
||||
import { MessageCircle } from 'lucide-react';
|
||||
|
||||
/** 与 Go formatSSRRelativeTime / 前端 formatTime 对齐的列表时间 */
|
||||
|
||||
function stripHtmlPlain(html: string): string {
|
||||
if (!html) return '';
|
||||
const t = html
|
||||
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/ /gi, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
return t;
|
||||
}
|
||||
|
||||
function truncateRunes(s: string, max: number): string {
|
||||
const chars = Array.from(s);
|
||||
if (chars.length <= max) return s;
|
||||
return chars.slice(0, max).join('');
|
||||
}
|
||||
|
||||
function firstImageSrc(html: string): string {
|
||||
const m = html.match(/<img[^>]+src=["']([^"']+)["']/i);
|
||||
const src = m?.[1]?.trim() || '';
|
||||
if (!src || src.startsWith('data:')) return '';
|
||||
return src;
|
||||
}
|
||||
|
||||
function displayName(post: PostItem): string {
|
||||
const n = post.user?.nickname?.trim() || post.user?.username?.trim();
|
||||
return n || '用户';
|
||||
}
|
||||
|
||||
type Props = {
|
||||
posts: PostItem[];
|
||||
sort: FeedSort;
|
||||
boardId: number;
|
||||
};
|
||||
|
||||
/** 与 Go writeSSRPostRow 同构的静态列表(hydrate 首帧专用) */
|
||||
export default function StaticFeedList({ posts, sort, boardId }: Props) {
|
||||
const { limits } = useForumLimits();
|
||||
const style = limits.feed_list_style ?? 'title';
|
||||
const titleOnly = style === 'title';
|
||||
const needExcerpt = style === 'excerpt' || style === 'thumbnail';
|
||||
const needThumb = style === 'thumbnail';
|
||||
|
||||
return (
|
||||
<div className="post-list-scroll post-list-scroll--ssr">
|
||||
<div className="content-surface content-surface--ssr">
|
||||
{posts.length === 0 ? (
|
||||
<div className="feed-empty">暂无帖子</div>
|
||||
) : (
|
||||
posts.map((post) => {
|
||||
const href = postPath(post.id, limits);
|
||||
const author = displayName(post);
|
||||
const initial = Array.from(author)[0] || '?';
|
||||
let excerpt = '';
|
||||
let thumb = '';
|
||||
if (needExcerpt || needThumb) {
|
||||
excerpt = truncateRunes(stripHtmlPlain(post.content || ''), 120);
|
||||
}
|
||||
if (needThumb) thumb = firstImageSrc(post.content || '');
|
||||
|
||||
const rowClass = [
|
||||
'post-row',
|
||||
'post-row--v2',
|
||||
titleOnly ? 'post-row--title-only' : '',
|
||||
thumb ? 'post-row--has-thumb' : '',
|
||||
].filter(Boolean).join(' ');
|
||||
|
||||
let timeLabel = formatTime(post.created_at);
|
||||
if (sort === 'reply' && !post.last_reply_at) {
|
||||
timeLabel = '暂无回复';
|
||||
}
|
||||
const lastReplyName = post.last_reply_user?.nickname?.trim()
|
||||
|| post.last_reply_user?.username?.trim()
|
||||
|| post.last_reply_guest_nick?.trim()
|
||||
|| '';
|
||||
const showLastReply = !!post.last_reply_at && (!!post.last_reply_user || !!lastReplyName);
|
||||
const commentCount = post.comment_count ?? 0;
|
||||
|
||||
const hasTypeBadge = post.post_type === 'question'
|
||||
|| post.post_type === 'poll'
|
||||
|| post.post_type === 'lottery'
|
||||
|| (post.post_type === 'bounty' && (
|
||||
(post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0)
|
||||
|| post.bounty_status === 'awarded'
|
||||
));
|
||||
|
||||
const titleRow = (
|
||||
<div className="post-title-row">
|
||||
{post.pinned ? (
|
||||
<span className="post-pin-badge" title="全局置顶">全局置顶</span>
|
||||
) : null}
|
||||
{post.board_pinned ? (
|
||||
<span className="post-pin-badge post-pin-badge--board" title="板块置顶">板块置顶</span>
|
||||
) : null}
|
||||
{post.featured ? <span className="post-feature-badge" title="推荐">推荐</span> : null}
|
||||
{post.status === 'pending' ? (
|
||||
<span className="post-status-badge post-status-badge--pending" title="审核中">审核中</span>
|
||||
) : null}
|
||||
{post.status === 'rejected' ? (
|
||||
<span className="post-status-badge post-status-badge--rejected" title="未通过">未通过</span>
|
||||
) : null}
|
||||
<span className="post-title">{post.title}</span>
|
||||
{hasTypeBadge ? (
|
||||
<span className="post-title-type-badges">
|
||||
{post.post_type === 'question' ? (
|
||||
<span
|
||||
className={`post-qa-badge${post.question_resolved ? ' post-qa-badge--resolved' : ' post-qa-badge--open'}`}
|
||||
title={post.question_resolved ? '已解决' : '未解决'}
|
||||
>
|
||||
{post.question_resolved ? '已解决' : '未解决'}
|
||||
</span>
|
||||
) : null}
|
||||
{post.post_type === 'poll' ? (
|
||||
<span className="post-type-badge post-type-badge--poll" title="投票">投票</span>
|
||||
) : null}
|
||||
{post.post_type === 'bounty' && post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0 ? (
|
||||
<span className="post-bounty-badge post-bounty-badge--open" title="悬赏">
|
||||
悬赏 {post.bounty_points}
|
||||
</span>
|
||||
) : null}
|
||||
{post.post_type === 'bounty' && post.bounty_status === 'awarded' ? (
|
||||
<span className="post-bounty-badge post-bounty-badge--awarded" title="已采纳">已采纳</span>
|
||||
) : null}
|
||||
{post.post_type === 'lottery' ? (
|
||||
<span className="post-type-badge post-type-badge--lottery" title="抽奖">
|
||||
{post.lottery_status === 'drawn' ? '已开奖' : '抽奖'}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
const metaLeft = (
|
||||
<div className="post-meta-left">
|
||||
{boardId === 0 && post.board?.id ? (
|
||||
<span className="post-list-board-btn">
|
||||
<span
|
||||
className={`post-list-board-badge board-badge board-badge--${getBoardThemeIndex(post.board)}`}
|
||||
>
|
||||
{post.board.name}
|
||||
</span>
|
||||
</span>
|
||||
) : null}
|
||||
<span className="post-meta-author">{author}</span>
|
||||
<span className="post-meta-sep post-meta-sep--before-time" aria-hidden>·</span>
|
||||
<span className="post-meta-time post-meta-time--created">{timeLabel}</span>
|
||||
{showLastReply ? (
|
||||
<span className="post-meta-last-reply">
|
||||
<span className="post-meta-last-reply-arrow" aria-hidden>←</span>
|
||||
{/* 外层是 <a class="post-row">,禁止嵌套 a */}
|
||||
<span className="post-meta-last-reply-user">{lastReplyName}</span>
|
||||
<span className="post-meta-last-reply-time">{formatTime(post.last_reply_at!)}</span>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
const stats = (
|
||||
<div className="post-stats">
|
||||
<span
|
||||
className={`post-stat${commentCount === 0 ? ' post-stat--zero' : ''}`}
|
||||
title="评论"
|
||||
>
|
||||
<MessageCircle aria-hidden />
|
||||
{commentCount}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<a key={post.id} className={rowClass} href={href}>
|
||||
{post.user?.avatar ? (
|
||||
<span className="post-avatar user-link--avatar-only">
|
||||
<img src={post.user.avatar} alt="" loading="lazy" decoding="async" />
|
||||
</span>
|
||||
) : (
|
||||
<span className="post-avatar user-link--avatar-only">{initial}</span>
|
||||
)}
|
||||
{thumb ? (
|
||||
<div className="post-main post-main--with-thumb">
|
||||
<div className="post-content">
|
||||
{titleRow}
|
||||
{excerpt ? <p className="post-excerpt">{excerpt}</p> : null}
|
||||
<div className="post-meta post-meta--inline">
|
||||
{metaLeft}
|
||||
{stats}
|
||||
</div>
|
||||
</div>
|
||||
<div className="post-aside">
|
||||
<div className="post-thumb" aria-hidden>
|
||||
<img src={thumb} alt="" loading="lazy" decoding="async" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="post-main">
|
||||
<div className="post-text">
|
||||
{titleRow}
|
||||
{excerpt ? <p className="post-excerpt">{excerpt}</p> : null}
|
||||
</div>
|
||||
<div className="post-meta">
|
||||
{metaLeft}
|
||||
{stats}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</a>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import type { TagCount } from '../api/types';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface Props {
|
||||
@@ -63,20 +62,7 @@ export default function TagCloud({ tags, loading = false, activeTag = '' }: Prop
|
||||
}, [tags]);
|
||||
|
||||
if (loading && tags.length === 0) {
|
||||
return (
|
||||
<div className="tag-cloud tag-cloud--skeleton" aria-busy="true" aria-label="标签加载中">
|
||||
{Array.from({ length: 10 }, (_, i) => (
|
||||
<Skeleton
|
||||
key={i}
|
||||
className="skeleton--tag-cloud"
|
||||
style={{
|
||||
width: `${42 + (i % 5) * 16}px`,
|
||||
height: `${20 + (i % 3) * 4}px`,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
|
||||
75
frontend/src/components/TopProgressBar.tsx
Normal file
75
frontend/src/components/TopProgressBar.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { subscribeSpaTransition } from '../utils/spaTransition';
|
||||
|
||||
/**
|
||||
* 视口顶部 2px 细进度条(类 Next.js / YouTube)。
|
||||
* 由 spaTransition start/done 驱动,假进度爬升至约 80%,结束冲到 100%。
|
||||
*/
|
||||
export default function TopProgressBar() {
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [width, setWidth] = useState(0);
|
||||
const [fading, setFading] = useState(false);
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const fadeRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const activeRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const clearTick = () => {
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
};
|
||||
const clearFade = () => {
|
||||
if (fadeRef.current) {
|
||||
clearTimeout(fadeRef.current);
|
||||
fadeRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
return subscribeSpaTransition((active) => {
|
||||
if (active) {
|
||||
activeRef.current = true;
|
||||
clearFade();
|
||||
setFading(false);
|
||||
setVisible(true);
|
||||
setWidth(12);
|
||||
clearTick();
|
||||
timerRef.current = setInterval(() => {
|
||||
setWidth((w) => {
|
||||
if (w >= 80) return w;
|
||||
// 越接近 80 越慢
|
||||
const step = Math.max(0.4, (80 - w) * 0.045);
|
||||
return Math.min(80, w + step);
|
||||
});
|
||||
}, 120);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!activeRef.current) return;
|
||||
activeRef.current = false;
|
||||
clearTick();
|
||||
setWidth(100);
|
||||
setFading(true);
|
||||
clearFade();
|
||||
fadeRef.current = setTimeout(() => {
|
||||
setVisible(false);
|
||||
setFading(false);
|
||||
setWidth(0);
|
||||
}, 220);
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (!visible && width <= 0) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={[
|
||||
'top-progress',
|
||||
fading ? 'top-progress--done' : '',
|
||||
].filter(Boolean).join(' ')}
|
||||
style={{ width: `${width}%` }}
|
||||
aria-hidden
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { Inbox, SearchX } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import PostListItem from './PostListItem';
|
||||
import PostListSkeleton, { feedListRowEstimate } from './PostListSkeleton';
|
||||
import { feedListRowEstimate } from './PostListSkeleton';
|
||||
import FeedPagination from './FeedPagination';
|
||||
import { InFlowSiteFooter } from './SiteFooter';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
@@ -14,6 +14,7 @@ import { loginPath } from '../utils/authRedirect';
|
||||
import { dispatchOpenPostSearch } from '../hooks/usePostSearch';
|
||||
import type { PostItem } from '../api/types';
|
||||
import type { FeedSort } from './FeedSortBar';
|
||||
import { getDefaultFeedSortFromCache } from './FeedSortBar';
|
||||
|
||||
interface Props {
|
||||
posts: PostItem[];
|
||||
@@ -56,7 +57,7 @@ function getMobileFeedScrollEl(): HTMLElement | null {
|
||||
|
||||
export default function VirtualPostList({
|
||||
posts,
|
||||
sort = 'latest',
|
||||
sort = getDefaultFeedSortFromCache(),
|
||||
loading,
|
||||
hasMore,
|
||||
showPagination,
|
||||
@@ -161,6 +162,12 @@ export default function VirtualPostList({
|
||||
onScrollTopChangeRef.current?.(0);
|
||||
}, [resetScrollKey, virtualizer, getScrollElement]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
// 收到新的恢复目标时允许再次 restore;null 表示已消费,勿动标记
|
||||
if (restoreScrollTop == null) return;
|
||||
restoredRef.current = false;
|
||||
}, [restoreScrollTop]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (restoreScrollTop == null || restoredRef.current || posts.length === 0) return;
|
||||
const el = getScrollElement();
|
||||
@@ -173,10 +180,6 @@ export default function VirtualPostList({
|
||||
onScrollRestoredRef.current?.();
|
||||
}, [restoreScrollTop, posts.length, virtualizer, getScrollElement]);
|
||||
|
||||
useEffect(() => {
|
||||
restoredRef.current = false;
|
||||
}, [restoreScrollTop]);
|
||||
|
||||
useEffect(() => {
|
||||
const el = getScrollElement();
|
||||
if (!el) return;
|
||||
@@ -240,9 +243,7 @@ export default function VirtualPostList({
|
||||
|
||||
return (
|
||||
<div className="post-list-scroll" ref={parentRef}>
|
||||
{isInitialLoad ? (
|
||||
<PostListSkeleton listStyle={feedStyle} />
|
||||
) : isEmpty ? (
|
||||
{isInitialLoad ? null : isEmpty ? (
|
||||
<div className="empty-feed" role="status">
|
||||
{isSearchEmpty
|
||||
? <SearchX className="empty-feed-icon" aria-hidden size={36} strokeWidth={1.5} />
|
||||
|
||||
@@ -18,6 +18,10 @@ const WIDGET_META: Record<AsideWidgetId, { label: string; hint: string }> = {
|
||||
label: '友情链接',
|
||||
hint: '关闭后不在右侧栏展示,友链仍可在「友情链接」页面查看与申请',
|
||||
},
|
||||
showcase: {
|
||||
label: '开源展柜',
|
||||
hint: '展示精选公网部署;关闭后仍可直接访问 /showcase',
|
||||
},
|
||||
};
|
||||
|
||||
type Props = {
|
||||
|
||||
90
frontend/src/components/admin/CommunitySupportStrip.tsx
Normal file
90
frontend/src/components/admin/CommunitySupportStrip.tsx
Normal file
@@ -0,0 +1,90 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Heart } from 'lucide-react';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '../../api/client';
|
||||
import type { CommunityConfig } from '../../api/types';
|
||||
|
||||
const EMPTY_COMMUNITY: CommunityConfig = {
|
||||
report_enabled: false,
|
||||
hub_enabled: false,
|
||||
hub_url: 'https://bbs.iioio.com',
|
||||
site_url: '',
|
||||
instance_id: '',
|
||||
};
|
||||
|
||||
/** 仪表盘页脚:自愿社区上报开关(默认关,即时保存;枢纽站不显示) */
|
||||
export default function CommunitySupportStrip() {
|
||||
const [community, setCommunity] = useState<CommunityConfig>(EMPTY_COMMUNITY);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
api.adminSettings()
|
||||
.then((s) => {
|
||||
if (!cancelled) {
|
||||
setCommunity({ ...EMPTY_COMMUNITY, ...(s.community ?? {}) });
|
||||
setReady(true);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setReady(true);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
const handleToggle = async () => {
|
||||
if (saving || !ready) return;
|
||||
const next = !community.report_enabled;
|
||||
const prev = community;
|
||||
setCommunity((c) => ({ ...c, report_enabled: next }));
|
||||
setSaving(true);
|
||||
try {
|
||||
const r = await api.adminUpdateCommunitySettings({
|
||||
...EMPTY_COMMUNITY,
|
||||
report_enabled: next,
|
||||
});
|
||||
setCommunity({ ...EMPTY_COMMUNITY, ...r.community });
|
||||
if (r.heartbeat_error) {
|
||||
notify.warning(`${r.message}:${r.heartbeat_error}`);
|
||||
} else {
|
||||
notify.success(next ? '已开启社区上报' : '已关闭社区上报');
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
setCommunity(prev);
|
||||
notify.error(e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 官网 / 枢纽站本身就是收报方,无需「支持开源」上报条
|
||||
if (!ready || community.hub_enabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="admin-community-support-strip" role="group" aria-label="支持姜十三开源">
|
||||
<div className="admin-community-support-strip-main">
|
||||
<Heart size={16} className="admin-community-support-strip-icon" aria-hidden />
|
||||
<div className="admin-community-support-strip-copy">
|
||||
<strong>支持姜十三开源</strong>
|
||||
<span>
|
||||
匿名向 bbs.iioio.com 上报站点地址、版本与规模;开启后有机会获官方演示站展示与推荐,可随时关闭
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={community.report_enabled}
|
||||
aria-busy={saving}
|
||||
disabled={saving || !ready}
|
||||
className={`admin-settings-switch${community.report_enabled ? ' is-on' : ''}`}
|
||||
onClick={() => void handleToggle()}
|
||||
>
|
||||
<span className="admin-settings-switch-ui" aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
89
frontend/src/components/admin/FeedSortTabList.tsx
Normal file
89
frontend/src/components/admin/FeedSortTabList.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
import { Pencil } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import AdminSortableList, { SortableDragHandle } from './AdminSortableList';
|
||||
import type { FeedSortId, FeedSortTab } from '../../api/types';
|
||||
import { normalizeFeedSortTabs } from '../../utils/feedSortTabs';
|
||||
|
||||
const TAB_META: Record<FeedSortId, { hint: string; placeholder: string }> = {
|
||||
reply: { hint: '按最近活动(发帖或评论)', placeholder: '最新' },
|
||||
latest: { hint: '按发帖时间', placeholder: '新帖子' },
|
||||
hot: { hint: '仅展示推荐帖', placeholder: '推荐帖' },
|
||||
};
|
||||
|
||||
type Props = {
|
||||
tabs: FeedSortTab[];
|
||||
onChange: (next: FeedSortTab[]) => void;
|
||||
};
|
||||
|
||||
export default function FeedSortTabList({ tabs, onChange }: Props) {
|
||||
const items = normalizeFeedSortTabs(tabs);
|
||||
|
||||
const handleToggle = (id: FeedSortId, enabled: boolean) => {
|
||||
const next = items.map(t => (t.id === id ? { ...t, enabled } : t));
|
||||
// 不允许全部关闭:关掉最后一项时忽略
|
||||
if (!enabled && !next.some(t => t.enabled)) return;
|
||||
onChange(normalizeFeedSortTabs(next));
|
||||
};
|
||||
|
||||
const handleLabel = (id: FeedSortId, label: string) => {
|
||||
onChange(normalizeFeedSortTabs(items.map(t => (t.id === id ? { ...t, label } : t))));
|
||||
};
|
||||
|
||||
return (
|
||||
<AdminSortableList
|
||||
items={items}
|
||||
getId={tab => tab.id}
|
||||
onReorder={next => onChange(normalizeFeedSortTabs(next))}
|
||||
showMoveButtons={false}
|
||||
className="admin-sortable-list admin-sortable-list--boxed"
|
||||
ariaLabel="首页排序标签"
|
||||
renderItem={(tab, _index, controls) => {
|
||||
const meta = TAB_META[tab.id];
|
||||
return (
|
||||
<div
|
||||
ref={controls.setNodeRef}
|
||||
style={controls.style}
|
||||
className={`admin-sortable-row admin-sortable-row--widget${controls.isDragging ? ' is-dragging' : ''}`}
|
||||
>
|
||||
<SortableDragHandle
|
||||
label={`拖拽调整「${tab.label || meta.placeholder}」顺序`}
|
||||
{...controls.dragHandleProps}
|
||||
/>
|
||||
<div className="admin-sortable-row__main">
|
||||
<label className="admin-sortable-row__field" htmlFor={`feed-sort-label-${tab.id}`}>
|
||||
<span className="admin-sortable-row__field-name">显示名称</span>
|
||||
<span className="admin-sortable-row__name-wrap">
|
||||
<Input
|
||||
id={`feed-sort-label-${tab.id}`}
|
||||
type="text"
|
||||
className="admin-sortable-row__name-input"
|
||||
value={tab.label}
|
||||
maxLength={16}
|
||||
placeholder={meta.placeholder}
|
||||
onChange={e => handleLabel(tab.id, e.target.value)}
|
||||
aria-describedby={`feed-sort-hint-${tab.id}`}
|
||||
/>
|
||||
<Pencil className="admin-sortable-row__name-icon" size={14} aria-hidden />
|
||||
</span>
|
||||
</label>
|
||||
<span className="admin-sortable-row__hint" id={`feed-sort-hint-${tab.id}`}>
|
||||
{meta.hint}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
id={`feed-sort-${tab.id}`}
|
||||
role="switch"
|
||||
aria-checked={tab.enabled}
|
||||
aria-label={`启用「${tab.label || meta.placeholder}」`}
|
||||
className={`admin-settings-switch${tab.enabled ? ' is-on' : ''}`}
|
||||
onClick={() => handleToggle(tab.id, !tab.enabled)}
|
||||
>
|
||||
<span className="admin-settings-switch-ui" aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
91
frontend/src/components/admin/MonitorChinaMap.tsx
Normal file
91
frontend/src/components/admin/MonitorChinaMap.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import china from '@svg-maps/china';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { buildChinaRegionCountMap, heatFill } from './monitorMapUtils';
|
||||
|
||||
type Loc = { id: string; name: string; path: string };
|
||||
|
||||
type RegionStat = {
|
||||
country: string;
|
||||
region?: string;
|
||||
region_iso?: string;
|
||||
count: number;
|
||||
};
|
||||
|
||||
type Props = {
|
||||
regions: RegionStat[];
|
||||
className?: string;
|
||||
/** 近 30 日是否已有国家级浏览量 */
|
||||
hasCountryHits?: boolean;
|
||||
/** 近 30 日是否已有省级浏览量 */
|
||||
hasRegionHits?: boolean;
|
||||
};
|
||||
|
||||
/** 中国省区地图:按 BIN 解析出的省/区填色 */
|
||||
export default function MonitorChinaMap({
|
||||
regions,
|
||||
className,
|
||||
hasCountryHits = false,
|
||||
hasRegionHits = false,
|
||||
}: Props) {
|
||||
const [hover, setHover] = useState<{ name: string; count: number } | null>(null);
|
||||
const counts = useMemo(() => buildChinaRegionCountMap(regions), [regions]);
|
||||
const max = useMemo(() => Math.max(0, ...Object.values(counts)), [counts]);
|
||||
const hasData = max > 0;
|
||||
const locations = (china as { locations: Loc[]; viewBox: string }).locations;
|
||||
const viewBox = (china as { viewBox: string }).viewBox;
|
||||
|
||||
let emptyTitle = '暂无省级访问数据';
|
||||
let emptyHint = '放置 IP2LOCATION-LITE-DB3.BIN 后按省/区填色';
|
||||
if (hasCountryHits && !hasRegionHits) {
|
||||
emptyTitle = '有国家浏览量,尚无省级数据';
|
||||
emptyHint = '需前台路由产生带省字段的浏览量;仅请求日志不会点亮中国地图。请确认已放置 IP2Location DB3 BIN。';
|
||||
} else if (!hasCountryHits) {
|
||||
emptyTitle = '暂无浏览量地理数据';
|
||||
emptyHint = '需前台路由产生浏览量后才会按省填色;仅请求日志不会点亮此处。';
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('admin-monitor-svg-wrap', className)}>
|
||||
<svg
|
||||
className="admin-monitor-svg-map"
|
||||
viewBox={viewBox}
|
||||
role="img"
|
||||
aria-label="中国访客地图"
|
||||
>
|
||||
{locations.map((loc) => {
|
||||
const count = counts[loc.id] || 0;
|
||||
return (
|
||||
<path
|
||||
key={loc.id}
|
||||
d={loc.path}
|
||||
fill={heatFill(count, max, hasData)}
|
||||
stroke="hsl(var(--background, 0 0% 100%))"
|
||||
strokeWidth={0.6}
|
||||
className={cn('admin-monitor-svg-path', count > 0 && 'has-data')}
|
||||
onMouseEnter={() => setHover({ name: loc.name, count })}
|
||||
onMouseLeave={() => setHover(null)}
|
||||
>
|
||||
<title>
|
||||
{loc.name}
|
||||
{count > 0 ? ` · ${count}` : ''}
|
||||
</title>
|
||||
</path>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
{hover && (
|
||||
<div className="admin-monitor-map-tip" role="status">
|
||||
<strong>{hover.name}</strong>
|
||||
<span>{hover.count > 0 ? hover.count : '—'}</span>
|
||||
</div>
|
||||
)}
|
||||
{!hasData && (
|
||||
<div className="admin-monitor-map-empty-overlay">
|
||||
<p>{emptyTitle}</p>
|
||||
<p>{emptyHint}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
121
frontend/src/components/admin/MonitorWorldMap.tsx
Normal file
121
frontend/src/components/admin/MonitorWorldMap.tsx
Normal file
@@ -0,0 +1,121 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import world from '@svg-maps/world';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
buildCountMap,
|
||||
countryLabelZh,
|
||||
emptyFill,
|
||||
heatFill,
|
||||
type GeoCountMap,
|
||||
} from './monitorMapUtils';
|
||||
|
||||
type Loc = { id: string; name: string; path: string };
|
||||
|
||||
type Props = {
|
||||
items: { country: string; count: number }[];
|
||||
className?: string;
|
||||
/** 裁切到东亚(中国模式) */
|
||||
focusChina?: boolean;
|
||||
};
|
||||
|
||||
const CHINA_VIEWBOX = '680 260 220 200';
|
||||
|
||||
export default function MonitorWorldMap({ items, className, focusChina }: Props) {
|
||||
const [hover, setHover] = useState<{ code: string; name: string; count: number } | null>(null);
|
||||
|
||||
const counts = useMemo(() => buildCountMap(items), [items]);
|
||||
const max = useMemo(() => Math.max(0, ...Object.values(counts)), [counts]);
|
||||
const hasData = max > 0;
|
||||
|
||||
const locations = (world as { locations: Loc[]; viewBox: string }).locations;
|
||||
const viewBox = focusChina ? CHINA_VIEWBOX : (world as { viewBox: string }).viewBox;
|
||||
|
||||
const filteredCounts: GeoCountMap = useMemo(() => {
|
||||
if (!focusChina) return counts;
|
||||
const allow = new Set(['CN', 'HK', 'MO', 'TW']);
|
||||
const m: GeoCountMap = {};
|
||||
for (const [k, v] of Object.entries(counts)) {
|
||||
if (allow.has(k)) m[k] = v;
|
||||
}
|
||||
return m;
|
||||
}, [counts, focusChina]);
|
||||
|
||||
const focusMax = useMemo(
|
||||
() => Math.max(0, ...Object.values(filteredCounts)),
|
||||
[filteredCounts],
|
||||
);
|
||||
const focusHas = focusMax > 0;
|
||||
|
||||
return (
|
||||
<div className={cn('admin-monitor-svg-wrap', className)}>
|
||||
<svg
|
||||
className="admin-monitor-svg-map"
|
||||
viewBox={viewBox}
|
||||
role="img"
|
||||
aria-label={focusChina ? '中国及周边访客地图' : '世界访客地图'}
|
||||
>
|
||||
{locations.map((loc) => {
|
||||
const code = loc.id.toUpperCase();
|
||||
if (focusChina) {
|
||||
// 中国模式下非本区域保持极淡灰,本区域按数据着色
|
||||
const inRegion = code === 'CN' || code === 'HK' || code === 'MO' || code === 'TW'
|
||||
|| code === 'JP' || code === 'KR' || code === 'MN' || code === 'KP'
|
||||
|| code === 'RU' || code === 'IN' || code === 'VN' || code === 'LA'
|
||||
|| code === 'MM' || code === 'BT' || code === 'NP' || code === 'KZ'
|
||||
|| code === 'KG' || code === 'TJ' || code === 'UZ' || code === 'AF'
|
||||
|| code === 'PK' || code === 'PH' || code === 'MY' || code === 'TH'
|
||||
|| code === 'KH' || code === 'BD' || code === 'LK';
|
||||
if (!inRegion) return null;
|
||||
}
|
||||
const count = filteredCounts[code] || (focusChina ? 0 : counts[code]) || 0;
|
||||
const useMax = focusChina ? focusMax : max;
|
||||
const useHas = focusChina ? focusHas : hasData;
|
||||
const isCore = !focusChina || code === 'CN' || code === 'HK' || code === 'MO' || code === 'TW';
|
||||
const fill = isCore
|
||||
? heatFill(count, useMax, useHas)
|
||||
: emptyFill(useHas);
|
||||
|
||||
return (
|
||||
<path
|
||||
key={loc.id}
|
||||
d={loc.path}
|
||||
data-code={code}
|
||||
fill={fill}
|
||||
stroke="hsl(var(--background, 0 0% 100%))"
|
||||
strokeWidth={focusChina ? 0.35 : 0.4}
|
||||
className={cn('admin-monitor-svg-path', count > 0 && 'has-data')}
|
||||
onMouseEnter={() => setHover({
|
||||
code,
|
||||
name: countryLabelZh(code, loc.name),
|
||||
count: focusChina && !isCore ? 0 : count,
|
||||
})}
|
||||
onMouseLeave={() => setHover(null)}
|
||||
>
|
||||
<title>
|
||||
{countryLabelZh(code, loc.name)}
|
||||
{count > 0 ? ` · ${count}` : ''}
|
||||
</title>
|
||||
</path>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
{hover && (
|
||||
<div className="admin-monitor-map-tip" role="status">
|
||||
<strong>{hover.name}</strong>
|
||||
<span>{hover.count > 0 ? hover.count : '—'}</span>
|
||||
</div>
|
||||
)}
|
||||
{!hasData && !focusChina && (
|
||||
<div className="admin-monitor-map-empty-overlay">
|
||||
<p>暂无国家数据</p>
|
||||
<p>配置 GeoIP 或 CDN 国家头后可见</p>
|
||||
</div>
|
||||
)}
|
||||
{focusChina && !focusHas && (
|
||||
<div className="admin-monitor-map-empty-overlay">
|
||||
<p>暂无中国地区访问数据</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
130
frontend/src/components/admin/monitorMapUtils.ts
Normal file
130
frontend/src/components/admin/monitorMapUtils.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
/** 监控地图共用:国家码 → 数量色阶(本站绿色) */
|
||||
|
||||
export type GeoCountMap = Record<string, number>;
|
||||
|
||||
const EMPTY = 'var(--j13-border, #e5e7eb)';
|
||||
const BASE = 'hsl(var(--muted, 210 20% 94%))';
|
||||
|
||||
/** 由浅到深的绿色阶 */
|
||||
const GREEN_STEPS = [
|
||||
'color-mix(in srgb, var(--j13-green) 28%, hsl(var(--card)))',
|
||||
'color-mix(in srgb, var(--j13-green) 45%, hsl(var(--card)))',
|
||||
'color-mix(in srgb, var(--j13-green) 62%, hsl(var(--card)))',
|
||||
'color-mix(in srgb, var(--j13-green) 80%, hsl(var(--card)))',
|
||||
'var(--j13-green)',
|
||||
];
|
||||
|
||||
export function buildCountMap(items: { country: string; count: number }[]): GeoCountMap {
|
||||
const m: GeoCountMap = {};
|
||||
for (const it of items) {
|
||||
const code = (it.country || '').toUpperCase();
|
||||
if (!code) continue;
|
||||
m[code] = (m[code] || 0) + it.count;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
/** MaxMind region_iso / 中英文省名 → @svg-maps/china 的 location id */
|
||||
const CN_ISO_TO_SVG: Record<string, string> = {
|
||||
AH: 'anhui', BJ: 'beijing', CQ: 'chongqing', FJ: 'fujian', GS: 'gansu',
|
||||
GD: 'guangdong', GX: 'guangxi-zhuang', GZ: 'guizhou', HI: 'hainan', HE: 'hebei',
|
||||
HL: 'heilongjiang', HA: 'henan', HB: 'hubei', HN: 'hunan', JS: 'jiangsu',
|
||||
JX: 'jiangxi', JL: 'jilin', LN: 'liaoning', NM: 'nei-mongol', NX: 'ningxia-hui',
|
||||
QH: 'quinghai', SN: 'shaanxi', SD: 'shandong', SH: 'shanghai', SX: 'shanxi',
|
||||
SC: 'sichuan', TJ: 'tianjin', XJ: 'xinjiang-uygur', XZ: 'xizang', YN: 'yunnan',
|
||||
ZJ: 'zhejiang', HK: 'hong-kong', MO: 'macau',
|
||||
};
|
||||
|
||||
const CN_NAME_TO_SVG: Record<string, string> = {
|
||||
安徽: 'anhui', anhui: 'anhui',
|
||||
北京: 'beijing', beijing: 'beijing',
|
||||
重庆: 'chongqing', chongqing: 'chongqing',
|
||||
福建: 'fujian', fujian: 'fujian',
|
||||
甘肃: 'gansu', gansu: 'gansu',
|
||||
广东: 'guangdong', guangdong: 'guangdong',
|
||||
广西: 'guangxi-zhuang', '广西壮族自治区': 'guangxi-zhuang', 'guangxi zhuang': 'guangxi-zhuang', guangxi: 'guangxi-zhuang',
|
||||
贵州: 'guizhou', guizhou: 'guizhou',
|
||||
海南: 'hainan', hainan: 'hainan',
|
||||
河北: 'hebei', hebei: 'hebei',
|
||||
黑龙江: 'heilongjiang', heilongjiang: 'heilongjiang',
|
||||
河南: 'henan', henan: 'henan',
|
||||
湖北: 'hubei', hubei: 'hubei',
|
||||
湖南: 'hunan', hunan: 'hunan',
|
||||
江苏: 'jiangsu', jiangsu: 'jiangsu',
|
||||
江西: 'jiangxi', jiangxi: 'jiangxi',
|
||||
吉林: 'jilin', jilin: 'jilin',
|
||||
辽宁: 'liaoning', liaoning: 'liaoning',
|
||||
内蒙古: 'nei-mongol', '内蒙古自治区': 'nei-mongol', 'nei mongol': 'nei-mongol', 'inner mongolia': 'nei-mongol',
|
||||
宁夏: 'ningxia-hui', '宁夏回族自治区': 'ningxia-hui', 'ningxia hui': 'ningxia-hui', ningxia: 'ningxia-hui',
|
||||
青海: 'quinghai', qinghai: 'quinghai', quinghai: 'quinghai',
|
||||
陕西: 'shaanxi', shaanxi: 'shaanxi',
|
||||
山东: 'shandong', shandong: 'shandong',
|
||||
上海: 'shanghai', shanghai: 'shanghai',
|
||||
山西: 'shanxi', shanxi: 'shanxi',
|
||||
四川: 'sichuan', sichuan: 'sichuan',
|
||||
天津: 'tianjin', tianjin: 'tianjin',
|
||||
新疆: 'xinjiang-uygur', '新疆维吾尔自治区': 'xinjiang-uygur', 'xinjiang uygur': 'xinjiang-uygur', xinjiang: 'xinjiang-uygur',
|
||||
西藏: 'xizang', '西藏自治区': 'xizang', xizang: 'xizang', tibet: 'xizang',
|
||||
云南: 'yunnan', yunnan: 'yunnan',
|
||||
浙江: 'zhejiang', zhejiang: 'zhejiang',
|
||||
香港: 'hong-kong', 'hong kong': 'hong-kong',
|
||||
澳门: 'macau', macau: 'macau', macao: 'macau',
|
||||
};
|
||||
|
||||
export function chinaRegionToSvgId(regionISO?: string, regionName?: string): string | null {
|
||||
const iso = (regionISO || '').trim().toUpperCase().replace(/^CN-/, '');
|
||||
if (iso && CN_ISO_TO_SVG[iso]) return CN_ISO_TO_SVG[iso];
|
||||
const name = (regionName || '').trim().toLowerCase();
|
||||
if (!name) return null;
|
||||
if (CN_NAME_TO_SVG[name]) return CN_NAME_TO_SVG[name];
|
||||
// 尝试去掉「省/市/自治区」后缀后再匹配中文键
|
||||
const zh = (regionName || '').trim()
|
||||
.replace(/(壮族|回族|维吾尔)?自治区$/, '')
|
||||
.replace(/(省|市)$/, '');
|
||||
if (CN_NAME_TO_SVG[zh]) return CN_NAME_TO_SVG[zh];
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 将省级统计聚合为 svg-maps/china 的 id → count */
|
||||
export function buildChinaRegionCountMap(
|
||||
regions: { country: string; region?: string; region_iso?: string; count: number }[],
|
||||
): GeoCountMap {
|
||||
const m: GeoCountMap = {};
|
||||
for (const it of regions) {
|
||||
const c = (it.country || '').toUpperCase();
|
||||
if (c && c !== 'CN' && c !== 'HK' && c !== 'MO' && c !== 'TW') continue;
|
||||
const id = chinaRegionToSvgId(it.region_iso, it.region);
|
||||
if (!id) continue;
|
||||
m[id] = (m[id] || 0) + it.count;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
export function heatFill(count: number, max: number, hasAnyData: boolean): string {
|
||||
if (!hasAnyData) return BASE;
|
||||
if (!count || max <= 0) return BASE;
|
||||
const t = Math.log1p(count) / Math.log1p(max);
|
||||
const idx = Math.min(GREEN_STEPS.length - 1, Math.floor(t * GREEN_STEPS.length));
|
||||
return GREEN_STEPS[Math.max(0, idx)];
|
||||
}
|
||||
|
||||
export function emptyFill(hasAnyData: boolean): string {
|
||||
return hasAnyData ? BASE : EMPTY;
|
||||
}
|
||||
|
||||
export const COUNTRY_NAMES_ZH: Record<string, string> = {
|
||||
CN: '中国', US: '美国', JP: '日本', KR: '韩国', HK: '中国香港', TW: '中国台湾', MO: '中国澳门',
|
||||
SG: '新加坡', DE: '德国', GB: '英国', FR: '法国', RU: '俄罗斯', AU: '澳大利亚',
|
||||
CA: '加拿大', IN: '印度', BR: '巴西', NL: '荷兰', IT: '意大利', ES: '西班牙',
|
||||
MY: '马来西亚', TH: '泰国', VN: '越南', ID: '印尼', PH: '菲律宾', MX: '墨西哥',
|
||||
TR: '土耳其', SA: '沙特', AE: '阿联酋', ZA: '南非', NZ: '新西兰', SE: '瑞典',
|
||||
NO: '挪威', FI: '芬兰', DK: '丹麦', PL: '波兰', CH: '瑞士', AT: '奥地利',
|
||||
BE: '比利时', IE: '爱尔兰', PT: '葡萄牙', AR: '阿根廷', CL: '智利', CO: '哥伦比亚',
|
||||
PK: '巴基斯坦', BD: '孟加拉', EG: '埃及', NG: '尼日利亚', KE: '肯尼亚',
|
||||
UA: '乌克兰', CZ: '捷克', RO: '罗马尼亚', HU: '匈牙利', GR: '希腊', IL: '以色列',
|
||||
};
|
||||
|
||||
export function countryLabelZh(code: string, fallbackName?: string) {
|
||||
const c = code.toUpperCase();
|
||||
return COUNTRY_NAMES_ZH[c] || fallbackName || c;
|
||||
}
|
||||
351
frontend/src/components/editor/ArticleImagePickerDialog.tsx
Normal file
351
frontend/src/components/editor/ArticleImagePickerDialog.tsx
Normal file
@@ -0,0 +1,351 @@
|
||||
import { useCallback, useEffect, useRef, useState, type DragEvent } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '@/api/client';
|
||||
import type { MediaItem } from '@/api/types';
|
||||
import { toPostImageThumbSrc } from '@/utils/postContent';
|
||||
import { Upload, Link2, Images, Loader2 } from 'lucide-react';
|
||||
|
||||
export type ImagePickerTarget = 'rich' | 'markdown';
|
||||
type PickerTab = 'upload' | 'link' | 'gallery';
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** 上传或选中后插入一张或多张图片 URL */
|
||||
onInsert: (urls: string[]) => void;
|
||||
}
|
||||
|
||||
/** 校验可插入的图片地址:外链或站内绝对路径 */
|
||||
export function isValidImageSrc(url: string): boolean {
|
||||
const u = url.trim();
|
||||
if (!u) return false;
|
||||
if (u.startsWith('/') && !u.startsWith('//')) return true;
|
||||
try {
|
||||
const parsed = new URL(u);
|
||||
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const ACCEPT = 'image/jpeg,image/png,image/gif,image/webp';
|
||||
const PAGE_SIZE = 24;
|
||||
|
||||
/** 文章编辑器:统一图片插入(上传 / 链接 / 我的图片) */
|
||||
export function ArticleImagePickerDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onInsert,
|
||||
}: Props) {
|
||||
const [tab, setTab] = useState<PickerTab>('upload');
|
||||
const [url, setUrl] = useState('');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [gallery, setGallery] = useState<MediaItem[]>([]);
|
||||
const [galleryPage, setGalleryPage] = useState(1);
|
||||
const [galleryTotalPages, setGalleryTotalPages] = useState(1);
|
||||
const [galleryLoading, setGalleryLoading] = useState(false);
|
||||
const [galleryLoaded, setGalleryLoaded] = useState(false);
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
|
||||
const resetState = useCallback(() => {
|
||||
setTab('upload');
|
||||
setUrl('');
|
||||
setUploading(false);
|
||||
setDragOver(false);
|
||||
setGallery([]);
|
||||
setGalleryPage(1);
|
||||
setGalleryTotalPages(1);
|
||||
setGalleryLoading(false);
|
||||
setGalleryLoaded(false);
|
||||
setSelected(new Set());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) resetState();
|
||||
}, [open, resetState]);
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next) resetState();
|
||||
onOpenChange(next);
|
||||
};
|
||||
|
||||
const finishInsert = (urls: string[]) => {
|
||||
if (!urls.length) return;
|
||||
onInsert(urls);
|
||||
handleOpenChange(false);
|
||||
};
|
||||
|
||||
const uploadFiles = async (files: File[]) => {
|
||||
const images = files.filter(f => f.type.startsWith('image/'));
|
||||
if (!images.length) {
|
||||
notify.warning('请选择图片文件(jpeg / png / gif / webp)');
|
||||
return;
|
||||
}
|
||||
setUploading(true);
|
||||
const urls: string[] = [];
|
||||
try {
|
||||
for (const file of images) {
|
||||
try {
|
||||
const { url: uploaded } = await api.uploadPostImage(file);
|
||||
urls.push(uploaded);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '图片上传失败');
|
||||
}
|
||||
}
|
||||
if (urls.length) finishInsert(urls);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onFileChange = (list: FileList | null) => {
|
||||
if (!list?.length) return;
|
||||
void uploadFiles([...list]);
|
||||
};
|
||||
|
||||
const onDrop = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
setDragOver(false);
|
||||
if (uploading) return;
|
||||
void uploadFiles([...e.dataTransfer.files]);
|
||||
};
|
||||
|
||||
const handleLinkInsert = () => {
|
||||
const next = url.trim();
|
||||
if (!next) {
|
||||
notify.warning('请输入图片地址');
|
||||
return;
|
||||
}
|
||||
if (!isValidImageSrc(next)) {
|
||||
notify.warning('请使用 http(s) 外链或本站以 / 开头的路径');
|
||||
return;
|
||||
}
|
||||
finishInsert([next]);
|
||||
};
|
||||
|
||||
const loadGallery = useCallback(async (page: number, append: boolean) => {
|
||||
setGalleryLoading(true);
|
||||
try {
|
||||
const res = await api.myPostImages({ page, size: PAGE_SIZE });
|
||||
setGallery(prev => (append ? [...prev, ...res.files] : res.files));
|
||||
setGalleryPage(res.page);
|
||||
setGalleryTotalPages(res.total_pages);
|
||||
setGalleryLoaded(true);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '加载图片失败');
|
||||
setGalleryLoaded(true);
|
||||
} finally {
|
||||
setGalleryLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (open && tab === 'gallery' && !galleryLoaded && !galleryLoading) {
|
||||
void loadGallery(1, false);
|
||||
}
|
||||
}, [open, tab, galleryLoaded, galleryLoading, loadGallery]);
|
||||
|
||||
const toggleSelect = (itemUrl: string) => {
|
||||
setSelected(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(itemUrl)) next.delete(itemUrl);
|
||||
else next.add(itemUrl);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleGalleryInsert = () => {
|
||||
if (!selected.size) {
|
||||
notify.warning('请先选择图片');
|
||||
return;
|
||||
}
|
||||
// 保持网格出现顺序
|
||||
const urls = gallery.filter(f => selected.has(f.url)).map(f => f.url);
|
||||
finishInsert(urls);
|
||||
};
|
||||
|
||||
const tabs: { id: PickerTab; label: string; icon: typeof Upload }[] = [
|
||||
{ id: 'upload', label: '上传', icon: Upload },
|
||||
{ id: 'link', label: '链接', icon: Link2 },
|
||||
{ id: 'gallery', label: '我的图片', icon: Images },
|
||||
];
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="article-image-picker">
|
||||
<DialogHeader>
|
||||
<DialogTitle>插入图片</DialogTitle>
|
||||
<DialogDescription>
|
||||
上传本地文件、粘贴链接,或从已上传图库中选择。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="article-image-picker__tabs" role="tablist">
|
||||
{tabs.map(t => {
|
||||
const Icon = t.icon;
|
||||
return (
|
||||
<button
|
||||
key={t.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === t.id}
|
||||
className={`article-image-picker__tab${tab === t.id ? ' is-active' : ''}`}
|
||||
onClick={() => setTab(t.id)}
|
||||
disabled={uploading}
|
||||
>
|
||||
<Icon size={14} aria-hidden />
|
||||
{t.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{tab === 'upload' && (
|
||||
<div className="article-image-picker__panel">
|
||||
<div
|
||||
className={`article-image-picker__drop${dragOver ? ' is-dragover' : ''}${uploading ? ' is-busy' : ''}`}
|
||||
onDragOver={e => {
|
||||
e.preventDefault();
|
||||
if (!uploading) setDragOver(true);
|
||||
}}
|
||||
onDragLeave={() => setDragOver(false)}
|
||||
onDrop={onDrop}
|
||||
onClick={() => !uploading && fileInputRef.current?.click()}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
fileInputRef.current?.click();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{uploading ? (
|
||||
<>
|
||||
<Loader2 size={28} className="article-image-picker__spin" />
|
||||
<p>正在上传…</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload size={28} />
|
||||
<p>拖拽图片到此处,或点击选择文件</p>
|
||||
<span>支持 jpeg / png / gif / webp;多选将并排成图组</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept={ACCEPT}
|
||||
multiple
|
||||
className="sr-only"
|
||||
onChange={e => {
|
||||
onFileChange(e.target.files);
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'link' && (
|
||||
<div className="article-image-picker__panel">
|
||||
<Input
|
||||
type="url"
|
||||
value={url}
|
||||
placeholder="https://… 或 /uploads/posts/…"
|
||||
onChange={e => setUrl(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleLinkInsert();
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
<p className="article-image-picker__hint">
|
||||
粘贴外链或本站已上传地址,无需重复上传。
|
||||
</p>
|
||||
<DialogFooter className="article-image-picker__footer">
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)}>
|
||||
取消
|
||||
</Button>
|
||||
<Button type="button" onClick={handleLinkInsert}>
|
||||
插入
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'gallery' && (
|
||||
<div className="article-image-picker__panel">
|
||||
{galleryLoading && !gallery.length ? (
|
||||
<div className="article-image-picker__empty">
|
||||
<Loader2 size={22} className="article-image-picker__spin" />
|
||||
<span>加载中…</span>
|
||||
</div>
|
||||
) : !gallery.length ? (
|
||||
<div className="article-image-picker__empty">暂无上传记录</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="article-image-picker__grid">
|
||||
{gallery.map(item => {
|
||||
const thumb = toPostImageThumbSrc(item.url) || item.url;
|
||||
const isSel = selected.has(item.url);
|
||||
return (
|
||||
<button
|
||||
key={item.url}
|
||||
type="button"
|
||||
className={`article-image-picker__thumb${isSel ? ' is-selected' : ''}`}
|
||||
title={item.name}
|
||||
onClick={() => toggleSelect(item.url)}
|
||||
>
|
||||
<img src={thumb} alt={item.name} loading="lazy" />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{galleryPage < galleryTotalPages && (
|
||||
<div className="article-image-picker__more">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={galleryLoading}
|
||||
onClick={() => void loadGallery(galleryPage + 1, true)}
|
||||
>
|
||||
{galleryLoading ? '加载中…' : '加载更多'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<DialogFooter className="article-image-picker__footer">
|
||||
<span className="article-image-picker__selected-count">
|
||||
已选 {selected.size}
|
||||
</span>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)}>
|
||||
取消
|
||||
</Button>
|
||||
<Button type="button" disabled={!selected.size} onClick={handleGalleryInsert}>
|
||||
插入选中
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,39 +1,172 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '@/api/client';
|
||||
import type { PostItem, SitePageSummary } from '@/api/types';
|
||||
import { pagePath, postPath } from '@/utils/permalink';
|
||||
import { useForumLimits } from '@/hooks/useForumLimits';
|
||||
import { ChevronDown, Loader2 } from 'lucide-react';
|
||||
|
||||
export interface ArticleLinkConfirm {
|
||||
url: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
initialUrl?: string;
|
||||
onConfirm: (url: string) => void;
|
||||
initialText?: string;
|
||||
/** 是否正在编辑已有链接 */
|
||||
editing?: boolean;
|
||||
onConfirm: (payload: ArticleLinkConfirm) => void;
|
||||
onRemove?: () => void;
|
||||
}
|
||||
|
||||
/** 文章编辑器链接输入弹窗 */
|
||||
type SiteHit = {
|
||||
key: string;
|
||||
title: string;
|
||||
url: string;
|
||||
kind: 'post' | 'page';
|
||||
};
|
||||
|
||||
/** 校验可插入的链接地址:外链或站内绝对路径 */
|
||||
export function isValidLinkHref(url: string): boolean {
|
||||
const u = url.trim();
|
||||
if (!u) return false;
|
||||
if (u.startsWith('/') && !u.startsWith('//')) return true;
|
||||
if (u.startsWith('#') && u.length > 1) return true;
|
||||
try {
|
||||
const parsed = new URL(u);
|
||||
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const SEARCH_DEBOUNCE_MS = 300;
|
||||
const POST_PAGE_SIZE = 12;
|
||||
|
||||
/** 文章/评论编辑器:插入或编辑链接(含站内内容搜索) */
|
||||
export function ArticleLinkDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
initialUrl = '',
|
||||
initialText = '',
|
||||
editing = false,
|
||||
onConfirm,
|
||||
onRemove,
|
||||
}: Props) {
|
||||
const [url, setUrl] = useState(initialUrl);
|
||||
const { limits } = useForumLimits();
|
||||
const [url, setUrl] = useState('');
|
||||
const [text, setText] = useState('');
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||
const [query, setQuery] = useState('');
|
||||
const [debouncedQuery, setDebouncedQuery] = useState('');
|
||||
const [posts, setPosts] = useState<PostItem[]>([]);
|
||||
const [pages, setPages] = useState<SitePageSummary[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) setUrl(initialUrl || 'https://');
|
||||
}, [open, initialUrl]);
|
||||
if (!open) return;
|
||||
setUrl(initialUrl || '');
|
||||
setText(initialText || '');
|
||||
setAdvancedOpen(false);
|
||||
setQuery('');
|
||||
setDebouncedQuery('');
|
||||
setPosts([]);
|
||||
setPages([]);
|
||||
setLoaded(false);
|
||||
}, [open, initialUrl, initialText]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !advancedOpen) return;
|
||||
const t = window.setTimeout(() => setDebouncedQuery(query.trim()), SEARCH_DEBOUNCE_MS);
|
||||
return () => window.clearTimeout(t);
|
||||
}, [query, open, advancedOpen]);
|
||||
|
||||
const loadSiteHits = useCallback(async (keyword: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [postsRes, pagesRes] = await Promise.all([
|
||||
api.posts({
|
||||
page: 1,
|
||||
size: POST_PAGE_SIZE,
|
||||
sort: 'new',
|
||||
...(keyword ? { keyword, title_only: '1' } : {}),
|
||||
}),
|
||||
api.pages(),
|
||||
]);
|
||||
setPosts(postsRes.posts || []);
|
||||
let nextPages = pagesRes.pages || [];
|
||||
if (keyword) {
|
||||
const q = keyword.toLowerCase();
|
||||
nextPages = nextPages.filter(
|
||||
p => p.title.toLowerCase().includes(q) || p.slug.toLowerCase().includes(q),
|
||||
);
|
||||
}
|
||||
setPages(nextPages.slice(0, POST_PAGE_SIZE));
|
||||
setLoaded(true);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '加载站内内容失败');
|
||||
setLoaded(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 仅展开高级选项时再请求站内内容,避免默认打开就打接口
|
||||
useEffect(() => {
|
||||
if (!open || !advancedOpen) return;
|
||||
void loadSiteHits(debouncedQuery);
|
||||
}, [open, advancedOpen, debouncedQuery, loadSiteHits]);
|
||||
|
||||
const hits: SiteHit[] = useMemo(() => {
|
||||
const postHits: SiteHit[] = posts.map(p => ({
|
||||
key: `post-${p.id}`,
|
||||
title: p.title,
|
||||
url: postPath(p.id, limits),
|
||||
kind: 'post',
|
||||
}));
|
||||
const pageHits: SiteHit[] = pages.map(p => ({
|
||||
key: `page-${p.slug}`,
|
||||
title: p.title,
|
||||
url: pagePath(p.slug, limits),
|
||||
kind: 'page',
|
||||
}));
|
||||
return [...postHits, ...pageHits];
|
||||
}, [posts, pages, limits]);
|
||||
|
||||
const pickHit = (hit: SiteHit) => {
|
||||
setUrl(hit.url);
|
||||
// 选站内内容时同步用标题作为链接文字
|
||||
setText(hit.title);
|
||||
};
|
||||
|
||||
const handleConfirm = () => {
|
||||
onConfirm(url.trim());
|
||||
const nextUrl = url.trim();
|
||||
if (!nextUrl) {
|
||||
notify.warning('请输入网址');
|
||||
return;
|
||||
}
|
||||
if (!isValidLinkHref(nextUrl)) {
|
||||
notify.warning('请使用 http(s) 外链或本站以 / 开头的路径');
|
||||
return;
|
||||
}
|
||||
onConfirm({
|
||||
url: nextUrl,
|
||||
text: text.trim() || '链接文字',
|
||||
});
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
@@ -41,25 +174,119 @@ export function ArticleLinkDialog({
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="article-link-dialog">
|
||||
<DialogHeader>
|
||||
<DialogTitle>插入链接</DialogTitle>
|
||||
<DialogDescription>输入完整 URL,留空并确认可移除已有链接。</DialogDescription>
|
||||
<DialogTitle>插入或编辑链接</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Input
|
||||
type="url"
|
||||
value={url}
|
||||
placeholder="https://"
|
||||
onChange={e => setUrl(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleConfirm();
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<section className="article-link-dialog__section">
|
||||
<div className="article-link-dialog__field">
|
||||
<Label htmlFor="article-link-url">网址</Label>
|
||||
<Input
|
||||
id="article-link-url"
|
||||
type="url"
|
||||
value={url}
|
||||
placeholder="https://… 或 /post/123"
|
||||
onChange={e => setUrl(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleConfirm();
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div className="article-link-dialog__field">
|
||||
<Label htmlFor="article-link-text">链接文字</Label>
|
||||
<Input
|
||||
id="article-link-text"
|
||||
value={text}
|
||||
placeholder="显示在正文中的文字"
|
||||
onChange={e => setText(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleConfirm();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="article-link-dialog__section article-link-dialog__advanced">
|
||||
<button
|
||||
type="button"
|
||||
className={`article-link-dialog__advanced-toggle${advancedOpen ? ' is-open' : ''}`}
|
||||
aria-expanded={advancedOpen}
|
||||
onClick={() => setAdvancedOpen(v => !v)}
|
||||
>
|
||||
<span>高级选项</span>
|
||||
<ChevronDown size={16} aria-hidden className="article-link-dialog__advanced-chevron" />
|
||||
</button>
|
||||
{advancedOpen ? (
|
||||
<div className="article-link-dialog__advanced-body">
|
||||
<h3 className="article-link-dialog__section-title">链接到站点中的内容</h3>
|
||||
<div className="article-link-dialog__field">
|
||||
<Label htmlFor="article-link-search">搜索</Label>
|
||||
<Input
|
||||
id="article-link-search"
|
||||
type="search"
|
||||
value={query}
|
||||
placeholder="搜索帖子或单页…"
|
||||
onChange={e => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="article-link-dialog__hits">
|
||||
<p className="article-link-dialog__hits-hint">
|
||||
{debouncedQuery
|
||||
? `搜索「${debouncedQuery}」`
|
||||
: '未指定搜索条件。自动显示最近发布条目。'}
|
||||
</p>
|
||||
{loading && !loaded ? (
|
||||
<div className="article-link-dialog__hits-empty">
|
||||
<Loader2 size={18} className="article-link-dialog__spin" />
|
||||
<span>加载中…</span>
|
||||
</div>
|
||||
) : !hits.length ? (
|
||||
<div className="article-link-dialog__hits-empty">暂无匹配内容</div>
|
||||
) : (
|
||||
<ul className="article-link-dialog__hit-list">
|
||||
{hits.map(hit => (
|
||||
<li key={hit.key}>
|
||||
<button
|
||||
type="button"
|
||||
className={`article-link-dialog__hit${url === hit.url ? ' is-selected' : ''}`}
|
||||
onClick={() => pickHit(hit)}
|
||||
>
|
||||
<span className="article-link-dialog__hit-title">{hit.title}</span>
|
||||
<span className="article-link-dialog__hit-kind">
|
||||
{hit.kind === 'post' ? '帖子' : '单页'}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{loading && loaded ? (
|
||||
<div className="article-link-dialog__hits-loading">
|
||||
<Loader2 size={14} className="article-link-dialog__spin" />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<DialogFooter className="article-link-dialog__footer">
|
||||
{onRemove && initialUrl ? (
|
||||
<Button type="button" variant="outline" onClick={() => { onRemove(); onOpenChange(false); }}>
|
||||
{editing && onRemove ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="article-link-dialog__remove"
|
||||
onClick={() => {
|
||||
onRemove();
|
||||
onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
移除链接
|
||||
</Button>
|
||||
) : null}
|
||||
@@ -67,7 +294,7 @@ export function ArticleLinkDialog({
|
||||
取消
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm}>
|
||||
确定
|
||||
{editing ? '更新链接' : '添加链接'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { createContext, useContext, useEffect, useState, useCallback, ReactNode } from 'react';
|
||||
import { createContext, useContext, useEffect, useState, useCallback, useRef, ReactNode } from 'react';
|
||||
import { api } from '../api/client';
|
||||
import type { User } from '../api/types';
|
||||
import { clearAllFeedCache } from '../utils/feedCache';
|
||||
import { clearSessionSnapshots } from '../utils/sessionPageCache';
|
||||
import { peekAuthSeed } from '../utils/authBoot';
|
||||
|
||||
interface AuthCtx {
|
||||
user: User | null;
|
||||
@@ -15,8 +18,12 @@ const AuthContext = createContext<AuthCtx>({
|
||||
});
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
// peek 不清种子,StrictMode 重挂 / initializer 双调仍与 SSR 同构
|
||||
const [user, setUser] = useState<User | null>(() => {
|
||||
const s = peekAuthSeed();
|
||||
return s.hasSeed ? s.user : null;
|
||||
});
|
||||
const [loading, setLoading] = useState(() => !peekAuthSeed().hasSeed);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
@@ -29,8 +36,24 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 初始化只拉一次用户信息
|
||||
useEffect(() => { refresh(); }, [refresh]);
|
||||
// 有 SSR 种子时仍后台校验;无种子则首屏拉取
|
||||
// 不清空 auth 种子:StrictMode 重挂会再次跑 useState initializer,破坏性 clear 会导致 user 空窗闪动
|
||||
useEffect(() => { void refresh(); }, [refresh]);
|
||||
|
||||
const prevUserId = useRef<number | null | 'init'>('init');
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
const id = user?.id ?? null;
|
||||
if (prevUserId.current === 'init') {
|
||||
prevUserId.current = id;
|
||||
return;
|
||||
}
|
||||
if (prevUserId.current !== id) {
|
||||
prevUserId.current = id;
|
||||
clearSessionSnapshots();
|
||||
clearAllFeedCache();
|
||||
}
|
||||
}, [user, loading]);
|
||||
|
||||
const logout = async () => {
|
||||
await api.logout();
|
||||
|
||||
@@ -2,38 +2,115 @@ import { useCallback, useEffect, useState } from 'react';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '../api/client';
|
||||
import type { CheckInStatus } from '../api/types';
|
||||
import { getSessionSnapshot, setSessionSnapshot } from '../utils/sessionPageCache';
|
||||
import { PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
|
||||
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
|
||||
import { useAuth } from './useAuth';
|
||||
|
||||
/** 签到会话快照键(与 prefetchRoute 共用) */
|
||||
export function checkInCacheKey(userId: number) {
|
||||
return `checkin:${userId}`;
|
||||
}
|
||||
|
||||
/** 每日签到状态与操作(侧栏、积分页等复用) */
|
||||
export function useCheckIn(enabled = true) {
|
||||
const { user, refresh } = useAuth();
|
||||
const [status, setStatus] = useState<CheckInStatus | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const userId = user?.id;
|
||||
|
||||
const [status, setStatus] = useState<CheckInStatus | null>(() => {
|
||||
if (!userId || !enabled) return null;
|
||||
return getSessionSnapshot<CheckInStatus>(checkInCacheKey(userId)) ?? null;
|
||||
});
|
||||
const [loading, setLoading] = useState(() => {
|
||||
if (!userId || !enabled) return false;
|
||||
return getSessionSnapshot<CheckInStatus>(checkInCacheKey(userId)) === undefined;
|
||||
});
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
if (!user || !enabled) {
|
||||
const load = useCallback((opts?: { force?: boolean }) => {
|
||||
if (!userId || !enabled) {
|
||||
setStatus(null);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
const key = checkInCacheKey(userId);
|
||||
if (!opts?.force) {
|
||||
const hit = getSessionSnapshot<CheckInStatus>(key);
|
||||
if (hit !== undefined) {
|
||||
setStatus(hit);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setLoading(true);
|
||||
api.checkInStatus()
|
||||
.then(d => setStatus(d.check_in))
|
||||
.catch(e => notify.error(e instanceof Error ? e.message : '加载签到状态失败'))
|
||||
.then((d) => {
|
||||
setSessionSnapshot(key, d.check_in);
|
||||
setStatus(d.check_in);
|
||||
})
|
||||
.catch((e) => notify.error(e instanceof Error ? e.message : '加载签到状态失败'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [user, enabled]);
|
||||
}, [userId, enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
if (!userId || !enabled) {
|
||||
setStatus(null);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
const key = checkInCacheKey(userId);
|
||||
const hit = getSessionSnapshot<CheckInStatus>(key);
|
||||
if (hit !== undefined) {
|
||||
setStatus(hit);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setStatus(null);
|
||||
setLoading(true);
|
||||
load({ force: true });
|
||||
}, [userId, enabled, load]);
|
||||
|
||||
// 软刷新 commit:仅快照命中才盖;未命中保持旧 UI,后台静默再拉
|
||||
useEffect(() => {
|
||||
const applyHitOrSilent = (forceLoading: boolean) => {
|
||||
if (!userId || !enabled) return;
|
||||
const key = checkInCacheKey(userId);
|
||||
const hit = getSessionSnapshot<CheckInStatus>(key);
|
||||
if (hit !== undefined) {
|
||||
setStatus(hit);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
if (forceLoading) {
|
||||
load({ force: true });
|
||||
return;
|
||||
}
|
||||
// 软刷新未命中:不 setLoading,静默覆盖
|
||||
api.checkInStatus()
|
||||
.then((d) => {
|
||||
setSessionSnapshot(key, d.check_in);
|
||||
setStatus(d.check_in);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch(() => { /* 保持旧 UI */ });
|
||||
};
|
||||
const onForce = () => applyHitOrSilent(true);
|
||||
const onCommit = () => applyHitOrSilent(false);
|
||||
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||
return () => {
|
||||
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||
};
|
||||
}, [userId, enabled, load]);
|
||||
|
||||
const doCheckIn = useCallback(async () => {
|
||||
if (!user) return;
|
||||
if (!userId) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await api.checkIn();
|
||||
notify.success(`签到成功,+${r.check_in.today_points} 积分`);
|
||||
setSessionSnapshot(checkInCacheKey(userId), r.check_in);
|
||||
setStatus(r.check_in);
|
||||
await refresh();
|
||||
} catch (e: unknown) {
|
||||
@@ -41,13 +118,13 @@ export function useCheckIn(enabled = true) {
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [user, refresh]);
|
||||
}, [userId, refresh]);
|
||||
|
||||
return {
|
||||
status,
|
||||
loading,
|
||||
busy,
|
||||
doCheckIn,
|
||||
reload: load,
|
||||
reload: () => load({ force: true }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api } from '../api/client';
|
||||
import type { ForumLimitsPublic } from '../api/types';
|
||||
import { DEFAULT_ASIDE_WIDGETS } from '../api/types';
|
||||
import { DEFAULT_ASIDE_WIDGETS, DEFAULT_FEED_SORT_TABS } from '../api/types';
|
||||
|
||||
const DEFAULT_LIMITS: ForumLimitsPublic = {
|
||||
post_title_max: 128,
|
||||
@@ -20,12 +20,17 @@ const DEFAULT_LIMITS: ForumLimitsPublic = {
|
||||
aside_show_tag_cloud: false,
|
||||
aside_show_recent_comments: false,
|
||||
aside_show_friend_links: true,
|
||||
aside_show_showcase: false,
|
||||
aside_widgets: DEFAULT_ASIDE_WIDGETS,
|
||||
nav_show_friend_links: true,
|
||||
footer_show_friend_links: true,
|
||||
nav_show_showcase: false,
|
||||
footer_show_showcase: false,
|
||||
feed_list_style: 'title',
|
||||
feed_sort_tabs: DEFAULT_FEED_SORT_TABS,
|
||||
permalink_enabled: false,
|
||||
permalink_ext: 'html',
|
||||
monitor_pageview: false,
|
||||
};
|
||||
|
||||
let cached: ForumLimitsPublic | null = null;
|
||||
@@ -75,6 +80,27 @@ export function useForumLimits() {
|
||||
return { limits, loading };
|
||||
}
|
||||
|
||||
/** 冷启动 / 预热:确保 limits 已写入模块缓存;force 时重拉并在成功后通知 hook */
|
||||
export async function ensureForumLimitsLoaded(opts?: { force?: boolean }): Promise<ForumLimitsPublic> {
|
||||
if (opts?.force) {
|
||||
cached = null;
|
||||
inflight = null;
|
||||
}
|
||||
const limits = await fetchLimits();
|
||||
if (opts?.force) {
|
||||
cacheEpoch += 1;
|
||||
listeners.forEach(fn => fn());
|
||||
}
|
||||
return limits;
|
||||
}
|
||||
|
||||
/** 文档 SSR / 管理端:同步写入 limits 模块缓存 */
|
||||
export function seedForumLimitsCache(limits: ForumLimitsPublic) {
|
||||
cached = limits;
|
||||
cacheEpoch += 1;
|
||||
listeners.forEach(fn => fn());
|
||||
}
|
||||
|
||||
/** 清除缓存并通知已挂载的 hook 重新拉取 */
|
||||
export function invalidateForumLimitsCache() {
|
||||
cached = null;
|
||||
|
||||
41
frontend/src/hooks/useMonitorPageview.ts
Normal file
41
frontend/src/hooks/useMonitorPageview.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { api } from '../api/client';
|
||||
import { useForumLimits } from './useForumLimits';
|
||||
|
||||
const DEDUPE_MS = 800;
|
||||
|
||||
function shouldSkipPath(pathname: string) {
|
||||
const p = pathname.toLowerCase();
|
||||
return (
|
||||
p === '/admin' ||
|
||||
p.startsWith('/admin/') ||
|
||||
p === '/login' ||
|
||||
p === '/register' ||
|
||||
p === '/forgot-password' ||
|
||||
p.startsWith('/oauth')
|
||||
);
|
||||
}
|
||||
|
||||
/** 主站布局:路由变化时上报第一方 pageview(采集关闭则不请求) */
|
||||
export function useMonitorPageview() {
|
||||
const loc = useLocation();
|
||||
const { limits } = useForumLimits();
|
||||
const lastRef = useRef<{ key: string; at: number }>({ key: '', at: 0 });
|
||||
const enabled = !!limits.monitor_pageview;
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
if (shouldSkipPath(loc.pathname)) return;
|
||||
|
||||
const path = `${loc.pathname}${loc.search || ''}`;
|
||||
const now = Date.now();
|
||||
if (lastRef.current.key === path && now - lastRef.current.at < DEDUPE_MS) {
|
||||
return;
|
||||
}
|
||||
lastRef.current = { key: path, at: now };
|
||||
|
||||
const referrer = typeof document !== 'undefined' ? document.referrer || '' : '';
|
||||
void api.monitorPageview({ path, referrer });
|
||||
}, [enabled, loc.pathname, loc.search]);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { useCallback, useMemo } from 'react';
|
||||
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { buildHomeUrl } from '../components/FeedSortBar';
|
||||
import { navigateFeed } from '../utils/feedCache';
|
||||
import { transitionTo } from '../utils/spaTransition';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { parsePermalinkID, type PermalinkOpts } from '../utils/permalink';
|
||||
|
||||
@@ -190,7 +191,7 @@ export function usePostSearch(
|
||||
}
|
||||
|
||||
saveRecentSearch({ keyword: kw, author, titleOnly, scopeBoardId });
|
||||
nav(target);
|
||||
void transitionTo(nav, target);
|
||||
return true;
|
||||
}, [nav, params, loc.pathname, limits, buildUrl]);
|
||||
|
||||
|
||||
144
frontend/src/hooks/useSessionResource.ts
Normal file
144
frontend/src/hooks/useSessionResource.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
|
||||
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
|
||||
import {
|
||||
getSessionSnapshot,
|
||||
setSessionSnapshot,
|
||||
deleteSessionSnapshot,
|
||||
} from '../utils/sessionPageCache';
|
||||
|
||||
type Fetcher<T> = () => Promise<T>;
|
||||
|
||||
/**
|
||||
* 会话快照数据源:有缓存则跳过请求;无缓存时保留上一份画面直到新数据返回。
|
||||
* 手机下拉软刷新 commit / PAGE_FORCE_REFRESH_EVENT 会应用新快照。
|
||||
*/
|
||||
export function useSessionResource<T>(
|
||||
key: string | null,
|
||||
fetcher: Fetcher<T>,
|
||||
opts?: {
|
||||
enabled?: boolean;
|
||||
onError?: (e: unknown) => void;
|
||||
},
|
||||
) {
|
||||
const enabled = opts?.enabled !== false;
|
||||
const fetcherRef = useRef(fetcher);
|
||||
fetcherRef.current = fetcher;
|
||||
const onErrorRef = useRef(opts?.onError);
|
||||
onErrorRef.current = opts?.onError;
|
||||
|
||||
const [data, setData] = useState<T | undefined>(() =>
|
||||
key && enabled ? getSessionSnapshot<T>(key) : undefined,
|
||||
);
|
||||
const [loading, setLoading] = useState(() => {
|
||||
if (!key || !enabled) return false;
|
||||
return getSessionSnapshot<T>(key) === undefined;
|
||||
});
|
||||
const [pending, setPending] = useState(false);
|
||||
const seqRef = useRef(0);
|
||||
const dataRef = useRef(data);
|
||||
dataRef.current = data;
|
||||
|
||||
useEffect(() => {
|
||||
if (!key || !enabled) {
|
||||
if (!enabled) {
|
||||
setLoading(false);
|
||||
setPending(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const hit = getSessionSnapshot<T>(key);
|
||||
if (hit !== undefined) {
|
||||
setData(hit);
|
||||
setLoading(false);
|
||||
setPending(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const seq = ++seqRef.current;
|
||||
const keep = dataRef.current !== undefined;
|
||||
if (keep) setPending(true);
|
||||
else setLoading(true);
|
||||
|
||||
fetcherRef.current()
|
||||
.then((next) => {
|
||||
if (seq !== seqRef.current) return;
|
||||
setSessionSnapshot(key, next);
|
||||
setData(next);
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (seq !== seqRef.current) return;
|
||||
onErrorRef.current?.(e);
|
||||
if (!keep) setData(undefined);
|
||||
})
|
||||
.finally(() => {
|
||||
if (seq !== seqRef.current) return;
|
||||
setLoading(false);
|
||||
setPending(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
seqRef.current += 1;
|
||||
};
|
||||
}, [key, enabled]);
|
||||
|
||||
const replace = useCallback((next: T | ((prev: T | undefined) => T)) => {
|
||||
setData((prev) => {
|
||||
const value = typeof next === 'function' ? (next as (p: T | undefined) => T)(prev) : next;
|
||||
if (key) setSessionSnapshot(key, value);
|
||||
return value;
|
||||
});
|
||||
}, [key]);
|
||||
|
||||
const invalidate = useCallback(() => {
|
||||
if (key) deleteSessionSnapshot(key);
|
||||
}, [key]);
|
||||
|
||||
useEffect(() => {
|
||||
const reload = (opts: { allowLoading: boolean }) => {
|
||||
if (!key || !enabled) return;
|
||||
const warm = getSessionSnapshot<T>(key);
|
||||
if (warm !== undefined) {
|
||||
setData(warm);
|
||||
setLoading(false);
|
||||
setPending(false);
|
||||
return;
|
||||
}
|
||||
const seq = ++seqRef.current;
|
||||
const keep = dataRef.current !== undefined;
|
||||
if (opts.allowLoading) {
|
||||
deleteSessionSnapshot(key);
|
||||
if (keep) setPending(true);
|
||||
else setLoading(true);
|
||||
}
|
||||
fetcherRef.current()
|
||||
.then((next) => {
|
||||
if (seq !== seqRef.current) return;
|
||||
setSessionSnapshot(key, next);
|
||||
setData(next);
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (seq !== seqRef.current) return;
|
||||
onErrorRef.current?.(e);
|
||||
if (opts.allowLoading && !keep) setData(undefined);
|
||||
})
|
||||
.finally(() => {
|
||||
if (seq !== seqRef.current) return;
|
||||
setLoading(false);
|
||||
setPending(false);
|
||||
});
|
||||
};
|
||||
const onForce = () => reload({ allowLoading: true });
|
||||
// 软刷新 commit:未命中不卸 UI,后台静默再拉
|
||||
const onCommit = () => reload({ allowLoading: false });
|
||||
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||
return () => {
|
||||
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||
};
|
||||
}, [key, enabled]);
|
||||
|
||||
return { data, loading, pending, replace, invalidate };
|
||||
}
|
||||
@@ -46,9 +46,15 @@ function readBootBranding(): SiteBranding | null {
|
||||
let cached: SiteBranding | null = readBootBranding();
|
||||
let inflight: Promise<SiteBranding> | null = null;
|
||||
let cacheEpoch = 0;
|
||||
/** force 预热刚写入后,hook 因 epoch 重跑时复用缓存,避免连打两次 API */
|
||||
let preferCacheOnce = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function fetchBranding(): Promise<SiteBranding> {
|
||||
if (preferCacheOnce && cached) {
|
||||
preferCacheOnce = false;
|
||||
return Promise.resolve(cached);
|
||||
}
|
||||
if (inflight) return inflight;
|
||||
// 有 boot/缓存时首屏已可用;仍请求 API 以同步最新配置
|
||||
inflight = api.siteBranding()
|
||||
@@ -123,6 +129,30 @@ export function useSiteBranding() {
|
||||
return { branding, loading };
|
||||
}
|
||||
|
||||
/** 保留当前画面,后台重拉品牌配置(下拉刷新等) */
|
||||
export function refetchSiteBranding() {
|
||||
inflight = null;
|
||||
cacheEpoch += 1;
|
||||
listeners.forEach(fn => fn());
|
||||
}
|
||||
|
||||
/** 冷启动 / 预热:确保品牌已写入模块缓存;force 时重拉并在成功后通知 hook */
|
||||
export async function ensureSiteBrandingLoaded(opts?: { force?: boolean }): Promise<SiteBranding> {
|
||||
if (!opts?.force && cached) return cached;
|
||||
if (opts?.force) {
|
||||
inflight = null;
|
||||
preferCacheOnce = false;
|
||||
}
|
||||
const next = await fetchBranding();
|
||||
applyDocumentBrand(next);
|
||||
if (opts?.force) {
|
||||
preferCacheOnce = true;
|
||||
cacheEpoch += 1;
|
||||
listeners.forEach(fn => fn());
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/** 清除缓存并通知已挂载的 hook 重新拉取 */
|
||||
export function invalidateSiteBrandingCache() {
|
||||
cached = null;
|
||||
|
||||
@@ -1,32 +1,60 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api } from '../api/client';
|
||||
import type { SitePageSummary } from '../api/types';
|
||||
import { PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
|
||||
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
|
||||
|
||||
let cache: SitePageSummary[] | null = null;
|
||||
let pending: Promise<SitePageSummary[]> | null = null;
|
||||
|
||||
/** 拉取或复用站点页摘要缓存(供冷启动门闩与 hook 共用) */
|
||||
export function ensureSitePagesLoaded(opts?: { force?: boolean }): Promise<SitePageSummary[]> {
|
||||
if (opts?.force) {
|
||||
cache = null;
|
||||
pending = null;
|
||||
}
|
||||
if (cache) return Promise.resolve(cache);
|
||||
if (!pending) {
|
||||
pending = api.pages()
|
||||
.then(d => {
|
||||
cache = d.pages ?? [];
|
||||
return cache;
|
||||
})
|
||||
.catch(() => {
|
||||
cache = [];
|
||||
return cache;
|
||||
})
|
||||
.finally(() => { pending = null; });
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** 已发布单页摘要(页脚/侧栏导航) */
|
||||
export function useSitePages() {
|
||||
const [pages, setPages] = useState<SitePageSummary[]>(cache ?? []);
|
||||
|
||||
useEffect(() => {
|
||||
if (cache) {
|
||||
setPages(cache);
|
||||
return;
|
||||
}
|
||||
if (!pending) {
|
||||
pending = api.pages()
|
||||
.then(d => {
|
||||
cache = d.pages ?? [];
|
||||
return cache;
|
||||
})
|
||||
.catch(() => {
|
||||
cache = [];
|
||||
return cache;
|
||||
})
|
||||
.finally(() => { pending = null; });
|
||||
}
|
||||
pending.then(setPages);
|
||||
const load = () => {
|
||||
void ensureSitePagesLoaded().then(setPages);
|
||||
};
|
||||
if (cache) setPages(cache);
|
||||
else load();
|
||||
|
||||
const onForce = () => {
|
||||
cache = null;
|
||||
pending = null;
|
||||
load();
|
||||
};
|
||||
const onCommit = () => {
|
||||
// 软刷新:cache 已由 prefetch 写好,同步进 state
|
||||
void ensureSitePagesLoaded().then(setPages);
|
||||
};
|
||||
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||
return () => {
|
||||
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
@@ -39,3 +67,9 @@ export function useSitePages() {
|
||||
export function invalidateSitePagesCache() {
|
||||
cache = null;
|
||||
}
|
||||
|
||||
/** 文档 SSR:同步写入站点页摘要缓存 */
|
||||
export function seedSitePagesCache(pages: SitePageSummary[]) {
|
||||
cache = Array.isArray(pages) ? pages : [];
|
||||
pending = null;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState, useCallback, useRef } from 'react';
|
||||
import { Outlet, NavLink, useNavigate, useLocation } from 'react-router-dom';
|
||||
import {
|
||||
LayoutDashboard, FolderKanban, FileText, MessageSquare, Flag, Users, Images, Settings, ArrowLeft, Moon, Sun, Menu, X, Award, Link2, BookOpen,
|
||||
LayoutDashboard, FolderKanban, FileText, MessageSquare, Flag, Users, Images, Settings, ArrowLeft, Moon, Sun, Menu, X, Award, Link2, BookOpen, Globe2, Activity,
|
||||
} from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
@@ -23,6 +23,8 @@ type NavItem = {
|
||||
label: string;
|
||||
icon: typeof LayoutDashboard;
|
||||
badgeKey?: BadgeKey;
|
||||
/** 仅社区枢纽开启时显示 */
|
||||
hubOnly?: boolean;
|
||||
};
|
||||
|
||||
type NavGroup = {
|
||||
@@ -36,6 +38,8 @@ const NAV_GROUPS: NavGroup[] = [
|
||||
label: '概览',
|
||||
items: [
|
||||
{ to: '/admin/dashboard', label: '仪表盘', icon: LayoutDashboard },
|
||||
{ to: '/admin/monitor', label: '网站监控', icon: Activity },
|
||||
{ to: '/admin/community', label: '公网实例', icon: Globe2, hubOnly: true },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -86,6 +90,7 @@ export default function AdminLayout() {
|
||||
const isNarrow = useMediaQuery('(max-width: 768px)');
|
||||
const [navOpen, setNavOpen] = useState(false);
|
||||
const [pending, setPending] = useState<PendingCounts>({ posts: 0, comments: 0, reports: 0, links: 0 });
|
||||
const [communityHub, setCommunityHub] = useState(false);
|
||||
const nav = useNavigate();
|
||||
const location = useLocation();
|
||||
const drawerRef = useRef<HTMLElement>(null);
|
||||
@@ -107,6 +112,13 @@ export default function AdminLayout() {
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || !user || user.role !== 'admin') return;
|
||||
api.adminSettings()
|
||||
.then(s => setCommunityHub(!!s.community?.hub_enabled))
|
||||
.catch(() => setCommunityHub(false));
|
||||
}, [loading, user]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || !user || user.role !== 'admin') return;
|
||||
refreshPending();
|
||||
@@ -156,7 +168,7 @@ export default function AdminLayout() {
|
||||
NAV_GROUPS.map(group => (
|
||||
<div key={group.label} className="admin-nav-group">
|
||||
<div className="admin-nav-group-label">{group.label}</div>
|
||||
{group.items.map(({ to, label, icon: Icon, badgeKey }) => {
|
||||
{group.items.filter(item => !item.hubOnly || communityHub).map(({ to, label, icon: Icon, badgeKey }) => {
|
||||
const badge = badgeKey ? formatNavBadge(pending[badgeKey]) : null;
|
||||
return (
|
||||
<NavLink
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { useState, useEffect, useCallback, useRef, useMemo, Suspense } from 'react';
|
||||
import PageLoader from '../components/PageLoader';
|
||||
import FeedPageSkeleton from '../components/FeedPageSkeleton';
|
||||
import { useState, useEffect, useCallback, useRef, useMemo, Suspense, startTransition } from 'react';
|
||||
import { Outlet, useNavigate, useSearchParams, useLocation } from 'react-router-dom';
|
||||
import { Menu, Moon, Sun, Search, Plus, PanelRight, X, Mail, SlidersHorizontal } from 'lucide-react';
|
||||
import {
|
||||
@@ -23,7 +21,12 @@ import BackToTop from '../components/BackToTop';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import { resolveAsideWidgets } from '../utils/asideWidgets';
|
||||
import { buildHomeUrl, parseFeedSort } from '../components/FeedSortBar';
|
||||
import { navigateFeed } from '../utils/feedCache';
|
||||
import { navigateFeed, PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
|
||||
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
|
||||
import { prefetchRoute, wasColdBootEnsured } from '../utils/prefetchRoute';
|
||||
import {
|
||||
transitionTo,
|
||||
} from '../utils/spaTransition';
|
||||
import PostSearchPanel from '../components/search/PostSearchPanel';
|
||||
import {
|
||||
POST_SEARCH_OPEN_EVENT,
|
||||
@@ -33,28 +36,42 @@ import { cn } from '@/lib/utils';
|
||||
import { getBoardThemeIndex } from '../utils/boardTheme';
|
||||
import { loginPath } from '../utils/authRedirect';
|
||||
import { openForumPost } from '../utils/openPost';
|
||||
import { useSiteBranding } from '../hooks/useSiteBranding';
|
||||
import { refetchSiteBranding, useSiteBranding } from '../hooks/useSiteBranding';
|
||||
import { useMonitorPageview } from '../hooks/useMonitorPageview';
|
||||
import SiteBrandMark from '../components/SiteBrandMark';
|
||||
import SiteFooter from '../components/SiteFooter';
|
||||
import { userPath } from '../utils/userPath';
|
||||
import { parsePermalinkID } from '../utils/permalink';
|
||||
import { ensureSitePagesLoaded } from '../hooks/useSitePages';
|
||||
import { endHomeHydrate, isHomeHydrating } from '../utils/homeHydrate';
|
||||
import { getBootUnread } from '../utils/authBoot';
|
||||
|
||||
export default function MainLayout() {
|
||||
const { user, loading: authLoading, logout } = useAuth();
|
||||
const { theme, toggle } = useTheme();
|
||||
const { branding } = useSiteBranding();
|
||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||
useMonitorPageview();
|
||||
const mqMobile = useMediaQuery('(max-width: 768px)');
|
||||
const hideAside = useMediaQuery('(max-width: 1100px)');
|
||||
/** hydrate 首帧强制桌面布局(SSR 为桌面三栏),随后再跟 matchMedia */
|
||||
const [forceDesktop, setForceDesktop] = useState(() => isHomeHydrating());
|
||||
const isMobile = forceDesktop ? false : mqMobile;
|
||||
const nav = useNavigate();
|
||||
const loc = useLocation();
|
||||
const [params] = useSearchParams();
|
||||
const isCompose = loc.pathname.startsWith('/compose') || /\/post\/\d+\/edit$/.test(loc.pathname);
|
||||
|
||||
useEffect(() => {
|
||||
if (!forceDesktop) return;
|
||||
endHomeHydrate();
|
||||
startTransition(() => setForceDesktop(false));
|
||||
}, [forceDesktop]);
|
||||
|
||||
const [boards, setBoards] = useState<Board[]>(() => getCachedBoards());
|
||||
const [stats, setStats] = useState<ForumStats | null>(() => getCachedStats());
|
||||
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
|
||||
const [recentUsers, setRecentUsers] = useState<RecentUser[]>(() => getCachedRecentUsers());
|
||||
const [unreadMessages, setUnreadMessages] = useState(0);
|
||||
const [unreadMessages, setUnreadMessages] = useState(() => getBootUnread());
|
||||
const [tags, setTags] = useState<TagCount[]>(() => getCachedTags());
|
||||
const [tagsLoading, setTagsLoading] = useState(() => getCachedTags().length === 0);
|
||||
const [postOutline, setPostOutline] = useState<{
|
||||
@@ -71,15 +88,20 @@ export default function MainLayout() {
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
const [asideLoading, setAsideLoading] = useState(() => !hasCachedAside());
|
||||
const [boardsLoading, setBoardsLoading] = useState(() => getCachedBoards().length === 0);
|
||||
const [layoutRefreshTick, setLayoutRefreshTick] = useState(0);
|
||||
const asideEverLoaded = useRef(false);
|
||||
/** 冷启动门闩:main.tsx 已预热则可同步放行;否则等齐再呈现 */
|
||||
const [shellReady, setShellReady] = useState(() => isCompose || wasColdBootEnsured());
|
||||
const coldBootDone = useRef(isCompose || wasColdBootEnsured());
|
||||
const bootGen = useRef(0);
|
||||
const [boardId, setBoardId] = useState(() => {
|
||||
const m = loc.pathname.match(/^\/board\/(\d+(?:\.[A-Za-z0-9]{1,16})?)$/);
|
||||
if (m) return parsePermalinkID(m[1]) || 0;
|
||||
return Number(params.get('board')) || 0;
|
||||
});
|
||||
const [keywordDraft, setKeywordDraft] = useState(params.get('keyword') || '');
|
||||
const feedSort = parseFeedSort(params.get('sort'));
|
||||
const { limits: forumLimits } = useForumLimits();
|
||||
const feedSort = parseFeedSort(params.get('sort'), forumLimits.feed_sort_tabs);
|
||||
const postSearch = usePostSearch(forumLimits);
|
||||
const asideWidgets = useMemo(() => resolveAsideWidgets(forumLimits), [forumLimits]);
|
||||
const showTagCloud = asideWidgets.some(w => w.id === 'tag_cloud' && w.enabled);
|
||||
@@ -126,7 +148,10 @@ export default function MainLayout() {
|
||||
setSidebarOpen(false);
|
||||
}, [loc.pathname, loc.search]);
|
||||
useEffect(() => {
|
||||
if (!/^\/post\/\d+/.test(loc.pathname)) setPostOutline(null);
|
||||
const isArticleAside =
|
||||
(/^\/post\/\d+/.test(loc.pathname) && !/\/edit$/.test(loc.pathname))
|
||||
|| /^\/page\//.test(loc.pathname);
|
||||
if (!isArticleAside) setPostOutline(null);
|
||||
}, [loc.pathname]);
|
||||
useEffect(() => {
|
||||
if (!hideAside) setAsideOpen(false);
|
||||
@@ -193,6 +218,94 @@ export default function MainLayout() {
|
||||
return () => window.removeEventListener('boards-refresh', onRefresh);
|
||||
}, [refreshBoards]);
|
||||
|
||||
// 冷启动兜底:main 未预热时静默等齐(不打进度条);站内已预热则保持打开
|
||||
useEffect(() => {
|
||||
if (isCompose) {
|
||||
coldBootDone.current = true;
|
||||
setShellReady(true);
|
||||
return;
|
||||
}
|
||||
if (coldBootDone.current || wasColdBootEnsured()) {
|
||||
coldBootDone.current = true;
|
||||
setShellReady(true);
|
||||
setBoardsLoading(false);
|
||||
setAsideLoading(false);
|
||||
setTagsLoading(false);
|
||||
asideEverLoaded.current = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const gen = ++bootGen.current;
|
||||
let cancelled = false;
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const path = `${loc.pathname}${loc.search}`;
|
||||
const tasks: Promise<unknown>[] = [
|
||||
prefetchRoute(path, { force: false }),
|
||||
refreshBoards(),
|
||||
ensureSitePagesLoaded(),
|
||||
];
|
||||
|
||||
if (!hideAside) {
|
||||
if (showRecentComments) {
|
||||
tasks.push(
|
||||
api.recentComments().then((d) => {
|
||||
const next = Array.isArray(d.comments) ? d.comments : [];
|
||||
setRecentComments(next);
|
||||
setCachedRecentComments(next);
|
||||
}).catch(() => undefined),
|
||||
);
|
||||
}
|
||||
if (showRecentUsers) {
|
||||
tasks.push(
|
||||
api.recentUsers().then((d) => {
|
||||
const next = Array.isArray(d.users) ? d.users : [];
|
||||
setRecentUsers(next);
|
||||
setCachedRecentUsers(next);
|
||||
}).catch(() => undefined),
|
||||
);
|
||||
}
|
||||
if (showTagCloud) {
|
||||
tasks.push(
|
||||
api.tags(40).then((d) => {
|
||||
const next = Array.isArray(d.tags) ? d.tags : [];
|
||||
setTags(next);
|
||||
setCachedTags(next);
|
||||
}).catch(() => undefined),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(tasks);
|
||||
} catch {
|
||||
// 失败也放行
|
||||
} finally {
|
||||
if (!cancelled && bootGen.current === gen) {
|
||||
asideEverLoaded.current = true;
|
||||
setAsideLoading(false);
|
||||
setTagsLoading(false);
|
||||
setBoardsLoading(false);
|
||||
coldBootDone.current = true;
|
||||
setShellReady(true);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [
|
||||
isCompose,
|
||||
loc.pathname,
|
||||
loc.search,
|
||||
hideAside,
|
||||
showRecentComments,
|
||||
showRecentUsers,
|
||||
showTagCloud,
|
||||
refreshBoards,
|
||||
]);
|
||||
|
||||
const refreshUnreadMessages = useCallback(() => {
|
||||
if (!user) {
|
||||
setUnreadMessages(0);
|
||||
@@ -214,10 +327,49 @@ export default function MainLayout() {
|
||||
};
|
||||
}, [refreshUnreadMessages]);
|
||||
|
||||
// 标签云:进页/离开发帖页时拉取;不跟 posts-refresh 联动(置顶/精华等不改标签)
|
||||
useEffect(() => {
|
||||
const syncFromCache = () => {
|
||||
// 仅当 cache 有内容时覆盖,避免空数组盖住已渲染的非空 UI
|
||||
const nextBoards = getCachedBoards();
|
||||
if (nextBoards.length > 0) setBoards(nextBoards);
|
||||
setBoardsLoading(false);
|
||||
const nextStats = getCachedStats();
|
||||
if (nextStats) setStats(nextStats);
|
||||
const nextComments = getCachedRecentComments();
|
||||
if (nextComments.length > 0 || hasCachedAside()) setRecentComments(nextComments);
|
||||
const nextUsers = getCachedRecentUsers();
|
||||
if (nextUsers.length > 0 || hasCachedAside()) setRecentUsers(nextUsers);
|
||||
const nextTags = getCachedTags();
|
||||
if (nextTags.length > 0) setTags(nextTags);
|
||||
setTagsLoading(false);
|
||||
setAsideLoading(false);
|
||||
asideEverLoaded.current = true;
|
||||
refreshUnreadMessages();
|
||||
};
|
||||
const onForce = () => {
|
||||
// 旧路径:仍可能被别处派发;尽量静默刷新壳层
|
||||
refreshBoards();
|
||||
refreshUnreadMessages();
|
||||
refetchSiteBranding();
|
||||
setLayoutRefreshTick(n => n + 1);
|
||||
};
|
||||
const onCommit = () => {
|
||||
// 软刷新:预热已写入 cache,同一拍同步进 state,不触发分批 loading
|
||||
syncFromCache();
|
||||
};
|
||||
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||
return () => {
|
||||
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||
};
|
||||
}, [refreshBoards, refreshUnreadMessages]);
|
||||
|
||||
// 标签云:进页/离开发帖页时拉取;不跟 posts-refresh 联动(置顶/推荐等不改标签)
|
||||
useEffect(() => {
|
||||
if (isCompose || !showTagCloud) return;
|
||||
let cancelled = false;
|
||||
// 有 session 缓存则静默刷新(软刷新不卸空白)
|
||||
if (getCachedTags().length === 0) setTagsLoading(true);
|
||||
api.tags(40).then(d => {
|
||||
if (cancelled) return;
|
||||
@@ -230,7 +382,7 @@ export default function MainLayout() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [isCompose, showTagCloud]);
|
||||
}, [isCompose, showTagCloud, layoutRefreshTick]);
|
||||
|
||||
const needAsideData = !isCompose && (!hideAside || asideOpen);
|
||||
const needRecentComments = needAsideData && showRecentComments;
|
||||
@@ -257,7 +409,7 @@ export default function MainLayout() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [needRecentComments]);
|
||||
}, [needRecentComments, layoutRefreshTick]);
|
||||
|
||||
const needRecentUsers = needAsideData && showRecentUsers;
|
||||
useEffect(() => {
|
||||
@@ -282,7 +434,7 @@ export default function MainLayout() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [needRecentUsers]);
|
||||
}, [needRecentUsers, layoutRefreshTick]);
|
||||
|
||||
const doQuickSearch = () => {
|
||||
const { author, titleOnly, scopeBoardId } = postSearch.filters;
|
||||
@@ -328,6 +480,10 @@ export default function MainLayout() {
|
||||
const activeChipIndex = Math.max(0, boardChipIds.indexOf(mobileActiveBoard === -1 ? 0 : mobileActiveBoard));
|
||||
|
||||
const isPostDetail = /^\/post\/\d+/.test(loc.pathname) && !/\/edit$/.test(loc.pathname);
|
||||
const isSitePage = /^\/page\//.test(loc.pathname);
|
||||
const isArticleAside = isPostDetail || isSitePage;
|
||||
// 帖子有作者 →「作者与目录」;单页仅目录
|
||||
const articleAsideLabel = isPostDetail ? '作者与目录' : '文章目录';
|
||||
const setPostOutlineSafe = useCallback((outline: {
|
||||
headings: PostHeading[];
|
||||
scrollRoot: HTMLElement | null;
|
||||
@@ -367,14 +523,14 @@ export default function MainLayout() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<div className={cn('app-shell', forceDesktop && 'ssr-home')}>
|
||||
<div className="app-frame">
|
||||
<header className="app-header">
|
||||
<div className="header-inner">
|
||||
{isMobile && !isCompose && (
|
||||
{!isCompose && (
|
||||
<button
|
||||
type="button"
|
||||
className="header-icon-btn"
|
||||
className="header-icon-btn header-menu-btn"
|
||||
onClick={openSidebar}
|
||||
aria-label="打开导航菜单"
|
||||
aria-expanded={sidebarOpen}
|
||||
@@ -384,9 +540,10 @@ export default function MainLayout() {
|
||||
<Menu size={18} aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="header-brand" onClick={() => navigateFeed(nav, '/')}>
|
||||
{/* 任意页点 Logo:回首页并强制刷新,不展示会话缓存 */}
|
||||
<button type="button" className="header-brand" onClick={() => navigateFeed(nav, '/', { refresh: true })}>
|
||||
<SiteBrandMark branding={branding} className="header-logo-mark" />
|
||||
{!isMobile && <span className="header-logo-text">{branding.name}</span>}
|
||||
<span className="header-logo-text">{branding.name}</span>
|
||||
</button>
|
||||
|
||||
{!isCompose && isMobile && (
|
||||
@@ -467,11 +624,11 @@ export default function MainLayout() {
|
||||
<button
|
||||
type="button"
|
||||
className="header-compose-btn"
|
||||
onClick={() => user ? nav('/compose') : nav(loginPath('/compose'))}
|
||||
onClick={() => user ? void transitionTo(nav, '/compose') : nav(loginPath('/compose'))}
|
||||
aria-label="发帖"
|
||||
>
|
||||
<Plus size={16} aria-hidden />
|
||||
{!isMobile && <span>发帖</span>}
|
||||
<span className="header-compose-btn__label">发帖</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
@@ -482,26 +639,24 @@ export default function MainLayout() {
|
||||
type="button"
|
||||
className="header-icon-btn"
|
||||
onClick={openAside}
|
||||
aria-label={isPostDetail ? '打开作者与目录' : '打开社区动态'}
|
||||
aria-label={isArticleAside ? `打开${articleAsideLabel}` : '打开社区动态'}
|
||||
aria-expanded={asideOpen}
|
||||
aria-controls="aside-drawer"
|
||||
title={isPostDetail ? '作者与目录' : '社区动态'}
|
||||
title={isArticleAside ? articleAsideLabel : '社区动态'}
|
||||
>
|
||||
<PanelRight size={18} aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<button
|
||||
<button
|
||||
type="button"
|
||||
className="header-icon-btn"
|
||||
className="header-icon-btn header-theme-btn"
|
||||
onClick={toggle}
|
||||
aria-label={theme === 'light' ? '切换暗色模式' : '切换亮色模式'}
|
||||
title={theme === 'light' ? '切换暗色模式' : '切换亮色模式'}
|
||||
>
|
||||
{theme === 'light' ? <Moon size={18} aria-hidden /> : <Sun size={18} aria-hidden />}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{authLoading ? (
|
||||
<span className="header-auth-slot header-auth-slot--loading" aria-hidden />
|
||||
@@ -512,7 +667,7 @@ export default function MainLayout() {
|
||||
className="header-icon-btn header-msg-btn"
|
||||
title={unreadMessages > 0 ? `${unreadMessages} 条未读消息` : '站内消息'}
|
||||
aria-label={unreadMessages > 0 ? `站内消息,${unreadMessages} 条未读` : '站内消息'}
|
||||
onClick={() => nav('/messages')}
|
||||
onClick={() => void transitionTo(nav, '/messages')}
|
||||
>
|
||||
<Mail size={18} aria-hidden />
|
||||
{unreadMessages > 0 && (
|
||||
@@ -532,14 +687,14 @@ export default function MainLayout() {
|
||||
className="w-40"
|
||||
onCloseAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<DropdownMenuItem onClick={() => nav(userPath(user.id))}>个人主页</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => nav('/profile')}>
|
||||
<DropdownMenuItem onClick={() => void transitionTo(nav, userPath(user.id))}>个人主页</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => void transitionTo(nav, '/profile')}>
|
||||
账号设置{typeof user.points === 'number' ? ` · ${user.points} 积分` : ''}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => nav('/messages')}>
|
||||
<DropdownMenuItem onClick={() => void transitionTo(nav, '/messages')}>
|
||||
站内消息{unreadMessages > 0 ? ` (${unreadMessages})` : ''}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => nav('/favorites')}>我的收藏</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => void transitionTo(nav, '/favorites')}>我的收藏</DropdownMenuItem>
|
||||
{isMobile && (
|
||||
<DropdownMenuItem onClick={toggle}>
|
||||
{theme === 'light' ? '切换暗色模式' : '切换亮色模式'}
|
||||
@@ -585,12 +740,13 @@ export default function MainLayout() {
|
||||
)}
|
||||
|
||||
<div className={`app-body${isCompose ? ' app-body--compose' : ''}`}>
|
||||
{!isCompose && (
|
||||
{!isCompose && shellReady && (
|
||||
<Sidebar
|
||||
boards={boards}
|
||||
activeBoard={boardId}
|
||||
onSelectBoard={setBoardId}
|
||||
boardsLoading={boardsLoading}
|
||||
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -599,13 +755,16 @@ export default function MainLayout() {
|
||||
isCompose && 'content-workspace--compose',
|
||||
hideAside && !isCompose && 'content-workspace--aside-hidden',
|
||||
)}>
|
||||
<main className={cn(
|
||||
'main-content',
|
||||
isCompose && 'main-content--compose',
|
||||
// 手机 Feed:整栏滚动,板块条 / 排序栏可滚出视口,多露出帖子列表
|
||||
isMobile && !isCompose && isFeedHome && 'main-content--feed-mobile-scroll',
|
||||
)}>
|
||||
{isMobile && !isCompose && isFeedHome && (
|
||||
<main
|
||||
className={cn(
|
||||
'main-content',
|
||||
isCompose && 'main-content--compose',
|
||||
// 手机 Feed:整栏滚动,板块条 / 排序栏可滚出视口,多露出帖子列表
|
||||
isMobile && !isCompose && isFeedHome && 'main-content--feed-mobile-scroll',
|
||||
)}
|
||||
aria-busy={!shellReady}
|
||||
>
|
||||
{shellReady && isMobile && !isCompose && isFeedHome && (
|
||||
<div
|
||||
ref={boardBarRef}
|
||||
className="mobile-board-bar"
|
||||
@@ -643,13 +802,16 @@ export default function MainLayout() {
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<Suspense fallback={isFeedHome ? <FeedPageSkeleton /> : <PageLoader />}>
|
||||
<Outlet context={layoutCtx} />
|
||||
</Suspense>
|
||||
{shellReady ? (
|
||||
<Suspense fallback={null}>
|
||||
<Outlet context={layoutCtx} />
|
||||
</Suspense>
|
||||
) : null}
|
||||
</main>
|
||||
|
||||
{!isCompose && (
|
||||
<aside className="aside-panel">
|
||||
<aside className="aside-panel" aria-busy={!shellReady}>
|
||||
{shellReady && (
|
||||
<RightPanel
|
||||
recentComments={recentComments}
|
||||
recentUsers={recentUsers}
|
||||
@@ -659,7 +821,8 @@ export default function MainLayout() {
|
||||
loading={asideLoading}
|
||||
asideWidgets={asideWidgets}
|
||||
onPostClick={openPost}
|
||||
postDetail={isPostDetail ? {
|
||||
|
||||
postDetail={isArticleAside ? {
|
||||
author: postOutline?.author ?? null,
|
||||
publishedAt: postOutline?.publishedAt,
|
||||
viewCount: postOutline?.viewCount,
|
||||
@@ -668,6 +831,7 @@ export default function MainLayout() {
|
||||
outlineTitle: postOutline?.title,
|
||||
} : null}
|
||||
/>
|
||||
)}
|
||||
</aside>
|
||||
)}
|
||||
</div>
|
||||
@@ -707,12 +871,14 @@ export default function MainLayout() {
|
||||
</button>
|
||||
</div>
|
||||
<div className="aside-drawer-body sidebar-drawer-body">
|
||||
{shellReady && (
|
||||
<Sidebar
|
||||
boards={boards}
|
||||
activeBoard={boardId}
|
||||
onSelectBoard={setBoardId}
|
||||
boardsLoading={boardsLoading}
|
||||
/>
|
||||
)}
|
||||
<div className="sidebar-drawer-extras">
|
||||
<button
|
||||
type="button"
|
||||
@@ -720,7 +886,7 @@ export default function MainLayout() {
|
||||
onClick={() => { closeSidebar(); openAside(); }}
|
||||
>
|
||||
<PanelRight size={16} aria-hidden />
|
||||
{isPostDetail ? '作者与目录' : '社区动态'}
|
||||
{isArticleAside ? articleAsideLabel : '社区动态'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -751,10 +917,10 @@ export default function MainLayout() {
|
||||
className="aside-drawer"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={isPostDetail ? '作者与目录' : '社区动态'}
|
||||
aria-label={isArticleAside ? articleAsideLabel : '社区动态'}
|
||||
>
|
||||
<div className="aside-drawer-head">
|
||||
<span>{isPostDetail ? '作者与目录' : '社区动态'}</span>
|
||||
<span>{isArticleAside ? articleAsideLabel : '社区动态'}</span>
|
||||
<button
|
||||
ref={asideCloseRef}
|
||||
type="button"
|
||||
@@ -775,7 +941,7 @@ export default function MainLayout() {
|
||||
loading={asideLoading}
|
||||
asideWidgets={asideWidgets}
|
||||
onPostClick={openPost}
|
||||
postDetail={isPostDetail ? {
|
||||
postDetail={isArticleAside ? {
|
||||
author: postOutline?.author ?? null,
|
||||
publishedAt: postOutline?.publishedAt,
|
||||
viewCount: postOutline?.viewCount,
|
||||
|
||||
@@ -1,12 +1,96 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { hydrateRoot, createRoot } from 'react-dom/client';
|
||||
import { applyTheme, getStoredTheme } from './utils/theme';
|
||||
import App from './App';
|
||||
import { consumeHomeBoot } from './utils/homeBoot';
|
||||
import { beginHomeHydrate } from './utils/homeHydrate';
|
||||
import { reloadForStaleChunk } from './utils/chunkLoad';
|
||||
import { ensureColdBootReady, isMainLayoutPath } from './utils/prefetchRoute';
|
||||
|
||||
applyTheme(getStoredTheme());
|
||||
consumeHomeBoot();
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
// Vite modulepreload / 动态 import 失败(发版后旧 hashed URL 404)
|
||||
window.addEventListener('vite:preloadError', (event) => {
|
||||
event.preventDefault();
|
||||
reloadForStaleChunk();
|
||||
});
|
||||
|
||||
function hasSSRHome(): boolean {
|
||||
return !!document.querySelector('#root .ssr-home');
|
||||
}
|
||||
|
||||
function waitForStylesheets(): Promise<void> {
|
||||
const links = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));
|
||||
if (links.length === 0) return Promise.resolve();
|
||||
return Promise.all(
|
||||
links.map(
|
||||
(node) =>
|
||||
new Promise<void>((resolve) => {
|
||||
const link = node as HTMLLinkElement;
|
||||
try {
|
||||
if (link.sheet) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
/* cross-origin */
|
||||
}
|
||||
const finish = () => resolve();
|
||||
link.addEventListener('load', finish, { once: true });
|
||||
link.addEventListener('error', finish, { once: true });
|
||||
}),
|
||||
),
|
||||
).then(() => undefined);
|
||||
}
|
||||
|
||||
function renderApp() {
|
||||
return (
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
}
|
||||
|
||||
function mountCreateRoot(el: HTMLElement) {
|
||||
createRoot(el).render(renderApp());
|
||||
}
|
||||
|
||||
/** 有 SSR 正文:hydrate 接管同一 DOM;失败则回退 createRoot */
|
||||
function mountHydrateHome(el: HTMLElement) {
|
||||
beginHomeHydrate();
|
||||
try {
|
||||
hydrateRoot(el, renderApp());
|
||||
} catch (err) {
|
||||
console.warn('[j13] hydrateRoot 失败,回退 createRoot', err);
|
||||
el.innerHTML = '';
|
||||
mountCreateRoot(el);
|
||||
}
|
||||
}
|
||||
|
||||
async function boot() {
|
||||
const path = `${window.location.pathname}${window.location.search}`;
|
||||
const ssr = hasSSRHome();
|
||||
|
||||
await waitForStylesheets();
|
||||
try {
|
||||
if (document.fonts?.ready) await document.fonts.ready;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
if (isMainLayoutPath(window.location.pathname)) {
|
||||
await ensureColdBootReady(path);
|
||||
}
|
||||
|
||||
const root = document.getElementById('root');
|
||||
if (!root) return;
|
||||
|
||||
if (ssr) {
|
||||
mountHydrateHome(root);
|
||||
} else {
|
||||
mountCreateRoot(root);
|
||||
}
|
||||
}
|
||||
|
||||
void boot();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { ArrowLeft, Star } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -7,6 +7,7 @@ import { notify } from '@/lib/notify';
|
||||
import { api } from '../api/client';
|
||||
import type { PostItem } from '../api/types';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { useSessionResource } from '../hooks/useSessionResource';
|
||||
import PostListItem from '../components/PostListItem';
|
||||
import { loginPath } from '../utils/authRedirect';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
@@ -26,16 +27,19 @@ export default function FavoritesPage() {
|
||||
const { user, loading: authLoading } = useAuth();
|
||||
const { limits } = useForumLimits();
|
||||
useNoIndexSEO('我的收藏');
|
||||
const [list, setList] = useState<FavItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const { data: list = [], loading } = useSessionResource<FavItem[]>(
|
||||
user ? 'favorites' : null,
|
||||
() => api.favorites().then(d => (Array.isArray(d.favorites) ? d.favorites as FavItem[] : [])),
|
||||
{
|
||||
enabled: !!user && !authLoading,
|
||||
onError: (e) => notify.error(e instanceof Error ? e.message : '加载失败'),
|
||||
},
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (authLoading) return;
|
||||
if (!user) { nav(loginPath('/favorites')); return; }
|
||||
api.favorites()
|
||||
.then(d => setList(Array.isArray(d.favorites) ? d.favorites as FavItem[] : []))
|
||||
.catch(e => notify.error(e.message))
|
||||
.finally(() => setLoading(false));
|
||||
if (!user) nav(loginPath('/favorites'));
|
||||
}, [user, authLoading, nav]);
|
||||
|
||||
if (authLoading || loading) return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
|
||||
|
||||
@@ -1,25 +1,35 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useNavigate, useOutletContext, useSearchParams, useLocation, useParams } from 'react-router-dom';
|
||||
import { useState, useEffect, useCallback, useRef, useMemo, startTransition as reactStartTransition } from 'react';
|
||||
import {
|
||||
useNavigate,
|
||||
useOutletContext,
|
||||
useSearchParams,
|
||||
useLocation,
|
||||
useParams,
|
||||
useNavigationType,
|
||||
} from 'react-router-dom';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '../api/client';
|
||||
import type { PostItem } from '../api/types';
|
||||
import type { LayoutCtx } from '../layouts/MainLayout';
|
||||
import VirtualPostList from '../components/VirtualPostList';
|
||||
import StaticFeedList from '../components/StaticFeedList';
|
||||
import FeedHeader from '../components/FeedHeader';
|
||||
import FeedSearchFilters from '../components/search/FeedSearchFilters';
|
||||
import FeedPageSkeleton from '../components/FeedPageSkeleton';
|
||||
import FeedSortBar, { parseFeedSort, buildHomeUrl, type FeedSort } from '../components/FeedSortBar';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import { parseSearchFromUrl, usePostSearch } from '../hooks/usePostSearch';
|
||||
import {
|
||||
getFeedCache,
|
||||
setFeedCache,
|
||||
clearAllFeedCache,
|
||||
navigateFeed,
|
||||
FEED_RESET_EVENT,
|
||||
FEED_PULL_REFRESH_EVENT,
|
||||
type FeedNavState,
|
||||
} from '../utils/feedCache';
|
||||
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
|
||||
import { feedCacheKey, getHomeStoreState } from '../store/homeStore';
|
||||
import { enabledFeedSortTabs, getDefaultFeedSort } from '../utils/feedSortTabs';
|
||||
import { openForumPost } from '../utils/openPost';
|
||||
import { startTransition, doneTransition } from '../utils/spaTransition';
|
||||
import { isHomeHydrating } from '../utils/homeHydrate';
|
||||
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
|
||||
import { siteMetaDescription, useSiteBranding } from '../hooks/useSiteBranding';
|
||||
import { boardPath, canonicalRedirectPath, parsePermalinkID } from '../utils/permalink';
|
||||
@@ -35,9 +45,41 @@ function boardIdFromLocation(routeId: string | undefined, searchParams: URLSearc
|
||||
return q > 0 ? q : 0;
|
||||
}
|
||||
|
||||
type FeedHydrate = {
|
||||
posts: PostItem[];
|
||||
postTotal: number;
|
||||
page: number;
|
||||
scrollTop: number;
|
||||
loading: boolean;
|
||||
};
|
||||
|
||||
/** 首屏同步读取 Zustand,避免先骨架屏再恢复 */
|
||||
function readHydrate(
|
||||
boardId: number,
|
||||
keyword: string,
|
||||
sort: FeedSort,
|
||||
tag: string,
|
||||
author: string,
|
||||
titleOnly: boolean,
|
||||
): FeedHydrate {
|
||||
const key = feedCacheKey({ boardId, keyword, sort, tag, author, titleOnly });
|
||||
const cached = getHomeStoreState().getFeed(key);
|
||||
if (cached && cached.posts.length > 0) {
|
||||
return {
|
||||
posts: cached.posts,
|
||||
postTotal: cached.postTotal,
|
||||
page: cached.page,
|
||||
scrollTop: cached.scrollTop,
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
return { posts: [], postTotal: 0, page: 1, scrollTop: 0, loading: true };
|
||||
}
|
||||
|
||||
export default function HomePage() {
|
||||
const nav = useNavigate();
|
||||
const location = useLocation();
|
||||
const navType = useNavigationType();
|
||||
const { id: boardRouteId } = useParams();
|
||||
const [params] = useSearchParams();
|
||||
const ctx = useOutletContext<LayoutCtx>();
|
||||
@@ -56,7 +98,8 @@ export default function HomePage() {
|
||||
const tag = params.get('tag') || '';
|
||||
const author = params.get('author') || '';
|
||||
const titleOnly = params.get('title_only') === '1';
|
||||
const sort = parseFeedSort(params.get('sort'));
|
||||
const rawSort = params.get('sort');
|
||||
const sort = parseFeedSort(rawSort, limits.feed_sort_tabs);
|
||||
const board = (ctx?.boards ?? []).find(b => b.id === boardId);
|
||||
const isSiteHome = !boardId && !keyword && !tag && !author;
|
||||
const siteIntro = siteMetaDescription(branding);
|
||||
@@ -96,20 +139,117 @@ export default function HomePage() {
|
||||
}
|
||||
}, [queryBoardId, boardId, boardRouteId, params, nav, limits, location.pathname, location.search]);
|
||||
|
||||
const [posts, setPosts] = useState<PostItem[]>([]);
|
||||
const [postTotal, setPostTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [restoreScrollTop, setRestoreScrollTop] = useState<number | null>(null);
|
||||
const [listResetKey, setListResetKey] = useState(0);
|
||||
// URL 上的 sort 已被后台关闭时,纠正为默认排序
|
||||
useEffect(() => {
|
||||
if (limitsLoading) return;
|
||||
if (rawSort !== 'latest' && rawSort !== 'hot' && rawSort !== 'reply') return;
|
||||
const stillOn = enabledFeedSortTabs(limits.feed_sort_tabs).some(t => t.id === rawSort);
|
||||
if (stillOn) return;
|
||||
const def = getDefaultFeedSort(limits.feed_sort_tabs);
|
||||
nav(buildHomeUrl(boardId, def, { keyword, tag, author, titleOnly, permalink: limits }), { replace: true });
|
||||
}, [
|
||||
limitsLoading,
|
||||
limits.feed_sort_tabs,
|
||||
limits,
|
||||
rawSort,
|
||||
boardId,
|
||||
keyword,
|
||||
tag,
|
||||
author,
|
||||
titleOnly,
|
||||
nav,
|
||||
]);
|
||||
|
||||
const scrollTopRef = useRef(0);
|
||||
const skipCacheSaveRef = useRef(false);
|
||||
const loadingRef = useRef(false);
|
||||
const pageRef = useRef(1);
|
||||
const cacheKey = useMemo(
|
||||
() => feedCacheKey({ boardId, keyword, sort, tag, author, titleOnly }),
|
||||
[boardId, keyword, sort, tag, author, titleOnly],
|
||||
);
|
||||
|
||||
// 筛选键变化时同步水合(含首次挂载),保证第一帧就有列表数据
|
||||
const initial = useMemo(
|
||||
() => readHydrate(boardId, keyword, sort, tag, author, titleOnly),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随筛选键变化重置
|
||||
[cacheKey],
|
||||
);
|
||||
|
||||
const [posts, setPosts] = useState<PostItem[]>(initial.posts);
|
||||
const [postTotal, setPostTotal] = useState(initial.postTotal);
|
||||
const [page, setPage] = useState(initial.page);
|
||||
const [loading, setLoading] = useState(initial.loading);
|
||||
/** 画面上已提交的筛选(URL 已变但数据未到时仍画上一份) */
|
||||
const [view, setView] = useState({
|
||||
cacheKey,
|
||||
sort,
|
||||
boardId,
|
||||
keyword,
|
||||
tag,
|
||||
author,
|
||||
titleOnly,
|
||||
});
|
||||
const [listPending, setListPending] = useState(false);
|
||||
const [restoreScrollTop, setRestoreScrollTop] = useState<number | null>(
|
||||
initial.posts.length > 0 ? initial.scrollTop : null,
|
||||
);
|
||||
const [listResetKey, setListResetKey] = useState(0);
|
||||
/** hydrate 首帧用静态列表;完成后升级 VirtualPostList */
|
||||
const [useVirtualList, setUseVirtualList] = useState(() => !isHomeHydrating());
|
||||
|
||||
useEffect(() => {
|
||||
if (useVirtualList) return;
|
||||
reactStartTransition(() => setUseVirtualList(true));
|
||||
}, [useVirtualList]);
|
||||
|
||||
const scrollTopRef = useRef(initial.scrollTop);
|
||||
const fetchSeqRef = useRef(0);
|
||||
const pageRef = useRef(initial.page);
|
||||
const cacheKeyRef = useRef(cacheKey);
|
||||
const viewKeyRef = useRef(view.cacheKey);
|
||||
const postsRef = useRef(posts);
|
||||
const scrollRafRef = useRef(0);
|
||||
/** 当前筛选键是否已完成「进入页」水合(避免 effect 重跑时反复 setRestoreScrollTop) */
|
||||
const hydratedKeyRef = useRef<string | null>(null);
|
||||
/** 强制刷新已发起 loadFirst:消费 refreshFeed 后 effect 再跑时勿因空缓存重复请求 */
|
||||
const refreshFetchKeyRef = useRef<string | null>(null);
|
||||
pageRef.current = page;
|
||||
// 与当前筛选一致的列表快照(供卸载/切换筛选时写入缓存)
|
||||
const feedSnapRef = useRef({ boardId, keyword, tag, author, titleOnly, sort, posts, postTotal, page });
|
||||
cacheKeyRef.current = cacheKey;
|
||||
viewKeyRef.current = view.cacheKey;
|
||||
postsRef.current = posts;
|
||||
|
||||
const commitDisplayed = useCallback((
|
||||
next: FeedHydrate,
|
||||
meta: { cacheKey: string; sort: FeedSort; boardId: number; keyword: string; tag: string; author: string; titleOnly: boolean },
|
||||
) => {
|
||||
setPosts(next.posts);
|
||||
setPostTotal(next.postTotal);
|
||||
setPage(next.page);
|
||||
pageRef.current = next.page;
|
||||
scrollTopRef.current = next.scrollTop;
|
||||
setRestoreScrollTop(next.posts.length > 0 ? next.scrollTop : null);
|
||||
setLoading(next.loading);
|
||||
setListPending(false);
|
||||
setView(meta);
|
||||
}, []);
|
||||
|
||||
// 筛选键切换:有快照则立刻换页;否则保留当前画面等请求结束
|
||||
useEffect(() => {
|
||||
if ((location.state as FeedNavState | null)?.refreshFeed && navType !== 'POP') {
|
||||
hydratedKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
const next = readHydrate(boardId, keyword, sort, tag, author, titleOnly);
|
||||
if (next.posts.length > 0) {
|
||||
hydratedKeyRef.current = cacheKey;
|
||||
commitDisplayed(next, { cacheKey, sort, boardId, keyword, tag, author, titleOnly });
|
||||
return;
|
||||
}
|
||||
hydratedKeyRef.current = null;
|
||||
if (postsRef.current.length > 0) {
|
||||
setListPending(true);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
commitDisplayed(next, { cacheKey, sort, boardId, keyword, tag, author, titleOnly });
|
||||
}, [cacheKey, boardId, keyword, sort, tag, author, titleOnly, commitDisplayed, location.state, navType]);
|
||||
|
||||
const totalPages = Math.max(1, Math.ceil(Math.max(postTotal, 0) / pageSize));
|
||||
const showPagination = totalPages > 1 && posts.length > 0;
|
||||
@@ -121,16 +261,39 @@ export default function HomePage() {
|
||||
setListResetKey(k => k + 1);
|
||||
}, []);
|
||||
|
||||
/** 同筛选强制刷新:只复位滚动,保留旧列表直到 loadFirst 覆盖 */
|
||||
const beginFeedRefresh = useCallback(() => {
|
||||
skipCacheSaveRef.current = true;
|
||||
clearAllFeedCache();
|
||||
resetFeedView();
|
||||
}, [resetFeedView]);
|
||||
|
||||
const fetchPage = useCallback(async (p: number) => {
|
||||
if (loadingRef.current) return;
|
||||
loadingRef.current = true;
|
||||
setLoading(true);
|
||||
/** 把当前列表写入 Zustand(滚动位置用 ref,避免闭包过期) */
|
||||
const persistFeed = useCallback((
|
||||
nextPosts: PostItem[],
|
||||
nextTotal: number,
|
||||
nextPage: number,
|
||||
opts?: { scrollTop?: number; touchFetchTime?: boolean; key?: string },
|
||||
) => {
|
||||
const key = opts?.key ?? cacheKeyRef.current;
|
||||
const prev = getHomeStoreState().getFeed(key);
|
||||
getHomeStoreState().setFeed(key, {
|
||||
posts: nextPosts,
|
||||
postTotal: nextTotal,
|
||||
page: nextPage,
|
||||
scrollTop: opts?.scrollTop ?? scrollTopRef.current,
|
||||
lastFetchTime: opts?.touchFetchTime === false
|
||||
? (prev?.lastFetchTime ?? Date.now())
|
||||
: Date.now(),
|
||||
});
|
||||
}, []);
|
||||
|
||||
const fetchPage = useCallback(async (p: number, opts?: { silent?: boolean; resetScroll?: boolean }) => {
|
||||
const seq = ++fetchSeqRef.current;
|
||||
const requestKey = cacheKeyRef.current;
|
||||
const silent = !!opts?.silent;
|
||||
const keepView = postsRef.current.length > 0;
|
||||
// 有旧列表时不卸页,只标 pending
|
||||
if (!silent && !keepView) setLoading(true);
|
||||
if (!silent && keepView) setListPending(true);
|
||||
try {
|
||||
const data = await api.posts({
|
||||
page: p,
|
||||
@@ -140,144 +303,229 @@ export default function HomePage() {
|
||||
tag: tag || '',
|
||||
author: tag ? '' : author,
|
||||
title_only: !tag && titleOnly ? '1' : '',
|
||||
sort: sort === 'latest' ? '' : sort,
|
||||
sort,
|
||||
});
|
||||
if (seq !== fetchSeqRef.current) return;
|
||||
const batch = Array.isArray(data.posts) ? data.posts : [];
|
||||
const total = data.total ?? 0;
|
||||
const jumpTop = opts?.resetScroll || (keepView && requestKey !== viewKeyRef.current);
|
||||
const scrollTop = jumpTop ? 0 : scrollTopRef.current;
|
||||
if (jumpTop) {
|
||||
setRestoreScrollTop(null);
|
||||
scrollTopRef.current = 0;
|
||||
setListResetKey(k => k + 1);
|
||||
}
|
||||
setPosts(batch);
|
||||
setPostTotal(total);
|
||||
setPage(p);
|
||||
pageRef.current = p;
|
||||
setView({ cacheKey: requestKey, sort, boardId, keyword, tag, author, titleOnly });
|
||||
persistFeed(batch, total, p, { scrollTop, touchFetchTime: true, key: requestKey });
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '加载失败');
|
||||
setPosts([]);
|
||||
setPostTotal(0);
|
||||
setPage(1);
|
||||
pageRef.current = 1;
|
||||
if (seq !== fetchSeqRef.current) return;
|
||||
if (!silent) {
|
||||
notify.error(e instanceof Error ? e.message : '加载失败');
|
||||
if (!keepView) {
|
||||
setPosts([]);
|
||||
setPostTotal(0);
|
||||
setPage(1);
|
||||
pageRef.current = 1;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
loadingRef.current = false;
|
||||
setLoading(false);
|
||||
if (seq === fetchSeqRef.current) {
|
||||
setLoading(false);
|
||||
setListPending(false);
|
||||
}
|
||||
}
|
||||
}, [boardId, keyword, tag, author, titleOnly, sort, pageSize]);
|
||||
}, [boardId, keyword, tag, author, titleOnly, sort, pageSize, persistFeed]);
|
||||
|
||||
const loadFirst = useCallback(() => fetchPage(1), [fetchPage]);
|
||||
const loadFirst = useCallback((opts?: { resetScroll?: boolean }) => (
|
||||
fetchPage(1, { resetScroll: opts?.resetScroll })
|
||||
), [fetchPage]);
|
||||
|
||||
const goToPage = useCallback((p: number) => {
|
||||
if (loadingRef.current) return;
|
||||
const maxPage = Math.max(1, Math.ceil(Math.max(postTotal, 0) / pageSize));
|
||||
if (p < 1 || p > maxPage) return;
|
||||
if (p === pageRef.current) return;
|
||||
resetFeedView();
|
||||
fetchPage(p);
|
||||
}, [fetchPage, postTotal, pageSize, resetFeedView]);
|
||||
void fetchPage(p, { resetScroll: true });
|
||||
}, [fetchPage, postTotal, pageSize]);
|
||||
|
||||
const handleSelectPost = useCallback((id: number) => {
|
||||
// 离开前再写一次滚动,确保详情页返回可还原
|
||||
getHomeStoreState().patchScroll(viewKeyRef.current, scrollTopRef.current);
|
||||
openForumPost(nav, id, limits.open_posts_in_new_tab);
|
||||
}, [nav, limits.open_posts_in_new_tab]);
|
||||
|
||||
// 等限制就绪后再拉列表;筛选变化时重载
|
||||
// 等限制就绪后再决定:强制刷新 / 用缓存 / 静默刷新 / 首拉
|
||||
useEffect(() => {
|
||||
if (limitsLoading || isInvalidBoardRoute || isMissingBoard) return;
|
||||
|
||||
const forceRefresh = (location.state as FeedNavState | null)?.refreshFeed;
|
||||
if (forceRefresh) {
|
||||
beginFeedRefresh();
|
||||
loadFirst();
|
||||
// 浏览器后退/前进(POP)忽略 history 上残留的 refreshFeed,避免误清空缓存
|
||||
if (forceRefresh && navType !== 'POP') {
|
||||
fetchSeqRef.current += 1;
|
||||
hydratedKeyRef.current = cacheKey;
|
||||
refreshFetchKeyRef.current = cacheKey;
|
||||
// 排序等强制刷新:丢弃该键旧分页/滚动,置顶重拉第 1 页
|
||||
getHomeStoreState().clearFeed(cacheKey);
|
||||
resetFeedView();
|
||||
setListPending(postsRef.current.length > 0);
|
||||
if (postsRef.current.length === 0) setLoading(true);
|
||||
setView({ cacheKey, sort, boardId, keyword, tag, author, titleOnly });
|
||||
void loadFirst({ resetScroll: true });
|
||||
// 消费后清掉 state,防止该 history 条目永远带着刷新标记
|
||||
nav(`${location.pathname}${location.search}${location.hash}`, { replace: true, state: null });
|
||||
return;
|
||||
}
|
||||
|
||||
const cached = getFeedCache(boardId, keyword, sort, tag, author, titleOnly);
|
||||
// POP 带回 refreshFeed 时也清掉,避免下次同条目再误触发
|
||||
if (forceRefresh && navType === 'POP') {
|
||||
nav(`${location.pathname}${location.search}${location.hash}`, { replace: true, state: null });
|
||||
}
|
||||
|
||||
// 刚强制刷新并清缓存:跳过随后因 state 清空触发的空缓存首拉
|
||||
if (refreshFetchKeyRef.current === cacheKey) {
|
||||
refreshFetchKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const cached = getHomeStoreState().getFeed(cacheKey);
|
||||
if (cached && cached.posts.length > 0) {
|
||||
setPosts(cached.posts);
|
||||
setPostTotal(cached.postTotal);
|
||||
setPage(cached.page);
|
||||
pageRef.current = cached.page;
|
||||
setRestoreScrollTop(cached.scrollTop);
|
||||
scrollTopRef.current = cached.scrollTop;
|
||||
setLoading(false);
|
||||
const needRestore = hydratedKeyRef.current !== cacheKey;
|
||||
hydratedKeyRef.current = cacheKey;
|
||||
if (needRestore) {
|
||||
commitDisplayed({
|
||||
posts: cached.posts,
|
||||
postTotal: cached.postTotal,
|
||||
page: cached.page,
|
||||
scrollTop: cached.scrollTop,
|
||||
loading: false,
|
||||
}, { cacheKey, sort, boardId, keyword, tag, author, titleOnly });
|
||||
} else {
|
||||
setPosts(cached.posts);
|
||||
setPostTotal(cached.postTotal);
|
||||
setPage(cached.page);
|
||||
pageRef.current = cached.page;
|
||||
setLoading(false);
|
||||
setListPending(false);
|
||||
setView({ cacheKey, sort, boardId, keyword, tag, author, titleOnly });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setRestoreScrollTop(null);
|
||||
scrollTopRef.current = 0;
|
||||
hydratedKeyRef.current = cacheKey;
|
||||
if (postsRef.current.length === 0) {
|
||||
setRestoreScrollTop(null);
|
||||
scrollTopRef.current = 0;
|
||||
}
|
||||
loadFirst();
|
||||
}, [
|
||||
limitsLoading,
|
||||
pageSize,
|
||||
cacheKey,
|
||||
location.key,
|
||||
location.state,
|
||||
location.pathname,
|
||||
location.search,
|
||||
location.hash,
|
||||
navType,
|
||||
nav,
|
||||
loadFirst,
|
||||
commitDisplayed,
|
||||
resetFeedView,
|
||||
isInvalidBoardRoute,
|
||||
isMissingBoard,
|
||||
sort,
|
||||
boardId,
|
||||
keyword,
|
||||
tag,
|
||||
author,
|
||||
titleOnly,
|
||||
sort,
|
||||
location.key,
|
||||
location.state,
|
||||
loadFirst,
|
||||
beginFeedRefresh,
|
||||
isInvalidBoardRoute,
|
||||
isMissingBoard,
|
||||
]);
|
||||
|
||||
// 筛选未变时同步列表快照;变筛选的那一帧先保留旧快照供 cleanup 写入
|
||||
if (
|
||||
feedSnapRef.current.boardId === boardId
|
||||
&& feedSnapRef.current.keyword === keyword
|
||||
&& feedSnapRef.current.tag === tag
|
||||
&& feedSnapRef.current.author === author
|
||||
&& feedSnapRef.current.titleOnly === titleOnly
|
||||
&& feedSnapRef.current.sort === sort
|
||||
) {
|
||||
feedSnapRef.current = { boardId, keyword, tag, author, titleOnly, sort, posts, postTotal, page };
|
||||
}
|
||||
|
||||
// 仅在筛选变化 / 卸载时缓存;勿把 posts 放进 deps(否则会用旧列表污染新 keyword)
|
||||
useEffect(() => {
|
||||
// cleanup 先保存上一档;再把快照重置为当前筛选的空占位
|
||||
feedSnapRef.current = { boardId, keyword, tag, author, titleOnly, sort, posts: [], postTotal: 0, page: 1 };
|
||||
return () => {
|
||||
if (skipCacheSaveRef.current) return;
|
||||
const snap = feedSnapRef.current;
|
||||
if (snap.posts.length === 0) return;
|
||||
setFeedCache(snap.boardId, snap.keyword, snap.sort, {
|
||||
posts: snap.posts,
|
||||
postTotal: snap.postTotal,
|
||||
page: snap.page,
|
||||
scrollTop: scrollTopRef.current,
|
||||
}, snap.tag, snap.author, snap.titleOnly);
|
||||
// Logo 等同 URL 强制刷新:仅复位滚动,不卸列表(数据由 transitionTo 预热)
|
||||
const onFeedReset = () => {
|
||||
fetchSeqRef.current += 1;
|
||||
resetFeedView();
|
||||
};
|
||||
}, [boardId, keyword, tag, author, titleOnly, sort]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!loading && posts.length > 0) skipCacheSaveRef.current = false;
|
||||
}, [loading, posts.length]);
|
||||
|
||||
useEffect(() => {
|
||||
const onFeedReset = () => beginFeedRefresh();
|
||||
window.addEventListener(FEED_RESET_EVENT, onFeedReset);
|
||||
return () => window.removeEventListener(FEED_RESET_EVENT, onFeedReset);
|
||||
}, [beginFeedRefresh]);
|
||||
}, [resetFeedView]);
|
||||
|
||||
useEffect(() => {
|
||||
const fn = () => {
|
||||
beginFeedRefresh();
|
||||
loadFirst();
|
||||
// 下拉 / posts-refresh / 软刷新 commit:有预热则一次覆盖;禁止先卸列表
|
||||
const applyWarmOrReload = () => {
|
||||
fetchSeqRef.current += 1;
|
||||
const key = cacheKeyRef.current;
|
||||
const warm = getHomeStoreState().getFeed(key);
|
||||
if (warm && warm.posts.length > 0) {
|
||||
// 先写入新数据,再复位滚动(避免先 reset 造成空白闪一下)
|
||||
commitDisplayed({
|
||||
posts: warm.posts,
|
||||
postTotal: warm.postTotal,
|
||||
page: warm.page,
|
||||
scrollTop: 0,
|
||||
loading: false,
|
||||
}, { cacheKey: key, sort, boardId, keyword, tag, author, titleOnly });
|
||||
setListResetKey((k) => k + 1);
|
||||
return;
|
||||
}
|
||||
// 未命中:保留旧 posts,静默重拉
|
||||
if (postsRef.current.length > 0) {
|
||||
setListPending(true);
|
||||
setLoading(false);
|
||||
void loadFirst();
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
void loadFirst();
|
||||
};
|
||||
window.addEventListener('posts-refresh', fn);
|
||||
return () => window.removeEventListener('posts-refresh', fn);
|
||||
}, [beginFeedRefresh, loadFirst]);
|
||||
window.addEventListener('posts-refresh', applyWarmOrReload);
|
||||
window.addEventListener(FEED_PULL_REFRESH_EVENT, applyWarmOrReload);
|
||||
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, applyWarmOrReload);
|
||||
return () => {
|
||||
window.removeEventListener('posts-refresh', applyWarmOrReload);
|
||||
window.removeEventListener(FEED_PULL_REFRESH_EVENT, applyWarmOrReload);
|
||||
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, applyWarmOrReload);
|
||||
};
|
||||
}, [
|
||||
commitDisplayed, loadFirst,
|
||||
sort, boardId, keyword, tag, author, titleOnly,
|
||||
]);
|
||||
|
||||
// 卸载时取消未执行的 scroll rAF
|
||||
useEffect(() => () => {
|
||||
if (scrollRafRef.current) cancelAnimationFrame(scrollRafRef.current);
|
||||
}, []);
|
||||
|
||||
const handleScrollTopChange = useCallback((top: number) => {
|
||||
scrollTopRef.current = top;
|
||||
// rAF 节流写入 store,避免每个 scroll 事件都触发订阅者
|
||||
if (scrollRafRef.current) return;
|
||||
scrollRafRef.current = requestAnimationFrame(() => {
|
||||
scrollRafRef.current = 0;
|
||||
getHomeStoreState().patchScroll(viewKeyRef.current, scrollTopRef.current);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSortChange = (next: FeedSort) => {
|
||||
const url = buildHomeUrl(boardId, next, { keyword, tag, author, titleOnly, permalink: limits });
|
||||
// 排序标签:一律强制刷新到第 1 页顶部,不恢复浏览进度
|
||||
if (next === sort) {
|
||||
const tid = startTransition();
|
||||
getHomeStoreState().clearFeed(cacheKeyRef.current);
|
||||
beginFeedRefresh();
|
||||
loadFirst();
|
||||
void Promise.resolve(loadFirst({ resetScroll: true })).finally(() => doneTransition(tid));
|
||||
return;
|
||||
}
|
||||
navigateFeed(nav, buildHomeUrl(boardId, next, { keyword, tag, author, titleOnly, permalink: limits }));
|
||||
navigateFeed(nav, url, { refresh: true });
|
||||
};
|
||||
|
||||
const showSortBar = !keyword && !tag && !author;
|
||||
const showSortBar = !view.keyword && !view.tag && !view.author;
|
||||
const searchFilters = parseSearchFromUrl(location.pathname, params);
|
||||
const isSearchActive = !!(keyword || author);
|
||||
const isSearchActive = !!(view.keyword || view.author);
|
||||
|
||||
if (isInvalidBoardRoute || isMissingBoard) {
|
||||
return (
|
||||
@@ -288,9 +536,9 @@ export default function HomePage() {
|
||||
);
|
||||
}
|
||||
|
||||
// 首屏用同构骨架,避免标题/列表分区先后出现造成闪动
|
||||
// 冷启动由门闩 / ensureColdBootReady 挡住;有旧列表时软刷新绝不卸空
|
||||
if ((loading || limitsLoading || (isBoardRoute && boardsLoading)) && posts.length === 0) {
|
||||
return <FeedPageSkeleton />;
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -298,15 +546,32 @@ export default function HomePage() {
|
||||
<div className="feed-panel">
|
||||
<div className="feed-top">
|
||||
<div className="feed-top__bar">
|
||||
<FeedHeader
|
||||
keyword={keyword}
|
||||
tag={tag}
|
||||
author={author}
|
||||
postTotal={postTotal}
|
||||
titleAs={isSiteHome ? 'h2' : 'h1'}
|
||||
/>
|
||||
{!useVirtualList ? (
|
||||
(view.keyword || view.tag || view.author) ? (
|
||||
<h1 className="feed-header-title">
|
||||
{view.tag
|
||||
? `#${view.tag}`
|
||||
: view.keyword
|
||||
? `搜索:${view.keyword}`
|
||||
: `作者:${view.author}`}
|
||||
</h1>
|
||||
) : null
|
||||
) : (
|
||||
<FeedHeader
|
||||
keyword={view.keyword}
|
||||
tag={view.tag}
|
||||
author={view.author}
|
||||
postTotal={postTotal}
|
||||
titleAs={isSiteHome ? 'h2' : 'h1'}
|
||||
/>
|
||||
)}
|
||||
{showSortBar && (
|
||||
<FeedSortBar value={sort} onChange={handleSortChange} postTotal={postTotal} />
|
||||
<FeedSortBar
|
||||
value={view.sort}
|
||||
pendingValue={listPending ? sort : null}
|
||||
onChange={handleSortChange}
|
||||
postTotal={postTotal}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{isSearchActive && (
|
||||
@@ -318,32 +583,36 @@ export default function HomePage() {
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<VirtualPostList
|
||||
posts={posts}
|
||||
sort={sort}
|
||||
loading={loading || limitsLoading}
|
||||
hasMore={hasMore}
|
||||
showPagination={showPagination}
|
||||
page={page}
|
||||
totalPages={totalPages}
|
||||
postTotal={postTotal}
|
||||
onPageChange={goToPage}
|
||||
onSelect={handleSelectPost}
|
||||
restoreScrollTop={restoreScrollTop}
|
||||
resetScrollKey={listResetKey}
|
||||
onScrollTopChange={(top) => { scrollTopRef.current = top; }}
|
||||
onScrollRestored={() => setRestoreScrollTop(null)}
|
||||
keyword={keyword || tag || author}
|
||||
isSearchMode={!!(keyword || author)}
|
||||
searchKeyword={keyword}
|
||||
searchAuthor={author}
|
||||
searchTitleOnly={titleOnly}
|
||||
searchScopeBoardId={searchFilters.scopeBoardId}
|
||||
onClearSearch={postSearch.clearSearch}
|
||||
boardId={boardId}
|
||||
boardName={ctx?.boards?.find(b => b.id === boardId)?.name || ''}
|
||||
noBoards={!ctx?.boardsLoading && (ctx?.boards?.length ?? 0) === 0}
|
||||
/>
|
||||
{!useVirtualList ? (
|
||||
<StaticFeedList posts={posts} sort={view.sort} boardId={view.boardId} />
|
||||
) : (
|
||||
<VirtualPostList
|
||||
posts={posts}
|
||||
sort={view.sort}
|
||||
loading={listPending ? false : (loading || limitsLoading)}
|
||||
hasMore={hasMore}
|
||||
showPagination={showPagination}
|
||||
page={page}
|
||||
totalPages={totalPages}
|
||||
postTotal={postTotal}
|
||||
onPageChange={goToPage}
|
||||
onSelect={handleSelectPost}
|
||||
restoreScrollTop={restoreScrollTop}
|
||||
resetScrollKey={listResetKey}
|
||||
onScrollTopChange={handleScrollTopChange}
|
||||
onScrollRestored={() => setRestoreScrollTop(null)}
|
||||
keyword={view.keyword || view.tag || view.author}
|
||||
isSearchMode={!!(view.keyword || view.author)}
|
||||
searchKeyword={view.keyword}
|
||||
searchAuthor={view.author}
|
||||
searchTitleOnly={view.titleOnly}
|
||||
searchScopeBoardId={searchFilters.scopeBoardId}
|
||||
onClearSearch={postSearch.clearSearch}
|
||||
boardId={view.boardId}
|
||||
boardName={ctx?.boards?.find(b => b.id === view.boardId)?.name || ''}
|
||||
noBoards={!ctx?.boardsLoading && (ctx?.boards?.length ?? 0) === 0}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -15,6 +15,7 @@ import { loginPath } from '../utils/authRedirect';
|
||||
import { resolveFriendLinkLogo, isReciprocalChecking, reciprocalStatusLabel } from '../utils/friendLink';
|
||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||
import FriendLinkApplyDialog from '../components/FriendLinkApplyDialog';
|
||||
import { useSessionResource } from '../hooks/useSessionResource';
|
||||
|
||||
const APPLY_STATUS_ORDER: Record<FriendLinkApply['status'], number> = {
|
||||
pending: 0,
|
||||
@@ -48,8 +49,6 @@ export default function LinksPage() {
|
||||
const { user } = useAuth();
|
||||
const [applyOpen, setApplyOpen] = useState(false);
|
||||
const [editApply, setEditApply] = useState<FriendLinkApply | null>(null);
|
||||
const [myApplies, setMyApplies] = useState<FriendLinkApply[]>([]);
|
||||
const [myLoading, setMyLoading] = useState(false);
|
||||
const [cancelingId, setCancelingId] = useState<number | null>(null);
|
||||
|
||||
usePageSEO({
|
||||
@@ -63,6 +62,15 @@ export default function LinksPage() {
|
||||
(l: FriendLink) => l.name?.trim() && l.url?.trim(),
|
||||
);
|
||||
|
||||
const { data: myApplies = [], loading: myLoading, replace: setMyApplies } = useSessionResource<FriendLinkApply[]>(
|
||||
user ? 'links:applies' : null,
|
||||
() => api.myFriendLinkApplies().then(r => r.applies ?? []),
|
||||
{
|
||||
enabled: !!user,
|
||||
onError: (e) => notify.error(e instanceof Error ? e.message : '加载失败'),
|
||||
},
|
||||
);
|
||||
|
||||
const sortedApplies = useMemo(
|
||||
() => [...myApplies].sort((a, b) => {
|
||||
const byStatus = APPLY_STATUS_ORDER[a.status] - APPLY_STATUS_ORDER[b.status];
|
||||
@@ -98,16 +106,10 @@ export default function LinksPage() {
|
||||
setMyApplies([]);
|
||||
return;
|
||||
}
|
||||
setMyLoading(true);
|
||||
api.myFriendLinkApplies()
|
||||
.then(r => setMyApplies(r.applies ?? []))
|
||||
.catch(e => notify.error(e instanceof Error ? e.message : '加载失败'))
|
||||
.finally(() => setMyLoading(false));
|
||||
}, [user]);
|
||||
|
||||
useEffect(() => {
|
||||
loadMyApplies();
|
||||
}, [loadMyApplies]);
|
||||
.catch(e => notify.error(e instanceof Error ? e.message : '加载失败'));
|
||||
}, [user, setMyApplies]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user || !myApplies.some(isReciprocalChecking)) return;
|
||||
|
||||
@@ -14,8 +14,14 @@ import { postPath } from '../utils/permalink';
|
||||
import { userPath } from '../utils/userPath';
|
||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { getSessionSnapshot, setSessionSnapshot, deleteSessionSnapshot } from '../utils/sessionPageCache';
|
||||
import { PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
|
||||
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
|
||||
|
||||
type MsgTab = 'dm' | 'notify';
|
||||
type ConvSnap = { conversations: MessageConversation[]; total: number; page: number };
|
||||
type NotifySnap = { notifications: PrivateMessage[]; total: number; page: number };
|
||||
type ThreadSnap = { messages: PrivateMessage[]; total: number; peerUser: User | null };
|
||||
|
||||
const NOTIFY_KINDS = [
|
||||
{ key: 'all', label: '全部' },
|
||||
@@ -136,11 +142,28 @@ export default function MessagesPage() {
|
||||
}, []);
|
||||
|
||||
const loadConversations = useCallback(async (page = 1, append = false) => {
|
||||
const key = `messages:conv:${page}`;
|
||||
if (!append) {
|
||||
const hit = getSessionSnapshot<ConvSnap>(key);
|
||||
if (hit) {
|
||||
setConversations(hit.conversations);
|
||||
setConvTotal(hit.total);
|
||||
setConvPage(hit.page);
|
||||
setListLoading(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setListLoading(true);
|
||||
try {
|
||||
const r = await api.messageConversations({ page, size: 30 });
|
||||
const next = r.conversations || [];
|
||||
setConversations((prev) => (append ? [...prev, ...next] : next));
|
||||
setConversations((prev) => {
|
||||
const merged = append ? [...prev, ...next] : next;
|
||||
if (!append) {
|
||||
setSessionSnapshot(key, { conversations: merged, total: r.total || 0, page: r.page || page });
|
||||
}
|
||||
return merged;
|
||||
});
|
||||
setConvTotal(r.total || 0);
|
||||
setConvPage(r.page || page);
|
||||
} catch (e: unknown) {
|
||||
@@ -151,6 +174,17 @@ export default function MessagesPage() {
|
||||
}, []);
|
||||
|
||||
const loadNotifications = useCallback(async (page = 1, append = false, kind = 'all') => {
|
||||
const key = `messages:notify:${kind}:${page}`;
|
||||
if (!append) {
|
||||
const hit = getSessionSnapshot<NotifySnap>(key);
|
||||
if (hit) {
|
||||
setNotifications(hit.notifications);
|
||||
setNotifyTotal(hit.total);
|
||||
setNotifyPage(hit.page);
|
||||
setNotifyLoading(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setNotifyLoading(true);
|
||||
try {
|
||||
const r = await api.messageNotifications({
|
||||
@@ -164,7 +198,9 @@ export default function MessagesPage() {
|
||||
// 打开通知页时标已读(首屏)
|
||||
if (!append && page === 1) {
|
||||
await api.markNotificationsRead().catch(() => undefined);
|
||||
setNotifications(next.map((m) => ({ ...m, is_read: true })));
|
||||
const marked = next.map((m) => ({ ...m, is_read: true }));
|
||||
setNotifications(marked);
|
||||
setSessionSnapshot(key, { notifications: marked, total: r.total || 0, page: r.page || page });
|
||||
setNotifyUnread(0);
|
||||
window.dispatchEvent(new Event('messages-unread-refresh'));
|
||||
} else {
|
||||
@@ -177,20 +213,47 @@ export default function MessagesPage() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const [threadEpoch, setThreadEpoch] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (authLoading) return;
|
||||
if (!user) {
|
||||
nav(loginPath('/messages'));
|
||||
return;
|
||||
}
|
||||
void refreshUnreadSplit();
|
||||
if (tab === 'dm') {
|
||||
if (!getSessionSnapshot('messages:conv:1')) void refreshUnreadSplit();
|
||||
loadConversations(1);
|
||||
} else {
|
||||
if (!getSessionSnapshot(`messages:notify:${notifyKind}:1`)) void refreshUnreadSplit();
|
||||
loadNotifications(1, false, notifyKind);
|
||||
}
|
||||
}, [user, authLoading, nav, tab, notifyKind, loadConversations, loadNotifications, refreshUnreadSplit]);
|
||||
|
||||
useEffect(() => {
|
||||
const onForce = () => {
|
||||
// 下拉预热会话列表后直接重读;线程快照需作废以便重拉
|
||||
void refreshUnreadSplit();
|
||||
if (tab === 'dm') {
|
||||
void loadConversations(1);
|
||||
if (peerSelected && selectedPeer !== null) {
|
||||
deleteSessionSnapshot(`messages:thread:${selectedPeer}`);
|
||||
setThreadEpoch(n => n + 1);
|
||||
}
|
||||
} else {
|
||||
// 通知列表:预热未覆盖 kind,作废后重拉
|
||||
deleteSessionSnapshot(`messages:notify:${notifyKind}:1`);
|
||||
void loadNotifications(1, false, notifyKind);
|
||||
}
|
||||
};
|
||||
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onForce);
|
||||
return () => {
|
||||
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onForce);
|
||||
};
|
||||
}, [tab, notifyKind, peerSelected, selectedPeer, loadConversations, loadNotifications, refreshUnreadSplit]);
|
||||
|
||||
const scrollToBottom = useCallback((smooth = false) => {
|
||||
requestAnimationFrame(() => {
|
||||
threadEndRef.current?.scrollIntoView({ behavior: smooth ? 'smooth' : 'auto', block: 'end' });
|
||||
@@ -204,15 +267,30 @@ export default function MessagesPage() {
|
||||
setMsgTotal(0);
|
||||
return;
|
||||
}
|
||||
const cached = getSessionSnapshot<ThreadSnap>(`messages:thread:${selectedPeer}`);
|
||||
if (cached) {
|
||||
setMessages(cached.messages);
|
||||
setMsgTotal(cached.total);
|
||||
setPeerUser(cached.peerUser);
|
||||
setThreadLoading(false);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
setThreadLoading(true);
|
||||
stickToBottomRef.current = true;
|
||||
api.conversationMessages(selectedPeer, { size: 50 })
|
||||
.then((r) => {
|
||||
if (cancelled) return;
|
||||
setMessages(r.messages || []);
|
||||
const messages = r.messages || [];
|
||||
const peer = r.peer_user || null;
|
||||
setMessages(messages);
|
||||
setMsgTotal(r.total || 0);
|
||||
setPeerUser(r.peer_user || null);
|
||||
setPeerUser(peer);
|
||||
setSessionSnapshot(`messages:thread:${selectedPeer}`, {
|
||||
messages,
|
||||
total: r.total || 0,
|
||||
peerUser: peer,
|
||||
});
|
||||
setConversations((prev) => prev.map((c) => (
|
||||
c.peer_user_id === selectedPeer ? { ...c, unread_count: 0 } : c
|
||||
)));
|
||||
@@ -226,7 +304,7 @@ export default function MessagesPage() {
|
||||
if (!cancelled) setThreadLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [user, peerSelected, selectedPeer, refreshUnreadSplit]);
|
||||
}, [user, peerSelected, selectedPeer, refreshUnreadSplit, threadEpoch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!threadLoading && stickToBottomRef.current) {
|
||||
@@ -321,7 +399,17 @@ export default function MessagesPage() {
|
||||
try {
|
||||
const r = await api.sendMessage({ to_user_id: selectedPeer, content });
|
||||
stickToBottomRef.current = true;
|
||||
setMessages((prev) => [...prev, r.message]);
|
||||
setMessages((prev) => {
|
||||
const next = [...prev, r.message];
|
||||
if (selectedPeer != null) {
|
||||
setSessionSnapshot(`messages:thread:${selectedPeer}`, {
|
||||
messages: next,
|
||||
total: msgTotal + 1,
|
||||
peerUser,
|
||||
});
|
||||
}
|
||||
return next;
|
||||
});
|
||||
setMsgTotal((n) => n + 1);
|
||||
setDraft('');
|
||||
setConversations((prev) => {
|
||||
@@ -335,7 +423,9 @@ export default function MessagesPage() {
|
||||
unread_count: 0,
|
||||
updated_at: r.message.created_at,
|
||||
};
|
||||
return [next, ...rest];
|
||||
const merged = [next, ...rest];
|
||||
setSessionSnapshot('messages:conv:1', { conversations: merged, total: convTotal, page: 1 });
|
||||
return merged;
|
||||
});
|
||||
scrollToBottom(true);
|
||||
} catch (e: unknown) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useLayoutEffect, useRef, useCallback } from 'react';
|
||||
import { useParams, useNavigate, useOutletContext, useLocation } from 'react-router-dom';
|
||||
import { ArrowLeft, ThumbsUp, Star, Pencil, Pin, History, Lock, LockOpen, MessageSquare, MessageSquareOff, Trash2, Sparkles, Flag, Ban, CircleCheck, CircleHelp, MoreHorizontal } from 'lucide-react';
|
||||
import { useState, useEffect, useLayoutEffect, useRef, useCallback, useMemo } from 'react';
|
||||
import { useParams, useNavigate, useOutletContext, useLocation, useNavigationType } from 'react-router-dom';
|
||||
import { ArrowLeft, ThumbsUp, Star, Lock, MessageSquare, MessageSquareOff, Flag, MoreHorizontal } from 'lucide-react';
|
||||
import FeaturedIcon from '@/components/FeaturedIcon';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -44,6 +43,7 @@ import PostBountyBanner from '../components/PostBountyBanner';
|
||||
import { findCommentFloor } from '../utils/bounty';
|
||||
import PostLotteryCard from '../components/PostLotteryCard';
|
||||
import PostRevisionPanel from '../components/PostRevisionPanel';
|
||||
import PostManageMenu from '../components/PostManageMenu';
|
||||
import ArticleOutline from '../components/ArticleOutline';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
|
||||
@@ -51,17 +51,41 @@ import { getCachedSiteBranding } from '../hooks/useSiteBranding';
|
||||
import { formatDateTime, isTimeDiffSignificant } from '../utils/content';
|
||||
import { collectCommentSubtreeIds } from '../utils/comment';
|
||||
import { loadMyCommentIds } from '../utils/guest';
|
||||
import { clearAllFeedCache } from '../utils/feedCache';
|
||||
import { clearAllFeedCache, PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
|
||||
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
|
||||
import { deleteSessionSnapshot, getSessionSnapshot, setSessionSnapshot } from '../utils/sessionPageCache';
|
||||
import { useGlobalWheelScroll } from '../hooks/useGlobalWheelScroll';
|
||||
import { loginPath } from '../utils/authRedirect';
|
||||
import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText';
|
||||
import { canonicalRedirectPath, parsePermalinkID, postPath } from '../utils/permalink';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import type { LayoutCtx } from '../layouts/MainLayout';
|
||||
import type { PostHeading } from '../utils/postHeadings';
|
||||
import { extractHeadingsFromHtml } from '../utils/postHeadings';
|
||||
import { renderPostContentHtml } from '../utils/postContent';
|
||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||
import NotFoundPage from './NotFoundPage';
|
||||
|
||||
type PostDetailSnapshot = {
|
||||
post: PostItem;
|
||||
comments: Comment[];
|
||||
poll: PollView | null;
|
||||
lottery: PostLotteryView | null;
|
||||
liked: boolean;
|
||||
favorited: boolean;
|
||||
canEdit: boolean;
|
||||
isEdited: boolean;
|
||||
editBlockReason: string;
|
||||
editWindowHours: number;
|
||||
bountyCanRefund: boolean;
|
||||
bountyRefundBlockReason: string;
|
||||
bountyEligibleReplyCount: number;
|
||||
scrollTop: number;
|
||||
};
|
||||
|
||||
function postDetailCacheKey(id: number) {
|
||||
return `post:${id}`;
|
||||
}
|
||||
|
||||
/** 格式化剩余可编辑时间 */
|
||||
function formatEditRemaining(createdAt: string, windowHours: number): string {
|
||||
if (windowHours <= 0) return '';
|
||||
@@ -80,29 +104,35 @@ export default function PostDetailPage() {
|
||||
const postId = parsePermalinkID(id);
|
||||
const nav = useNavigate();
|
||||
const location = useLocation();
|
||||
const navType = useNavigationType();
|
||||
const { user, refresh } = useAuth();
|
||||
const { limits } = useForumLimits();
|
||||
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
|
||||
|
||||
const [post, setPost] = useState<PostItem | null>(null);
|
||||
const [poll, setPoll] = useState<PollView | null>(null);
|
||||
const [lottery, setLottery] = useState<PostLotteryView | null>(null);
|
||||
const [comments, setComments] = useState<Comment[]>([]);
|
||||
const [liked, setLiked] = useState(false);
|
||||
const [favorited, setFavorited] = useState(false);
|
||||
const initialSnap = (postId && !Number.isNaN(postId))
|
||||
? getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId))
|
||||
: undefined;
|
||||
|
||||
const [post, setPost] = useState<PostItem | null>(initialSnap?.post ?? null);
|
||||
const [poll, setPoll] = useState<PollView | null>(initialSnap?.poll ?? null);
|
||||
const [lottery, setLottery] = useState<PostLotteryView | null>(initialSnap?.lottery ?? null);
|
||||
const [comments, setComments] = useState<Comment[]>(initialSnap?.comments ?? []);
|
||||
const [liked, setLiked] = useState(initialSnap?.liked ?? false);
|
||||
const [favorited, setFavorited] = useState(initialSnap?.favorited ?? false);
|
||||
const [replyTo, setReplyTo] = useState<Comment | null>(null);
|
||||
const [editingCommentId, setEditingCommentId] = useState<number | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loading, setLoading] = useState(!initialSnap);
|
||||
const [highlightFloor, setHighlightFloor] = useState<number | null>(null);
|
||||
const [submitCount, setSubmitCount] = useState(0);
|
||||
const [canEdit, setCanEdit] = useState(false);
|
||||
const [isEdited, setIsEdited] = useState(false);
|
||||
const [editBlockReason, setEditBlockReason] = useState('');
|
||||
const [editWindowHours, setEditWindowHours] = useState(0);
|
||||
const [canEdit, setCanEdit] = useState(initialSnap?.canEdit ?? false);
|
||||
const [isEdited, setIsEdited] = useState(initialSnap?.isEdited ?? false);
|
||||
const [editBlockReason, setEditBlockReason] = useState(initialSnap?.editBlockReason ?? '');
|
||||
const [editWindowHours, setEditWindowHours] = useState(initialSnap?.editWindowHours ?? 0);
|
||||
const [showRevisions, setShowRevisions] = useState(false);
|
||||
const [deletingPost, setDeletingPost] = useState(false);
|
||||
const [headings, setHeadings] = useState<PostHeading[]>([]);
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
const [composerOpen, setComposerOpen] = useState(false);
|
||||
const [reportOpen, setReportOpen] = useState(false);
|
||||
const [reportReason, setReportReason] = useState<ReportReason>('spam');
|
||||
const [reportDetail, setReportDetail] = useState('');
|
||||
@@ -112,14 +142,25 @@ export default function PostDetailPage() {
|
||||
const [rejecting, setRejecting] = useState(false);
|
||||
const [bountyAwardTarget, setBountyAwardTarget] = useState<number | null>(null);
|
||||
const [bountyAwarding, setBountyAwarding] = useState(false);
|
||||
const [bountyCanRefund, setBountyCanRefund] = useState(true);
|
||||
const [bountyRefundBlockReason, setBountyRefundBlockReason] = useState('');
|
||||
const [bountyEligibleReplyCount, setBountyEligibleReplyCount] = useState(0);
|
||||
const [bountyCanRefund, setBountyCanRefund] = useState(initialSnap?.bountyCanRefund ?? true);
|
||||
const [bountyRefundBlockReason, setBountyRefundBlockReason] = useState(initialSnap?.bountyRefundBlockReason ?? '');
|
||||
const [bountyEligibleReplyCount, setBountyEligibleReplyCount] = useState(initialSnap?.bountyEligibleReplyCount ?? 0);
|
||||
/** 仅浏览器后退/前进还原滚动;从列表再次点进帖子从顶部开始 */
|
||||
const [restoreScrollTop, setRestoreScrollTop] = useState<number | null>(() => {
|
||||
if (!initialSnap) return null;
|
||||
if (navType === 'POP' && !location.hash) return initialSnap.scrollTop;
|
||||
return 0;
|
||||
});
|
||||
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
const commentSectionRef = useRef<HTMLDivElement>(null);
|
||||
const commentBoxRef = useRef<HTMLDivElement>(null);
|
||||
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
|
||||
const postRef = useRef<PostItem | null>(null);
|
||||
const scrollTopRef = useRef(
|
||||
initialSnap && navType === 'POP' && !location.hash ? initialSnap.scrollTop : 0,
|
||||
);
|
||||
postRef.current = post;
|
||||
|
||||
useGlobalWheelScroll(pageRef, !loading && !!post);
|
||||
|
||||
@@ -132,6 +173,15 @@ export default function PostDetailPage() {
|
||||
|
||||
const brand = getCachedSiteBranding();
|
||||
const postContent = post?.content ?? '';
|
||||
const isLoggedIn = !!user;
|
||||
// 同步从正文派生目录,避免预取缓存命中后 setHeadings([]) 盖掉子组件上报且不再回调
|
||||
const headings = useMemo(() => {
|
||||
if (!postContent.trim()) return [];
|
||||
const rendered = renderPostContentHtml(postContent, isLoggedIn, {
|
||||
openLinksInNewTab: limits.open_content_links_in_new_tab,
|
||||
});
|
||||
return extractHeadingsFromHtml(rendered);
|
||||
}, [postContent, isLoggedIn, limits.open_content_links_in_new_tab]);
|
||||
const postSEO = post ? {
|
||||
title: post.title,
|
||||
description: excerptFromHTML(postContent),
|
||||
@@ -155,10 +205,6 @@ export default function PostDetailPage() {
|
||||
} : null;
|
||||
usePageSEO(postSEO);
|
||||
|
||||
const handleHeadingsChange = useCallback((next: PostHeading[]) => {
|
||||
setHeadings(next);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || !post) {
|
||||
setPostOutline({ headings: [], scrollRoot: null, title: '文章目录' });
|
||||
@@ -178,18 +224,62 @@ export default function PostDetailPage() {
|
||||
const loadSeq = useRef(0);
|
||||
const detailPath = postPath(postId, limits);
|
||||
|
||||
useEffect(() => {
|
||||
const applySnapshot = useCallback((snap: PostDetailSnapshot, opts?: { restoreScroll?: boolean }) => {
|
||||
setPost(snap.post);
|
||||
setPoll(snap.poll);
|
||||
setLottery(snap.lottery);
|
||||
setLiked(snap.liked);
|
||||
setFavorited(snap.favorited);
|
||||
setCanEdit(snap.canEdit);
|
||||
setIsEdited(snap.isEdited);
|
||||
setEditBlockReason(snap.editBlockReason);
|
||||
setEditWindowHours(snap.editWindowHours);
|
||||
setBountyCanRefund(snap.bountyCanRefund);
|
||||
setBountyRefundBlockReason(snap.bountyRefundBlockReason);
|
||||
setBountyEligibleReplyCount(snap.bountyEligibleReplyCount);
|
||||
setComments(snap.comments);
|
||||
if (opts?.restoreScroll) {
|
||||
scrollTopRef.current = snap.scrollTop;
|
||||
setRestoreScrollTop(snap.scrollTop);
|
||||
} else {
|
||||
scrollTopRef.current = 0;
|
||||
// 同组件换帖时容器可能仍停在上一帖位置;初次进入已是 0 则不动,避免覆盖 #floor-N
|
||||
const el = pageRef.current;
|
||||
if (el && el.scrollTop !== 0) setRestoreScrollTop(0);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadPostRef = useRef<(mode: 'auto' | 'force') => void>(() => {});
|
||||
loadPostRef.current = (mode: 'auto' | 'force') => {
|
||||
if (!postId || Number.isNaN(postId)) {
|
||||
setPost(null);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
if (mode === 'force') {
|
||||
deleteSessionSnapshot(postDetailCacheKey(postId));
|
||||
}
|
||||
const cached = mode === 'force'
|
||||
? undefined
|
||||
: getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId));
|
||||
if (cached) {
|
||||
loadSeq.current += 1;
|
||||
applySnapshot(cached, { restoreScroll: navType === 'POP' && !location.hash });
|
||||
setReplyTo(null);
|
||||
setEditingCommentId(null);
|
||||
setComposerOpen(false);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
const seq = ++loadSeq.current;
|
||||
const keep = !!postRef.current;
|
||||
setReplyTo(null);
|
||||
setEditingCommentId(null);
|
||||
setHeadings([]);
|
||||
const seq = ++loadSeq.current;
|
||||
setLoading(true);
|
||||
setPost(null);
|
||||
setComposerOpen(false);
|
||||
if (!keep) {
|
||||
setLoading(true);
|
||||
setPost(null);
|
||||
}
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
@@ -199,30 +289,118 @@ export default function PostDetailPage() {
|
||||
api.comments(postId, myIds),
|
||||
]);
|
||||
if (seq !== loadSeq.current) return;
|
||||
setPost(detail.post);
|
||||
setPoll(detail.poll ?? null);
|
||||
setLottery(detail.lottery ?? null);
|
||||
setLiked(detail.liked);
|
||||
setFavorited(detail.favorited);
|
||||
setCanEdit(detail.can_edit ?? false);
|
||||
setIsEdited(detail.is_edited ?? isTimeDiffSignificant(detail.post.created_at, detail.post.updated_at ?? detail.post.created_at));
|
||||
setEditBlockReason(detail.edit_block_reason ?? '');
|
||||
setEditWindowHours(detail.post_edit_window_hours ?? 0);
|
||||
setBountyCanRefund(detail.bounty_can_refund ?? true);
|
||||
setBountyRefundBlockReason(detail.bounty_refund_block_reason ?? '');
|
||||
setBountyEligibleReplyCount(detail.bounty_eligible_reply_count ?? 0);
|
||||
setComments(Array.isArray(comm.comments) ? comm.comments : []);
|
||||
const commentsList = Array.isArray(comm.comments) ? comm.comments : [];
|
||||
const snap: PostDetailSnapshot = {
|
||||
post: detail.post,
|
||||
comments: commentsList,
|
||||
poll: detail.poll ?? null,
|
||||
lottery: detail.lottery ?? null,
|
||||
liked: detail.liked,
|
||||
favorited: detail.favorited,
|
||||
canEdit: detail.can_edit ?? false,
|
||||
isEdited: detail.is_edited ?? isTimeDiffSignificant(detail.post.created_at, detail.post.updated_at ?? detail.post.created_at),
|
||||
editBlockReason: detail.edit_block_reason ?? '',
|
||||
editWindowHours: detail.post_edit_window_hours ?? 0,
|
||||
bountyCanRefund: detail.bounty_can_refund ?? true,
|
||||
bountyRefundBlockReason: detail.bounty_refund_block_reason ?? '',
|
||||
bountyEligibleReplyCount: detail.bounty_eligible_reply_count ?? 0,
|
||||
scrollTop: 0,
|
||||
};
|
||||
setSessionSnapshot(postDetailCacheKey(postId), snap);
|
||||
applySnapshot(snap, { restoreScroll: false });
|
||||
if (mode === 'force') {
|
||||
const el = pageRef.current;
|
||||
if (el) el.scrollTop = 0;
|
||||
scrollTopRef.current = 0;
|
||||
}
|
||||
void refresh();
|
||||
} catch {
|
||||
if (seq !== loadSeq.current) return;
|
||||
setPost(null);
|
||||
if (!keep) setPost(null);
|
||||
} finally {
|
||||
if (seq === loadSeq.current) setLoading(false);
|
||||
}
|
||||
})();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadPostRef.current('auto');
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅 postId 变化时加载
|
||||
}, [postId]);
|
||||
|
||||
useEffect(() => {
|
||||
// 下拉已预热则应用快照;否则强制重拉
|
||||
const onForce = () => {
|
||||
if (!postId || Number.isNaN(postId)) return;
|
||||
const warm = getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId));
|
||||
if (warm) {
|
||||
loadSeq.current += 1;
|
||||
applySnapshot(warm, { restoreScroll: false });
|
||||
setLoading(false);
|
||||
const el = pageRef.current;
|
||||
if (el) el.scrollTop = 0;
|
||||
scrollTopRef.current = 0;
|
||||
return;
|
||||
}
|
||||
loadPostRef.current('force');
|
||||
};
|
||||
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onForce);
|
||||
return () => {
|
||||
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onForce);
|
||||
};
|
||||
}, [postId, applySnapshot]);
|
||||
|
||||
useEffect(() => {
|
||||
const el = pageRef.current;
|
||||
if (!el || loading || !post) return;
|
||||
const onScroll = () => {
|
||||
scrollTopRef.current = el.scrollTop;
|
||||
};
|
||||
el.addEventListener('scroll', onScroll, { passive: true });
|
||||
return () => el.removeEventListener('scroll', onScroll);
|
||||
}, [loading, post]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (restoreScrollTop == null || !pageRef.current || loading || !post) return;
|
||||
pageRef.current.scrollTop = restoreScrollTop;
|
||||
scrollTopRef.current = restoreScrollTop;
|
||||
setRestoreScrollTop(null);
|
||||
}, [restoreScrollTop, loading, post]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!post || post.id !== postId || loading) return;
|
||||
setSessionSnapshot(postDetailCacheKey(post.id), {
|
||||
post,
|
||||
comments,
|
||||
poll,
|
||||
lottery,
|
||||
liked,
|
||||
favorited,
|
||||
canEdit,
|
||||
isEdited,
|
||||
editBlockReason,
|
||||
editWindowHours,
|
||||
bountyCanRefund,
|
||||
bountyRefundBlockReason,
|
||||
bountyEligibleReplyCount,
|
||||
scrollTop: scrollTopRef.current,
|
||||
});
|
||||
}, [
|
||||
post, comments, poll, lottery, liked, favorited, canEdit, isEdited,
|
||||
editBlockReason, editWindowHours, bountyCanRefund, bountyRefundBlockReason,
|
||||
bountyEligibleReplyCount, postId, loading,
|
||||
]);
|
||||
|
||||
useEffect(() => () => {
|
||||
const p = postRef.current;
|
||||
if (!p) return;
|
||||
const prev = getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(p.id));
|
||||
if (!prev) return;
|
||||
setSessionSnapshot(postDetailCacheKey(p.id), { ...prev, scrollTop: scrollTopRef.current });
|
||||
}, []);
|
||||
|
||||
const reloadComments = useCallback(async () => {
|
||||
const myIds = user ? [] : loadMyCommentIds();
|
||||
const comm = await api.comments(postId, myIds);
|
||||
@@ -244,15 +422,54 @@ export default function PostDetailPage() {
|
||||
}
|
||||
}, [postId]);
|
||||
|
||||
const scrollToCommentBox = useCallback(() => {
|
||||
const target = commentBoxRef.current || commentSectionRef.current;
|
||||
target?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
window.setTimeout(() => {
|
||||
const ta = commentBoxRef.current?.querySelector('textarea');
|
||||
ta?.focus({ preventScroll: true });
|
||||
}, 320);
|
||||
const focusCommentEditor = useCallback(() => {
|
||||
const root = commentBoxRef.current;
|
||||
if (!root) return;
|
||||
const editable = root.querySelector<HTMLElement>('.ProseMirror, [contenteditable="true"]');
|
||||
editable?.focus({ preventScroll: true });
|
||||
}, []);
|
||||
|
||||
const scrollToCommentBox = useCallback(() => {
|
||||
setComposerOpen(true);
|
||||
// 等折叠条展开后再滚入视口并聚焦 TipTap
|
||||
window.setTimeout(() => {
|
||||
const target = commentBoxRef.current || commentSectionRef.current;
|
||||
target?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
window.setTimeout(focusCommentEditor, 80);
|
||||
}, 50);
|
||||
}, [focusCommentEditor]);
|
||||
|
||||
// 手机端展开输入框后聚焦编辑器
|
||||
useEffect(() => {
|
||||
if (!composerOpen || !isMobile) return;
|
||||
const timer = window.setTimeout(focusCommentEditor, 60);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [composerOpen, isMobile, focusCommentEditor]);
|
||||
|
||||
// 手机端:焦点离开评论输入区(含工具栏)后收起为「说点什么…」
|
||||
useEffect(() => {
|
||||
if (!isMobile || !composerOpen) return;
|
||||
const root = commentBoxRef.current;
|
||||
if (!root) return;
|
||||
|
||||
const onFocusOut = (e: FocusEvent) => {
|
||||
const next = e.relatedTarget as Node | null;
|
||||
if (next && root.contains(next)) return;
|
||||
|
||||
// 等焦点真正落定(工具栏 / Dialog / 系统弹窗)后再判断是否收起
|
||||
window.setTimeout(() => {
|
||||
const active = document.activeElement;
|
||||
if (active && root.contains(active)) return;
|
||||
// 代码块 Dialog 等浮层打开时不收起
|
||||
if (document.querySelector('[role="dialog"][data-state="open"]')) return;
|
||||
setComposerOpen(false);
|
||||
}, 50);
|
||||
};
|
||||
|
||||
root.addEventListener('focusout', onFocusOut);
|
||||
return () => root.removeEventListener('focusout', onFocusOut);
|
||||
}, [isMobile, composerOpen]);
|
||||
|
||||
const jumpToFloor = useCallback((floor: number) => {
|
||||
const el = document.getElementById(`floor-${floor}`);
|
||||
if (!el) return false;
|
||||
@@ -468,6 +685,7 @@ export default function PostDetailPage() {
|
||||
});
|
||||
setReplyTo(null);
|
||||
setSubmitCount(c => c + 1);
|
||||
if (isMobile) setComposerOpen(false);
|
||||
notify.success(r.message || (r.status === 'pending' ? '评论已提交审核' : '评论成功'));
|
||||
await Promise.all([reloadComments(), reloadPostContent()]);
|
||||
setTimeout(() => jumpToFloor(r.floor), 100);
|
||||
@@ -530,6 +748,7 @@ export default function PostDetailPage() {
|
||||
setDeletingPost(true);
|
||||
try {
|
||||
await api.deletePost(postId);
|
||||
deleteSessionSnapshot(postDetailCacheKey(postId));
|
||||
clearAllFeedCache();
|
||||
window.dispatchEvent(new Event('posts-refresh'));
|
||||
notify.success('帖子已删除');
|
||||
@@ -549,7 +768,7 @@ export default function PostDetailPage() {
|
||||
onCancelReply: () => setReplyTo(null),
|
||||
};
|
||||
|
||||
if (loading) return <div className="post-detail-loading flex justify-center py-16"><Spinner size="lg" /></div>;
|
||||
if (loading && !post) return <div className="post-detail-loading flex justify-center py-16"><Spinner size="lg" /></div>;
|
||||
if (!post) {
|
||||
return (
|
||||
<NotFoundPage
|
||||
@@ -738,12 +957,38 @@ export default function PostDetailPage() {
|
||||
<article className="page-wrap post-detail-page" ref={pageRef}>
|
||||
<div className="post-detail-header">
|
||||
<div className="post-detail-nav">
|
||||
<Button variant="ghost" size="sm" onClick={() => nav(-1)}>
|
||||
<ArrowLeft />
|
||||
返回
|
||||
</Button>
|
||||
{post.board && (
|
||||
<BoardBadge board={post.board} className="post-detail-board-tag" />
|
||||
<div className="post-detail-nav-left">
|
||||
<Button variant="ghost" size="sm" onClick={() => nav(-1)}>
|
||||
<ArrowLeft />
|
||||
返回
|
||||
</Button>
|
||||
{post.board && (
|
||||
<BoardBadge board={post.board} className="post-detail-board-tag" />
|
||||
)}
|
||||
</div>
|
||||
{(isOwnerOrAdmin || canEdit || isAdmin) && (
|
||||
<PostManageMenu
|
||||
post={post}
|
||||
isAdmin={isAdmin}
|
||||
isOwnerOrAdmin={isOwnerOrAdmin}
|
||||
canEdit={canEdit}
|
||||
isEdited={isEdited}
|
||||
isMobile={isMobile}
|
||||
editRemaining={editRemaining}
|
||||
editBlockReason={editBlockReason}
|
||||
deleting={deletingPost}
|
||||
onEdit={() => nav(`/post/${postId}/edit`)}
|
||||
onShowRevisions={() => setShowRevisions(true)}
|
||||
onToggleResolved={handleToggleResolved}
|
||||
onApprove={handleApprove}
|
||||
onReject={() => setRejectOpen(true)}
|
||||
onFeature={handleFeature}
|
||||
onPin={handlePin}
|
||||
onBoardPin={handleBoardPin}
|
||||
onLock={handleLock}
|
||||
onCommentsLock={handleCommentsLock}
|
||||
onDelete={() => setDeleteOpen(true)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -882,9 +1127,8 @@ export default function PostDetailPage() {
|
||||
|
||||
<PostContent
|
||||
html={post.content || ''}
|
||||
isLoggedIn={!!user}
|
||||
isLoggedIn={isLoggedIn}
|
||||
postId={post.id}
|
||||
onHeadingsChange={handleHeadingsChange}
|
||||
onRequestReply={scrollToCommentBox}
|
||||
onUnlocked={() => { void reloadPostContent(); }}
|
||||
/>
|
||||
@@ -943,101 +1187,32 @@ export default function PostDetailPage() {
|
||||
</DropdownMenu>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{(isOwnerOrAdmin || canEdit || isAdmin) && (
|
||||
<div className="post-detail-actions-manage">
|
||||
{isOwnerOrAdmin && post.post_type === 'question' && (
|
||||
<Button
|
||||
variant={post.question_resolved ? 'outline' : 'default'}
|
||||
size="sm"
|
||||
onClick={handleToggleResolved}
|
||||
>
|
||||
{post.question_resolved ? <CircleHelp /> : <CircleCheck />}
|
||||
{post.question_resolved ? '标为未解决' : '标为已解决'}
|
||||
</Button>
|
||||
)}
|
||||
{canEdit && (
|
||||
<Button variant="outline" size="sm" onClick={() => nav(`/post/${postId}/edit`)}>
|
||||
<Pencil />
|
||||
编辑
|
||||
</Button>
|
||||
)}
|
||||
{isOwnerOrAdmin && isEdited && (
|
||||
<Button variant="outline" size="sm" onClick={() => setShowRevisions(true)}>
|
||||
<History />
|
||||
编辑历史
|
||||
</Button>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="outline" size="sm" disabled={deletingPost}>
|
||||
<Trash2 />
|
||||
删除
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确定删除该帖子?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
帖子与评论将移入回收站,可在后台恢复或永久删除。普通用户不可自行删除内容。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDeletePost}>删除</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
{editRemaining && (
|
||||
<span className="post-detail-edit-hint">{editRemaining}</span>
|
||||
)}
|
||||
{isOwnerOrAdmin && !canEdit && editBlockReason && (
|
||||
<span className="post-detail-edit-hint" title={editBlockReason}>
|
||||
{editBlockReason}
|
||||
</span>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<>
|
||||
{(post.status === 'pending' || post.status === 'rejected') && (
|
||||
<Button variant="default" size="sm" onClick={handleApprove}>
|
||||
通过审核
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" size="sm" onClick={handleFeature}>
|
||||
<Sparkles />
|
||||
{post.featured ? '取消精华' : '设为精华'}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={handlePin}>
|
||||
<Pin />
|
||||
{post.pinned ? '取消全局置顶' : '全局置顶'}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={handleBoardPin}>
|
||||
<Pin />
|
||||
{post.board_pinned ? '取消板块置顶' : '板块置顶'}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={handleLock}>
|
||||
<Lock />
|
||||
{post.edit_locked ? '解锁编辑' : '锁定编辑'}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={handleCommentsLock}>
|
||||
{post.comments_locked ? <LockOpen /> : <MessageSquareOff />}
|
||||
{post.comments_locked ? '开放讨论' : '锁定讨论'}
|
||||
</Button>
|
||||
{post.status !== 'rejected' && (
|
||||
<Button variant="outline" size="sm" onClick={() => setRejectOpen(true)}>
|
||||
<Ban />
|
||||
拒绝并通知
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确定删除该帖子?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
帖子与评论将移入回收站,可在后台恢复或永久删除。普通用户不可自行删除内容。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deletingPost}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
disabled={deletingPost}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
void handleDeletePost();
|
||||
}}
|
||||
>
|
||||
删除
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<Dialog open={reportOpen} onOpenChange={setReportOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
@@ -1122,7 +1297,45 @@ export default function PostDetailPage() {
|
||||
</div>
|
||||
) : !replyTo && (
|
||||
<div className="comment-box-wrap" ref={commentBoxRef}>
|
||||
<CommentBox {...commentBoxProps} />
|
||||
{isMobile && !composerOpen && (
|
||||
<button
|
||||
type="button"
|
||||
className="comment-composer-collapsed"
|
||||
onClick={() => {
|
||||
if (!user) {
|
||||
requireLogin('评论');
|
||||
return;
|
||||
}
|
||||
setComposerOpen(true);
|
||||
window.requestAnimationFrame(() => {
|
||||
window.setTimeout(focusCommentEditor, 50);
|
||||
});
|
||||
}}
|
||||
>
|
||||
{user ? (
|
||||
<>
|
||||
<span className="comment-composer-collapsed-avatar" aria-hidden>
|
||||
{user.avatar
|
||||
? <img src={user.avatar} alt="" loading="lazy" decoding="async" />
|
||||
: (user.nickname?.[0] || '?')}
|
||||
</span>
|
||||
<span className="comment-composer-collapsed-placeholder">说点什么…</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="comment-composer-collapsed-placeholder">登录后即可评论</span>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
<div
|
||||
className={
|
||||
isMobile && !composerOpen
|
||||
? 'comment-box-expanded-slot is-collapsed'
|
||||
: 'comment-box-expanded-slot'
|
||||
}
|
||||
aria-hidden={isMobile && !composerOpen}
|
||||
>
|
||||
<CommentBox {...commentBoxProps} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ import { openForumPost } from '../utils/openPost';
|
||||
import { formatDateTime } from '../utils/content';
|
||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||
import { userPath } from '../utils/userPath';
|
||||
import { useSessionResource } from '../hooks/useSessionResource';
|
||||
|
||||
const nickSchema = z.object({
|
||||
nickname: z.string().min(1, '请输入昵称').max(64),
|
||||
@@ -75,7 +76,7 @@ export default function ProfilePage() {
|
||||
const nav = useNavigate();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const tab = parseTab(params.get('tab'));
|
||||
const { user, loading: authLoading, refresh } = useAuth();
|
||||
const { user, loading: authLoading, refresh, logout } = useAuth();
|
||||
useNoIndexSEO('个人中心');
|
||||
const [nickLoading, setNickLoading] = useState(false);
|
||||
const [sigLoading, setSigLoading] = useState(false);
|
||||
@@ -88,12 +89,6 @@ export default function ProfilePage() {
|
||||
const [cropFileName, setCropFileName] = useState('');
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const [idCopied, setIdCopied] = useState(false);
|
||||
const [stats, setStats] = useState<UserActivityStats | null>(null);
|
||||
const [statsLoading, setStatsLoading] = useState(true);
|
||||
const [posts, setPosts] = useState<PostItem[]>([]);
|
||||
const [postsLoading, setPostsLoading] = useState(false);
|
||||
const [postPage, setPostPage] = useState(1);
|
||||
const [postTotal, setPostTotal] = useState(0);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const dragCounter = useRef(0);
|
||||
const copyTimer = useRef<ReturnType<typeof setTimeout>>();
|
||||
@@ -102,7 +97,6 @@ export default function ProfilePage() {
|
||||
|
||||
const { limits } = useForumLimits();
|
||||
const pageSize = limits.page_size_default > 0 ? limits.page_size_default : 20;
|
||||
const totalPages = Math.max(1, Math.ceil(postTotal / pageSize));
|
||||
|
||||
const nickForm = useForm<NickValues>({
|
||||
resolver: zodResolver(nickSchema),
|
||||
@@ -181,37 +175,26 @@ export default function ProfilePage() {
|
||||
if (copyTimer.current) clearTimeout(copyTimer.current);
|
||||
}, []);
|
||||
|
||||
const loadStats = useCallback(() => {
|
||||
setStatsLoading(true);
|
||||
api.profileStats()
|
||||
.then(d => setStats(d.stats))
|
||||
.catch(() => setStats(null))
|
||||
.finally(() => setStatsLoading(false));
|
||||
}, []);
|
||||
const { data: stats = null, loading: statsLoading } = useSessionResource<UserActivityStats | null>(
|
||||
user ? `profile:stats:${user.id}` : null,
|
||||
() => api.profileStats().then(d => d.stats ?? null),
|
||||
{ enabled: !!user },
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
loadStats();
|
||||
}, [user, loadStats]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user || tab !== 'posts') return;
|
||||
let cancelled = false;
|
||||
setPostsLoading(true);
|
||||
api.posts({ user_id: user.id, page: postPage, size: pageSize, sort: 'latest' })
|
||||
.then(d => {
|
||||
if (cancelled) return;
|
||||
setPosts(Array.isArray(d.posts) ? d.posts : []);
|
||||
setPostTotal(d.total ?? 0);
|
||||
})
|
||||
.catch(e => {
|
||||
if (!cancelled) notify.error(e instanceof Error ? e.message : '加载帖子失败');
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setPostsLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [user, tab, postPage, pageSize]);
|
||||
const [postPage, setPostPage] = useState(1);
|
||||
const postsKey = user && tab === 'posts' ? `profile:posts:${user.id}:${postPage}:${pageSize}` : null;
|
||||
const { data: postsSnap, loading: postsLoading } = useSessionResource<{ posts: PostItem[]; total: number }>(
|
||||
postsKey,
|
||||
() => api.posts({ user_id: user!.id, page: postPage, size: pageSize, sort: 'latest' })
|
||||
.then(d => ({ posts: Array.isArray(d.posts) ? d.posts : [], total: d.total ?? 0 })),
|
||||
{
|
||||
enabled: !!postsKey,
|
||||
onError: (e) => notify.error(e instanceof Error ? e.message : '加载帖子失败'),
|
||||
},
|
||||
);
|
||||
const posts = postsSnap?.posts ?? [];
|
||||
const postTotal = postsSnap?.total ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(postTotal / pageSize));
|
||||
|
||||
const closeCropDialog = useCallback((open: boolean) => {
|
||||
if (!open) {
|
||||
@@ -263,7 +246,7 @@ export default function ProfilePage() {
|
||||
await api.updatePassword(values.old_password, values.new_password);
|
||||
notify.success('密码已修改,请重新登录');
|
||||
pwdForm.reset();
|
||||
await api.logout();
|
||||
await logout();
|
||||
nav('/login');
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '修改失败');
|
||||
|
||||
@@ -10,14 +10,13 @@ import ProjectListItem from '../components/ProjectListItem';
|
||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
|
||||
import { getCachedSiteBranding } from '../hooks/useSiteBranding';
|
||||
import { useSessionResource } from '../hooks/useSessionResource';
|
||||
|
||||
type ProjectsSnap = { list: GiteaProject[]; total: number; totalPages: number };
|
||||
|
||||
export default function ProjectsPage() {
|
||||
const nav = useNavigate();
|
||||
const [list, setList] = useState<GiteaProject[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [queryInput, setQueryInput] = useState('');
|
||||
const [query, setQuery] = useState('');
|
||||
|
||||
@@ -40,24 +39,20 @@ export default function ProjectsPage() {
|
||||
return () => window.clearTimeout(t);
|
||||
}, [queryInput]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
api.projects({ page, limit: 30, q: query || undefined })
|
||||
.then(d => {
|
||||
if (cancelled) return;
|
||||
setList(Array.isArray(d.projects) ? d.projects : []);
|
||||
setTotal(d.total ?? 0);
|
||||
setTotalPages(d.total_pages ?? 0);
|
||||
})
|
||||
.catch(e => {
|
||||
if (!cancelled) notify.error(e instanceof Error ? e.message : '加载失败');
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [page, query]);
|
||||
const { data, loading } = useSessionResource<ProjectsSnap>(
|
||||
`projects:${page}:${query}`,
|
||||
() => api.projects({ page, limit: 30, q: query || undefined }).then(d => ({
|
||||
list: Array.isArray(d.projects) ? d.projects : [],
|
||||
total: d.total ?? 0,
|
||||
totalPages: d.total_pages ?? 0,
|
||||
})),
|
||||
{
|
||||
onError: (e) => notify.error(e instanceof Error ? e.message : '加载失败'),
|
||||
},
|
||||
);
|
||||
const list = data?.list ?? [];
|
||||
const total = data?.total ?? 0;
|
||||
const totalPages = data?.totalPages ?? 0;
|
||||
|
||||
return (
|
||||
<div className="page-wrap">
|
||||
|
||||
76
frontend/src/pages/ShowcasePage.tsx
Normal file
76
frontend/src/pages/ShowcasePage.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import { ExternalLink, Globe2 } from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { api } from '../api/client';
|
||||
import type { CommunityShowcaseItem } from '../api/types';
|
||||
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
|
||||
import { getCachedSiteBranding, useSiteBranding } from '../hooks/useSiteBranding';
|
||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||
import { useSessionResource } from '../hooks/useSessionResource';
|
||||
|
||||
/** 官方精选的公网部署展柜(只读;仅人工精选条目) */
|
||||
export default function ShowcasePage() {
|
||||
const { branding } = useSiteBranding();
|
||||
const { data: items = [], loading } = useSessionResource<CommunityShowcaseItem[]>(
|
||||
'showcase',
|
||||
() => api.communityShowcase().then((r) => (Array.isArray(r.items) ? r.items : [])),
|
||||
);
|
||||
|
||||
usePageSEO({
|
||||
title: '开源部署展柜',
|
||||
description: `${branding.name} 精选的姜十三论坛公网部署`,
|
||||
keywords: joinSEOKeywords('开源', '部署', '展柜', getCachedSiteBranding().keywords),
|
||||
canonicalPath: '/showcase',
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="page-wrap">
|
||||
<div className="showcase-page">
|
||||
<header className="showcase-head">
|
||||
<div className="showcase-head-mark" aria-hidden>
|
||||
<Globe2 size={22} />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="showcase-title">开源部署展柜</h1>
|
||||
<p className="showcase-desc">
|
||||
以下站点自愿开启社区上报,并由官方演示站精选推荐(非全量目录)
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-16"><Spinner size="lg" /></div>
|
||||
) : items.length === 0 ? (
|
||||
<p className="showcase-empty">暂无精选实例</p>
|
||||
) : (
|
||||
<ul className="showcase-list">
|
||||
{items.map((item) => (
|
||||
<li key={item.site_url} className="showcase-item">
|
||||
<a
|
||||
href={item.site_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="showcase-item-link"
|
||||
>
|
||||
<span className="showcase-item-name">{item.site_name || '未命名站点'}</span>
|
||||
<span className="showcase-item-url">
|
||||
{item.site_url}
|
||||
<ExternalLink size={12} aria-hidden />
|
||||
</span>
|
||||
{(item.featured_note || item.version) && (
|
||||
<span className="showcase-item-meta">
|
||||
{item.featured_note || null}
|
||||
{item.featured_note && item.version ? ' · ' : null}
|
||||
{item.version ? `v${item.version}` : null}
|
||||
</span>
|
||||
)}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<InFlowSiteFooter />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import { useOutletContext, useParams } from 'react-router-dom';
|
||||
import NotFoundPage from './NotFoundPage';
|
||||
import { api } from '../api/client';
|
||||
import type { SitePage } from '../api/types';
|
||||
import ArticleOutline from '../components/ArticleOutline';
|
||||
import PostContent from '../components/PostContent';
|
||||
import PageLoader from '../components/PageLoader';
|
||||
import { usePageSEO } from '../hooks/usePageSEO';
|
||||
import { parsePermalinkSlug, pagePath } from '../utils/permalink';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { useSessionResource } from '../hooks/useSessionResource';
|
||||
import type { LayoutCtx } from '../layouts/MainLayout';
|
||||
import { extractHeadingsFromHtml } from '../utils/postHeadings';
|
||||
import { renderPostContentHtml } from '../utils/postContent';
|
||||
|
||||
/** 自定义单页(关于我们、版规等) */
|
||||
export default function SitePageView() {
|
||||
@@ -16,22 +20,25 @@ export default function SitePageView() {
|
||||
const slug = parsePermalinkSlug(rawSlug);
|
||||
const { limits } = useForumLimits();
|
||||
const { user } = useAuth();
|
||||
const [page, setPage] = useState<SitePage | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [notFound, setNotFound] = useState(false);
|
||||
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
const { data: page, loading } = useSessionResource<SitePage | null>(
|
||||
slug ? `sitepage:${slug}` : null,
|
||||
() => api.page(slug).then(d => d.page),
|
||||
{ enabled: !!slug },
|
||||
);
|
||||
const notFound = !slug || (!loading && !page);
|
||||
const isLoggedIn = !!user;
|
||||
const pageContent = page?.content ?? '';
|
||||
|
||||
useEffect(() => {
|
||||
if (!slug) {
|
||||
setNotFound(true);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
api.page(slug)
|
||||
.then(d => setPage(d.page))
|
||||
.catch(() => setNotFound(true))
|
||||
.finally(() => setLoading(false));
|
||||
}, [slug]);
|
||||
// 同步从正文派生目录,与帖子详情共用右侧栏目录布局
|
||||
const headings = useMemo(() => {
|
||||
if (!pageContent.trim()) return [];
|
||||
const rendered = renderPostContentHtml(pageContent, isLoggedIn, {
|
||||
openLinksInNewTab: limits.open_content_links_in_new_tab,
|
||||
});
|
||||
return extractHeadingsFromHtml(rendered);
|
||||
}, [pageContent, isLoggedIn, limits.open_content_links_in_new_tab]);
|
||||
|
||||
usePageSEO({
|
||||
title: page?.title,
|
||||
@@ -40,19 +47,42 @@ export default function SitePageView() {
|
||||
ogType: 'article',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || !page) {
|
||||
setPostOutline({ headings: [], scrollRoot: null, title: '文章目录' });
|
||||
return () => setPostOutline(null);
|
||||
}
|
||||
setPostOutline({
|
||||
headings,
|
||||
scrollRoot: pageRef.current,
|
||||
title: '文章目录',
|
||||
});
|
||||
return () => setPostOutline(null);
|
||||
}, [headings, loading, page, setPostOutline]);
|
||||
|
||||
if (!slug) return <NotFoundPage title="页面不存在" />;
|
||||
if (loading) return <PageLoader />;
|
||||
if (loading) return null;
|
||||
if (notFound || !page) return <NotFoundPage title="页面不存在" description="该页面不存在或未发布" />;
|
||||
|
||||
return (
|
||||
<div className="page-wrap">
|
||||
<div className="page-wrap" ref={pageRef}>
|
||||
<article className="site-page">
|
||||
<header className="site-page__head">
|
||||
<h1>{page.title}</h1>
|
||||
</header>
|
||||
{isMobile && headings.length > 0 && (
|
||||
<details className="post-detail-toc-mobile">
|
||||
<summary>文章目录({headings.length})</summary>
|
||||
<ArticleOutline
|
||||
headings={headings}
|
||||
scrollRoot={pageRef.current}
|
||||
title="目录"
|
||||
/>
|
||||
</details>
|
||||
)}
|
||||
<PostContent
|
||||
html={page.content}
|
||||
isLoggedIn={!!user}
|
||||
isLoggedIn={isLoggedIn}
|
||||
className="site-page__body post-detail-content"
|
||||
/>
|
||||
</article>
|
||||
|
||||
@@ -20,6 +20,7 @@ import { api } from '../api/client';
|
||||
import type { PostItem, UserActivityStats, UserPublic } from '../api/types';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import { useSessionResource } from '../hooks/useSessionResource';
|
||||
import PostListItem from '../components/PostListItem';
|
||||
import FeedPagination from '../components/FeedPagination';
|
||||
import ComposeMessageDialog from '../components/ComposeMessageDialog';
|
||||
@@ -31,6 +32,9 @@ import { canonicalRedirectPath, parsePermalinkID, userPath } from '../utils/perm
|
||||
import NotFoundPage from './NotFoundPage';
|
||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||
|
||||
type ProfileSnap = { profile: UserPublic; stats: UserActivityStats | null };
|
||||
type PostsSnap = { posts: PostItem[]; total: number };
|
||||
|
||||
export default function UserProfilePage() {
|
||||
const { id: idParam } = useParams();
|
||||
const userId = parsePermalinkID(idParam);
|
||||
@@ -40,15 +44,34 @@ export default function UserProfilePage() {
|
||||
const { limits } = useForumLimits();
|
||||
const pageSize = limits.page_size_default > 0 ? limits.page_size_default : 20;
|
||||
|
||||
const [profile, setProfile] = useState<UserPublic | null>(null);
|
||||
const [stats, setStats] = useState<UserActivityStats | null>(null);
|
||||
const [msgOpen, setMsgOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [notFound, setNotFound] = useState(false);
|
||||
const [posts, setPosts] = useState<PostItem[]>([]);
|
||||
const [postsLoading, setPostsLoading] = useState(false);
|
||||
const [postPage, setPostPage] = useState(1);
|
||||
const [postTotal, setPostTotal] = useState(0);
|
||||
|
||||
const profileKey = userId && !Number.isNaN(userId) ? `user:${userId}` : null;
|
||||
const { data: profileSnap, loading } = useSessionResource<ProfileSnap>(
|
||||
profileKey,
|
||||
() => api.userProfile(userId).then(d => ({ profile: d.user, stats: d.stats ?? null })),
|
||||
{
|
||||
enabled: !!profileKey,
|
||||
onError: () => setNotFound(true),
|
||||
},
|
||||
);
|
||||
const profile = profileSnap?.profile ?? null;
|
||||
const stats = profileSnap?.stats ?? null;
|
||||
|
||||
const postsKey = profileKey && profile ? `${profileKey}:posts:${postPage}:${pageSize}` : null;
|
||||
const { data: postsSnap, loading: postsLoading } = useSessionResource<PostsSnap>(
|
||||
postsKey,
|
||||
() => api.posts({ user_id: userId, page: postPage, size: pageSize, sort: 'latest' })
|
||||
.then(d => ({ posts: Array.isArray(d.posts) ? d.posts : [], total: d.total ?? 0 })),
|
||||
{
|
||||
enabled: !!postsKey,
|
||||
onError: (e) => notify.error(e instanceof Error ? e.message : '加载帖子失败'),
|
||||
},
|
||||
);
|
||||
const posts = postsSnap?.posts ?? [];
|
||||
const postTotal = postsSnap?.total ?? 0;
|
||||
|
||||
const isSelf = !!me && me.id === userId;
|
||||
const totalPages = Math.max(1, Math.ceil(postTotal / pageSize));
|
||||
@@ -56,43 +79,13 @@ export default function UserProfilePage() {
|
||||
useEffect(() => {
|
||||
if (!userId || Number.isNaN(userId)) {
|
||||
setNotFound(true);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setNotFound(false);
|
||||
setPostPage(1);
|
||||
api.userProfile(userId)
|
||||
.then(d => {
|
||||
setProfile(d.user);
|
||||
setStats(d.stats);
|
||||
})
|
||||
.catch(() => {
|
||||
setProfile(null);
|
||||
setStats(null);
|
||||
setNotFound(true);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [userId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!userId || Number.isNaN(userId) || !profile) return;
|
||||
let cancelled = false;
|
||||
setPostsLoading(true);
|
||||
api.posts({ user_id: userId, page: postPage, size: pageSize, sort: 'latest' })
|
||||
.then(d => {
|
||||
if (cancelled) return;
|
||||
setPosts(Array.isArray(d.posts) ? d.posts : []);
|
||||
setPostTotal(d.total ?? 0);
|
||||
})
|
||||
.catch(e => {
|
||||
if (!cancelled) notify.error(e instanceof Error ? e.message : '加载帖子失败');
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setPostsLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [userId, profile, postPage, pageSize]);
|
||||
setNotFound(false);
|
||||
setPostPage(1);
|
||||
}, [userId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!userId || Number.isNaN(userId)) return;
|
||||
|
||||
302
frontend/src/pages/admin/AdminCommunityPage.tsx
Normal file
302
frontend/src/pages/admin/AdminCommunityPage.tsx
Normal file
@@ -0,0 +1,302 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Globe2, ExternalLink, Star } from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { api } from '../../api/client';
|
||||
import type { CommunityInstance, ForumLimits } from '../../api/types';
|
||||
import { useAdminGuard } from '../../layouts/AdminLayout';
|
||||
import { formatTime } from '../../utils/content';
|
||||
import { invalidateForumLimitsCache } from '../../hooks/useForumLimits';
|
||||
import {
|
||||
mergeForumLimitsWithAsideWidgets,
|
||||
normalizeAsideWidgets,
|
||||
resolveAsideWidgets,
|
||||
} from '../../utils/asideWidgets';
|
||||
|
||||
type EntryFlags = {
|
||||
nav: boolean;
|
||||
footer: boolean;
|
||||
aside: boolean;
|
||||
};
|
||||
|
||||
/** 后台:公网实例列表 + 开源展柜入口位置 */
|
||||
export default function AdminCommunityPage() {
|
||||
const { ready } = useAdminGuard();
|
||||
const [hubEnabled, setHubEnabled] = useState(false);
|
||||
const [list, setList] = useState<CommunityInstance[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [featuringId, setFeaturingId] = useState<string | null>(null);
|
||||
const [forumLimits, setForumLimits] = useState<ForumLimits | null>(null);
|
||||
const [entrySaving, setEntrySaving] = useState(false);
|
||||
|
||||
const entryFlags = useMemo<EntryFlags>(() => {
|
||||
const widgets = resolveAsideWidgets({
|
||||
aside_widgets: forumLimits?.aside_widgets,
|
||||
aside_show_tag_cloud: forumLimits?.aside_show_tag_cloud ?? false,
|
||||
aside_show_recent_comments: forumLimits?.aside_show_recent_comments ?? false,
|
||||
aside_show_friend_links: forumLimits?.aside_show_friend_links ?? true,
|
||||
aside_show_showcase: forumLimits?.aside_show_showcase ?? false,
|
||||
});
|
||||
return {
|
||||
nav: !!forumLimits?.nav_show_showcase,
|
||||
footer: !!forumLimits?.footer_show_showcase,
|
||||
aside: widgets.find(w => w.id === 'showcase')?.enabled ?? false,
|
||||
};
|
||||
}, [forumLimits]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
setLoading(true);
|
||||
Promise.all([
|
||||
api.adminCommunityInstances(),
|
||||
api.adminSettings().catch(() => null),
|
||||
])
|
||||
.then(([instancesRes, settings]) => {
|
||||
setHubEnabled(!!instancesRes.hub_enabled);
|
||||
setList(Array.isArray(instancesRes.instances) ? instancesRes.instances : []);
|
||||
if (settings?.limits) {
|
||||
const loaded = normalizeAsideWidgets(
|
||||
resolveAsideWidgets({
|
||||
aside_widgets: settings.limits.aside_widgets,
|
||||
aside_show_tag_cloud: settings.limits.aside_show_tag_cloud ?? false,
|
||||
aside_show_recent_comments: settings.limits.aside_show_recent_comments ?? false,
|
||||
aside_show_friend_links: settings.limits.aside_show_friend_links ?? true,
|
||||
aside_show_showcase: settings.limits.aside_show_showcase ?? false,
|
||||
}),
|
||||
);
|
||||
setForumLimits(mergeForumLimitsWithAsideWidgets({
|
||||
...settings.limits,
|
||||
nav_show_showcase: !!settings.limits.nav_show_showcase,
|
||||
footer_show_showcase: !!settings.limits.footer_show_showcase,
|
||||
aside_show_showcase: !!settings.limits.aside_show_showcase,
|
||||
}, loaded));
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
setList([]);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [ready]);
|
||||
|
||||
const patchEntryVisibility = async (patch: Partial<EntryFlags>) => {
|
||||
if (entrySaving) return;
|
||||
const prev = entryFlags;
|
||||
const nextFlags = { ...prev, ...patch };
|
||||
setForumLimits((fl) => {
|
||||
if (!fl) return fl;
|
||||
const widgets = normalizeAsideWidgets(fl.aside_widgets).map(w => (
|
||||
w.id === 'showcase' ? { ...w, enabled: nextFlags.aside } : w
|
||||
));
|
||||
return mergeForumLimitsWithAsideWidgets({
|
||||
...fl,
|
||||
nav_show_showcase: nextFlags.nav,
|
||||
footer_show_showcase: nextFlags.footer,
|
||||
aside_show_showcase: nextFlags.aside,
|
||||
}, widgets);
|
||||
});
|
||||
setEntrySaving(true);
|
||||
try {
|
||||
const body: {
|
||||
nav_show_showcase?: boolean;
|
||||
footer_show_showcase?: boolean;
|
||||
aside_show_showcase?: boolean;
|
||||
} = {};
|
||||
if (patch.nav !== undefined) body.nav_show_showcase = patch.nav;
|
||||
if (patch.footer !== undefined) body.footer_show_showcase = patch.footer;
|
||||
if (patch.aside !== undefined) body.aside_show_showcase = patch.aside;
|
||||
const r = await api.adminUpdateShowcaseEntry(body);
|
||||
setForumLimits((base) => {
|
||||
if (!base) return base;
|
||||
const widgets = normalizeAsideWidgets(base.aside_widgets).map(w => (
|
||||
w.id === 'showcase' ? { ...w, enabled: r.aside_show_showcase } : w
|
||||
));
|
||||
return mergeForumLimitsWithAsideWidgets({
|
||||
...base,
|
||||
nav_show_showcase: r.nav_show_showcase,
|
||||
footer_show_showcase: r.footer_show_showcase,
|
||||
aside_show_showcase: r.aside_show_showcase,
|
||||
}, widgets);
|
||||
});
|
||||
invalidateForumLimitsCache();
|
||||
notify.success(r.message);
|
||||
} catch (e: unknown) {
|
||||
setForumLimits((fl) => {
|
||||
if (!fl) return fl;
|
||||
const widgets = normalizeAsideWidgets(fl.aside_widgets).map(w => (
|
||||
w.id === 'showcase' ? { ...w, enabled: prev.aside } : w
|
||||
));
|
||||
return mergeForumLimitsWithAsideWidgets({
|
||||
...fl,
|
||||
nav_show_showcase: prev.nav,
|
||||
footer_show_showcase: prev.footer,
|
||||
aside_show_showcase: prev.aside,
|
||||
}, widgets);
|
||||
});
|
||||
notify.error(e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
setEntrySaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleFeatured = async (row: CommunityInstance) => {
|
||||
if (featuringId) return;
|
||||
setFeaturingId(row.instance_id);
|
||||
try {
|
||||
const r = await api.adminFeatureCommunityInstance(row.instance_id, {
|
||||
featured: !row.featured,
|
||||
featured_note: row.featured_note || '',
|
||||
});
|
||||
setList((prev) => prev.map((item) => (
|
||||
item.instance_id === row.instance_id ? { ...item, ...r.instance } : item
|
||||
)));
|
||||
notify.success(r.message);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '操作失败');
|
||||
} finally {
|
||||
setFeaturingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (!ready || loading) {
|
||||
return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="admin-page">
|
||||
<div className="admin-page-head">
|
||||
<div>
|
||||
<h1 className="admin-page-title">
|
||||
<Globe2 size={22} aria-hidden />
|
||||
公网实例
|
||||
</h1>
|
||||
<p className="admin-page-desc">
|
||||
接收自愿上报的心跳;设为精选后会出现在
|
||||
{' '}
|
||||
<Link to="/showcase" className="admin-inline-link" target="_blank" rel="noopener noreferrer">开源部署展柜</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!hubEnabled && (
|
||||
<div className="admin-card admin-settings-card" style={{ marginBottom: 16 }}>
|
||||
<div className="admin-card-body">
|
||||
<p>
|
||||
本站未开启社区枢纽。该能力仅供官方主站运维配置开启(
|
||||
<code>app.ini</code> 的 <code>[community] hub = true</code>
|
||||
{' '}或环境变量 <code>JIANG13_COMMUNITY_HUB=1</code>
|
||||
),普通部署无需也无法在后台打开。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hubEnabled && (
|
||||
<div className="admin-card admin-links-entry-card" style={{ marginBottom: 16 }}>
|
||||
<div className="admin-card-head">展柜入口</div>
|
||||
<p className="admin-card-desc">
|
||||
控制「开源展柜」出现在何处;关闭后仍可直接访问 /showcase。右侧栏开关与「系统设置 → 右侧栏组件」同源。
|
||||
</p>
|
||||
<div className="admin-card-body admin-links-entry-body">
|
||||
{(
|
||||
[
|
||||
{ key: 'nav' as const, label: '左侧栏(站点)', on: entryFlags.nav },
|
||||
{ key: 'aside' as const, label: '右侧栏', on: entryFlags.aside },
|
||||
{ key: 'footer' as const, label: '页脚', on: entryFlags.footer },
|
||||
]
|
||||
).map(item => (
|
||||
<div key={item.key} className="admin-links-entry-row">
|
||||
<span id={`admin-showcase-entry-${item.key}`}>{item.label}</span>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={item.on}
|
||||
aria-labelledby={`admin-showcase-entry-${item.key}`}
|
||||
disabled={entrySaving}
|
||||
className={cn('admin-settings-switch', item.on && 'is-on')}
|
||||
onClick={() => void patchEntryVisibility({ [item.key]: !item.on })}
|
||||
>
|
||||
<span className="admin-settings-switch-ui" aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="admin-card">
|
||||
<div className="admin-card-head">
|
||||
<span>实例列表</span>
|
||||
<span className="admin-settings-card-badge">{list.length} 个</span>
|
||||
</div>
|
||||
<div className="admin-card-body" style={{ padding: 0 }}>
|
||||
{list.length === 0 ? (
|
||||
<p className="admin-empty" style={{ padding: 24 }}>暂无上报记录</p>
|
||||
) : (
|
||||
<div className="admin-table-wrap">
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>状态</th>
|
||||
<th>站点</th>
|
||||
<th>版本</th>
|
||||
<th>用户</th>
|
||||
<th>帖子</th>
|
||||
<th>最近心跳</th>
|
||||
<th>精选</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{list.map((row) => (
|
||||
<tr key={row.instance_id}>
|
||||
<td>
|
||||
<Badge variant={row.online ? 'default' : 'secondary'}>
|
||||
{row.online ? '在线' : '离线'}
|
||||
</Badge>
|
||||
</td>
|
||||
<td>
|
||||
<div className="admin-community-site">
|
||||
<strong>
|
||||
{row.featured && <Star size={12} className="admin-community-star" aria-hidden />}
|
||||
{row.site_name || '未命名站点'}
|
||||
</strong>
|
||||
<a
|
||||
href={row.site_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={cn('admin-inline-link', 'admin-community-url')}
|
||||
>
|
||||
{row.site_url}
|
||||
<ExternalLink size={12} aria-hidden />
|
||||
</a>
|
||||
</div>
|
||||
</td>
|
||||
<td><code>{row.version || '—'}</code></td>
|
||||
<td>{row.users}</td>
|
||||
<td>{row.posts}</td>
|
||||
<td title={row.last_seen_at}>{formatTime(row.last_seen_at)}</td>
|
||||
<td>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
loading={featuringId === row.instance_id}
|
||||
disabled={!!featuringId}
|
||||
onClick={() => void handleToggleFeatured(row)}
|
||||
>
|
||||
{row.featured ? '取消精选' : '精选'}
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,37 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { FileText, Flag, MessageSquare, Link2 } from 'lucide-react';
|
||||
import { FileText, Flag, MessageSquare, Link2, Activity } from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { api } from '../../api/client';
|
||||
import { useAdminGuard } from '../../layouts/AdminLayout';
|
||||
import type { AdminDashboard } from '../../api/types';
|
||||
import type { AdminDashboard, AdminDashboardTraffic } from '../../api/types';
|
||||
import { cn } from '@/lib/utils';
|
||||
import CommunitySupportStrip from '../../components/admin/CommunitySupportStrip';
|
||||
|
||||
function formatDashNum(n: number) {
|
||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
||||
if (n >= 10_000) return `${(n / 1000).toFixed(1)}k`;
|
||||
return String(n ?? 0);
|
||||
}
|
||||
|
||||
function pvTrendLabel(today: number, yesterday: number) {
|
||||
if (yesterday <= 0) {
|
||||
return today > 0 ? '昨日无数据' : '较昨日 —';
|
||||
}
|
||||
const delta = ((today - yesterday) / yesterday) * 100;
|
||||
if (Math.abs(delta) < 0.5) return '与昨日持平';
|
||||
const abs = Math.abs(delta).toFixed(0);
|
||||
return delta > 0 ? `较昨日 ↑ ${abs}%` : `较昨日 ↓ ${abs}%`;
|
||||
}
|
||||
|
||||
function trendTone(today: number, yesterday: number): 'up' | 'down' | 'flat' {
|
||||
if (yesterday <= 0) return 'flat';
|
||||
const delta = today - yesterday;
|
||||
if (delta > 0) return 'up';
|
||||
if (delta < 0) return 'down';
|
||||
return 'flat';
|
||||
}
|
||||
|
||||
export default function AdminDashboardPage() {
|
||||
const nav = useNavigate();
|
||||
@@ -31,20 +56,16 @@ export default function AdminDashboardPage() {
|
||||
const pendingReports = data.pending_reports ?? 0;
|
||||
const pendingFriendLinks = data.pending_friend_links ?? 0;
|
||||
const pendingTotal = pendingPosts + pendingComments + pendingReports + pendingFriendLinks;
|
||||
|
||||
const stats = [
|
||||
{ label: '注册用户', value: data.users },
|
||||
{ label: '帖子总数', value: data.posts },
|
||||
{ label: '板块数量', value: data.boards },
|
||||
{ label: '评论总数', value: data.comments },
|
||||
];
|
||||
const traffic: AdminDashboardTraffic = data.traffic ?? {
|
||||
enabled: false, today_pv: 0, today_uv: 0, yesterday_pv: 0, total_pv: 0,
|
||||
};
|
||||
|
||||
const queues = [
|
||||
{
|
||||
key: 'posts',
|
||||
label: '待审帖子',
|
||||
count: pendingPosts,
|
||||
hint: '新帖与修改待审核',
|
||||
hint: '新帖与修改',
|
||||
to: '/admin/posts',
|
||||
icon: FileText,
|
||||
},
|
||||
@@ -52,7 +73,7 @@ export default function AdminDashboardPage() {
|
||||
key: 'comments',
|
||||
label: '待审评论',
|
||||
count: pendingComments,
|
||||
hint: '评论与回复待审核',
|
||||
hint: '评论与回复',
|
||||
to: '/admin/comments',
|
||||
icon: MessageSquare,
|
||||
},
|
||||
@@ -60,7 +81,7 @@ export default function AdminDashboardPage() {
|
||||
key: 'reports',
|
||||
label: '待处理举报',
|
||||
count: pendingReports,
|
||||
hint: '用户举报需人工处理',
|
||||
hint: '用户举报',
|
||||
to: '/admin/reports',
|
||||
icon: Flag,
|
||||
},
|
||||
@@ -68,65 +89,128 @@ export default function AdminDashboardPage() {
|
||||
key: 'links',
|
||||
label: '待审友链',
|
||||
count: pendingFriendLinks,
|
||||
hint: '用户提交的友情链接申请',
|
||||
hint: '友链申请',
|
||||
to: '/admin/links',
|
||||
icon: Link2,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="admin-page">
|
||||
<div className="admin-page-head">
|
||||
<h1>仪表盘</h1>
|
||||
<p>优先处理待办,再查看运行概览</p>
|
||||
</div>
|
||||
const scale = [
|
||||
{ label: '注册用户', value: data.users },
|
||||
{ label: '帖子总数', value: data.posts },
|
||||
{ label: '板块数量', value: data.boards },
|
||||
{ label: '评论总数', value: data.comments },
|
||||
];
|
||||
|
||||
<section className="admin-queue-section" aria-label="待处理事项">
|
||||
<div className="admin-section-label">
|
||||
<span>待处理</span>
|
||||
{pendingTotal > 0 ? (
|
||||
<Badge variant="orange">{pendingTotal} 项</Badge>
|
||||
) : (
|
||||
<span className="admin-section-muted">暂无积压</span>
|
||||
const tone = trendTone(traffic.today_pv, traffic.yesterday_pv);
|
||||
|
||||
return (
|
||||
<div className="admin-page admin-dash-page">
|
||||
<div className="admin-page-head admin-dash-head">
|
||||
<div className="admin-dash-head-title">
|
||||
<h1>仪表盘</h1>
|
||||
{pendingTotal > 0 && (
|
||||
<Badge variant="orange">{pendingTotal} 项待处理</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="admin-queue-grid">
|
||||
{queues.map(q => {
|
||||
const Icon = q.icon;
|
||||
const hasWork = q.count > 0;
|
||||
return (
|
||||
<button
|
||||
key={q.key}
|
||||
type="button"
|
||||
className={cn('admin-queue-card', hasWork && 'has-work')}
|
||||
onClick={() => nav(q.to)}
|
||||
>
|
||||
<div className="admin-queue-card-top">
|
||||
<Icon size={18} aria-hidden />
|
||||
<span className="admin-queue-count">{q.count}</span>
|
||||
</div>
|
||||
<div className="admin-queue-label">{q.label}</div>
|
||||
<div className="admin-queue-hint">{q.hint}</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
<p>处理待办,并一眼看到今日访问</p>
|
||||
</div>
|
||||
|
||||
<section className="admin-stat-section" aria-label="运行概览">
|
||||
<div className="admin-section-label">
|
||||
<span>运行概览</span>
|
||||
<div className="admin-dash-bento">
|
||||
<section className="admin-dash-traffic" aria-label="今日访问">
|
||||
<div className="admin-dash-traffic-top">
|
||||
<div className="admin-dash-section-label">
|
||||
<span className="admin-monitor-section-bar" aria-hidden />
|
||||
<h2>今日访问</h2>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-text-link admin-dash-link"
|
||||
onClick={() => nav('/admin/monitor')}
|
||||
>
|
||||
<Activity size={14} aria-hidden />
|
||||
网站监控 →
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!traffic.enabled ? (
|
||||
<div className="admin-dash-traffic-empty">
|
||||
<p>访问采集尚未开启,流量统计暂不可用。</p>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-text-link"
|
||||
onClick={() => nav('/admin/monitor?tab=settings')}
|
||||
>
|
||||
前往开启 →
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="admin-dash-traffic-pv">{formatDashNum(traffic.today_pv)}</div>
|
||||
<div className="admin-dash-traffic-meta">
|
||||
<span>今日访问 (PV)</span>
|
||||
<span className="admin-dash-traffic-uv">今日访客 (UV) {formatDashNum(traffic.today_uv)}</span>
|
||||
</div>
|
||||
<div className={cn('admin-dash-traffic-trend', `is-${tone}`)}>
|
||||
{pvTrendLabel(traffic.today_pv, traffic.yesterday_pv)}
|
||||
</div>
|
||||
<p className="admin-dash-traffic-total">
|
||||
累计访问 {formatDashNum(traffic.total_pv)}
|
||||
<span className="admin-dash-traffic-hint">(受日志保留天数影响)</span>
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="admin-dash-queue" aria-label="待处理事项">
|
||||
<div className="admin-dash-section-label admin-dash-queue-head">
|
||||
<span className="admin-monitor-section-bar" aria-hidden />
|
||||
<h2>待处理</h2>
|
||||
{pendingTotal === 0 && (
|
||||
<span className="admin-section-muted">暂无积压</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="admin-dash-queue-grid">
|
||||
{queues.map((q) => {
|
||||
const Icon = q.icon;
|
||||
const hasWork = q.count > 0;
|
||||
return (
|
||||
<button
|
||||
key={q.key}
|
||||
type="button"
|
||||
className={cn('admin-dash-queue-card', hasWork && 'has-work')}
|
||||
onClick={() => nav(q.to)}
|
||||
>
|
||||
<div className="admin-dash-queue-card-top">
|
||||
<Icon size={16} aria-hidden />
|
||||
<span className="admin-dash-queue-count">{q.count}</span>
|
||||
</div>
|
||||
<div className="admin-dash-queue-label">{q.label}</div>
|
||||
<div className="admin-dash-queue-hint">{q.hint}</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section className="admin-dash-scale" aria-label="内容规模">
|
||||
<div className="admin-dash-section-label">
|
||||
<span className="admin-monitor-section-bar" aria-hidden />
|
||||
<h2>内容规模</h2>
|
||||
</div>
|
||||
<div className="admin-stat-grid">
|
||||
{stats.map(s => (
|
||||
<div key={s.label} className="admin-stat-card">
|
||||
<div className="admin-stat-value">{s.value}</div>
|
||||
<div className="admin-stat-label">{s.label}</div>
|
||||
<div className="admin-dash-metric-grid">
|
||||
{scale.map((s) => (
|
||||
<div key={s.label} className="admin-dash-metric-card">
|
||||
<div className="admin-dash-metric-value">{formatDashNum(s.value)}</div>
|
||||
<div className="admin-dash-metric-label">{s.label}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<CommunitySupportStrip />
|
||||
|
||||
<div className="admin-card">
|
||||
<div className="admin-card-head">
|
||||
<span>最新帖子</span>
|
||||
@@ -145,7 +229,7 @@ export default function AdminDashboardPage() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.recent_posts.map(p => (
|
||||
{data.recent_posts.map((p) => (
|
||||
<tr key={p.id}>
|
||||
<td>{p.id}</td>
|
||||
<td>
|
||||
@@ -161,7 +245,7 @@ export default function AdminDashboardPage() {
|
||||
) : '—'}
|
||||
</td>
|
||||
<td className="space-x-1">
|
||||
{p.featured ? <Badge variant="orange">精华</Badge> : null}
|
||||
{p.featured ? <Badge variant="orange">推荐</Badge> : null}
|
||||
{p.pinned ? <Badge variant="green">全局置顶</Badge> : null}
|
||||
{p.board_pinned ? <Badge variant="green">板块置顶</Badge> : null}
|
||||
{!p.featured && !p.pinned && !p.board_pinned ? '—' : null}
|
||||
|
||||
@@ -22,6 +22,7 @@ import { cn } from '@/lib/utils';
|
||||
import { api } from '../../api/client';
|
||||
import { useAdminGuard } from '../../layouts/AdminLayout';
|
||||
import type { ForumLimits, FriendLink, FriendLinkApply, SiteBranding } from '../../api/types';
|
||||
import { DEFAULT_FEED_SORT_TABS } from '../../api/types';
|
||||
import { useSiteBranding, seedSiteBrandingCache, invalidateSiteBrandingCache } from '../../hooks/useSiteBranding';
|
||||
import { invalidateForumLimitsCache } from '../../hooks/useForumLimits';
|
||||
import { formatTime } from '../../utils/content';
|
||||
@@ -178,10 +179,14 @@ export default function AdminLinksPage() {
|
||||
aside_show_tag_cloud: false,
|
||||
aside_show_recent_comments: false,
|
||||
aside_show_friend_links: true,
|
||||
aside_show_showcase: false,
|
||||
aside_widgets: loadedAsideWidgets,
|
||||
nav_show_friend_links: true,
|
||||
footer_show_friend_links: true,
|
||||
nav_show_showcase: false,
|
||||
footer_show_showcase: false,
|
||||
feed_list_style: 'title',
|
||||
feed_sort_tabs: DEFAULT_FEED_SORT_TABS,
|
||||
permalink_enabled: false,
|
||||
permalink_ext: 'html',
|
||||
...s.limits,
|
||||
@@ -350,15 +355,20 @@ export default function AdminLinksPage() {
|
||||
aside_show_tag_cloud: false,
|
||||
aside_show_recent_comments: false,
|
||||
aside_show_friend_links: nextFlags.aside,
|
||||
aside_show_showcase: false,
|
||||
aside_widgets: normalizeAsideWidgets([
|
||||
{ id: 'tag_cloud', enabled: false },
|
||||
{ id: 'recent_comments', enabled: false },
|
||||
{ id: 'recent_users', enabled: false },
|
||||
{ id: 'friend_links', enabled: nextFlags.aside },
|
||||
{ id: 'showcase', enabled: false },
|
||||
]),
|
||||
nav_show_friend_links: nextFlags.nav,
|
||||
footer_show_friend_links: nextFlags.footer,
|
||||
nav_show_showcase: false,
|
||||
footer_show_showcase: false,
|
||||
feed_list_style: 'title',
|
||||
feed_sort_tabs: DEFAULT_FEED_SORT_TABS,
|
||||
permalink_enabled: false,
|
||||
permalink_ext: 'html',
|
||||
post_edit_window_hours: 24,
|
||||
|
||||
733
frontend/src/pages/admin/AdminMonitorPage.tsx
Normal file
733
frontend/src/pages/admin/AdminMonitorPage.tsx
Normal file
@@ -0,0 +1,733 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { Activity, AlertTriangle } from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { api } from '../../api/client';
|
||||
import type {
|
||||
MonitorASNItem,
|
||||
MonitorCityItem,
|
||||
MonitorConfig,
|
||||
MonitorGeoResult,
|
||||
MonitorLogItem,
|
||||
MonitorOverview,
|
||||
MonitorRealtime,
|
||||
MonitorStatItem,
|
||||
} from '../../api/types';
|
||||
import { useAdminGuard } from '../../layouts/AdminLayout';
|
||||
import { formatTime } from '../../utils/content';
|
||||
import { invalidateForumLimitsCache } from '../../hooks/useForumLimits';
|
||||
import MonitorWorldMap from '../../components/admin/MonitorWorldMap';
|
||||
import MonitorChinaMap from '../../components/admin/MonitorChinaMap';
|
||||
import { countryLabelZh } from '../../components/admin/monitorMapUtils';
|
||||
|
||||
type TabKey = 'overview' | 'stats' | 'logs' | 'settings';
|
||||
type StatsDim = 'url' | 'referer' | 'browser' | 'os' | 'device' | 'status';
|
||||
type StatsRange = '1d' | '7d' | '30d' | '90d';
|
||||
type MapMode = 'world' | 'china';
|
||||
type RankMode = 'city' | 'asn';
|
||||
|
||||
function countryLabel(code: string) {
|
||||
return countryLabelZh(code);
|
||||
}
|
||||
|
||||
function formatBytes(n: number) {
|
||||
if (!n || n < 0) return '0 B';
|
||||
const u = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
let v = n;
|
||||
let i = 0;
|
||||
while (v >= 1024 && i < u.length - 1) {
|
||||
v /= 1024;
|
||||
i++;
|
||||
}
|
||||
return `${v < 10 && i > 0 ? v.toFixed(1) : Math.round(v)} ${u[i]}`;
|
||||
}
|
||||
|
||||
function formatNum(n: number) {
|
||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
||||
if (n >= 10_000) return `${(n / 1000).toFixed(1)}k`;
|
||||
return String(n ?? 0);
|
||||
}
|
||||
|
||||
function MiniSparkline({ series }: { series: { count: number }[] }) {
|
||||
const max = Math.max(1, ...series.map((p) => p.count));
|
||||
const w = 240;
|
||||
const h = 48;
|
||||
const pts = series.map((p, i) => {
|
||||
const x = series.length <= 1 ? 0 : (i / (series.length - 1)) * w;
|
||||
const y = h - (p.count / max) * (h - 4) - 2;
|
||||
return `${x},${y}`;
|
||||
}).join(' ');
|
||||
return (
|
||||
<svg className="admin-monitor-spark" viewBox={`0 0 ${w} ${h}`} width="100%" height={h} aria-hidden>
|
||||
<polyline fill="none" stroke="var(--j13-green)" strokeWidth="2" points={pts} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const CHINA_CODES = new Set(['CN', 'HK', 'TW', 'MO']);
|
||||
|
||||
function geoCountries(geo: MonitorGeoResult | null) {
|
||||
return geo?.countries || [];
|
||||
}
|
||||
|
||||
function GeoRankTable({
|
||||
cities,
|
||||
asns,
|
||||
mode,
|
||||
rankMode,
|
||||
onRankMode,
|
||||
hasCountryHits,
|
||||
}: {
|
||||
cities: MonitorCityItem[];
|
||||
asns: MonitorASNItem[];
|
||||
mode: MapMode;
|
||||
rankMode: RankMode;
|
||||
onRankMode: (m: RankMode) => void;
|
||||
/** 近 30 日是否已有国家级浏览量(用于区分「无 PV 地理」与缺库) */
|
||||
hasCountryHits: boolean;
|
||||
}) {
|
||||
const cityRows = mode === 'china'
|
||||
? cities.filter((i) => CHINA_CODES.has((i.country || '').toUpperCase()))
|
||||
: cities;
|
||||
const rows = rankMode === 'city' ? cityRows : asns;
|
||||
const emptyHint = rankMode === 'city'
|
||||
? (hasCountryHits
|
||||
? '需前台路由产生带城市的浏览量;仅请求日志不会进入此排行。请确认已放置 IP2Location DB3 BIN。'
|
||||
: '需前台路由产生浏览量后才会有城市排行;仅请求日志不会点亮此处。')
|
||||
: (hasCountryHits
|
||||
? '需浏览量写入 ASN;请确认已放置 GeoLite2-ASN.mmdb。仅请求日志不会进入此排行。'
|
||||
: '需前台路由产生浏览量后才会有运营商排行;仅请求日志不会点亮此处。');
|
||||
|
||||
return (
|
||||
<div className="admin-monitor-rank">
|
||||
<div className="admin-monitor-seg" role="group" aria-label="排行维度">
|
||||
<button
|
||||
type="button"
|
||||
className={cn('admin-monitor-seg-btn', rankMode === 'city' && 'active')}
|
||||
onClick={() => onRankMode('city')}
|
||||
>
|
||||
城市
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cn('admin-monitor-seg-btn', rankMode === 'asn' && 'active')}
|
||||
onClick={() => onRankMode('asn')}
|
||||
>
|
||||
运营商
|
||||
</button>
|
||||
</div>
|
||||
{rows.length === 0 ? (
|
||||
<div className="admin-monitor-geo-empty">
|
||||
<p>暂无浏览量来源数据</p>
|
||||
<p className="admin-monitor-muted">{emptyHint}</p>
|
||||
</div>
|
||||
) : (
|
||||
<table className="admin-monitor-geo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{rankMode === 'city' ? '城市' : '运营商'}</th>
|
||||
<th>数量</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rankMode === 'city'
|
||||
? cityRows.slice(0, 12).map((item, idx) => (
|
||||
<tr key={`${item.country}-${item.city}-${idx}`}>
|
||||
<td title={[item.region, item.city].filter(Boolean).join(' · ')}>
|
||||
{item.city}
|
||||
{item.region ? <span className="admin-monitor-muted"> · {item.region}</span> : null}
|
||||
</td>
|
||||
<td>{formatNum(item.count)}</td>
|
||||
</tr>
|
||||
))
|
||||
: asns.slice(0, 12).map((item) => (
|
||||
<tr key={item.asn}>
|
||||
<td title={item.as_org || `AS${item.asn}`}>
|
||||
{item.as_org || `AS${item.asn}`}
|
||||
<span className="admin-monitor-muted"> · AS{item.asn}</span>
|
||||
</td>
|
||||
<td>{formatNum(item.count)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function parseMonitorTab(raw: string | null): TabKey {
|
||||
if (raw === 'stats' || raw === 'logs' || raw === 'settings' || raw === 'overview') {
|
||||
return raw;
|
||||
}
|
||||
return 'overview';
|
||||
}
|
||||
|
||||
export default function AdminMonitorPage() {
|
||||
const { ready } = useAdminGuard();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [tab, setTab] = useState<TabKey>(() => parseMonitorTab(searchParams.get('tab')));
|
||||
const [overview, setOverview] = useState<MonitorOverview | null>(null);
|
||||
const [geo, setGeo] = useState<MonitorGeoResult | null>(null);
|
||||
const [realtime, setRealtime] = useState<MonitorRealtime | null>(null);
|
||||
const [mapMode, setMapMode] = useState<MapMode>('world');
|
||||
const [rankMode, setRankMode] = useState<RankMode>('city');
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const [statsDim, setStatsDim] = useState<StatsDim>('url');
|
||||
const [statsRange, setStatsRange] = useState<StatsRange>('30d');
|
||||
const [statsItems, setStatsItems] = useState<MonitorStatItem[]>([]);
|
||||
const [statsLoading, setStatsLoading] = useState(false);
|
||||
|
||||
const [logs, setLogs] = useState<MonitorLogItem[]>([]);
|
||||
const [logsTotal, setLogsTotal] = useState(0);
|
||||
const [logsPage, setLogsPage] = useState(1);
|
||||
const [logMethod, setLogMethod] = useState('');
|
||||
const [logPath, setLogPath] = useState('');
|
||||
const [logStatus, setLogStatus] = useState('');
|
||||
const [logIP, setLogIP] = useState('');
|
||||
const [logsLoading, setLogsLoading] = useState(false);
|
||||
|
||||
const [settings, setSettings] = useState<MonitorConfig | null>(null);
|
||||
const [excludeText, setExcludeText] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const next = parseMonitorTab(searchParams.get('tab'));
|
||||
setTab((prev) => (prev === next ? prev : next));
|
||||
}, [searchParams]);
|
||||
|
||||
const selectTab = (key: TabKey) => {
|
||||
setTab(key);
|
||||
const next = new URLSearchParams(searchParams);
|
||||
if (key === 'overview') next.delete('tab');
|
||||
else next.set('tab', key);
|
||||
setSearchParams(next, { replace: true });
|
||||
};
|
||||
|
||||
const loadOverview = useCallback(async () => {
|
||||
const [ov, g, rt] = await Promise.all([
|
||||
api.adminMonitorOverview(),
|
||||
api.adminMonitorGeo('30d'),
|
||||
api.adminMonitorRealtime(),
|
||||
]);
|
||||
setOverview(ov);
|
||||
setGeo(g);
|
||||
setRealtime(rt);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
setLoading(true);
|
||||
loadOverview()
|
||||
.catch(() => notify.error('加载监控概览失败'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [ready, loadOverview]);
|
||||
|
||||
// 概览页实时轮询
|
||||
useEffect(() => {
|
||||
if (!ready || tab !== 'overview') return;
|
||||
const id = window.setInterval(() => {
|
||||
api.adminMonitorRealtime().then(setRealtime).catch(() => {});
|
||||
api.adminMonitorOverview().then(setOverview).catch(() => {});
|
||||
}, 5000);
|
||||
return () => window.clearInterval(id);
|
||||
}, [ready, tab]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || tab !== 'stats') return;
|
||||
setStatsLoading(true);
|
||||
api.adminMonitorStats(statsDim, statsRange)
|
||||
.then((r) => setStatsItems(r.items || []))
|
||||
.catch(() => notify.error('加载统计失败'))
|
||||
.finally(() => setStatsLoading(false));
|
||||
}, [ready, tab, statsDim, statsRange]);
|
||||
|
||||
const loadLogs = useCallback(async (page = 1) => {
|
||||
setLogsLoading(true);
|
||||
try {
|
||||
const r = await api.adminMonitorLogs({
|
||||
page,
|
||||
size: 20,
|
||||
method: logMethod || undefined,
|
||||
path: logPath || undefined,
|
||||
status: logStatus || undefined,
|
||||
ip: logIP || undefined,
|
||||
});
|
||||
setLogs(r.items || []);
|
||||
setLogsTotal(r.total || 0);
|
||||
setLogsPage(r.page || page);
|
||||
} catch {
|
||||
notify.error('加载请求日志失败');
|
||||
} finally {
|
||||
setLogsLoading(false);
|
||||
}
|
||||
}, [logMethod, logPath, logStatus, logIP]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || tab !== 'logs') return;
|
||||
loadLogs(1);
|
||||
}, [ready, tab, loadLogs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || tab !== 'settings') return;
|
||||
api.adminMonitorSettings()
|
||||
.then((cfg) => {
|
||||
setSettings(cfg);
|
||||
setExcludeText((cfg.exclude_rules || []).join('\n'));
|
||||
})
|
||||
.catch(() => notify.error('加载设置失败'));
|
||||
}, [ready, tab]);
|
||||
|
||||
const enabled = overview?.enabled ?? settings?.enabled ?? false;
|
||||
|
||||
const metrics = useMemo(() => {
|
||||
if (!overview) return [];
|
||||
const pvHint = '前台浏览';
|
||||
const accessHintShort = '服务端请求';
|
||||
const accessHintFull = '服务端请求(含 API,重启后重计)';
|
||||
return [
|
||||
{ label: '浏览量', hint: pvHint, title: pvHint, value: formatNum(overview.pageviews) },
|
||||
{ label: '访客数', hint: pvHint, title: pvHint, value: formatNum(overview.visitors) },
|
||||
{ label: '独立 IP', hint: accessHintShort, title: accessHintFull, value: formatNum(overview.unique_ips) },
|
||||
{ label: '流量', hint: accessHintShort, title: accessHintFull, value: formatBytes(overview.traffic) },
|
||||
{ label: '蜘蛛', hint: accessHintShort, title: accessHintFull, value: formatNum(overview.bots) },
|
||||
{ label: '请求数', hint: accessHintShort, title: accessHintFull, value: formatNum(overview.requests) },
|
||||
{ label: '4xx', hint: accessHintShort, title: accessHintFull, value: formatNum(overview.status_4xx) },
|
||||
{ label: '5xx', hint: accessHintShort, title: accessHintFull, value: formatNum(overview.status_5xx) },
|
||||
];
|
||||
}, [overview]);
|
||||
|
||||
const hasCountryHits = (geo?.countries?.length || 0) > 0;
|
||||
const hasRegionHits = (geo?.regions?.length || 0) > 0;
|
||||
|
||||
const saveSettings = async () => {
|
||||
if (!settings) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const rules = excludeText.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
||||
const r = await api.adminUpdateMonitorSettings({
|
||||
...settings,
|
||||
exclude_rules: rules,
|
||||
});
|
||||
setSettings(r.monitor);
|
||||
setExcludeText((r.monitor.exclude_rules || []).join('\n'));
|
||||
invalidateForumLimitsCache();
|
||||
notify.success(r.message);
|
||||
const ov = await api.adminMonitorOverview();
|
||||
setOverview(ov);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!ready || (loading && tab === 'overview')) {
|
||||
return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
|
||||
}
|
||||
|
||||
const tabs: { key: TabKey; label: string }[] = [
|
||||
{ key: 'overview', label: '概览' },
|
||||
{ key: 'stats', label: '访问统计' },
|
||||
{ key: 'logs', label: '请求日志' },
|
||||
{ key: 'settings', label: '设置' },
|
||||
];
|
||||
|
||||
const dims: { key: StatsDim; label: string }[] = [
|
||||
{ key: 'url', label: 'URL' },
|
||||
{ key: 'referer', label: '来源' },
|
||||
{ key: 'browser', label: '浏览器' },
|
||||
{ key: 'os', label: '系统' },
|
||||
{ key: 'device', label: '设备' },
|
||||
{ key: 'status', label: '状态码' },
|
||||
];
|
||||
|
||||
const ranges: { key: StatsRange; label: string }[] = [
|
||||
{ key: '1d', label: '今日' },
|
||||
{ key: '7d', label: '7 日' },
|
||||
{ key: '30d', label: '30 日' },
|
||||
{ key: '90d', label: '90 日' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="admin-page admin-monitor-page">
|
||||
<div className="admin-page-head">
|
||||
<div>
|
||||
<h1 className="admin-page-title">
|
||||
<Activity size={22} aria-hidden />
|
||||
网站监控
|
||||
</h1>
|
||||
<p className="admin-page-desc">
|
||||
浏览量/访客与访客地图来自前台路由 pageview;请求数、流量与请求日志来自服务端访问采集(含 /api,重启后请求类今日指标重计)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-tabs" role="tablist" aria-label="监控分类">
|
||||
{tabs.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === t.key}
|
||||
className={cn('admin-tab', tab === t.key && 'active')}
|
||||
onClick={() => selectTab(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{!enabled && tab !== 'settings' && (
|
||||
<div className="admin-monitor-banner" role="status">
|
||||
<AlertTriangle size={16} aria-hidden />
|
||||
<span>访问采集尚未开启,指标可能为空。</span>
|
||||
<button type="button" className="admin-text-link" onClick={() => selectTab('settings')}>
|
||||
前往设置开启
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'overview' && overview && (
|
||||
<>
|
||||
<section className="admin-card admin-monitor-today" aria-label="今日状态">
|
||||
<div className="admin-monitor-today-head">
|
||||
<span className="admin-monitor-section-bar" aria-hidden />
|
||||
<h2 className="admin-monitor-section-title">今日状态</h2>
|
||||
</div>
|
||||
<div className="admin-monitor-today-grid">
|
||||
{metrics.map((m) => (
|
||||
<div key={m.label} className="admin-monitor-today-item" title={m.title}>
|
||||
<div className="admin-monitor-today-label">
|
||||
{m.label}
|
||||
<span className="admin-monitor-today-hint">{m.hint}</span>
|
||||
</div>
|
||||
<div className="admin-monitor-today-value">{m.value}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="admin-monitor-main">
|
||||
<section className="admin-card admin-monitor-map-panel">
|
||||
<div className="admin-card-head admin-monitor-map-head">
|
||||
<div className="admin-monitor-today-head" style={{ marginBottom: 0 }}>
|
||||
<span className="admin-monitor-section-bar" aria-hidden />
|
||||
<div>
|
||||
<h2 className="admin-monitor-section-title">访客地图</h2>
|
||||
<p className="admin-monitor-map-sub">
|
||||
基于前台浏览 · 近 30 日
|
||||
{mapMode === 'china' ? ' · 按省/区填色' : ' · 按国家填色'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-monitor-seg" role="group" aria-label="地图范围">
|
||||
<button
|
||||
type="button"
|
||||
className={cn('admin-monitor-seg-btn', mapMode === 'world' && 'active')}
|
||||
onClick={() => setMapMode('world')}
|
||||
>
|
||||
世界
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cn('admin-monitor-seg-btn', mapMode === 'china' && 'active')}
|
||||
onClick={() => setMapMode('china')}
|
||||
>
|
||||
中国
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-card-body admin-monitor-map-body">
|
||||
<div className="admin-monitor-map-visual">
|
||||
{mapMode === 'world' ? (
|
||||
<MonitorWorldMap items={geoCountries(geo)} />
|
||||
) : (
|
||||
<MonitorChinaMap
|
||||
regions={geo?.regions || []}
|
||||
hasCountryHits={hasCountryHits}
|
||||
hasRegionHits={hasRegionHits}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="admin-monitor-map-side">
|
||||
<GeoRankTable
|
||||
cities={geo?.cities || []}
|
||||
asns={geo?.asns || []}
|
||||
mode={mapMode}
|
||||
rankMode={rankMode}
|
||||
onRankMode={setRankMode}
|
||||
hasCountryHits={hasCountryHits}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="admin-monitor-rt-stack">
|
||||
<section className="admin-card admin-monitor-rt-card">
|
||||
<div className="admin-monitor-today-head">
|
||||
<span className="admin-monitor-section-bar" aria-hidden />
|
||||
<h2 className="admin-monitor-section-title">实时请求数(1 分钟)</h2>
|
||||
</div>
|
||||
<div className="admin-monitor-rt-value">{formatNum(realtime?.requests_1m || 0)}</div>
|
||||
</section>
|
||||
<section className="admin-card admin-monitor-rt-card">
|
||||
<div className="admin-monitor-today-head">
|
||||
<span className="admin-monitor-section-bar" aria-hidden />
|
||||
<h2 className="admin-monitor-section-title">实时流量(1 分钟)</h2>
|
||||
</div>
|
||||
<div className="admin-monitor-rt-value">{formatBytes(realtime?.traffic_1m || 0)}</div>
|
||||
<p className="admin-monitor-muted admin-monitor-rt-spark-label">近 1 小时请求</p>
|
||||
<MiniSparkline series={realtime?.hourly_series || []} />
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === 'stats' && (
|
||||
<div className="admin-card">
|
||||
<div className="admin-card-head">
|
||||
<div className="admin-tabs" style={{ marginBottom: 0 }}>
|
||||
{dims.map((d) => (
|
||||
<button
|
||||
key={d.key}
|
||||
type="button"
|
||||
className={cn('admin-tab', statsDim === d.key && 'active')}
|
||||
onClick={() => setStatsDim(d.key)}
|
||||
>
|
||||
{d.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="admin-tabs" style={{ marginBottom: 0 }}>
|
||||
{ranges.map((r) => (
|
||||
<button
|
||||
key={r.key}
|
||||
type="button"
|
||||
className={cn('admin-tab', statsRange === r.key && 'active')}
|
||||
onClick={() => setStatsRange(r.key)}
|
||||
>
|
||||
{r.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-card-body" style={{ padding: 0 }}>
|
||||
{statsLoading ? (
|
||||
<div className="flex justify-center py-12"><Spinner /></div>
|
||||
) : statsItems.length === 0 ? (
|
||||
<p className="admin-empty">暂无统计数据</p>
|
||||
) : (
|
||||
<div className="admin-table-wrap">
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 48 }}>#</th>
|
||||
<th>名称</th>
|
||||
<th style={{ width: 100 }}>数量</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{statsItems.map((item, idx) => (
|
||||
<tr key={`${item.key}-${idx}`}>
|
||||
<td>{idx + 1}</td>
|
||||
<td className="admin-table-mono" title={item.key}>{item.key}</td>
|
||||
<td>{formatNum(item.count)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'logs' && (
|
||||
<div className="admin-card">
|
||||
<div className="admin-form-row admin-monitor-log-filters">
|
||||
<Input value={logMethod} onChange={(e) => setLogMethod(e.target.value)} placeholder="方法 GET" aria-label="方法" style={{ width: 100 }} />
|
||||
<Input value={logPath} onChange={(e) => setLogPath(e.target.value)} placeholder="路径包含…" aria-label="路径" />
|
||||
<Input value={logStatus} onChange={(e) => setLogStatus(e.target.value)} placeholder="状态码" aria-label="状态码" style={{ width: 90 }} />
|
||||
<Input value={logIP} onChange={(e) => setLogIP(e.target.value)} placeholder="IP 包含…" aria-label="IP" style={{ width: 140 }} />
|
||||
<Button type="button" variant="outline" onClick={() => loadLogs(1)}>筛选</Button>
|
||||
</div>
|
||||
<div className="admin-card-body" style={{ padding: 0 }}>
|
||||
{logsLoading ? (
|
||||
<div className="flex justify-center py-12"><Spinner /></div>
|
||||
) : logs.length === 0 ? (
|
||||
<p className="admin-empty">暂无请求日志</p>
|
||||
) : (
|
||||
<div className="admin-table-wrap">
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>时间</th>
|
||||
<th>方法</th>
|
||||
<th>路径</th>
|
||||
<th>状态</th>
|
||||
<th>IP</th>
|
||||
<th>耗时</th>
|
||||
<th>地区</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{logs.map((row) => {
|
||||
const placeBits = [row.region, row.city, row.as_org].filter(Boolean);
|
||||
const geoBits = [
|
||||
row.country ? countryLabel(row.country) : '',
|
||||
...placeBits,
|
||||
].filter(Boolean);
|
||||
return (
|
||||
<tr key={row.id}>
|
||||
<td>{formatTime(row.created_at)}</td>
|
||||
<td>{row.method}</td>
|
||||
<td className="admin-table-mono" title={row.path}>{row.path}</td>
|
||||
<td>{row.status}</td>
|
||||
<td className="admin-table-mono">
|
||||
{row.ip || '—'}
|
||||
{row.is_bot ? ' · bot' : ''}
|
||||
{placeBits.length > 0 ? (
|
||||
<div className="admin-monitor-muted" style={{ fontSize: 12 }}>
|
||||
{placeBits.join(' · ')}
|
||||
</div>
|
||||
) : null}
|
||||
</td>
|
||||
<td>{row.duration_ms}ms</td>
|
||||
<td title={geoBits.join(' · ')}>{row.country ? countryLabel(row.country) : '—'}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{logsTotal > 20 && (
|
||||
<div className="admin-form-row" style={{ justifyContent: 'flex-end' }}>
|
||||
<Button type="button" variant="outline" disabled={logsPage <= 1} onClick={() => loadLogs(logsPage - 1)}>上一页</Button>
|
||||
<span className="admin-monitor-muted">第 {logsPage} 页 / 共 {logsTotal} 条</span>
|
||||
<Button type="button" variant="outline" disabled={logsPage * 20 >= logsTotal} onClick={() => loadLogs(logsPage + 1)}>下一页</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'settings' && settings && (
|
||||
<div className="admin-card admin-settings-card">
|
||||
<div className="admin-card-head">采集设置</div>
|
||||
<div className="admin-card-body admin-monitor-settings">
|
||||
<label className="admin-monitor-switch-row">
|
||||
<div>
|
||||
<strong>启用访问采集</strong>
|
||||
<p className="admin-monitor-muted">
|
||||
默认关闭。开启后:前台路由上报浏览量/访客;服务端记录请求日志与请求数(含 API)。后台与登录页不上报 pageview。
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={settings.enabled}
|
||||
onCheckedChange={(v) => setSettings({ ...settings, enabled: v })}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="admin-monitor-field">
|
||||
<span>浏览量保留天数(独立 monitor.db,1–365)</span>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={365}
|
||||
value={settings.retention_days}
|
||||
onChange={(e) => setSettings({ ...settings, retention_days: Number(e.target.value) || 30 })}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="admin-monitor-field">
|
||||
<span>请求日志保留天数(JSONL,1–365)</span>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={365}
|
||||
value={settings.access_log_retention_days ?? 7}
|
||||
onChange={(e) => setSettings({ ...settings, access_log_retention_days: Number(e.target.value) || 7 })}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="admin-monitor-switch-row">
|
||||
<div>
|
||||
<strong>信任代理头</strong>
|
||||
<p className="admin-monitor-muted">从 X-Forwarded-For / CF-Connecting-IP 等读取真实 IP</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={settings.trust_proxy}
|
||||
onCheckedChange={(v) => setSettings({ ...settings, trust_proxy: v })}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="admin-monitor-field">
|
||||
<span>排除规则(每行一条:路径前缀或扩展名如 .js)</span>
|
||||
<textarea
|
||||
className="admin-monitor-textarea"
|
||||
rows={8}
|
||||
value={excludeText}
|
||||
onChange={(e) => setExcludeText(e.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
style={{ marginTop: 8 }}
|
||||
onClick={() => setExcludeText((settings.default_exclude_rules || []).join('\n'))}
|
||||
>
|
||||
恢复推荐排除规则
|
||||
</Button>
|
||||
</label>
|
||||
|
||||
<div className="admin-monitor-geo-note">
|
||||
<strong>GeoIP(地理与运营商)</strong>
|
||||
<p className="admin-monitor-muted">
|
||||
国家/省/市由 IP2Location DB3 BIN 解析;ASN 由 GeoLite2-ASN.mmdb 解析(Docker 镜像不内置,需放入数据目录):
|
||||
</p>
|
||||
<ul className="admin-monitor-muted" style={{ margin: '8px 0 0', paddingLeft: 18 }}>
|
||||
<li>
|
||||
IPv4 BIN:<code>{settings.ip2location_v4_path || 'data/IP2LOCATION-LITE-DB3.BIN'}</code>
|
||||
{' · '}{settings.ip2location_v4_available ? '已加载' : '未检测到'}
|
||||
</li>
|
||||
<li>
|
||||
IPv6 BIN:<code>{settings.ip2location_v6_path || 'data/IP2LOCATION-LITE-DB3.IPV6.BIN'}</code>
|
||||
{' · '}{settings.ip2location_v6_available ? '已加载' : '未检测到'}
|
||||
</li>
|
||||
<li>
|
||||
ASN:<code>{settings.geoip_asn_path || 'data/GeoLite2-ASN.mmdb'}</code>
|
||||
{' · '}{settings.geoip_asn_available ? '已加载' : '未检测到'}
|
||||
</li>
|
||||
<li>
|
||||
Country 兜底:<code>{settings.geoip_country_path || 'data/GeoLite2-Country.mmdb'}</code>
|
||||
{' · '}{settings.geoip_country_available ? '已加载' : '未检测到(可选)'}
|
||||
</li>
|
||||
</ul>
|
||||
<p className="admin-monitor-muted" style={{ marginTop: 8 }}>
|
||||
请求日志目录:<code>{settings.access_log_dir || 'data/logs/access'}</code>
|
||||
(按日 JSONL 文件,删除过期文件即可释放磁盘)
|
||||
</p>
|
||||
<p className="admin-monitor-muted" style={{ marginTop: 8 }}>
|
||||
CDN 国家头(如 CF-IPCountry)仅在本地库无国家码时补全。管理端展示完整客户端 IP。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Button type="button" onClick={saveSettings} disabled={saving}>
|
||||
{saving ? '保存中…' : '保存设置'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -218,7 +218,7 @@ export default function AdminPostsPage() {
|
||||
? '回收站中的帖子可恢复或永久删除;永久删除后不可撤销'
|
||||
: tab === 'pending'
|
||||
? '审核普通用户提交的帖子;通过后公开,拒绝后仅作者可见并私信通知'
|
||||
: '精华、全局置顶、板块置顶、锁定编辑/讨论、删除(移入回收站);支持按标题、标签或正文搜索'}
|
||||
: '推荐、全局置顶、板块置顶、锁定编辑/讨论、删除(移入回收站);支持按标题、标签或正文搜索'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -337,7 +337,7 @@ export default function AdminPostsPage() {
|
||||
<th>作者</th>
|
||||
<th>标签</th>
|
||||
<th>评论</th>
|
||||
<th>精华</th>
|
||||
<th>推荐</th>
|
||||
<th>全局置顶</th>
|
||||
<th>板块置顶</th>
|
||||
<th>编辑锁</th>
|
||||
@@ -396,7 +396,7 @@ export default function AdminPostsPage() {
|
||||
</Button>
|
||||
)}
|
||||
<Button size="sm" variant="outline" onClick={() => toggleFeature(p)}>
|
||||
{p.featured ? '取消精华' : '精华'}
|
||||
{p.featured ? '取消推荐' : '推荐'}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => togglePin(p)}>
|
||||
{p.pinned ? '取消全局置顶' : '全局置顶'}
|
||||
|
||||
@@ -11,9 +11,11 @@ import { invalidateForumLimitsCache } from '../../hooks/useForumLimits';
|
||||
import { DEFAULT_BRANDING, seedSiteBrandingCache } from '../../hooks/useSiteBranding';
|
||||
import { clearAllFeedCache } from '../../utils/feedCache';
|
||||
import { normalizeAsideWidgets, resolveAsideWidgets, mergeForumLimitsWithAsideWidgets, resolveSavedAsideWidgets } from '../../utils/asideWidgets';
|
||||
import { normalizeFeedSortTabs } from '../../utils/feedSortTabs';
|
||||
import AsideWidgetList from '../../components/admin/AsideWidgetList';
|
||||
import FeedSortTabList from '../../components/admin/FeedSortTabList';
|
||||
import type { AdminSettings, ForumLimits, MailConfig, OIDCConfig, OAuthClient, GiteaSyncConfig, StorageConfig, SiteBranding, AsideWidget } from '../../api/types';
|
||||
import { DEFAULT_ASIDE_WIDGETS } from '../../api/types';
|
||||
import { DEFAULT_ASIDE_WIDGETS, DEFAULT_FEED_SORT_TABS } from '../../api/types';
|
||||
|
||||
type TabId = 'branding' | 'limits' | 'mail' | 'oidc' | 'gitea' | 'storage' | 'filter' | 'system';
|
||||
|
||||
@@ -298,10 +300,14 @@ export default function AdminSettingsPage() {
|
||||
aside_show_tag_cloud: false,
|
||||
aside_show_recent_comments: false,
|
||||
aside_show_friend_links: true,
|
||||
aside_show_showcase: false,
|
||||
aside_widgets: loadedAsideWidgets,
|
||||
nav_show_friend_links: true,
|
||||
footer_show_friend_links: true,
|
||||
nav_show_showcase: false,
|
||||
footer_show_showcase: false,
|
||||
feed_list_style: 'title',
|
||||
feed_sort_tabs: normalizeFeedSortTabs(s.limits?.feed_sort_tabs ?? DEFAULT_FEED_SORT_TABS),
|
||||
permalink_enabled: false,
|
||||
permalink_ext: 'html',
|
||||
...s.limits,
|
||||
@@ -913,7 +919,7 @@ export default function AdminSettingsPage() {
|
||||
<section className="admin-settings-section" id="settings-feed-list">
|
||||
<div className="admin-settings-section-head">
|
||||
<h3>列表呈现</h3>
|
||||
<p>首页及帖子列表的信息密度与缩略图展示</p>
|
||||
<p>首页及帖子列表的信息密度、缩略图与排序标签</p>
|
||||
</div>
|
||||
<div className="admin-settings-table" role="group" aria-label="列表呈现">
|
||||
<div className="admin-settings-row">
|
||||
@@ -943,6 +949,16 @@ export default function AdminSettingsPage() {
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-settings-subsection">
|
||||
<h4 className="admin-settings-subsection-title">首页排序标签</h4>
|
||||
<p className="admin-settings-subsection-desc">
|
||||
拖拽调整顺序;在「显示名称」框中改首页文案;右侧开关控制启停。第一个启用项为默认排序。「最新」按发帖与评论的最近时间混排
|
||||
</p>
|
||||
<FeedSortTabList
|
||||
tabs={normalizeFeedSortTabs(limits.feed_sort_tabs ?? DEFAULT_FEED_SORT_TABS)}
|
||||
onChange={tabs => setLimits(prev => prev ? { ...prev, feed_sort_tabs: tabs } : prev)}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="admin-settings-section" id="settings-permalink">
|
||||
@@ -1676,7 +1692,7 @@ export default function AdminSettingsPage() {
|
||||
<div className="admin-card admin-settings-card">
|
||||
<div className="admin-card-head">数据备份</div>
|
||||
<div className="admin-card-body admin-settings-backup-body">
|
||||
<p>导出当前 SQLite 数据库副本,便于迁移或灾难恢复。</p>
|
||||
<p>导出当前主库 SQLite 副本,便于迁移或灾难恢复。不含 <code>monitor.db</code> 浏览量。</p>
|
||||
<p className="admin-settings-backup-name">
|
||||
文件名:<code>jiang13_backup_YYYYMMDD_HHMMSS.db</code>
|
||||
</p>
|
||||
|
||||
106
frontend/src/store/homeStore.ts
Normal file
106
frontend/src/store/homeStore.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { create } from 'zustand';
|
||||
import type { PostItem } from '../api/types';
|
||||
import type { FeedSort } from '../components/FeedSortBar';
|
||||
|
||||
/** 列表缓存过期时间:超过后返回首页时静默刷新,仍先展示旧数据 */
|
||||
export const FEED_STALE_MS = 5 * 60 * 1000;
|
||||
|
||||
/** 单条 Feed 筛选对应的缓存快照 */
|
||||
export type FeedCacheEntry = {
|
||||
posts: PostItem[];
|
||||
postTotal: number;
|
||||
page: number;
|
||||
scrollTop: number;
|
||||
/** 上次成功拉取 API 的时间戳(ms) */
|
||||
lastFetchTime: number;
|
||||
};
|
||||
|
||||
type FeedKeyParts = {
|
||||
boardId: number;
|
||||
keyword: string;
|
||||
sort: FeedSort;
|
||||
tag?: string;
|
||||
author?: string;
|
||||
titleOnly?: boolean;
|
||||
};
|
||||
|
||||
/** 与筛选条件一一对应的缓存键 */
|
||||
export function feedCacheKey(parts: FeedKeyParts): string {
|
||||
const {
|
||||
boardId,
|
||||
keyword,
|
||||
sort,
|
||||
tag = '',
|
||||
author = '',
|
||||
titleOnly = false,
|
||||
} = parts;
|
||||
return `${boardId}:${keyword}:${tag}:${author}:${titleOnly ? 1 : 0}:${sort}`;
|
||||
}
|
||||
|
||||
type HomeStoreState = {
|
||||
/** 按筛选键存放多份列表,首页 / 板块 / 搜索互不覆盖 */
|
||||
feeds: Record<string, FeedCacheEntry>;
|
||||
getFeed: (key: string) => FeedCacheEntry | null;
|
||||
setFeed: (key: string, data: Omit<FeedCacheEntry, 'lastFetchTime'> & { lastFetchTime?: number }) => void;
|
||||
/** 滚动时只更新 scrollTop,不改动列表数据 */
|
||||
patchScroll: (key: string, scrollTop: number) => void;
|
||||
isStale: (key: string, now?: number) => boolean;
|
||||
clearFeed: (key: string) => void;
|
||||
clearAll: () => void;
|
||||
};
|
||||
|
||||
export const useHomeStore = create<HomeStoreState>((set, get) => ({
|
||||
feeds: {},
|
||||
|
||||
getFeed: (key) => get().feeds[key] ?? null,
|
||||
|
||||
setFeed: (key, data) => {
|
||||
set((state) => ({
|
||||
feeds: {
|
||||
...state.feeds,
|
||||
[key]: {
|
||||
posts: data.posts,
|
||||
postTotal: data.postTotal,
|
||||
page: data.page,
|
||||
scrollTop: data.scrollTop,
|
||||
lastFetchTime: data.lastFetchTime ?? Date.now(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
},
|
||||
|
||||
patchScroll: (key, scrollTop) => {
|
||||
const prev = get().feeds[key];
|
||||
if (!prev) return;
|
||||
// 数值未变则跳过,减少无意义的 store 更新
|
||||
if (prev.scrollTop === scrollTop) return;
|
||||
set((state) => ({
|
||||
feeds: {
|
||||
...state.feeds,
|
||||
[key]: { ...prev, scrollTop },
|
||||
},
|
||||
}));
|
||||
},
|
||||
|
||||
isStale: (key, now = Date.now()) => {
|
||||
const entry = get().feeds[key];
|
||||
if (!entry) return true;
|
||||
return now - entry.lastFetchTime > FEED_STALE_MS;
|
||||
},
|
||||
|
||||
clearFeed: (key) => {
|
||||
set((state) => {
|
||||
if (!(key in state.feeds)) return state;
|
||||
const next = { ...state.feeds };
|
||||
delete next[key];
|
||||
return { feeds: next };
|
||||
});
|
||||
},
|
||||
|
||||
clearAll: () => set({ feeds: {} }),
|
||||
}));
|
||||
|
||||
/** 非 React 路径(如 feedCache 封装)直接读写 */
|
||||
export function getHomeStoreState() {
|
||||
return useHomeStore.getState();
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
17
frontend/src/types/svg-maps.d.ts
vendored
Normal file
17
frontend/src/types/svg-maps.d.ts
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
declare module '@svg-maps/world' {
|
||||
const map: {
|
||||
label: string;
|
||||
viewBox: string;
|
||||
locations: Array<{ id: string; name: string; path: string }>;
|
||||
};
|
||||
export default map;
|
||||
}
|
||||
|
||||
declare module '@svg-maps/china' {
|
||||
const map: {
|
||||
label: string;
|
||||
viewBox: string;
|
||||
locations: Array<{ id: string; name: string; path: string }>;
|
||||
};
|
||||
export default map;
|
||||
}
|
||||
@@ -1,19 +1,29 @@
|
||||
import type { AsideWidget, AsideWidgetId, ForumLimits, ForumLimitsPublic } from '../api/types';
|
||||
import { DEFAULT_ASIDE_WIDGETS } from '../api/types';
|
||||
|
||||
const ASIDE_WIDGET_IDS: AsideWidgetId[] = ['tag_cloud', 'recent_comments', 'recent_users', 'friend_links'];
|
||||
const ASIDE_WIDGET_IDS: AsideWidgetId[] = [
|
||||
'tag_cloud',
|
||||
'recent_comments',
|
||||
'recent_users',
|
||||
'friend_links',
|
||||
'showcase',
|
||||
];
|
||||
|
||||
/** 从 limits 解析右侧栏组件列表(兼容仅有布尔开关的旧数据) */
|
||||
export function resolveAsideWidgets(
|
||||
limits: Pick<ForumLimitsPublic, 'aside_widgets' | 'aside_show_tag_cloud' | 'aside_show_recent_comments' | 'aside_show_friend_links'>,
|
||||
limits: Partial<Pick<
|
||||
ForumLimitsPublic,
|
||||
'aside_widgets' | 'aside_show_tag_cloud' | 'aside_show_recent_comments' | 'aside_show_friend_links' | 'aside_show_showcase'
|
||||
>>,
|
||||
): AsideWidget[] {
|
||||
if (limits.aside_widgets?.length) {
|
||||
return normalizeAsideWidgets(limits.aside_widgets);
|
||||
}
|
||||
return [
|
||||
{ id: 'tag_cloud', enabled: limits.aside_show_tag_cloud },
|
||||
{ id: 'recent_comments', enabled: limits.aside_show_recent_comments },
|
||||
{ id: 'friend_links', enabled: limits.aside_show_friend_links },
|
||||
{ id: 'tag_cloud', enabled: !!limits.aside_show_tag_cloud },
|
||||
{ id: 'recent_comments', enabled: !!limits.aside_show_recent_comments },
|
||||
{ id: 'friend_links', enabled: limits.aside_show_friend_links !== false },
|
||||
{ id: 'showcase', enabled: !!limits.aside_show_showcase },
|
||||
];
|
||||
}
|
||||
|
||||
@@ -33,12 +43,16 @@ export function normalizeAsideWidgets(widgets: AsideWidget[]): AsideWidget[] {
|
||||
}
|
||||
|
||||
/** 将 aside_widgets 同步回 ForumLimits 布尔字段 */
|
||||
export function syncAsideBoolsFromWidgets(widgets: AsideWidget[]): Pick<ForumLimits, 'aside_show_tag_cloud' | 'aside_show_recent_comments' | 'aside_show_friend_links'> {
|
||||
export function syncAsideBoolsFromWidgets(widgets: AsideWidget[]): Pick<
|
||||
ForumLimits,
|
||||
'aside_show_tag_cloud' | 'aside_show_recent_comments' | 'aside_show_friend_links' | 'aside_show_showcase'
|
||||
> {
|
||||
const normalized = normalizeAsideWidgets(widgets);
|
||||
return {
|
||||
aside_show_tag_cloud: normalized.find(w => w.id === 'tag_cloud')?.enabled ?? false,
|
||||
aside_show_recent_comments: normalized.find(w => w.id === 'recent_comments')?.enabled ?? false,
|
||||
aside_show_friend_links: normalized.find(w => w.id === 'friend_links')?.enabled ?? true,
|
||||
aside_show_showcase: normalized.find(w => w.id === 'showcase')?.enabled ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -64,6 +78,7 @@ export function isAsideWidgetEnabled(widgets: AsideWidget[], id: AsideWidgetId):
|
||||
aside_show_tag_cloud: false,
|
||||
aside_show_recent_comments: false,
|
||||
aside_show_friend_links: false,
|
||||
aside_show_showcase: false,
|
||||
}).find(w => w.id === id)?.enabled ?? false;
|
||||
}
|
||||
|
||||
|
||||
43
frontend/src/utils/authBoot.ts
Normal file
43
frontend/src/utils/authBoot.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import type { User } from '../api/types';
|
||||
|
||||
/** 首页 SSR boot 注入的鉴权种子(consumeHomeBoot 写入;AuthProvider 仅 peek,保留至下次 boot) */
|
||||
let seededUser: User | null | undefined;
|
||||
let seededUnread = 0;
|
||||
let hasAuthSeed = false;
|
||||
/** 未读数可被 MainLayout 同步读取 */
|
||||
let bootUnread = 0;
|
||||
|
||||
export function seedAuthFromHomeBoot(user: User | null | undefined, unread: number) {
|
||||
hasAuthSeed = true;
|
||||
seededUser = user ?? null;
|
||||
seededUnread = Math.max(0, unread | 0);
|
||||
bootUnread = seededUnread;
|
||||
}
|
||||
|
||||
type AuthSeed = { hasSeed: boolean; user: User | null; unread: number };
|
||||
|
||||
/** 只读种子,不清空(StrictMode 双挂 / useState initializer 可重复调用) */
|
||||
export function peekAuthSeed(): AuthSeed {
|
||||
if (!hasAuthSeed) {
|
||||
return { hasSeed: false, user: null, unread: bootUnread };
|
||||
}
|
||||
return { hasSeed: true, user: seededUser ?? null, unread: seededUnread };
|
||||
}
|
||||
|
||||
/** mount 后清除用户种子,避免后续误用 */
|
||||
export function clearAuthSeed() {
|
||||
hasAuthSeed = false;
|
||||
seededUser = undefined;
|
||||
seededUnread = 0;
|
||||
}
|
||||
|
||||
/** @deprecated 改用 peekAuthSeed + clearAuthSeed;保留兼容 */
|
||||
export function takeAuthSeed(): AuthSeed {
|
||||
const s = peekAuthSeed();
|
||||
if (s.hasSeed) clearAuthSeed();
|
||||
return s;
|
||||
}
|
||||
|
||||
export function getBootUnread(): number {
|
||||
return bootUnread;
|
||||
}
|
||||
@@ -2,6 +2,22 @@
|
||||
const RELOAD_AT_KEY = 'j13:chunk-reload-at';
|
||||
const RELOAD_COOLDOWN_MS = 15_000;
|
||||
|
||||
/** 从 HTML 中提取入口 module script(Vite 产物:/assets/index-*.js) */
|
||||
function extractEntryScriptSrc(html: string): string | null {
|
||||
const re = /<script[^>]*\stype=["']module["'][^>]*\ssrc=["']([^"']+)["'][^>]*>/i;
|
||||
const m = html.match(re);
|
||||
if (m?.[1]) return m[1];
|
||||
// src 在 type 之前
|
||||
const re2 = /<script[^>]*\ssrc=["']([^"']+)["'][^>]*\stype=["']module["'][^>]*>/i;
|
||||
return html.match(re2)?.[1] ?? null;
|
||||
}
|
||||
|
||||
/** 当前文档已加载的入口 script src */
|
||||
export function getDocumentEntryScriptSrc(): string | null {
|
||||
const el = document.querySelector<HTMLScriptElement>('script[type="module"][src]');
|
||||
return el?.getAttribute('src') ?? null;
|
||||
}
|
||||
|
||||
/** 判断是否为「发版后旧 JS chunk 失效」类错误 */
|
||||
export function isChunkLoadError(error: unknown): boolean {
|
||||
const msg = error instanceof Error
|
||||
@@ -32,3 +48,29 @@ export function reloadForStaleChunk(): boolean {
|
||||
window.location.reload();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 软刷新前对比入口 HTML 中的 index-*.js 哈希。
|
||||
* 发版后当前页 chunk 仍在内存,裸 import() 不会重新拉文件,必须主动检测。
|
||||
* @returns 是否已触发硬刷新(调用方应停止后续软刷新)
|
||||
*/
|
||||
export async function reloadIfShellStale(): Promise<boolean> {
|
||||
const current = getDocumentEntryScriptSrc();
|
||||
if (!current) return false;
|
||||
|
||||
try {
|
||||
const res = await fetch(`${window.location.pathname}${window.location.search}`, {
|
||||
cache: 'no-store',
|
||||
headers: { Accept: 'text/html' },
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (!res.ok) return false;
|
||||
const html = await res.text();
|
||||
const next = extractEntryScriptSrc(html);
|
||||
if (!next || next === current) return false;
|
||||
return reloadForStaleChunk();
|
||||
} catch {
|
||||
// 网络失败:跳过,继续软刷新
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
import type { NavigateFunction } from 'react-router-dom';
|
||||
import type { PostItem } from '../api/types';
|
||||
import type { FeedSort } from '../components/FeedSortBar';
|
||||
import {
|
||||
feedCacheKey,
|
||||
getHomeStoreState,
|
||||
type FeedCacheEntry,
|
||||
} from '../store/homeStore';
|
||||
import { clearSessionSnapshots } from './sessionPageCache';
|
||||
import { softRefreshCurrentPage } from './softRefresh';
|
||||
import { transitionTo } from './spaTransition';
|
||||
|
||||
/** 导航到帖子列表时附带的状态,用于同 URL 重复点击时强制刷新 */
|
||||
export type FeedNavState = { refreshFeed?: boolean };
|
||||
|
||||
/** 对外暴露的缓存形状(兼容旧调用方;不含 lastFetchTime) */
|
||||
export type FeedCache = {
|
||||
posts: PostItem[];
|
||||
postTotal: number;
|
||||
@@ -12,18 +21,13 @@ export type FeedCache = {
|
||||
scrollTop: number;
|
||||
};
|
||||
|
||||
/** 仅存内存:SPA 内返回可恢复,浏览器刷新自动清空 */
|
||||
const store = new Map<string, FeedCache>();
|
||||
|
||||
function cacheKey(
|
||||
boardId: number,
|
||||
keyword: string,
|
||||
sort: FeedSort,
|
||||
tag = '',
|
||||
author = '',
|
||||
titleOnly = false,
|
||||
) {
|
||||
return `${boardId}:${keyword}:${tag}:${author}:${titleOnly ? 1 : 0}:${sort}`;
|
||||
function toPublic(entry: FeedCacheEntry): FeedCache {
|
||||
return {
|
||||
posts: entry.posts,
|
||||
postTotal: entry.postTotal,
|
||||
page: entry.page,
|
||||
scrollTop: entry.scrollTop,
|
||||
};
|
||||
}
|
||||
|
||||
/** 读取帖子列表缓存(从详情页返回时恢复浏览位置) */
|
||||
@@ -35,10 +39,12 @@ export function getFeedCache(
|
||||
author = '',
|
||||
titleOnly = false,
|
||||
): FeedCache | null {
|
||||
return store.get(cacheKey(boardId, keyword, sort, tag, author, titleOnly)) ?? null;
|
||||
const key = feedCacheKey({ boardId, keyword, sort, tag, author, titleOnly });
|
||||
const entry = getHomeStoreState().getFeed(key);
|
||||
return entry ? toPublic(entry) : null;
|
||||
}
|
||||
|
||||
/** 保存帖子列表缓存 */
|
||||
/** 保存帖子列表缓存(写入 Zustand,并记录拉取时间) */
|
||||
export function setFeedCache(
|
||||
boardId: number,
|
||||
keyword: string,
|
||||
@@ -48,20 +54,55 @@ export function setFeedCache(
|
||||
author = '',
|
||||
titleOnly = false,
|
||||
) {
|
||||
store.set(cacheKey(boardId, keyword, sort, tag, author, titleOnly), data);
|
||||
const key = feedCacheKey({ boardId, keyword, sort, tag, author, titleOnly });
|
||||
getHomeStoreState().setFeed(key, data);
|
||||
}
|
||||
|
||||
/** 清除所有帖子列表缓存 */
|
||||
/** 清除所有帖子列表缓存(手动刷新 / 帖子变更时连详情快照一起作废) */
|
||||
export function clearAllFeedCache() {
|
||||
store.clear();
|
||||
getHomeStoreState().clearAll();
|
||||
clearSessionSnapshots('post:');
|
||||
}
|
||||
|
||||
/** 主动刷新帖子列表时派发,用于同页内立即回到顶部 */
|
||||
export const FEED_RESET_EVENT = 'feed-reset';
|
||||
|
||||
/** 清除缓存并导航到帖子列表(重复点击同一入口时也会刷新) */
|
||||
export function navigateFeed(nav: NavigateFunction, url: string) {
|
||||
clearAllFeedCache();
|
||||
window.dispatchEvent(new Event(FEED_RESET_EVENT));
|
||||
nav(url, { state: { refreshFeed: true } satisfies FeedNavState });
|
||||
/** 手机下拉刷新(Feed 页):强制重拉列表并重置滚动,不整页 reload */
|
||||
export const FEED_PULL_REFRESH_EVENT = 'feed-pull-refresh';
|
||||
|
||||
/** 手机下拉:强制刷新当前前台页(绕过会话快照,非整页 reload) */
|
||||
export const PAGE_FORCE_REFRESH_EVENT = 'page-force-refresh';
|
||||
|
||||
/** 当前浏览器地址是否已是目标 Feed URL(忽略 hash) */
|
||||
function isSameFeedUrl(url: string): boolean {
|
||||
try {
|
||||
const target = new URL(url, window.location.origin);
|
||||
return (
|
||||
window.location.pathname === target.pathname
|
||||
&& window.location.search === target.search
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导航到帖子列表。
|
||||
* 默认:等待预热后再换页;同 URL 或 `refresh: true` 时软刷新(带顶栏进度条)。
|
||||
*/
|
||||
export function navigateFeed(nav: NavigateFunction, url: string, opts?: { refresh?: boolean }) {
|
||||
const same = isSameFeedUrl(url);
|
||||
const refresh = opts?.refresh ?? same;
|
||||
if (refresh) {
|
||||
if (same) {
|
||||
void softRefreshCurrentPage(url, { progress: true });
|
||||
return;
|
||||
}
|
||||
void transitionTo(nav, url, {
|
||||
force: true,
|
||||
state: { refreshFeed: true } satisfies FeedNavState,
|
||||
});
|
||||
return;
|
||||
}
|
||||
void transitionTo(nav, url);
|
||||
}
|
||||
|
||||
41
frontend/src/utils/feedSortTabs.ts
Normal file
41
frontend/src/utils/feedSortTabs.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import type { FeedSortId, FeedSortTab } from '../api/types';
|
||||
import { DEFAULT_FEED_SORT_TABS } from '../api/types';
|
||||
|
||||
const FEED_SORT_IDS: FeedSortId[] = ['reply', 'latest', 'hot'];
|
||||
|
||||
const DEFAULT_LABELS: Record<FeedSortId, string> = {
|
||||
reply: '最新',
|
||||
latest: '新帖子',
|
||||
hot: '推荐帖',
|
||||
};
|
||||
|
||||
/** 校验并补全 Feed 排序标签;至少保留一项启用 */
|
||||
export function normalizeFeedSortTabs(tabs?: FeedSortTab[] | null): FeedSortTab[] {
|
||||
const seen = new Set<FeedSortId>();
|
||||
const out: FeedSortTab[] = [];
|
||||
for (const t of tabs ?? []) {
|
||||
if (!FEED_SORT_IDS.includes(t.id) || seen.has(t.id)) continue;
|
||||
seen.add(t.id);
|
||||
const label = (t.label || '').trim() || DEFAULT_LABELS[t.id];
|
||||
out.push({ id: t.id, label, enabled: !!t.enabled });
|
||||
}
|
||||
for (const id of FEED_SORT_IDS) {
|
||||
if (seen.has(id)) continue;
|
||||
const fallback = DEFAULT_FEED_SORT_TABS.find(t => t.id === id)!;
|
||||
out.push({ ...fallback });
|
||||
}
|
||||
if (!out.some(t => t.enabled) && out.length > 0) {
|
||||
out[0] = { ...out[0], enabled: true };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 启用中的排序标签(按配置顺序) */
|
||||
export function enabledFeedSortTabs(tabs?: FeedSortTab[] | null): FeedSortTab[] {
|
||||
return normalizeFeedSortTabs(tabs).filter(t => t.enabled);
|
||||
}
|
||||
|
||||
/** 默认排序 = 第一个启用项 */
|
||||
export function getDefaultFeedSort(tabs?: FeedSortTab[] | null): FeedSortId {
|
||||
return enabledFeedSortTabs(tabs)[0]?.id ?? 'reply';
|
||||
}
|
||||
110
frontend/src/utils/homeBoot.ts
Normal file
110
frontend/src/utils/homeBoot.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import type {
|
||||
Board,
|
||||
CheckInStatus,
|
||||
CommunityShowcaseItem,
|
||||
ForumLimitsPublic,
|
||||
ForumStats,
|
||||
PostItem,
|
||||
RecentComment,
|
||||
RecentUser,
|
||||
SiteBranding,
|
||||
SitePageSummary,
|
||||
TagCount,
|
||||
User,
|
||||
} from '../api/types';
|
||||
import { seedSiteBrandingCache } from '../hooks/useSiteBranding';
|
||||
import { seedForumLimitsCache } from '../hooks/useForumLimits';
|
||||
import { seedSitePagesCache } from '../hooks/useSitePages';
|
||||
import { feedCacheKey, getHomeStoreState } from '../store/homeStore';
|
||||
import {
|
||||
setCachedBoards,
|
||||
setCachedRecentComments,
|
||||
setCachedRecentUsers,
|
||||
setCachedStats,
|
||||
setCachedTags,
|
||||
} from './layoutCache';
|
||||
import { setSessionSnapshot } from './sessionPageCache';
|
||||
import { seedAuthFromHomeBoot } from './authBoot';
|
||||
import { checkInCacheKey } from '../hooks/useCheckIn';
|
||||
import type { FeedSort } from '../components/FeedSortBar';
|
||||
|
||||
/** 与 Go homeBootPayload / window.__J13_HOME_BOOT__ 对齐 */
|
||||
export type HomeBootPayload = {
|
||||
board_id: number;
|
||||
sort: string;
|
||||
keyword: string;
|
||||
tag: string;
|
||||
author: string;
|
||||
title_only: boolean;
|
||||
posts: PostItem[];
|
||||
post_total: number;
|
||||
page: number;
|
||||
boards: Board[];
|
||||
stats: ForumStats;
|
||||
recent_comments: RecentComment[];
|
||||
recent_users: RecentUser[];
|
||||
tags: TagCount[];
|
||||
showcase: CommunityShowcaseItem[];
|
||||
pages: SitePageSummary[];
|
||||
limits: ForumLimitsPublic;
|
||||
branding: SiteBranding;
|
||||
user?: User | null;
|
||||
unread_messages?: number;
|
||||
check_in?: CheckInStatus | null;
|
||||
};
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__J13_HOME_BOOT__?: HomeBootPayload;
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取并清除文档 SSR 注入的首页 boot,灌入各层缓存 */
|
||||
export function consumeHomeBoot(): HomeBootPayload | null {
|
||||
const boot = window.__J13_HOME_BOOT__;
|
||||
try {
|
||||
delete window.__J13_HOME_BOOT__;
|
||||
} catch {
|
||||
window.__J13_HOME_BOOT__ = undefined;
|
||||
}
|
||||
if (!boot || typeof boot !== 'object') return null;
|
||||
|
||||
if (boot.limits) seedForumLimitsCache(boot.limits);
|
||||
if (boot.branding) seedSiteBrandingCache(boot.branding);
|
||||
if (Array.isArray(boot.pages)) seedSitePagesCache(boot.pages);
|
||||
if (Array.isArray(boot.boards)) setCachedBoards(boot.boards);
|
||||
if (boot.stats) setCachedStats(boot.stats);
|
||||
if (Array.isArray(boot.recent_comments)) setCachedRecentComments(boot.recent_comments);
|
||||
if (Array.isArray(boot.recent_users)) setCachedRecentUsers(boot.recent_users);
|
||||
if (Array.isArray(boot.tags)) setCachedTags(boot.tags);
|
||||
if (Array.isArray(boot.showcase)) setSessionSnapshot('showcase', boot.showcase);
|
||||
|
||||
// 鉴权 / 签到:有 user 字段即种子(含 null = 已确认访客)
|
||||
if ('user' in boot) {
|
||||
seedAuthFromHomeBoot(boot.user ?? null, boot.unread_messages ?? 0);
|
||||
const uid = boot.user?.id;
|
||||
if (uid && boot.check_in) {
|
||||
setSessionSnapshot(checkInCacheKey(uid), boot.check_in);
|
||||
}
|
||||
}
|
||||
|
||||
const sort = (boot.sort || 'reply') as FeedSort;
|
||||
const key = feedCacheKey({
|
||||
boardId: boot.board_id || 0,
|
||||
keyword: boot.keyword || '',
|
||||
tag: boot.tag || '',
|
||||
author: boot.author || '',
|
||||
titleOnly: !!boot.title_only,
|
||||
sort,
|
||||
});
|
||||
const posts = Array.isArray(boot.posts) ? boot.posts : [];
|
||||
getHomeStoreState().setFeed(key, {
|
||||
posts,
|
||||
postTotal: boot.post_total ?? posts.length,
|
||||
page: boot.page || 1,
|
||||
scrollTop: 0,
|
||||
lastFetchTime: Date.now(),
|
||||
});
|
||||
|
||||
return boot;
|
||||
}
|
||||
41
frontend/src/utils/homeHydrate.ts
Normal file
41
frontend/src/utils/homeHydrate.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/** 首页 SSR hydrate 首帧同构标志(仅 / 与板块首页) */
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__J13_HYDRATING_HOME__?: boolean;
|
||||
}
|
||||
}
|
||||
|
||||
let hydrating = false;
|
||||
|
||||
export function beginHomeHydrate() {
|
||||
hydrating = true;
|
||||
try {
|
||||
window.__J13_HYDRATING_HOME__ = true;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
export function endHomeHydrate() {
|
||||
hydrating = false;
|
||||
try {
|
||||
delete window.__J13_HYDRATING_HOME__;
|
||||
} catch {
|
||||
try {
|
||||
window.__J13_HYDRATING_HOME__ = undefined;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 首帧是否必须与 Go SSR DOM 同构 */
|
||||
export function isHomeHydrating(): boolean {
|
||||
if (hydrating) return true;
|
||||
try {
|
||||
return !!window.__J13_HYDRATING_HOME__;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -122,9 +122,12 @@ export function insertMarkdownLink(
|
||||
value: string,
|
||||
url: string,
|
||||
onChange: ChangeHandler,
|
||||
opts?: { text?: string },
|
||||
) {
|
||||
const { selectionStart, selectionEnd } = textarea;
|
||||
const selected = value.slice(selectionStart, selectionEnd) || '链接文字';
|
||||
const selected = opts?.text?.trim()
|
||||
|| value.slice(selectionStart, selectionEnd)
|
||||
|| '链接文字';
|
||||
const insert = `[${selected}](${url})`;
|
||||
const next = value.slice(0, selectionStart) + insert + value.slice(selectionEnd);
|
||||
applyTextareaChange(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { NavigateFunction } from 'react-router-dom';
|
||||
import { postPath, type PermalinkOpts } from './permalink';
|
||||
import { transitionTo } from './spaTransition';
|
||||
|
||||
export type OpenForumPostOpts = PermalinkOpts & {
|
||||
/** 跳转到指定楼层(#floor-N) */
|
||||
@@ -18,5 +19,5 @@ export function openForumPost(
|
||||
window.open(path, '_blank', 'noopener,noreferrer');
|
||||
return;
|
||||
}
|
||||
nav(path);
|
||||
void transitionTo(nav, path);
|
||||
}
|
||||
|
||||
447
frontend/src/utils/prefetchRoute.ts
Normal file
447
frontend/src/utils/prefetchRoute.ts
Normal file
@@ -0,0 +1,447 @@
|
||||
import type { To } from 'react-router-dom';
|
||||
import { api } from '../api/client';
|
||||
import type {
|
||||
CheckInStatus,
|
||||
Comment,
|
||||
CommunityShowcaseItem,
|
||||
FriendLinkApply,
|
||||
PollView,
|
||||
PostItem,
|
||||
PostLotteryView,
|
||||
SitePage,
|
||||
} from '../api/types';
|
||||
import { parseFeedSort } from '../components/FeedSortBar';
|
||||
import { checkInCacheKey } from '../hooks/useCheckIn';
|
||||
import { ensureForumLimitsLoaded, getCachedForumLimits } from '../hooks/useForumLimits';
|
||||
import { ensureSiteBrandingLoaded } from '../hooks/useSiteBranding';
|
||||
import { ensureSitePagesLoaded } from '../hooks/useSitePages';
|
||||
import { feedCacheKey, getHomeStoreState } from '../store/homeStore';
|
||||
import { resolveAsideWidgets } from './asideWidgets';
|
||||
import { isTimeDiffSignificant } from './content';
|
||||
import { loadMyCommentIds } from './guest';
|
||||
import {
|
||||
setCachedBoards,
|
||||
setCachedStats,
|
||||
setCachedRecentComments,
|
||||
setCachedRecentUsers,
|
||||
setCachedTags,
|
||||
} from './layoutCache';
|
||||
import { isChunkLoadError, reloadForStaleChunk } from './chunkLoad';
|
||||
import { parsePermalinkID, parsePermalinkSlug } from './permalink';
|
||||
import { getSessionSnapshot, setSessionSnapshot } from './sessionPageCache';
|
||||
|
||||
/** 与 PostDetailPage 会话快照同形,供预取写入 */
|
||||
type PostDetailSnapshot = {
|
||||
post: PostItem;
|
||||
comments: Comment[];
|
||||
poll: PollView | null;
|
||||
lottery: PostLotteryView | null;
|
||||
liked: boolean;
|
||||
favorited: boolean;
|
||||
canEdit: boolean;
|
||||
isEdited: boolean;
|
||||
editBlockReason: string;
|
||||
editWindowHours: number;
|
||||
bountyCanRefund: boolean;
|
||||
bountyRefundBlockReason: string;
|
||||
bountyEligibleReplyCount: number;
|
||||
scrollTop: number;
|
||||
};
|
||||
|
||||
function resolveUrl(to: To): URL {
|
||||
if (typeof to === 'string') return new URL(to, window.location.origin);
|
||||
const path = to.pathname ?? '/';
|
||||
const search = to.search ?? '';
|
||||
const hash = to.hash ?? '';
|
||||
return new URL(path + search + hash, window.location.origin);
|
||||
}
|
||||
|
||||
/** 预加载对应路由的 lazy chunk(与 App.tsx lazyWithRetry 对齐) */
|
||||
function preloadChunk(pathname: string): Promise<unknown> {
|
||||
let load: Promise<unknown>;
|
||||
if (pathname === '/' || /^\/board\//.test(pathname)) {
|
||||
load = import('../pages/HomePage');
|
||||
} else if (/^\/post\/[^/]+\/edit$/.test(pathname) || pathname === '/compose') {
|
||||
load = import('../pages/ComposePage');
|
||||
} else if (/^\/post\//.test(pathname)) {
|
||||
load = import('../pages/PostDetailPage');
|
||||
} else if (pathname === '/profile') {
|
||||
load = import('../pages/ProfilePage');
|
||||
} else if (/^\/user\//.test(pathname)) {
|
||||
load = import('../pages/UserProfilePage');
|
||||
} else if (pathname === '/favorites') {
|
||||
load = import('../pages/FavoritesPage');
|
||||
} else if (pathname === '/projects') {
|
||||
load = import('../pages/ProjectsPage');
|
||||
} else if (pathname === '/links') {
|
||||
load = import('../pages/LinksPage');
|
||||
} else if (pathname === '/showcase') {
|
||||
load = import('../pages/ShowcasePage');
|
||||
} else if (pathname === '/messages') {
|
||||
load = import('../pages/MessagesPage');
|
||||
} else if (/^\/page\//.test(pathname)) {
|
||||
load = import('../pages/SitePageView');
|
||||
} else if (pathname === '/login') {
|
||||
load = import('../pages/LoginPage');
|
||||
} else if (pathname === '/register') {
|
||||
load = import('../pages/RegisterPage');
|
||||
} else if (pathname === '/forgot-password') {
|
||||
load = import('../pages/ForgotPasswordPage');
|
||||
} else {
|
||||
return Promise.resolve();
|
||||
}
|
||||
// 发版后旧 hashed URL 404:硬刷新,挂起 Promise 避免落到 toast
|
||||
return load.catch((err: unknown) => {
|
||||
if (isChunkLoadError(err) && reloadForStaleChunk()) {
|
||||
return new Promise(() => {});
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
async function prefetchFeed(url: URL, force: boolean): Promise<void> {
|
||||
const limits = getCachedForumLimits();
|
||||
const pageSize = Math.max(1, limits.page_size_default);
|
||||
const boardMatch = url.pathname.match(/^\/board\/([^/]+)/);
|
||||
const boardId = boardMatch ? (parsePermalinkID(boardMatch[1]) || 0) : 0;
|
||||
const keyword = url.searchParams.get('keyword') || '';
|
||||
const tag = url.searchParams.get('tag') || '';
|
||||
const author = url.searchParams.get('author') || '';
|
||||
const titleOnly = url.searchParams.get('title_only') === '1';
|
||||
const sort = parseFeedSort(url.searchParams.get('sort'), limits.feed_sort_tabs);
|
||||
const key = feedCacheKey({ boardId, keyword, sort, tag, author, titleOnly });
|
||||
|
||||
if (!force) {
|
||||
const hit = getHomeStoreState().getFeed(key);
|
||||
if (hit && hit.posts.length > 0) return;
|
||||
}
|
||||
// force:不提前清空 store,等新数据写入时覆盖,避免软刷新中间态读到空列表
|
||||
|
||||
const data = await api.posts({
|
||||
page: 1,
|
||||
size: pageSize,
|
||||
board_id: boardId || '',
|
||||
keyword: tag ? '' : keyword,
|
||||
tag: tag || '',
|
||||
author: tag ? '' : author,
|
||||
title_only: !tag && titleOnly ? '1' : '',
|
||||
sort,
|
||||
});
|
||||
getHomeStoreState().setFeed(key, {
|
||||
posts: Array.isArray(data.posts) ? data.posts : [],
|
||||
postTotal: data.total ?? 0,
|
||||
page: 1,
|
||||
scrollTop: 0,
|
||||
lastFetchTime: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
async function prefetchPost(id: number, force: boolean): Promise<void> {
|
||||
const key = `post:${id}`;
|
||||
if (!force && getSessionSnapshot(key) !== undefined) return;
|
||||
// force:保留旧快照直到新数据写回,避免软刷新中间态空白
|
||||
|
||||
const myIds = loadMyCommentIds();
|
||||
const [detail, comm] = await Promise.all([
|
||||
api.post(id),
|
||||
api.comments(id, myIds),
|
||||
]);
|
||||
const snap: PostDetailSnapshot = {
|
||||
post: detail.post,
|
||||
comments: Array.isArray(comm.comments) ? comm.comments : [],
|
||||
poll: detail.poll ?? null,
|
||||
lottery: detail.lottery ?? null,
|
||||
liked: detail.liked,
|
||||
favorited: detail.favorited,
|
||||
canEdit: detail.can_edit ?? false,
|
||||
isEdited: detail.is_edited
|
||||
?? isTimeDiffSignificant(detail.post.created_at, detail.post.updated_at ?? detail.post.created_at),
|
||||
editBlockReason: detail.edit_block_reason ?? '',
|
||||
editWindowHours: detail.post_edit_window_hours ?? 0,
|
||||
bountyCanRefund: detail.bounty_can_refund ?? true,
|
||||
bountyRefundBlockReason: detail.bounty_refund_block_reason ?? '',
|
||||
bountyEligibleReplyCount: detail.bounty_eligible_reply_count ?? 0,
|
||||
scrollTop: 0,
|
||||
};
|
||||
setSessionSnapshot(key, snap);
|
||||
}
|
||||
|
||||
async function prefetchUser(id: number, force: boolean): Promise<void> {
|
||||
const profileKey = `user:${id}`;
|
||||
if (!force && getSessionSnapshot(profileKey) !== undefined) return;
|
||||
|
||||
const limits = getCachedForumLimits();
|
||||
const pageSize = limits.page_size_default > 0 ? limits.page_size_default : 20;
|
||||
const [profileRes, postsRes] = await Promise.all([
|
||||
api.userProfile(id),
|
||||
api.posts({ user_id: id, page: 1, size: pageSize, sort: 'latest' }),
|
||||
]);
|
||||
setSessionSnapshot(profileKey, {
|
||||
profile: profileRes.user,
|
||||
stats: profileRes.stats ?? null,
|
||||
});
|
||||
setSessionSnapshot(`${profileKey}:posts:1:${pageSize}`, {
|
||||
posts: Array.isArray(postsRes.posts) ? postsRes.posts : [],
|
||||
total: postsRes.total ?? 0,
|
||||
});
|
||||
}
|
||||
|
||||
async function prefetchKeyed<T>(
|
||||
key: string,
|
||||
force: boolean,
|
||||
fetcher: () => Promise<T>,
|
||||
): Promise<void> {
|
||||
if (!force && getSessionSnapshot(key) !== undefined) return;
|
||||
const data = await fetcher();
|
||||
setSessionSnapshot(key, data);
|
||||
}
|
||||
|
||||
/** 静默预热签到(401 / 失败不阻断跳转) */
|
||||
async function prefetchCheckIn(force: boolean): Promise<void> {
|
||||
try {
|
||||
const me = await api.me();
|
||||
const id = me.user?.id;
|
||||
if (!id) return;
|
||||
const key = checkInCacheKey(id);
|
||||
if (!force && getSessionSnapshot<CheckInStatus>(key) !== undefined) return;
|
||||
const d = await api.checkInStatus();
|
||||
setSessionSnapshot(key, d.check_in);
|
||||
} catch {
|
||||
// 未登录或接口失败:忽略
|
||||
}
|
||||
}
|
||||
|
||||
/** 右栏展柜与全页共用 showcase 快照 */
|
||||
async function prefetchShowcaseIfEnabled(force: boolean): Promise<void> {
|
||||
const limits = getCachedForumLimits();
|
||||
const enabled = resolveAsideWidgets(limits).some((w) => w.id === 'showcase' && w.enabled);
|
||||
if (!enabled) return;
|
||||
await prefetchKeyed<CommunityShowcaseItem[]>('showcase', force, () =>
|
||||
api.communityShowcase().then((r) => (Array.isArray(r.items) ? r.items : [])),
|
||||
).catch(() => undefined);
|
||||
}
|
||||
|
||||
/** MainLayout 壳层:签到 +(可选)展柜,与主内容并行 */
|
||||
function prefetchShell(force: boolean): Promise<void> {
|
||||
return Promise.all([
|
||||
prefetchCheckIn(force),
|
||||
prefetchShowcaseIfEnabled(force),
|
||||
]).then(() => undefined);
|
||||
}
|
||||
|
||||
/** 是否会挂载前台 MainLayout(非纯 auth / 后台页) */
|
||||
export function isMainLayoutPath(pathname: string): boolean {
|
||||
if (pathname.startsWith('/admin')) return false;
|
||||
if (pathname === '/login' || pathname === '/register' || pathname === '/forgot-password') return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 按目标 URL 预热会话快照 / Feed 缓存(不改 fetch 缓存策略) */
|
||||
export async function prefetchData(to: To, opts?: { force?: boolean }): Promise<void> {
|
||||
const force = !!opts?.force;
|
||||
const url = resolveUrl(to);
|
||||
const { pathname } = url;
|
||||
|
||||
const shell = isMainLayoutPath(pathname) ? prefetchShell(force) : Promise.resolve();
|
||||
|
||||
if (pathname === '/' || /^\/board\//.test(pathname)) {
|
||||
await Promise.all([prefetchFeed(url, force), shell]);
|
||||
return;
|
||||
}
|
||||
|
||||
const postEdit = pathname.match(/^\/post\/([^/]+)\/edit$/);
|
||||
if (postEdit) {
|
||||
await shell;
|
||||
return;
|
||||
}
|
||||
|
||||
const postMatch = pathname.match(/^\/post\/([^/]+)/);
|
||||
if (postMatch) {
|
||||
const id = parsePermalinkID(postMatch[1]);
|
||||
await Promise.all([
|
||||
id && !Number.isNaN(id) ? prefetchPost(id, force) : Promise.resolve(),
|
||||
shell,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
const userMatch = pathname.match(/^\/user\/([^/]+)/);
|
||||
if (userMatch) {
|
||||
const id = parsePermalinkID(userMatch[1]);
|
||||
await Promise.all([
|
||||
id && !Number.isNaN(id) ? prefetchUser(id, force) : Promise.resolve(),
|
||||
shell,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/favorites') {
|
||||
await Promise.all([
|
||||
prefetchKeyed('favorites', force, () =>
|
||||
api.favorites().then((d) => (Array.isArray(d.favorites) ? d.favorites : [])),
|
||||
),
|
||||
shell,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/projects') {
|
||||
await Promise.all([
|
||||
prefetchKeyed(`projects:1:`, force, () =>
|
||||
api.projects({ page: 1, limit: 30 }).then((d) => ({
|
||||
list: Array.isArray(d.projects) ? d.projects : [],
|
||||
total: d.total ?? 0,
|
||||
totalPages: d.total_pages ?? 0,
|
||||
})),
|
||||
),
|
||||
shell,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/links') {
|
||||
await Promise.all([
|
||||
prefetchKeyed<FriendLinkApply[]>('links:applies', force, () =>
|
||||
api.myFriendLinkApplies().then((r) => r.applies ?? []).catch(() => []),
|
||||
),
|
||||
shell,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/showcase') {
|
||||
await Promise.all([
|
||||
prefetchKeyed('showcase', force, () =>
|
||||
api.communityShowcase().then((r) => (Array.isArray(r.items) ? r.items : [])),
|
||||
),
|
||||
shell,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/messages') {
|
||||
await Promise.all([
|
||||
prefetchKeyed('messages:conv:1', force, () =>
|
||||
api.messageConversations({ page: 1, size: 30 }).then((r) => ({
|
||||
conversations: r.conversations || [],
|
||||
total: r.total || 0,
|
||||
page: r.page || 1,
|
||||
})),
|
||||
),
|
||||
shell,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/profile' || pathname === '/compose') {
|
||||
await shell;
|
||||
return;
|
||||
}
|
||||
|
||||
const pageMatch = pathname.match(/^\/page\/([^/]+)/);
|
||||
if (pageMatch) {
|
||||
const slug = parsePermalinkSlug(pageMatch[1]);
|
||||
await Promise.all([
|
||||
slug
|
||||
? prefetchKeyed<SitePage | null>(`sitepage:${slug}`, force, () =>
|
||||
api.page(slug).then((d) => d.page),
|
||||
)
|
||||
: Promise.resolve(),
|
||||
shell,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/** chunk + 数据并行预热 */
|
||||
export async function prefetchRoute(to: To, opts?: { force?: boolean }): Promise<void> {
|
||||
const url = resolveUrl(to);
|
||||
await Promise.all([
|
||||
preloadChunk(url.pathname),
|
||||
prefetchData(to, opts),
|
||||
]);
|
||||
}
|
||||
|
||||
/** 壳层数据:boards/stats/站点页/右栏(与冷启动、软刷新共用) */
|
||||
export async function prefetchLayoutShell(opts?: { force?: boolean }): Promise<void> {
|
||||
const force = !!opts?.force;
|
||||
await ensureForumLimitsLoaded({ force });
|
||||
const limits = getCachedForumLimits();
|
||||
const widgets = resolveAsideWidgets(limits);
|
||||
const showRecentComments = widgets.some((w) => w.id === 'recent_comments' && w.enabled);
|
||||
const showRecentUsers = widgets.some((w) => w.id === 'recent_users' && w.enabled);
|
||||
const showTagCloud = widgets.some((w) => w.id === 'tag_cloud' && w.enabled);
|
||||
const hideAside = typeof window !== 'undefined'
|
||||
&& window.matchMedia('(max-width: 1100px)').matches;
|
||||
|
||||
const tasks: Promise<unknown>[] = [
|
||||
api.boards().then((d) => {
|
||||
setCachedBoards(d.boards ?? []);
|
||||
}).catch(() => undefined),
|
||||
api.stats().then((next) => {
|
||||
if (next) setCachedStats(next);
|
||||
}).catch(() => undefined),
|
||||
ensureSitePagesLoaded({ force }),
|
||||
];
|
||||
|
||||
// 软刷新:与壳层同拍重拉站名 / 友链等品牌文案
|
||||
if (force) {
|
||||
tasks.push(ensureSiteBrandingLoaded({ force: true }).catch(() => undefined));
|
||||
}
|
||||
|
||||
if (!hideAside) {
|
||||
if (showRecentComments) {
|
||||
tasks.push(
|
||||
api.recentComments().then((d) => {
|
||||
setCachedRecentComments(Array.isArray(d.comments) ? d.comments : []);
|
||||
}).catch(() => undefined),
|
||||
);
|
||||
}
|
||||
if (showRecentUsers) {
|
||||
tasks.push(
|
||||
api.recentUsers().then((d) => {
|
||||
setCachedRecentUsers(Array.isArray(d.users) ? d.users : []);
|
||||
}).catch(() => undefined),
|
||||
);
|
||||
}
|
||||
if (showTagCloud) {
|
||||
tasks.push(
|
||||
api.tags(40).then((d) => {
|
||||
setCachedTags(Array.isArray(d.tags) ? d.tags : []);
|
||||
}).catch(() => undefined),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(tasks);
|
||||
}
|
||||
|
||||
let coldBootEnsured = false;
|
||||
|
||||
/** main.tsx 是否已完成前台冷启动预热(MainLayout 可同步放行) */
|
||||
export function wasColdBootEnsured(): boolean {
|
||||
return coldBootEnsured;
|
||||
}
|
||||
|
||||
/**
|
||||
* 冷启动:在 createRoot 之前静默预热当前前台路由与壳层。
|
||||
* 不触发顶栏进度条;失败也放行,避免永久空白。
|
||||
*/
|
||||
export async function ensureColdBootReady(to?: string): Promise<void> {
|
||||
const path = to ?? `${window.location.pathname}${window.location.search}`;
|
||||
const url = resolveUrl(path);
|
||||
if (!isMainLayoutPath(url.pathname)) {
|
||||
coldBootEnsured = true;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await Promise.all([
|
||||
prefetchRoute(path, { force: false }),
|
||||
prefetchLayoutShell(),
|
||||
]);
|
||||
} catch {
|
||||
// 忽略:仍挂载 App
|
||||
} finally {
|
||||
coldBootEnsured = true;
|
||||
}
|
||||
}
|
||||
45
frontend/src/utils/sessionPageCache.ts
Normal file
45
frontend/src/utils/sessionPageCache.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/** 会话内页面快照:前进后退命中则不再请求,手动刷新或登录态变化时清空 */
|
||||
|
||||
const MAX_ENTRIES = 48;
|
||||
|
||||
const order: string[] = [];
|
||||
const store = new Map<string, unknown>();
|
||||
|
||||
function touch(key: string) {
|
||||
const i = order.indexOf(key);
|
||||
if (i >= 0) order.splice(i, 1);
|
||||
order.push(key);
|
||||
while (order.length > MAX_ENTRIES) {
|
||||
const old = order.shift();
|
||||
if (old) store.delete(old);
|
||||
}
|
||||
}
|
||||
|
||||
export function getSessionSnapshot<T>(key: string): T | undefined {
|
||||
if (!store.has(key)) return undefined;
|
||||
touch(key);
|
||||
return store.get(key) as T;
|
||||
}
|
||||
|
||||
export function setSessionSnapshot<T>(key: string, data: T): void {
|
||||
store.set(key, data);
|
||||
touch(key);
|
||||
}
|
||||
|
||||
export function deleteSessionSnapshot(key: string): void {
|
||||
if (!store.delete(key)) return;
|
||||
const i = order.indexOf(key);
|
||||
if (i >= 0) order.splice(i, 1);
|
||||
}
|
||||
|
||||
/** 不传 prefix 则清空全部;否则只删该前缀的 key */
|
||||
export function clearSessionSnapshots(prefix?: string): void {
|
||||
if (!prefix) {
|
||||
store.clear();
|
||||
order.length = 0;
|
||||
return;
|
||||
}
|
||||
for (const key of [...store.keys()]) {
|
||||
if (key.startsWith(prefix)) deleteSessionSnapshot(key);
|
||||
}
|
||||
}
|
||||
38
frontend/src/utils/softRefresh.ts
Normal file
38
frontend/src/utils/softRefresh.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { isChunkLoadError, reloadForStaleChunk, reloadIfShellStale } from './chunkLoad';
|
||||
import { prefetchLayoutShell, prefetchRoute } from './prefetchRoute';
|
||||
import { doneTransition, startTransition } from './spaTransition';
|
||||
|
||||
/** 软刷新齐套后的单一提交:各组件同一拍从 cache/快照同步 UI,禁止分批闪烁 */
|
||||
export const PAGE_SOFT_REFRESH_COMMIT_EVENT = 'page-soft-refresh-commit';
|
||||
|
||||
export type SoftRefreshOpts = {
|
||||
/** 是否显示顶栏进度条(Logo 刷新开;下拉关) */
|
||||
progress?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* 软刷新当前页:先检测入口壳是否过期,再预热齐套后派发一次 commit。
|
||||
* `progress: true` 时走顶栏进度条。
|
||||
*/
|
||||
export async function softRefreshCurrentPage(to?: string, opts?: SoftRefreshOpts): Promise<void> {
|
||||
const path = to ?? `${window.location.pathname}${window.location.search}`;
|
||||
const id = opts?.progress ? startTransition() : undefined;
|
||||
try {
|
||||
// 发版后旧壳仍在内存:先对比入口 script,过期则硬刷新
|
||||
if (await reloadIfShellStale()) {
|
||||
return;
|
||||
}
|
||||
await Promise.all([
|
||||
prefetchRoute(path, { force: true }),
|
||||
prefetchLayoutShell({ force: true }),
|
||||
]);
|
||||
} catch (e: unknown) {
|
||||
if (isChunkLoadError(e) && reloadForStaleChunk()) {
|
||||
return;
|
||||
}
|
||||
// 其它错误仍派发 commit,让界面有机会用已有缓存自愈
|
||||
} finally {
|
||||
if (id != null) doneTransition(id);
|
||||
}
|
||||
window.dispatchEvent(new Event(PAGE_SOFT_REFRESH_COMMIT_EVENT));
|
||||
}
|
||||
113
frontend/src/utils/spaTransition.ts
Normal file
113
frontend/src/utils/spaTransition.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import type { NavigateFunction, NavigateOptions, To } from 'react-router-dom';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { isChunkLoadError, reloadForStaleChunk } from './chunkLoad';
|
||||
import { prefetchRoute } from './prefetchRoute';
|
||||
|
||||
type Listener = (active: boolean) => void;
|
||||
|
||||
const listeners = new Set<Listener>();
|
||||
let activeCount = 0;
|
||||
let seq = 0;
|
||||
|
||||
function emit() {
|
||||
const active = activeCount > 0;
|
||||
listeners.forEach((fn) => fn(active));
|
||||
}
|
||||
|
||||
/** 订阅顶栏进度条显隐 */
|
||||
export function subscribeSpaTransition(fn: Listener): () => void {
|
||||
listeners.add(fn);
|
||||
fn(activeCount > 0);
|
||||
return () => { listeners.delete(fn); };
|
||||
}
|
||||
|
||||
/** 开始一次过渡(可嵌套,全部结束才收条) */
|
||||
export function startTransition(): number {
|
||||
const id = ++seq;
|
||||
activeCount += 1;
|
||||
emit();
|
||||
return id;
|
||||
}
|
||||
|
||||
/** 结束过渡;若 id 已过期则忽略 */
|
||||
export function doneTransition(id?: number) {
|
||||
if (id != null && id !== seq && activeCount > 0) {
|
||||
// 仍允许减计数,避免卡死;连续点击用 seq 作废预取即可
|
||||
}
|
||||
activeCount = Math.max(0, activeCount - 1);
|
||||
emit();
|
||||
}
|
||||
|
||||
export function isSpaTransitionActive(): boolean {
|
||||
return activeCount > 0;
|
||||
}
|
||||
|
||||
export type TransitionToOpts = NavigateOptions & {
|
||||
/** 强制重拉(Logo / 同 URL 刷新),跳过会话快照 */
|
||||
force?: boolean;
|
||||
/** 跳过等待,立即导航(纠偏、POP 等) */
|
||||
immediate?: boolean;
|
||||
/** 不显示顶栏进度条(软刷新换页) */
|
||||
silent?: boolean;
|
||||
};
|
||||
|
||||
function toPathname(to: To): string {
|
||||
if (typeof to === 'number') return '';
|
||||
if (typeof to === 'string') {
|
||||
try {
|
||||
return new URL(to, window.location.origin).pathname;
|
||||
} catch {
|
||||
return to.split('?')[0].split('#')[0];
|
||||
}
|
||||
}
|
||||
return to.pathname ?? '';
|
||||
}
|
||||
|
||||
function isOnlyHashChange(to: To): boolean {
|
||||
if (typeof to !== 'string') return false;
|
||||
if (!to.startsWith('#')) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 站内点击:顶栏进度条 + 预热 chunk/接口后再跳转。
|
||||
* `nav(-1)`、仅 hash、immediate、外链风格路径直接走。
|
||||
*/
|
||||
export async function transitionTo(
|
||||
nav: NavigateFunction,
|
||||
to: To | number,
|
||||
opts?: TransitionToOpts,
|
||||
): Promise<void> {
|
||||
const { force, immediate, silent, ...navOpts } = opts ?? {};
|
||||
|
||||
if (typeof to === 'number' || immediate || isOnlyHashChange(to as To)) {
|
||||
nav(to as To, navOpts);
|
||||
return;
|
||||
}
|
||||
|
||||
const target = to as To;
|
||||
const path = toPathname(target);
|
||||
// 后台第一期不做等待跳转
|
||||
if (path.startsWith('/admin')) {
|
||||
nav(target, navOpts);
|
||||
return;
|
||||
}
|
||||
|
||||
const id = silent ? undefined : startTransition();
|
||||
const mySeq = silent ? seq : (id as number);
|
||||
try {
|
||||
await prefetchRoute(target, { force: !!force });
|
||||
if (!silent && mySeq !== seq) return;
|
||||
nav(target, navOpts);
|
||||
} catch (e: unknown) {
|
||||
if (!silent && mySeq !== seq) return;
|
||||
// 发版后 chunk 404:整页刷新,不 toast 英文原错
|
||||
if (isChunkLoadError(e) && reloadForStaleChunk()) return;
|
||||
notify.error(e instanceof Error ? e.message : '加载失败');
|
||||
} finally {
|
||||
if (id != null) {
|
||||
if (mySeq === seq) doneTransition(id);
|
||||
else doneTransition();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,40 @@
|
||||
import path from 'path';
|
||||
import { defineConfig } from 'vite';
|
||||
import { defineConfig, type Plugin } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
// 与 Go 后端默认端口一致,可通过 VITE_API_PORT 覆盖
|
||||
const apiPort = process.env.VITE_API_PORT || '3000';
|
||||
const apiTarget = `http://localhost:${apiPort}`;
|
||||
|
||||
/** 把 stylesheet 挪到 head 靠前(先于 module script),接近 Gitea 外链 CSS 顺序 */
|
||||
function htmlStylesheetsFirst(): Plugin {
|
||||
return {
|
||||
name: 'html-stylesheets-first',
|
||||
enforce: 'post',
|
||||
transformIndexHtml(html) {
|
||||
// 只处理真实标签,忽略注释里的示例文字
|
||||
const linkRe = /<link\b(?![^>]*\/?>)[^>]*\brel=["']stylesheet["'][^>]*>\s*/gi;
|
||||
// 更稳妥:逐个找 link 标签
|
||||
const styles: string[] = [];
|
||||
const out = html.replace(/<link\b[^>]*>/gi, (tag) => {
|
||||
if (/\brel=["']stylesheet["']/i.test(tag)) {
|
||||
styles.push(tag);
|
||||
return '';
|
||||
}
|
||||
return tag;
|
||||
});
|
||||
if (!styles.length) return html;
|
||||
const inject = `${styles.join('\n ')}\n `;
|
||||
if (/<script\b/i.test(out)) {
|
||||
return out.replace(/<script\b/i, `${inject}<script`);
|
||||
}
|
||||
return out.replace(/<\/head>/i, ` ${inject}</head>`);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
plugins: [react(), htmlStylesheetsFirst()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
|
||||
5
go.mod
5
go.mod
@@ -7,9 +7,12 @@ require (
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
github.com/glebarez/sqlite v1.11.0
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/ip2location/ip2location-go/v9 v9.8.0
|
||||
github.com/kardianos/service v1.2.2
|
||||
github.com/microcosm-cc/bluemonday v1.0.27
|
||||
github.com/minio/minio-go/v7 v7.0.98
|
||||
github.com/oschwald/maxminddb-golang v1.13.1
|
||||
golang.org/x/crypto v0.46.0
|
||||
golang.org/x/image v0.44.0
|
||||
gopkg.in/ini.v1 v1.67.3
|
||||
@@ -31,7 +34,6 @@ require (
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/css v1.0.1 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
@@ -59,6 +61,7 @@ require (
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
google.golang.org/protobuf v1.34.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
lukechampine.com/uint128 v1.2.0 // indirect
|
||||
modernc.org/libc v1.22.5 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.5.0 // indirect
|
||||
|
||||
6
go.sum
6
go.sum
@@ -48,6 +48,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
|
||||
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
|
||||
github.com/ip2location/ip2location-go/v9 v9.8.0 h1:drPzGjj1EBl45I33ErMHFtIfsQ3mR85dAQbqMDbi9mc=
|
||||
github.com/ip2location/ip2location-go/v9 v9.8.0/go.mod h1:MPLnsKxwQlvd2lBNcQCsLoyzJLDBFizuO67wXXdzoyI=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
@@ -82,6 +84,8 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/oschwald/maxminddb-golang v1.13.1 h1:G3wwjdN9JmIK2o/ermkHM+98oX5fS+k5MbwsmL4MRQE=
|
||||
github.com/oschwald/maxminddb-golang v1.13.1/go.mod h1:K4pgV9N/GcK694KSTmVSDTODk4IsCNThNdTmnaBZ/F8=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||
@@ -142,6 +146,8 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
|
||||
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
|
||||
lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI=
|
||||
lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=
|
||||
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
|
||||
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
|
||||
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user