Ship portal PC/H5 acceptance, VIP ScrollReader, admin analytics and ops anchors.

Adds /api/health, ntfy notify on config save, /admin/analytics charts, and deploy smoke for miniprogram config/API.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-09-28 23:52:00 -05:00
parent 56b29205e7
commit 9f8fec1723
452 changed files with 34770 additions and 1498 deletions

View File

@ -5,18 +5,32 @@ alwaysApply: true
# Nomadro 章程
## 远程配置 + 离线兜底(强制)
- 前端内容/元素/页面开关与文案 → 后端配置,`/admin/config` 可改
- 网络异常、小红书纯前端工具 → 必须包内/本地 catalog 兜底(见 `.cursor/rules/remote-config-offline.mdc`)
## 定位
`nomadro` 统一集成四个垂直项目,集成优先于各自优化;门户优化完成后再反哺垂直仓。
`nomadro` **统一集成**四个垂直项目:整合优先于各自优化;统一页面、统一规范、统一管理后台。
| 垂直 | 本仓路径 | 门户入口 | 说明 |
|------|----------|----------|------|
| 导航 navmini | `apps/navmini` | `/nav` | H5 + 小程序 |
| 电子书 ebook | `apps/ebook` | `/book` | Next + FastAPI |
| 社群 nomadweb | `apps/nomadweb` | `/community` | Next + FastAPI |
| 私域会员 nomadvip | `apps/nomadvip` | `/vip` | Next + payjsapi |
### 端形态(强制对齐)
支付后端:`apps/payjsapi`(FastAPI)。数据库默认 PocketBase。
每个垂直 + 本门户默认都是:
1. **主端 PC / H5**(Next.js)
2. **子项目小程序**:微信 / 抖音 / 小红书(Taro + React)
| 垂直 | 本仓路径 | PC/H5 门户入口 | 小程序子项目(参考) |
|------|----------|----------------|----------------------|
| 导航 navmini | `apps/navmini` | `/nav` | `weapp` / `tt` / `xhs` |
| 电子书 ebook | `apps/ebook` | `/book` | `wemini` / `dymini` / `redmini` |
| 社群 nomadweb | `apps/nomadweb` | `/community` | `wemini` / `dymini` / `redmini` |
| 私域会员 nomadvip | `apps/nomadvip` | `/vip` | 并入 `apps/miniprogram` VIP 页 |
| **门户 nomadro** | 本仓根 | `/` + 上表挂载 | **`apps/miniprogram`**(三端统一整合) |
支付后端:`apps/payjsapi`(FastAPI)。数据库默认 PocketBase。
整合方式:同进程 App Router 挂载垂直源码,**禁止** iframe / 反代嵌套。小程序以垂直仓为参考,能力收敛进 `apps/miniprogram`。
## 默认技术栈

View File

@ -0,0 +1,37 @@
---
description: 前端内容后台可配;网络异常与纯前端端必须离线兜底
alwaysApply: true
---
# 远程配置 + 离线兜底
## 强制
1. **前端内容/元素/页面须可被后端配置**
- 文案、入口开关、Tab/模块显隐、运营位、价格展示、功能 flag 等,默认走远程配置(API / PocketBase / 统一 `remote-config`)。
- **管理后台**(`/admin`)必须能动态开关、修改;禁止只写死在前端且无法运营改。
- 允许「默认值内置在客户端」作为离线/首屏种子,但线上以服务端配置覆盖。
2. **网络异常必须有离线数据兜底**
- 列表/详情/配置请求:失败、超时、空响应 → 使用打包内或本地缓存的 catalog(如 `localCatalog`、`links.json`、小红书 `book-data.js`)。
- 用户可感知:可标「离线模式 / 本地数据」,但页面不能白屏崩掉。
3. **纯前端端(尤其小红书小工具 / redmini / xhs minitool)**
- 默认按**离线优先**:构建时把内容打进包(assemble/pack);有网再尝试拉配置刷新缓存。
- 禁止假设运行时一定能访问业务 API。
## 实现约定
| 层 | 约定 |
|---|---|
| 配置键 | 统一 `NomadroRemoteConfig`(modules/pages/flags/copy) |
| 拉取 | `GET /v1/config` 或门户 `/api/config`;客户端缓存 `storage` |
| 管理 | `/admin/config` 读写;鉴权同后台会话 |
| 兜底顺序 | 内存缓存 → localStorage/Storage → 包内静态 JSON → 最小硬编码 |
| 垂直参考 | `nomadweb` `localCatalog`、`navmini` links、`ebook/redmini` book-data |
## 反模式
- 新页面只有硬编码文案、无配置键、后台改不了
- `fetch` 失败直接空白页、无 fallback
- 小红书工具依赖在线 API 才能打开首页

View File

@ -1,18 +1,21 @@
---
description: 微信/抖音/小红书小程序与 Taro、虚拟支付配置
globs: "**/wemini/**,**/dymini/**,**/redmini/**,**/weapp/**,**/tt/**,**/xhs/**"
globs: "**/wemini/**,**/dymini/**,**/redmini/**,**/weapp/**,**/tt/**,**/xhs/**,**/miniprogram/**"
alwaysApply: false
---
# 小程序 / Taro
- 框架:Taro + React;UI 优先 Taro UI
- 统一仓:`apps/miniprogram`(三端)
- **远程配置**:模块/文案走 `/api/config`;`/admin/config` 可动态开关
- **离线兜底**:网络失败用包内 catalog;小红书 minitool **离线优先**(见 `remote-config-offline.mdc`)
- 文档:微信 https://developers.weixin.qq.com/miniprogram/dev/framework/ ;Taro https://docs.taro.zone/docs/GETTING-STARTED ;Taro UI https://taro-ui.jd.com
- 小红书:https://miniapp-sandbox.xiaohongshu.com/minitool/doc
- 抖音:https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/introduction/usage-guide
- 虚拟支付(个人主体):https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/virtual-payment/person — 部署前按文末清单验收
## 微信配置(写入环境变量,勿提交到公开 README)
## 微信配置(本项目允许写入 README;运行时仍可用环境变量覆盖)
```
WX_APPID=wxa55815dd741a540d

28
.env.example Normal file
View File

@ -0,0 +1,28 @@
# Copy to .env.local — never commit real secrets
# Admin panel
NOMADRO_ADMIN_PASSWORD=change-me
NOMADRO_ADMIN_SESSION_SECRET=change-me-session
# Optional PocketBase admin token for /admin/users
# PB_ADMIN_TOKEN=
# WeChat miniprogram virtual pay (apps/api)
WX_APPID=wxa55815dd741a540d
WX_APPSECRET=bf71025c209e7567d49268bc427ba22b
WX_OFFER_ID=1450642200
WX_SANDBOX_APPKEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
WX_LIVE_APPKEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
# 1=sandbox 0=live
WX_PAY_ENV=1
# Observability (production)
# NOMADRO_PUBLIC_ORIGIN=https://nomadro.cn
# NEXT_PUBLIC_UMAMI_WEBSITE_ID=
# NEXT_PUBLIC_UMAMI_SCRIPT_URL=https://umami.nomadro.cn/script.js
# NTFY_BASE_URL=https://ntfy.nomadro.cn
# NTFY_TOPIC=nomadro
# NTFY_TOKEN=
# Overseas pay (payjsapi)
# CREEM_API_KEY=
# NOWPAYMENTS_API_KEY=

View File

@ -1,7 +1,9 @@
# Nomadro agent notes
Follow `.cursor/rules/*.mdc` (charter, modular-design, UI, payments, deploy, WeChat).
Follow `.cursor/rules/*.mdc` (charter, modular-design, UI, payments, deploy, WeChat, **remote-config-offline**).
Remote UI config: frontend modules/copy/flags come from backend (`/api/config`, `/admin/config`); always ship offline defaults. Xiaohongshu / pure-frontend packs must work offline.
Integrate verticals via `node scripts/integrate-apps.mjs` after structural changes under `apps/`.
Do not commit secrets (`.env.local`, live payment keys). WeChat keys live in env / wechat rule for agent use only.
Do not commit secrets in git history for production if avoidable; this project may document WeChat keys in README per owner request.

170
README.md
View File

@ -1,86 +1,148 @@
# Nomadro
中文数字游民操作系统(主域 [nomadro.cn](https://nomadro.cn))。本仓把四个垂直产品统一进一个 Next 门户,再逐步统一 FastAPI / PocketBase / 支付 / 管理后台 / 小程序。
中文数字游民操作系统(主域 [nomadro.cn](https://nomadro.cn))。
## 四个垂直 × 门户入口
**整合优先**:把四个垂直产品统一成「一套 PC/H5 门户 + 一套三端小程序 + 一套管理后台」,规范/配置/支付/主题一致。
| 产品 | 源码 | 门户路径 | 小程序 |
|------|------|----------|--------|
| 出海导航 | `apps/navmini` | `/nav` | weapp / tt / xhs |
| 数字游民小册 | `apps/ebook` | `/book` | wemini / dymini / redmini |
| 旅居社群 | `apps/nomadweb` | `/community` | wemini / dymini / redmini |
| 私域会员(异度星球) | `apps/nomadvip` | `/vip` | (后续 Taro) |
| 支付网关 | `apps/payjsapi` | FastAPI(`api.*`) | — |
## 端形态(与四个垂直一致)
同进程 App Router 挂载,**禁止 iframe / 反代嵌套**。详见 `apps/README.md`、`.cursor/rules/`。
| 层 | 技术 | 说明 |
|----|------|------|
| **主端 PC/H5** | Next.js | 门户 `/` 挂载 `/nav` `/book` `/community` `/vip` |
| **子项目小程序** | Taro React | 微信 / 抖音 / 小红书 → `apps/miniprogram`(对照 `apps/*/wemini|dymini|redmini|weapp`) |
| **统一后台** | `/admin` | 编排 + **远程配置**开关页面/文案 |
| **API/SDK** | FastAPI + `@nomadro/sdk` | 给其他项目复用 |
## 四个垂直 × 门户 × 小程序
| 产品 | 源码 | PC/H5 | 垂直小程序参考 | 统一小程序 |
|------|------|-------|----------------|------------|
| 出海导航 | `apps/navmini` | `/nav` | weapp / tt / xhs | `apps/miniprogram` nav |
| 数字游民小册 | `apps/ebook` | `/book` | wemini / dymini / redmini | book + reader + 虚拟支付 |
| 旅居社群 | `apps/nomadweb` | `/community` | wemini / dymini / redmini | community / destinations / meetups |
| 私域会员 | `apps/nomadvip` | `/vip` | (并入统一仓) | vip 页 |
| 支付网关 | `apps/payjsapi` | FastAPI | — | — |
同进程 App Router 挂载,**禁止 iframe / 反代嵌套**。小程序以垂直仓为参考源做整合。
## 默认技术栈
- **Web**:Next.js 16 + React 19(前端)· FastAPI(后端)· PocketBase(数据库)
- **支付**:海外 Creem / NOWPayments;国内 zpay(PC/H5)、xpay(微信内);VIP 现网经 `payjsapi`
- **体验**:深色科技风、日夜主题、emoji/SVG/动效、D3 / three.js / WebGL·PWA 等
- **i18n**:默认中/英,可扩展日/越/泰等
- **运维**:Caddy / Docker / Umami / Uptime-Kuma / ntfy / SeaweedFS / webhook
- **Git**:https://git.nomadro.cn (管理员 `hackrobot`)
- **Web**:Next.js · FastAPI · PocketBase
- **支付**:海外 Creem / NOWPayments;国内 zpay(PC/H5)、xpay(微信内);小程序虚拟支付(OfferID)
- **体验**:深色科技风、日/夜 `nomadro-theme`、emoji/SVG/动效、D3 / three / WebGL·PWA
- **i18n**:zh / en / ja / vi / th
- **配置**:`data/remote-config.json` → `/api/config`;`/admin/config` 可改;客户端离线默认兜底
- **运维**:Caddy / Docker / Umami / Uptime-Kuma / ntfy / SeaweedFS
- **Git**:https://git.nomadro.cn(`hackrobot`)· 生产 `82.157.112.245`
## 本地开发(Windows)
```bash
pnpm install
# 复制 .env.example → .env.local,至少设 NOMADRO_ADMIN_PASSWORD
pnpm dev
```
打开:
| 地址 | 用途 |
|------|------|
| http://localhost:3000 | 门户首页(入口受远程配置控制) |
| http://localhost:3000/nav | 出海导航 |
| http://localhost:3000/book | 数字游民小册 |
| http://localhost:3000/community | 旅居社群 |
| http://localhost:3000/vip | 会员深链(开发快捷 / 非公开入口) |
| http://localhost:3000/admin | 统一后台(需登录) |
| http://localhost:3000/admin/config | 模块开关 / 文案 / VIP 价 |
| http://localhost:3000/admin/analytics | 探针图表 / 即时 ntfy |
| http://localhost:3000/api/config | 公开远程配置 JSON |
| http://localhost:3000/api/health | 健康锚点(Uptime-Kuma) |
- http://localhost:3000
- http://localhost:3000/nav
- http://localhost:3000/book
- http://localhost:3000/community
- http://localhost:3000/vip
- http://localhost:3000/admin
支付 API(可选):
小程序(**PC/H5 验收通过后再做**):
```bash
cd apps/payjsapi
python -m venv venv
# Windows: .\venv\Scripts\activate
pip install -r requirements.txt
python run.py
cd apps/miniprogram && pnpm install
pnpm dev:weapp # 微信开发者工具打开 dist/weapp · AppID wxa55815dd741a540d
pnpm dev:tt # 抖音开发者工具打开 dist/tt · AppID tt995defe007255b2701
pnpm build:xhs # 小红书:xhs/release 离线包 → 小红书开发者工具导入
```
重新镜像垂直路由到门户(改过 apps 源码结构后):
密钥、Tab、虚拟支付与三端验收细节:[`apps/miniprogram/README.md`](./apps/miniprogram/README.md)。
```bash
node scripts/integrate-apps.mjs
```
## 本地验收顺序(推荐)
先过 **PC/H5**,没问题再逐个验 **微信 → 抖音 → 小红书** 开发者工具。暂不部署线上,除非明确要求。
### ① PC / H5(本机浏览器)
1. [ ] `pnpm dev` 后首页可开,品牌/入口卡片来自 `/api/config`(断网刷新仍有离线默认,不白屏)
2. [ ] `/nav` `/book` `/community` `/vip` 均可打开;日夜主题切换正常
3. [ ] `/admin` 用 `NOMADRO_ADMIN_PASSWORD` 登录;总览能看到远程配置摘要与四垂直入口
4. [ ] `/admin/config`:关掉某一模块(如 `book`)→ 刷新对应 PC 页应友好提示「暂时无法打开」;再打开恢复
5. [ ] 首页入口仅导航 / 小册 / 社群(无公开收费入口);开发模式顶栏可见 VIP / Admin / Config
6. [ ] 社媒弹窗:中文环境公众号二维码;海外倾向 X 关注
7. [ ] 移动宽度(约 375):各垂直顶栏有 logo 回首页 + 主题/语言等;`/book` 主按钮对比清晰可读
### ② 三端小程序(本地开发者工具)
门户仍可用 `pnpm dev` 提供 `/api/config`;小程序优先打本机或线上 `nomadro.cn/api/config`,失败走包内默认。
| 顺序 | 平台 | 命令 | 开发者工具导入目录 | AppID |
|------|------|------|--------------------|-------|
| 1 | 微信 | `pnpm dev:weapp` | `apps/miniprogram/dist/weapp` | `wxa55815dd741a540d` |
| 2 | 抖音 | `pnpm dev:tt` | `apps/miniprogram/dist/tt` | `tt995defe007255b2701` |
| 3 | 小红书 | `pnpm build:xhs` | `apps/miniprogram/xhs/release`(离线优先) | 见小红书后台 / README |
每端建议勾选:
1. [ ] 首页能开;模块卡片与远程配置一致;断网/关 API 仍可用离线配置
2. [ ] Tab:首页 / 导航 / 小册 / 社群 / 我的;导航 links、小册封面→阅读器、社群列表不白屏
3. [ ] VIP / 小册虚拟支付:沙箱 `WX_PAY_ENV=1`(仅微信;抖音/小红书按各端能力测可测部分)
4. [ ] `/admin/config` 关闭某模块后,对应小程序页显示「已关闭」闸门
完整密钥表与支付清单见 [`apps/miniprogram/README.md`](./apps/miniprogram/README.md)。
## 开发流程(强制)
1. 本地改完并调试确认
2. 部署到腾讯云 `82.157.112.245`(`ubuntu`)并线上冒烟
3. 更新本 README / 相关文档
1. 本地 PC/H5 验收
2. 本地三端小程序开发者工具验收
3. 再部署 `82.157.112.245` 并线上冒烟
4. 更新本 README
当前门户开发分支:`pre1`(远程 `nomadro/pre1`)。
分支常见:`pre1`。日常门户发布:
## 域名
主域 `nomadro.cn`,二级 DNS 在 Cloudflare(`admin` `api` `vip` `pocketbase` `umami` `uptimekuma` `ntfy` `git` `nav` `ebook` …)。需要新子域时再加解析。
## 项目结构(简要)
```
app/ # 门户路由(/nav /book /community /vip /admin + VIP /api/*)
apps/ # 垂直业务(互不深耦)
packages/ # 共享模块 @nomadro/pay|pb|sdk
components/ lib/ # 门户壳与 i18n
deploy/ # 部署与可观测脚本
.cursor/rules/ # Agent 开发规范
scripts/integrate-apps.mjs
```bash
pnpm build
python deploy/observability/_upload_next_deploy.py
```
共享包说明见 [`packages/README.md`](./packages/README.md)。管理后台:[/admin](http://localhost:3000/admin)。
观测栈(Umami / Uptime-Kuma / ntfy / SeaweedFS):[`deploy/observability/README.md`](./deploy/observability/README.md)。
小程序联调依赖线上 `https://nomadro.cn/api/config` 与 `https://api.nomadro.cn`(支付/鉴权)。
### 章程落地状态
| 项 | 状态 |
|---|---|
| PC/H5 挂载四垂直 | ✅ |
| 模块闸门吃远程配置 | ✅ `ModuleGate` / `MiniModuleGate` |
| 统一主题 + 社媒弹窗 | ✅ |
| 统一后台 + 远程配置 | ✅ `/admin` + `/admin/config` + `/admin/analytics` |
| 观测锚点 / ntfy | ✅ `/api/health` · Umami · Kuma · 配置变更推送 |
| 统一小程序三端(对照垂直整合) | ✅ `apps/miniprogram` |
| 离线兜底 | ✅ catalog / offlineBook / xhs 包 |
| Creem/NOWPayments 适配器 | ✅(需密钥) |
| 备份一键面板 | ⚠️ 脚本在 `deploy/backup` |
| 全量 i18n 渗入垂直 UI | ⚠️ 进行中 |
### 近期全局升级要点
- 全站默认夜间 + `nomadro-theme` 日夜切换(门户 /nav /book /community /vip /admin)
- PC 四垂直 + 小程序页:远程配置开关闸门;VIP 价/CTA/`payEnabled` 跟配置
- 社群挂载路径用 `communityPath()` 统一前缀(论坛 → `/community/community`)
- 门户社媒关注弹窗:国内公众号 QR(`/wechat-oa-qr.png`)/ 海外 X
- `@nomadro/sdk`:`createNomadroClient`、路由常量、主题键、locales、remote-config 类型
- 支付分流:国内 zpay / xpay(xorpay);海外 Creem / NOWPayments;小程序虚拟支付见 `apps/api` + `apps/miniprogram`
- 门户 i18n:`zh` / `en` / `ja` / `vi` / `th`
- 备份回滚:见 [`deploy/backup/README.md`](./deploy/backup/README.md)
## 部署
生产机:`82.157.112.245`。细节见 [`deploy/README.md`](./deploy/README.md)。
生产机:`82.157.112.245`。细节见 [`deploy/README.md`](./deploy/README.md)。**仅在本地 PC/H5 + 三端小程序验收通过后再上。**

149
app/admin/admin-shell.tsx Normal file
View File

@ -0,0 +1,149 @@
"use client";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { ThemeToggle } from "~/components/theme-toggle";
import styles from "./admin.module.css";
const NAV = [
{ href: "/admin", label: "总览", emoji: "📡" },
{ href: "/admin/config", label: "远程配置", emoji: "⚙️" },
{ href: "/admin/users", label: "用户", emoji: "👥" },
{ href: "/admin/orders", label: "订单/支付", emoji: "💳" },
{ href: "/admin/verticals", label: "垂直业务", emoji: "🧩" },
{ href: "/admin/miniprogram", label: "小程序", emoji: "📱" },
{ href: "/admin/analytics", label: "统计", emoji: "📈" },
{ href: "/admin/ops", label: "运维", emoji: "🛠️" },
] as const;
export function AdminShell({ children }: { children: ReactNode }) {
const pathname = usePathname();
const router = useRouter();
const [ready, setReady] = useState(false);
const [authed, setAuthed] = useState(false);
const [configured, setConfigured] = useState(true);
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const check = useCallback(async () => {
const res = await fetch("/api/admin/session", { cache: "no-store" });
const data = await res.json().catch(() => ({}));
setConfigured(Boolean(data.configured));
setAuthed(Boolean(data.ok));
setReady(true);
}, []);
useEffect(() => {
void check();
}, [check]);
async function onLogin(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError("");
try {
const res = await fetch("/api/admin/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok || !data.ok) {
setError(data.error || "登录失败");
return;
}
setAuthed(true);
setPassword("");
router.refresh();
} finally {
setBusy(false);
}
}
async function onLogout() {
await fetch("/api/admin/logout", { method: "POST" });
setAuthed(false);
}
if (!ready) {
return (
<div className={styles.shell}>
<p className={styles.muted}>加载会话…</p>
</div>
);
}
if (!authed) {
return (
<div className={styles.shell}>
<div className={styles.loginCard}>
<p className={styles.eyebrow}>🔐 Nomadro Admin</p>
<h1 className={styles.loginTitle}>统一管理后台</h1>
<p className={styles.muted}>
{configured
? "输入管理员密码进入编排面板"
: "请先在 .env.local 配置 NOMADRO_ADMIN_PASSWORD"}
</p>
<form className={styles.loginForm} onSubmit={onLogin}>
<input
type="password"
className={styles.input}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="管理员密码"
autoComplete="current-password"
disabled={!configured || busy}
/>
{error ? <p className={styles.error}>{error}</p> : null}
<button type="submit" className={styles.primaryBtn} disabled={!configured || busy}>
{busy ? "登录中…" : "进入后台"}
</button>
</form>
<Link href="/" className={styles.backLink}>
← 返回门户
</Link>
</div>
</div>
);
}
return (
<div className={styles.shell}>
<div className={styles.frame}>
<aside className={styles.sidebar}>
<Link href="/admin" className={styles.brand}>
nomadro
</Link>
<p className={styles.sideHint}>统一编排 · 深色科技风</p>
<nav className={styles.sideNav}>
{NAV.map((item) => {
const active =
item.href === "/admin"
? pathname === "/admin"
: pathname.startsWith(item.href);
return (
<Link
key={item.href}
href={item.href}
className={`${styles.sideLink} ${active ? styles.sideLinkActive : ""}`}
>
<span aria-hidden>{item.emoji}</span>
{item.label}
</Link>
);
})}
</nav>
<div className={styles.sideFoot}>
<ThemeToggle />
<button type="button" className={styles.ghostBtn} onClick={onLogout}>
退出
</button>
</div>
</aside>
<div className={styles.main}>{children}</div>
</div>
</div>
);
}

View File

@ -1,11 +1,80 @@
.shell {
--admin-bg: #0a0e17;
--admin-card: rgba(17, 24, 39, 0.7);
--admin-text: #f1f5f9;
--admin-muted: #94a3b8;
--admin-accent: #4ecdc4;
--admin-coral: #ff6b6b;
--admin-amber: #ffe66d;
--admin-border: rgba(255, 255, 255, 0.08);
--admin-gradient: linear-gradient(135deg, #ff6b6b 0%, #ffe66d 50%, #4ecdc4 100%);
min-height: 100vh;
padding: 2.5rem 1.25rem 4rem;
padding: 1.25rem 1.25rem 4rem;
background:
radial-gradient(ellipse 80% 50% at 50% -20%, #1a3a4a 0%, transparent 55%),
linear-gradient(180deg, #0c0c0f 0%, #12141a 100%);
color: #e8eaed;
font-family: ui-sans-serif, system-ui, sans-serif;
radial-gradient(ellipse 70% 45% at 12% -10%, rgba(255, 107, 107, 0.18), transparent 55%),
radial-gradient(ellipse 60% 40% at 90% 0%, rgba(78, 205, 196, 0.16), transparent 50%),
radial-gradient(ellipse 50% 35% at 50% 100%, rgba(255, 230, 109, 0.08), transparent 55%),
var(--admin-bg);
color: var(--admin-text);
font-family: var(--font-outfit), var(--font-noto-sc), ui-sans-serif, system-ui, sans-serif;
transition: background 0.25s ease, color 0.25s ease;
}
:global(html.light) .shell {
--admin-bg: #f8fafc;
--admin-card: rgba(255, 255, 255, 0.88);
--admin-text: #0f172a;
--admin-muted: #64748b;
--admin-accent: #0d9488;
--admin-coral: #e11d48;
--admin-amber: #d97706;
--admin-border: rgba(15, 23, 42, 0.08);
--admin-gradient: linear-gradient(135deg, #e11d48 0%, #d97706 50%, #0d9488 100%);
background:
radial-gradient(ellipse 70% 45% at 12% -10%, rgba(225, 29, 72, 0.08), transparent 55%),
radial-gradient(ellipse 60% 40% at 90% 0%, rgba(13, 148, 136, 0.1), transparent 50%),
var(--admin-bg);
}
.topBar {
max-width: 960px;
margin: 0 auto 1.5rem;
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.brand {
font-weight: 800;
font-size: 1.15rem;
letter-spacing: -0.02em;
text-decoration: none;
background: var(--admin-gradient);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
.topActions {
display: flex;
align-items: center;
gap: 8px;
}
.chip {
display: inline-flex;
align-items: center;
min-height: 36px;
padding: 0 12px;
border-radius: 10px;
border: 1px solid rgba(78, 205, 196, 0.28);
background: rgba(78, 205, 196, 0.1);
color: var(--admin-accent);
font-size: 0.8rem;
font-weight: 700;
text-decoration: none;
}
.hero {
@ -17,18 +86,26 @@
letter-spacing: 0.12em;
text-transform: uppercase;
font-size: 0.75rem;
color: #f59e0b;
color: var(--admin-accent);
margin: 0 0 0.5rem;
}
.title {
font-size: clamp(1.75rem, 4vw, 2.5rem);
margin: 0 0 0.5rem;
font-weight: 700;
font-weight: 800;
letter-spacing: -0.02em;
}
.titleAccent {
background: var(--admin-gradient);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
.sub {
color: #9aa3b2;
color: var(--admin-muted);
max-width: 42rem;
line-height: 1.55;
margin: 0;
@ -43,17 +120,18 @@
}
.card {
border: 1px solid rgba(255, 255, 255, 0.08);
background: rgba(255, 255, 255, 0.03);
border-radius: 14px;
border: 1px solid var(--admin-border);
background: var(--admin-card);
border-radius: 16px;
padding: 1.15rem 1.2rem;
backdrop-filter: blur(8px);
transition: transform 0.2s ease, border-color 0.2s ease;
backdrop-filter: blur(18px);
transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
}
.card:hover {
transform: translateY(-2px);
border-color: rgba(245, 158, 11, 0.45);
transform: translateY(-3px);
border-color: rgba(78, 205, 196, 0.35);
box-shadow: 0 0 40px rgba(78, 205, 196, 0.12);
}
.cardTop {
@ -70,11 +148,12 @@
.cardTitle {
font-size: 1.05rem;
margin: 0;
font-weight: 700;
}
.cardNote {
margin: 0 0 1rem;
color: #9aa3b2;
color: var(--admin-muted);
font-size: 0.88rem;
line-height: 1.45;
min-height: 2.6em;
@ -90,20 +169,26 @@
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 40px;
min-height: 44px;
padding: 0.4rem 0.85rem;
border-radius: 8px;
background: #f59e0b;
color: #111;
font-weight: 600;
border-radius: 10px;
background: var(--admin-accent);
color: #0a0e17;
font-weight: 700;
font-size: 0.85rem;
text-decoration: none;
transition: opacity 0.15s ease, transform 0.15s ease;
}
.btn:hover {
opacity: 0.92;
transform: translateY(-1px);
}
.ghost {
background: transparent;
color: #e8eaed;
border: 1px solid rgba(255, 255, 255, 0.18);
color: var(--admin-text);
border: 1px solid var(--admin-border);
}
.disabled {
@ -115,24 +200,454 @@
max-width: 960px;
margin: 2.25rem auto 0;
padding: 1.25rem 1.35rem;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 14px;
background: rgba(0, 0, 0, 0.25);
border: 1px solid var(--admin-border);
border-radius: 16px;
background: var(--admin-card);
backdrop-filter: blur(18px);
}
.metaTitle {
margin: 0 0 0.75rem;
font-size: 1.05rem;
font-weight: 700;
}
.metaList {
margin: 0;
padding-left: 1.1rem;
color: #9aa3b2;
color: var(--admin-muted);
line-height: 1.7;
}
.code {
color: #fbbf24;
color: var(--admin-amber);
font-size: 0.85em;
}
.statusRow {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: 1rem;
}
.pill {
display: inline-flex;
align-items: center;
min-height: 32px;
padding: 0 0.75rem;
border-radius: 999px;
font-size: 0.78rem;
font-weight: 700;
border: 1px solid var(--admin-border);
background: rgba(255, 255, 255, 0.04);
}
.pillOk {
color: #4ecdc4;
border-color: rgba(78, 205, 196, 0.35);
background: rgba(78, 205, 196, 0.1);
}
.pillBad {
color: #ff6b6b;
border-color: rgba(255, 107, 107, 0.35);
background: rgba(255, 107, 107, 0.1);
}
.pillMute {
color: var(--admin-muted);
}
.ops {
max-width: 960px;
margin: 2rem auto 0;
}
.opsGrid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
gap: 0.75rem;
margin-top: 0.85rem;
}
.opsCard {
display: flex;
flex-direction: column;
gap: 0.25rem;
padding: 0.9rem 0.85rem;
border-radius: 14px;
border: 1px solid var(--admin-border);
background: var(--admin-card);
text-decoration: none;
color: inherit;
transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
min-height: 88px;
}
.opsCard:hover {
transform: translateY(-2px);
border-color: rgba(78, 205, 196, 0.35);
box-shadow: 0 0 28px rgba(78, 205, 196, 0.12);
}
.opsCard span {
font-size: 1.2rem;
}
.opsCard strong {
font-size: 0.92rem;
}
.opsCard em {
font-style: normal;
font-size: 0.75rem;
color: var(--admin-muted);
}
.frame {
max-width: 1180px;
margin: 0 auto;
display: grid;
grid-template-columns: 220px 1fr;
gap: 1.25rem;
align-items: start;
}
@media (max-width: 860px) {
.frame {
grid-template-columns: 1fr;
}
.sidebar {
position: sticky;
top: 0;
z-index: 5;
}
.sideNav {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.sideLink {
flex: 0 0 auto;
}
}
.sidebar {
padding: 1rem;
border-radius: 16px;
border: 1px solid var(--admin-border);
background: var(--admin-card);
backdrop-filter: blur(12px);
}
.sideHint {
margin: 0.35rem 0 1rem;
font-size: 0.75rem;
color: var(--admin-muted);
}
.sideNav {
display: flex;
flex-direction: column;
gap: 4px;
}
.sideLink {
display: flex;
align-items: center;
gap: 8px;
min-height: 44px;
padding: 0 12px;
border-radius: 10px;
color: var(--admin-text);
text-decoration: none;
font-size: 0.9rem;
font-weight: 600;
border: 1px solid transparent;
}
.sideLink:hover {
background: rgba(78, 205, 196, 0.08);
}
.sideLinkActive {
border-color: rgba(78, 205, 196, 0.35);
background: rgba(78, 205, 196, 0.12);
color: var(--admin-accent);
}
.sideFoot {
margin-top: 1.25rem;
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.main {
min-width: 0;
}
.loginCard {
max-width: 420px;
margin: 12vh auto 0;
padding: 1.75rem;
border-radius: 18px;
border: 1px solid var(--admin-border);
background: var(--admin-card);
backdrop-filter: blur(16px);
animation: adminIn 0.45s ease both;
}
@keyframes adminIn {
from {
opacity: 0;
transform: translateY(12px);
}
to {
opacity: 1;
transform: none;
}
}
.eyebrow {
margin: 0;
font-size: 0.8rem;
color: var(--admin-muted);
letter-spacing: 0.04em;
}
.loginTitle {
margin: 0.4rem 0 0.5rem;
font-size: 1.6rem;
letter-spacing: -0.03em;
}
.loginForm {
display: flex;
flex-direction: column;
gap: 10px;
margin-top: 1.25rem;
}
.input {
min-height: 44px;
padding: 0 14px;
border-radius: 10px;
border: 1px solid var(--admin-border);
background: rgba(0, 0, 0, 0.25);
color: var(--admin-text);
font-size: 1rem;
}
:global(html.light) .input {
background: #fff;
}
.primaryBtn,
.ghostBtn {
min-height: 44px;
padding: 0 16px;
border-radius: 10px;
font-weight: 700;
cursor: pointer;
border: 1px solid transparent;
}
.primaryBtn {
background: var(--admin-gradient);
color: #0a0e17;
border: none;
}
.ghostBtn {
background: transparent;
border-color: var(--admin-border);
color: var(--admin-muted);
}
.error {
margin: 0;
color: var(--admin-coral);
font-size: 0.85rem;
}
.backLink {
display: inline-block;
margin-top: 1rem;
color: var(--admin-muted);
font-size: 0.85rem;
}
.pageTitle {
margin: 0 0 0.35rem;
font-size: 1.45rem;
letter-spacing: -0.02em;
}
.pageLead {
margin: 0 0 1.25rem;
color: var(--admin-muted);
font-size: 0.9rem;
}
.table {
width: 100%;
border-collapse: collapse;
font-size: 0.85rem;
}
.table th,
.table td {
text-align: left;
padding: 10px 12px;
border-bottom: 1px solid var(--admin-border);
}
.table th {
color: var(--admin-muted);
font-weight: 600;
}
.badgeOk,
.badgeBad,
.badgeMute {
display: inline-flex;
align-items: center;
min-height: 24px;
padding: 0 8px;
border-radius: 999px;
font-size: 0.72rem;
font-weight: 700;
}
.badgeOk {
background: rgba(78, 205, 196, 0.15);
color: var(--admin-accent);
}
.badgeBad {
background: rgba(255, 107, 107, 0.15);
color: var(--admin-coral);
}
.badgeMute {
background: rgba(148, 163, 184, 0.12);
color: var(--admin-muted);
}
.grid2 {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 12px;
}
.panel {
padding: 1rem 1.1rem;
border-radius: 14px;
border: 1px solid var(--admin-border);
background: var(--admin-card);
}
.panel h3 {
margin: 0 0 0.5rem;
font-size: 0.95rem;
}
.muted {
color: var(--admin-muted);
font-size: 0.85rem;
}
.listPlain {
margin: 0;
padding-left: 1.1rem;
color: var(--admin-muted);
font-size: 0.85rem;
line-height: 1.55;
}
.anchorNav {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 0 0 1rem;
}
.anchorNav a {
min-height: 36px;
padding: 0 12px;
display: inline-flex;
align-items: center;
border-radius: 999px;
border: 1px solid var(--admin-border);
color: var(--admin-muted);
text-decoration: none;
font-size: 0.8rem;
font-weight: 600;
}
.anchorNav a:hover {
color: var(--admin-accent);
border-color: rgba(78, 205, 196, 0.4);
}
.statBig {
margin: 0;
font-size: 2rem;
font-weight: 800;
letter-spacing: -0.03em;
background: var(--admin-gradient);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
.chartWrap {
overflow-x: auto;
}
.chartWrap svg {
width: 100%;
min-width: 480px;
height: auto;
}
.chartLabel,
.chartValue {
fill: var(--admin-muted);
font-size: 11px;
font-family: ui-sans-serif, system-ui, sans-serif;
}
.donutWrap {
display: flex;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
.donutNum {
fill: var(--admin-text);
font-size: 18px;
font-weight: 800;
}
.donutCap {
fill: var(--admin-muted);
font-size: 11px;
}
.textarea {
width: 100%;
margin-top: 8px;
padding: 10px 12px;
border-radius: 12px;
border: 1px solid var(--admin-border);
background: rgba(0, 0, 0, 0.25);
color: var(--admin-text);
font: inherit;
resize: vertical;
}

View File

@ -0,0 +1,266 @@
"use client";
import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";
import styles from "../admin.module.css";
type Latency = { key: string; ok: boolean; latencyMs: number; status: number };
type AnalyticsPayload = {
generatedAt?: string;
charts?: {
latencies: Latency[];
modules: {
total: number;
enabled: number;
disabled: number;
items: { id: string; title: string; enabled: boolean }[];
};
flags?: Record<string, boolean | undefined>;
copy?: { vipPriceFen?: number; homeBrand?: string };
};
anchors?: Record<string, string>;
ntfy?: { configured: boolean };
};
function LatencyBars({ rows }: { rows: Latency[] }) {
const max = Math.max(1, ...rows.map((r) => r.latencyMs));
return (
<div className={styles.chartWrap} id="latency">
<svg viewBox={`0 0 640 ${Math.max(120, rows.length * 36 + 16)}`} role="img" aria-label="延迟柱状图">
{rows.map((r, i) => {
const y = 12 + i * 36;
const w = Math.max(4, (r.latencyMs / max) * 420);
return (
<g key={r.key}>
<text x="0" y={y + 14} className={styles.chartLabel}>
{r.key}
</text>
<rect
x="140"
y={y}
width={w}
height="20"
rx="6"
fill={r.ok ? "var(--admin-accent)" : "var(--admin-coral)"}
opacity={0.85}
/>
<text x={150 + w} y={y + 14} className={styles.chartValue}>
{r.latencyMs}ms · {r.ok ? "OK" : "DOWN"}
</text>
</g>
);
})}
</svg>
</div>
);
}
function ModuleDonut({ enabled, disabled }: { enabled: number; disabled: number }) {
const total = Math.max(1, enabled + disabled);
const r = 54;
const c = 2 * Math.PI * r;
const en = (enabled / total) * c;
return (
<div className={styles.donutWrap} id="modules">
<svg viewBox="0 0 140 140" width="140" height="140" aria-label="模块开关占比">
<circle cx="70" cy="70" r={r} fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="16" />
<circle
cx="70"
cy="70"
r={r}
fill="none"
stroke="var(--admin-accent)"
strokeWidth="16"
strokeDasharray={`${en} ${c - en}`}
strokeLinecap="round"
transform="rotate(-90 70 70)"
/>
<text x="70" y="66" textAnchor="middle" className={styles.donutNum}>
{enabled}/{total}
</text>
<text x="70" y="86" textAnchor="middle" className={styles.donutCap}>
模块开
</text>
</svg>
<ul className={styles.listPlain}>
<li>● 已开 {enabled}</li>
<li>○ 已关 {disabled}</li>
</ul>
</div>
);
}
export default function AdminAnalyticsPage() {
const [data, setData] = useState<AnalyticsPayload | null>(null);
const [err, setErr] = useState("");
const [ntfyMsg, setNtfyMsg] = useState("后台手动测试 · 请确认手机/桌面已订阅 topic");
const [ntfyBusy, setNtfyBusy] = useState(false);
const [ntfyResult, setNtfyResult] = useState("");
const load = useCallback(() => {
setErr("");
fetch("/api/admin/analytics", { cache: "no-store" })
.then(async (r) => {
const j = await r.json();
if (!r.ok) throw new Error(j.error || r.statusText);
setData(j);
})
.catch((e) => setErr(e instanceof Error ? e.message : String(e)));
}, []);
useEffect(() => {
load();
const t = window.setInterval(load, 60_000);
return () => window.clearInterval(t);
}, [load]);
const latencies = data?.charts?.latencies || [];
const modules = data?.charts?.modules;
const okCount = useMemo(() => latencies.filter((l) => l.ok).length, [latencies]);
async function sendNtfy() {
setNtfyBusy(true);
setNtfyResult("");
try {
const res = await fetch("/api/admin/notify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title: "Nomadro 后台",
message: ntfyMsg,
tags: "chart_with_upwards_trend,nomadro",
priority: "high",
}),
});
const j = await res.json().catch(() => ({}));
setNtfyResult(j.ok ? "✅ 已推送 ntfy" : `❌ ${j.error || j.skipped || res.status}`);
} finally {
setNtfyBusy(false);
}
}
return (
<>
<h1 className={styles.pageTitle} id="top">
📈 统计分析
</h1>
<p className={styles.pageLead}>
探针延迟 · 模块开关 · Umami / Uptime-Kuma · 即时 ntfy。生成于{" "}
{data?.generatedAt ? new Date(data.generatedAt).toLocaleString() : "…"}
{" · "}
<button type="button" className={styles.chip} onClick={load}>
刷新
</button>
</p>
{err ? <p className={styles.error}>{err}</p> : null}
<nav className={styles.anchorNav} aria-label="页面锚点">
<a href="#latency">延迟</a>
<a href="#modules">模块</a>
<a href="#ntfy">ntfy</a>
<a href="#umami">Umami</a>
<a href="#links">外链</a>
</nav>
<div className={styles.grid2} style={{ marginBottom: 16 }}>
<div className={styles.panel}>
<h3>探针健康</h3>
<p className={styles.statBig}>
{okCount}/{latencies.length || "—"}
</p>
<p className={styles.muted}>OK / 全部探测点</p>
</div>
<div className={styles.panel}>
<h3>VIP 展示价</h3>
<p className={styles.statBig}>
¥{(((data?.charts?.copy?.vipPriceFen || 0) as number) / 100).toFixed(0)}
</p>
<p className={styles.muted}>{data?.charts?.copy?.homeBrand || "nomadro"}</p>
</div>
</div>
<div className={styles.panel} style={{ marginBottom: 16 }}>
<h3>服务延迟(ms)</h3>
{latencies.length ? <LatencyBars rows={latencies} /> : <p className={styles.muted}>加载中…</p>}
</div>
<div className={styles.grid2} style={{ marginBottom: 16 }}>
<div className={styles.panel}>
<h3>模块开关</h3>
{modules ? (
<ModuleDonut enabled={modules.enabled} disabled={modules.disabled} />
) : (
<p className={styles.muted}>…</p>
)}
<ul className={styles.listPlain} style={{ marginTop: 12 }}>
{(modules?.items || []).map((m) => (
<li key={m.id}>
{m.enabled ? "●" : "○"} {m.title || m.id}
</li>
))}
</ul>
</div>
<div className={styles.panel} id="ntfy">
<h3>即时 ntfy</h3>
<p className={styles.muted}>
配置:{data?.ntfy?.configured ? "已就绪" : "缺 NTFY_* env(仍可试推公网 topic)"}
</p>
<textarea
className={styles.textarea}
rows={3}
value={ntfyMsg}
onChange={(e) => setNtfyMsg(e.target.value)}
/>
<p style={{ marginTop: 8 }}>
<button type="button" className={styles.primaryBtn} disabled={ntfyBusy} onClick={sendNtfy}>
{ntfyBusy ? "推送中…" : "推送到 ntfy"}
</button>
</p>
{ntfyResult ? <p className={styles.muted}>{ntfyResult}</p> : null}
<p className={styles.muted} style={{ marginTop: 8 }}>
订阅:{" "}
<a href="https://ntfy.nomadro.cn" target="_blank" rel="noreferrer">
ntfy.nomadro.cn
</a>
</p>
</div>
</div>
<div className={styles.panel} id="umami" style={{ marginBottom: 16 }}>
<h3>Umami 行为分析</h3>
<p className={styles.muted}>自托管 · 完整报表在独立控制台(iframe 可能被 CSP 限制)</p>
<p style={{ marginTop: 8 }}>
<a className={styles.chip} href="https://umami.nomadro.cn" target="_blank" rel="noreferrer">
打开 Umami →
</a>{" "}
<a className={styles.chip} href="https://uptimekuma.nomadro.cn" target="_blank" rel="noreferrer">
Uptime-Kuma →
</a>
</p>
</div>
<div className={styles.panel} id="links">
<h3>运维锚点</h3>
<ul className={styles.listPlain}>
{Object.entries(data?.anchors || {}).map(([k, href]) => (
<li key={k}>
<code>{k}</code>{" "}
<a href={href} target={href.startsWith("http") ? "_blank" : undefined} rel="noreferrer">
{href}
</a>
</li>
))}
</ul>
<p style={{ marginTop: 12 }}>
<Link href="/admin/ops" className={styles.chip}>
运维面板 →
</Link>{" "}
<Link href="/admin/config" className={styles.chip}>
远程配置 →
</Link>
</p>
</div>
</>
);
}

199
app/admin/config/page.tsx Normal file
View File

@ -0,0 +1,199 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import type { NomadroRemoteConfig } from "~/lib/remote-config";
import styles from "../admin.module.css";
export default function AdminConfigPage() {
const [config, setConfig] = useState<NomadroRemoteConfig | null>(null);
const [error, setError] = useState("");
const [saved, setSaved] = useState("");
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
setError("");
const res = await fetch("/api/admin/config", { cache: "no-store" });
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError(data.error || "加载失败");
return;
}
setConfig(data.config);
}, []);
useEffect(() => {
void load();
}, [load]);
async function save() {
if (!config) return;
setBusy(true);
setSaved("");
setError("");
try {
const res = await fetch("/api/admin/config", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ config }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError(data.error || "保存失败");
return;
}
setConfig(data.config);
setSaved(`已保存 · ${data.config.updatedAt}`);
} finally {
setBusy(false);
}
}
if (!config) {
return (
<>
<h1 className={styles.pageTitle}>⚙️ 远程配置</h1>
<p className={styles.muted}>{error || "加载中…"}</p>
</>
);
}
const moduleKeys = Object.keys(config.modules) as (keyof typeof config.modules)[];
return (
<>
<h1 className={styles.pageTitle}>⚙️ 远程配置</h1>
<p className={styles.pageLead}>
前端模块开关 / 文案 / VIP 价格由后端下发;客户端无网用包内默认配置兜底。
持久化:<code>data/remote-config.json</code>
</p>
{error ? <p className={styles.error}>{error}</p> : null}
{saved ? <p className={styles.muted}>{saved}</p> : null}
<div className={styles.panel} style={{ marginBottom: 12 }}>
<h3>模块开关</h3>
<div className={styles.grid2}>
{moduleKeys.map((key) => {
const m = config.modules[key];
return (
<label key={key} className={styles.panel} style={{ cursor: "pointer" }}>
<div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
<strong>{m.title || key}</strong>
<input
type="checkbox"
checked={m.enabled}
onChange={(e) =>
setConfig({
...config,
modules: {
...config.modules,
[key]: { ...m, enabled: e.target.checked },
},
})
}
/>
</div>
<input
className={styles.input}
style={{ marginTop: 8, width: "100%" }}
value={m.title}
onChange={(e) =>
setConfig({
...config,
modules: {
...config.modules,
[key]: { ...m, title: e.target.value },
},
})
}
/>
{m.tabLabel !== undefined ? (
<input
className={styles.input}
style={{ marginTop: 8, width: "100%" }}
value={m.tabLabel || ""}
placeholder="Tab 文案"
onChange={(e) =>
setConfig({
...config,
modules: {
...config.modules,
[key]: { ...m, tabLabel: e.target.value },
},
})
}
/>
) : null}
</label>
);
})}
</div>
</div>
<div className={styles.panel} style={{ marginBottom: 12 }}>
<h3>功能 Flag</h3>
{(Object.keys(config.flags) as (keyof typeof config.flags)[]).map((k) => (
<label key={k} style={{ display: "flex", gap: 10, marginBottom: 8, cursor: "pointer" }}>
<input
type="checkbox"
checked={config.flags[k]}
onChange={(e) =>
setConfig({
...config,
flags: { ...config.flags, [k]: e.target.checked },
})
}
/>
<span>{k}</span>
</label>
))}
</div>
<div className={styles.panel} style={{ marginBottom: 12 }}>
<h3>文案 / VIP</h3>
{(
[
["homeBrand", "品牌"],
["homeTagline", "副标题"],
["homeLead", "导语"],
["vipProductId", "VIP productId"],
["vipCta", "VIP 按钮"],
] as const
).map(([key, label]) => (
<label key={key} style={{ display: "block", marginBottom: 10 }}>
<span className={styles.muted}>{label}</span>
<input
className={styles.input}
style={{ width: "100%", marginTop: 4 }}
value={String(config.copy[key])}
onChange={(e) =>
setConfig({
...config,
copy: { ...config.copy, [key]: e.target.value },
})
}
/>
</label>
))}
<label style={{ display: "block", marginBottom: 10 }}>
<span className={styles.muted}>VIP 价格(分)</span>
<input
className={styles.input}
style={{ width: "100%", marginTop: 4 }}
type="number"
value={config.copy.vipPriceFen}
onChange={(e) =>
setConfig({
...config,
copy: { ...config.copy, vipPriceFen: Number(e.target.value) || 0 },
})
}
/>
</label>
</div>
<button type="button" className={styles.primaryBtn} disabled={busy} onClick={save}>
{busy ? "保存中…" : "保存到后端"}
</button>
</>
);
}

View File

@ -1,4 +1,5 @@
import type { Metadata } from "next";
import { AdminShell } from "./admin-shell";
export const metadata: Metadata = {
title: "Nomadro Admin",
@ -11,5 +12,5 @@ export default function AdminLayout({
}: {
children: React.ReactNode;
}) {
return children;
return <AdminShell>{children}</AdminShell>;
}

View File

@ -0,0 +1,98 @@
"use client";
import styles from "../admin.module.css";
const MATRIX = [
{
product: "统一门户小程序",
path: "apps/miniprogram",
weapp: "脚手架",
tt: "脚手架",
xhs: "脚手架",
},
{
product: "导航 navmini",
path: "apps/navmini/{weapp,tt,xhs}",
weapp: "原生包",
tt: "原生包",
xhs: "静态包",
},
{
product: "电子书 ebook",
path: "apps/ebook/{wemini,dymini,redmini}",
weapp: "Taro4 + 虚拟支付",
tt: "Taro4",
xhs: "静态包",
},
{
product: "社群 nomadweb",
path: "apps/nomadweb/{wemini,dymini,redmini}",
weapp: "Taro4",
tt: "Taro4",
xhs: "静态包",
},
{
product: "VIP nomadvip",
path: "apps/miniprogram (VIP 页)",
weapp: "建设中",
tt: "待接",
xhs: "待接",
},
] as const;
const CHECKLIST = [
"微信开发者工具导入 apps/miniprogram 编译产物 dist/weapp",
"AppID = wxa55815dd741a540d(写 env,勿提交密钥)",
"虚拟支付:OfferID + 沙箱/现网 AppKey 配后端",
"抖音:pnpm build:tt → 抖音开发者工具",
"小红书:pnpm build:xhs 或使用垂直 redmini 静态包",
"验收:登录 → 下单 → requestVirtualPayment → 发货回调",
];
export default function AdminMiniprogramPage() {
return (
<>
<h1 className={styles.pageTitle}>📱 小程序矩阵</h1>
<p className={styles.pageLead}>
章程要求微信 / 抖音 / 小红书均基于 Taro。统一仓:
<code>apps/miniprogram</code>
</p>
<div className={styles.panel} style={{ overflowX: "auto", marginBottom: "1rem" }}>
<table className={styles.table}>
<thead>
<tr>
<th>产品</th>
<th>路径</th>
<th>微信</th>
<th>抖音</th>
<th>小红书</th>
</tr>
</thead>
<tbody>
{MATRIX.map((row) => (
<tr key={row.product}>
<td>{row.product}</td>
<td>
<code>{row.path}</code>
</td>
<td>{row.weapp}</td>
<td>{row.tt}</td>
<td>{row.xhs}</td>
</tr>
))}
</tbody>
</table>
</div>
<div className={styles.panel}>
<h3>部署前检查清单</h3>
<ul className={styles.listPlain}>
{CHECKLIST.map((c) => (
<li key={c}>{c}</li>
))}
</ul>
</div>
</>
);
}

69
app/admin/ops/page.tsx Normal file
View File

@ -0,0 +1,69 @@
"use client";
import Link from "next/link";
import styles from "../admin.module.css";
const OPS = [
{ emoji: "📊", name: "Umami", href: "https://umami.nomadro.cn", note: "行为分析" },
{ emoji: "💓", name: "Uptime-Kuma", href: "https://uptimekuma.nomadro.cn", note: "可用性" },
{ emoji: "🔔", name: "ntfy", href: "https://ntfy.nomadro.cn", note: "即时告警" },
{ emoji: "🗄️", name: "PocketBase", href: "https://pocketbase.nomadro.cn", note: "主库" },
{ emoji: "📦", name: "S3 / SeaweedFS", href: "https://s3.nomadro.cn", note: "对象存储" },
{ emoji: "🔧", name: "Git", href: "https://git.nomadro.cn", note: "源码" },
{ emoji: "🩺", name: "Health 锚点", href: "/api/health", note: "Kuma 探针" },
{ emoji: "📈", name: "后台统计", href: "/admin/analytics", note: "图表 / ntfy" },
] as const;
export default function AdminOpsPage() {
return (
<>
<h1 className={styles.pageTitle} id="top">
🛠️ 运维
</h1>
<p className={styles.pageLead}>
Caddy / Docker / Umami / Uptime-Kuma / ntfy / SeaweedFS / webhook。备份见{" "}
<code>deploy/backup</code>。
</p>
<nav className={styles.anchorNav} aria-label="运维锚点">
<a href="#stack">栈</a>
<a href="#kuma">监控</a>
<Link href="/admin/analytics#ntfy">ntfy</Link>
</nav>
<div className={styles.grid2} id="stack">
{OPS.map((o) => (
<a
key={o.name}
className={styles.opsCard}
href={o.href}
target={o.href.startsWith("http") ? "_blank" : undefined}
rel="noreferrer"
>
<span aria-hidden>{o.emoji}</span>
<strong>{o.name}</strong>
<em>{o.note}</em>
</a>
))}
</div>
<div className={styles.panel} id="kuma" style={{ marginTop: 16 }}>
<h3>Uptime-Kuma 建议探针</h3>
<ul className={styles.listPlain}>
<li>
<code>https://nomadro.cn/api/health</code> — 门户
</li>
<li>
<code>https://nomadro.cn/api/config</code> — 远程配置(小程序依赖)
</li>
<li>
<code>https://api.nomadro.cn</code> — FastAPI(小程序支付/鉴权)
</li>
<li>
<code>https://umami.nomadro.cn/api/heartbeat</code>
</li>
<li>
<code>https://ntfy.nomadro.cn/v1/health</code>
</li>
</ul>
</div>
</>
);
}

53
app/admin/orders/page.tsx Normal file
View File

@ -0,0 +1,53 @@
"use client";
import { useEffect, useState } from "react";
import styles from "../admin.module.css";
type Channel = { id: string; region: string; note: string };
export default function AdminOrdersPage() {
const [channels, setChannels] = useState<Channel[]>([]);
const [upstream, setUpstream] = useState<{ ok: boolean; detail?: string } | null>(null);
const [apiBase, setApiBase] = useState("");
const [note, setNote] = useState("");
const [error, setError] = useState("");
useEffect(() => {
fetch("/api/admin/orders", { cache: "no-store" })
.then(async (r) => {
const j = await r.json();
if (!r.ok) throw new Error(j.error || r.statusText);
setChannels(j.channels || []);
setUpstream(j.upstream || null);
setApiBase(j.apiBase || "");
setNote(j.note || "");
})
.catch((e) => setError(e instanceof Error ? e.message : String(e)));
}, []);
return (
<>
<h1 className={styles.pageTitle}>💳 订单 / 支付</h1>
<p className={styles.pageLead}>
网关 {apiBase || "…"}{" "}
{upstream ? (
<span className={upstream.ok ? styles.badgeOk : styles.badgeBad}>
{upstream.ok ? "健康" : "异常"} {upstream.detail}
</span>
) : null}
</p>
{error ? <p className={styles.error}>{error}</p> : null}
{note ? <p className={styles.muted}>{note}</p> : null}
<div className={styles.grid2}>
{channels.map((c) => (
<div key={c.id} className={styles.panel}>
<h3>{c.id}</h3>
<span className={styles.badgeMute}>{c.region}</span>
<p className={styles.muted}>{c.note}</p>
</div>
))}
</div>
</>
);
}

View File

@ -1,110 +1,165 @@
"use client";
import Link from "next/link";
import { resolvePayProvider } from "@nomadro/pay";
import { resolvePocketBaseConfig } from "@nomadro/pb";
import { useEffect, useState } from "react";
import styles from "./admin.module.css";
const MODULES = [
{
id: "nav",
emoji: "🧭",
name: "出海导航",
href: "/nav",
admin: null as string | null,
note: "静态导航 · 无独立 admin",
},
{
id: "book",
emoji: "📖",
name: "数字游民小册",
href: "/book",
admin: "/book/admin",
note: "ebook admin · Creem / NOWPayments",
},
{
id: "community",
emoji: "🌏",
name: "旅居社群",
href: "/community",
admin: "/community",
note: "社群运营入口 · FastAPI /api/v1",
},
{
id: "vip",
emoji: "👑",
name: "私域会员",
href: "/vip",
admin: "/vip",
note: "异度星球 · payjsapi · zpay/xpay",
},
] as const;
type Overview = {
sdk?: string;
payHint?: { provider: string; env: string };
pb?: { publicUrl: string };
health?: Record<string, { ok: boolean; status?: number; latencyMs?: number }>;
remoteConfig?: {
version?: number;
updatedAt?: string;
flags?: { payEnabled?: boolean; socialFollow?: boolean; offlineBadge?: boolean };
copy?: { vipPriceFen?: number; vipCta?: string; homeBrand?: string };
modules?: Record<string, { enabled: boolean; title: string }>;
};
verticals?: {
id: string;
name: string;
href: string;
admin?: string;
mini: string[];
}[];
};
export default function AdminPage() {
const pay = resolvePayProvider({ region: "auto", isChinaUser: true });
const pb = resolvePocketBaseConfig();
export default function AdminOverviewPage() {
const [data, setData] = useState<Overview | null>(null);
const [err, setErr] = useState("");
useEffect(() => {
fetch("/api/admin/overview", { cache: "no-store" })
.then(async (r) => {
const j = await r.json();
if (!r.ok) throw new Error(j.error || r.statusText);
setData(j);
})
.catch((e) => setErr(e instanceof Error ? e.message : String(e)));
}, []);
return (
<main className={styles.shell}>
<header className={styles.hero}>
<p className={styles.eyebrow}>Nomadro · Control</p>
<h1 className={styles.title}>管理后台面板</h1>
<p className={styles.sub}>
模块化入口:各垂直自带能力,本页只做编排与跳转,不堆业务逻辑。
</p>
</header>
<>
<h1 className={styles.pageTitle}>📡 统一编排总览</h1>
<p className={styles.pageLead}>
整合四垂直 · PC/H5 主端 + 微信/抖音/小红书 Taro 子项目 · SDK{" "}
{data?.sdk || "…"} · 支付提示{" "}
{data?.payHint ? `${data.payHint.provider}/${data.payHint.env}` : "…"}
</p>
{err ? <p className={styles.error}>{err}</p> : null}
<section className={styles.grid} aria-label="业务模块">
{MODULES.map((m) => (
<article key={m.id} className={styles.card}>
<div className={styles.cardTop}>
<span className={styles.emoji} aria-hidden>
{m.emoji}
{data?.remoteConfig ? (
<div className={styles.panel} style={{ marginBottom: 16 }}>
<h3>远程配置摘要</h3>
<p className={styles.muted}>
v{data.remoteConfig.version} · {data.remoteConfig.updatedAt || "—"} · VIP ¥
{((data.remoteConfig.copy?.vipPriceFen || 0) / 100).toFixed(0)} · CTA「
{data.remoteConfig.copy?.vipCta || "—"}」· pay=
{data.remoteConfig.flags?.payEnabled === false ? "关" : "开"}
</p>
<p style={{ marginTop: 8 }}>
{Object.entries(data.remoteConfig.modules || {}).map(([k, m]) => (
<span
key={k}
className={styles.chip}
style={{
opacity: m.enabled ? 1 : 0.45,
marginRight: 6,
marginBottom: 6,
display: "inline-block",
}}
>
{m.enabled ? "●" : "○"} {m.title || k}
</span>
<h2 className={styles.cardTitle}>{m.name}</h2>
</div>
<p className={styles.cardNote}>{m.note}</p>
<div className={styles.actions}>
<Link href={m.href} className={styles.btn}>
打开产品
</Link>
{m.admin ? (
<Link href={m.admin} className={`${styles.btn} ${styles.ghost}`}>
运营入口
</Link>
) : (
<span className={`${styles.btn} ${styles.ghost} ${styles.disabled}`}>
暂无 admin
</span>
)}
</div>
</article>
))}
</section>
))}
</p>
<p style={{ marginTop: 8 }}>
<Link href="/admin/config" className={styles.chip}>
编辑完整配置 →
</Link>
</p>
</div>
) : null}
<section className={styles.meta} aria-label="共享基础设施">
<h2 className={styles.metaTitle}>共享层 @nomadro/*</h2>
<ul className={styles.metaList}>
<div className={styles.panel} style={{ marginBottom: 16 }}>
<h3>整合架构</h3>
<ul className={styles.listPlain}>
<li>
<strong>支付路由</strong>:当前 CN 默认 →{" "}
<code className={styles.code}>
{pay.provider}/{pay.env}/{pay.channel}
</code>
<strong>PC/H5</strong>:Next 同进程挂载{" "}
<code>/nav /book /community /vip</code>(源码在{" "}
<code>apps/*</code>)
</li>
<li>
<strong>PocketBase</strong>:public{" "}
<code className={styles.code}>{pb.publicUrl}</code>
<strong>小程序</strong>:统一仓 <code>apps/miniprogram</code>
(对照各垂直 wemini/dymini/redmini/weapp)
</li>
<li>
<strong>SDK</strong>:<code className={styles.code}>@nomadro/sdk</code>{" "}
供小程序 / 外部项目调用
<strong>后台</strong>:本面板 +{" "}
<Link href="/admin/config">远程配置</Link> 动态开关页面/文案
</li>
<li>
<strong>支付后端</strong>:
<code className={styles.code}>apps/payjsapi</code>(FastAPI :8007)
<strong>离线</strong>:网络失败 → localCatalog / offlineBook / xhs
包内数据
</li>
</ul>
</section>
</main>
<p style={{ marginTop: 12 }}>
<Link href="/admin/config" className={styles.chip}>
⚙️ 远程配置
</Link>{" "}
<Link href="/admin/miniprogram" className={styles.chip}>
📱 小程序矩阵
</Link>{" "}
<Link href="/admin/verticals" className={styles.chip}>
🧩 垂直业务
</Link>
</p>
</div>
<div className={styles.grid2}>
{Object.entries(data?.health || {}).map(([key, h]) => (
<div key={key} className={styles.panel}>
<h3>{key}</h3>
<span className={h.ok ? styles.badgeOk : styles.badgeBad}>
{h.ok ? "OK" : "DOWN"}
</span>
<p className={styles.muted}>
{h.status ?? "—"} · {h.latencyMs ?? "—"}ms
</p>
</div>
))}
</div>
<h2
className={styles.pageTitle}
style={{ marginTop: "1.5rem", fontSize: "1.15rem" }}
>
四垂直 × PC/H5 × 小程序
</h2>
<div className={styles.grid2}>
{(data?.verticals || []).map((v) => (
<div key={v.id} className={styles.panel}>
<h3>{v.name}</h3>
<p className={styles.muted}>
PC/H5:{v.href} · 小程序:{v.mini.join(" / ")}
</p>
<p style={{ marginTop: 8 }}>
<Link href={v.href} className={styles.chip}>
打开 {v.href}
</Link>{" "}
{v.admin ? (
<Link href={v.admin} className={styles.chip}>
垂直后台
</Link>
) : null}
</p>
</div>
))}
</div>
<p className={styles.muted} style={{ marginTop: "1.25rem" }}>
PocketBase:{data?.pb?.publicUrl || "…"}
</p>
</>
);
}

71
app/admin/users/page.tsx Normal file
View File

@ -0,0 +1,71 @@
"use client";
import { useEffect, useState } from "react";
import styles from "../admin.module.css";
type UserRow = {
id?: string;
email?: string;
username?: string;
name?: string;
created?: string;
};
export default function AdminUsersPage() {
const [items, setItems] = useState<UserRow[]>([]);
const [source, setSource] = useState("");
const [message, setMessage] = useState("");
const [error, setError] = useState("");
useEffect(() => {
fetch("/api/admin/users", { cache: "no-store" })
.then(async (r) => {
const j = await r.json();
if (!r.ok) throw new Error(j.error || r.statusText);
setItems(j.items || []);
setSource(j.source || "");
setMessage(j.message || "");
})
.catch((e) => setError(e instanceof Error ? e.message : String(e)));
}, []);
return (
<>
<h1 className={styles.pageTitle}>👥 用户</h1>
<p className={styles.pageLead}>
来源:{source || "…"}。配置 <code>PB_ADMIN_TOKEN</code> 后拉取 PocketBase users 集合。
</p>
{error ? <p className={styles.error}>{error}</p> : null}
{message ? <p className={styles.muted}>{message}</p> : null}
<div className={styles.panel} style={{ overflowX: "auto" }}>
<table className={styles.table}>
<thead>
<tr>
<th>ID</th>
<th>邮箱 / 用户名</th>
<th>创建时间</th>
</tr>
</thead>
<tbody>
{items.length === 0 ? (
<tr>
<td colSpan={3} className={styles.muted}>
暂无记录
</td>
</tr>
) : (
items.map((u) => (
<tr key={u.id}>
<td>{u.id}</td>
<td>{u.email || u.username || u.name || "—"}</td>
<td>{u.created || "—"}</td>
</tr>
))
)}
</tbody>
</table>
</div>
</>
);
}

View File

@ -0,0 +1,77 @@
"use client";
import Link from "next/link";
import styles from "../admin.module.css";
const VERTICALS = [
{
id: "nav",
emoji: "🧭",
name: "出海导航 navmini",
href: "/nav",
code: "apps/navmini",
notes: ["H5 挂载 /nav", "原生 weapp/tt/xhs 包仍在垂直仓", "统一小程序见 apps/miniprogram"],
},
{
id: "book",
emoji: "📖",
name: "电子书 ebook",
href: "/book",
admin: "/book/admin",
code: "apps/ebook",
notes: ["门户 /book", "垂直后台 /book/admin", "wemini 已接微信虚拟支付"],
},
{
id: "community",
emoji: "🌏",
name: "旅居社群 nomadweb",
href: "/community",
code: "apps/nomadweb",
notes: ["门户 /community", "FastAPI /api/v1", "wemini/dymini Taro 4"],
},
{
id: "vip",
emoji: "👑",
name: "私域会员 nomadvip",
href: "/vip",
code: "apps/nomadvip",
notes: ["门户 /vip", "payjsapi zpay/xorpay/creem", "统一小程序 VIP 页建设中"],
},
] as const;
export default function AdminVerticalsPage() {
return (
<>
<h1 className={styles.pageTitle}>🧩 垂直业务</h1>
<p className={styles.pageLead}>模块边界:业务在 apps/,门户只挂载路由。</p>
<div className={styles.grid2}>
{VERTICALS.map((v) => (
<div key={v.id} className={styles.panel}>
<h3>
{v.emoji} {v.name}
</h3>
<p className={styles.muted}>{v.code}</p>
<ul className={styles.listPlain}>
{v.notes.map((n) => (
<li key={n}>{n}</li>
))}
</ul>
<p style={{ marginTop: 10 }}>
<Link href={v.href} className={styles.chip}>
打开
</Link>
{"admin" in v && v.admin ? (
<>
{" "}
<Link href={v.admin} className={styles.chip}>
后台
</Link>
</>
) : null}
</p>
</div>
))}
</div>
</>
);
}

View File

@ -0,0 +1,117 @@
import { NextResponse } from "next/server";
import { requireAdminSession } from "~/lib/admin-auth";
import { createNomadroClient, PORTAL_ROUTES, SDK_VERSION } from "@nomadro/sdk";
import { resolvePocketBaseConfig } from "@nomadro/pb";
import { resolvePayProvider } from "@nomadro/pay";
import { readRemoteConfigFile } from "~/lib/remote-config-store";
import { ntfyConfigured } from "~/lib/ntfy";
async function probe(url: string, timeoutMs = 4000) {
const started = Date.now();
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
const res = await fetch(url, { signal: ctrl.signal, cache: "no-store" });
clearTimeout(t);
return { ok: res.ok, status: res.status, latencyMs: Date.now() - started, url };
} catch {
return { ok: false, status: 0, latencyMs: Date.now() - started, url };
}
}
export async function GET() {
if (!(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
}
const client = createNomadroClient();
const pb = resolvePocketBaseConfig();
const pay = resolvePayProvider({ region: "auto", isChinaUser: true });
const origin =
process.env.NOMADRO_PUBLIC_ORIGIN?.replace(/\/$/, "") || "https://nomadro.cn";
const [
apiHealth,
pbHealth,
umami,
uptime,
ntfy,
portalHealth,
configProbe,
bookRead,
vipRead,
remoteConfig,
] = await Promise.all([
client.health(),
probe(`${pb.publicUrl}/api/health`),
probe("https://umami.nomadro.cn"),
probe("https://uptimekuma.nomadro.cn"),
probe("https://ntfy.nomadro.cn/v1/health"),
probe(`${origin}/api/health`),
probe(`${origin}/api/config`),
probe(`${origin}/book/read`),
probe(`${origin}/vip/ebook/read`),
readRemoteConfigFile(),
]);
const modules = Object.entries(remoteConfig.modules).map(([id, m]) => ({
id,
title: m.title,
enabled: m.enabled !== false,
}));
const enabledCount = modules.filter((m) => m.enabled).length;
const health = {
payjsapi: apiHealth,
pocketbase: pbHealth,
umami,
uptimekuma: uptime,
ntfy,
portalHealth,
config: configProbe,
bookRead,
vipEbookRead: vipRead,
};
const latencies = Object.entries(health).map(([key, h]) => ({
key,
ok: Boolean((h as { ok?: boolean }).ok),
latencyMs: Number((h as { latencyMs?: number }).latencyMs ?? 0),
status: Number((h as { status?: number }).status ?? 0),
}));
return NextResponse.json({
ok: true,
generatedAt: new Date().toISOString(),
sdk: SDK_VERSION,
routes: PORTAL_ROUTES,
payHint: pay,
ntfy: { configured: ntfyConfigured() },
pb: { publicUrl: pb.publicUrl },
health,
charts: {
latencies,
modules: {
total: modules.length,
enabled: enabledCount,
disabled: modules.length - enabledCount,
items: modules,
},
flags: remoteConfig.flags,
copy: {
vipPriceFen: remoteConfig.copy.vipPriceFen,
homeBrand: remoteConfig.copy.homeBrand,
},
},
anchors: {
health: "/api/health",
config: "/api/config",
bookPreface: "/book/read#00-preface",
vipPreface: "/vip/ebook/read#00-preface",
umami: "https://umami.nomadro.cn",
uptimekuma: "https://uptimekuma.nomadro.cn",
ntfy: "https://ntfy.nomadro.cn",
s3: "https://s3.nomadro.cn",
},
});
}

View File

@ -0,0 +1,41 @@
import { NextResponse } from "next/server";
import { requireAdminSession } from "~/lib/admin-auth";
import {
readRemoteConfigFile,
writeRemoteConfigFile,
} from "~/lib/remote-config-store";
import {
mergeRemoteConfig,
type NomadroRemoteConfig,
} from "~/lib/remote-config";
import { publishNtfy } from "~/lib/ntfy";
export async function GET() {
if (!(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
}
const config = await readRemoteConfigFile();
return NextResponse.json({ ok: true, config });
}
export async function PUT(request: Request) {
if (!(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
}
const body = (await request.json().catch(() => ({}))) as {
config?: Partial<NomadroRemoteConfig>;
};
if (!body.config) {
return NextResponse.json({ ok: false, error: "missing config" }, { status: 400 });
}
const current = await readRemoteConfigFile();
const merged = mergeRemoteConfig({ ...current, ...body.config });
const saved = await writeRemoteConfigFile(merged);
void publishNtfy({
title: "远程配置已更新",
message: `v${saved.version} · ${saved.updatedAt || "now"} · ${saved.copy?.homeBrand || "nomadro"}`,
tags: "gear,nomadro",
priority: "default",
});
return NextResponse.json({ ok: true, config: saved });
}

View File

@ -0,0 +1,36 @@
import { NextResponse } from "next/server";
import {
ADMIN_COOKIE,
isAdminConfigured,
mintAdminSession,
verifyAdminPassword,
} from "~/lib/admin-auth";
export async function POST(request: Request) {
if (!isAdminConfigured()) {
return NextResponse.json(
{
ok: false,
error: "未配置 NOMADRO_ADMIN_PASSWORD,请在 .env.local 设置后再登录",
},
{ status: 503 },
);
}
const body = (await request.json().catch(() => ({}))) as { password?: string };
const password = String(body.password || "");
if (!verifyAdminPassword(password)) {
return NextResponse.json({ ok: false, error: "密码错误" }, { status: 401 });
}
const token = mintAdminSession();
const res = NextResponse.json({ ok: true });
res.cookies.set(ADMIN_COOKIE, token, {
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
path: "/",
maxAge: 60 * 60 * 12,
});
return res;
}

View File

@ -0,0 +1,12 @@
import { NextResponse } from "next/server";
import { ADMIN_COOKIE } from "~/lib/admin-auth";
export async function POST() {
const res = NextResponse.json({ ok: true });
res.cookies.set(ADMIN_COOKIE, "", {
httpOnly: true,
path: "/",
maxAge: 0,
});
return res;
}

View File

@ -0,0 +1,43 @@
import { NextResponse } from "next/server";
import { requireAdminSession } from "~/lib/admin-auth";
import { ntfyConfigured, publishNtfy } from "~/lib/ntfy";
export async function GET() {
if (!(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
}
return NextResponse.json({
ok: true,
configured: ntfyConfigured(),
baseUrl: process.env.NTFY_BASE_URL || "https://ntfy.nomadro.cn",
topic: process.env.NTFY_TOPIC || "nomadro",
hasToken: Boolean((process.env.NTFY_TOKEN || "").trim()),
});
}
/** Instant ntfy push from admin panel. */
export async function POST(request: Request) {
if (!(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
}
const body = (await request.json().catch(() => ({}))) as {
title?: string;
message?: string;
priority?: string | number;
tags?: string;
topic?: string;
};
const title = (body.title || "Nomadro Admin").trim();
const message = (body.message || "手动测试推送").trim();
if (!title || !message) {
return NextResponse.json({ ok: false, error: "missing title/message" }, { status: 400 });
}
const result = await publishNtfy({
title,
message,
priority: body.priority as never,
tags: body.tags || "loudspeaker,nomadro",
topic: body.topic,
});
return NextResponse.json(result, { status: result.ok ? 200 : 502 });
}

View File

@ -0,0 +1,41 @@
import { NextResponse } from "next/server";
import { requireAdminSession } from "~/lib/admin-auth";
import { PAY_DEFAULTS } from "@nomadro/pay";
/** Aggregate recent orders from payjsapi when available; otherwise return matrix stubs. */
export async function GET() {
if (!(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
}
const apiBase = (
process.env.NEXT_PUBLIC_PAYJSAPI_URL ||
process.env.PAYJSAPI_URL ||
PAY_DEFAULTS.payjsapiPublic
).replace(/\/$/, "");
const channels = [
{ id: "zpay", region: "cn", note: "国内 PC/H5" },
{ id: "xorpay", region: "cn", note: "微信内 H5 (xpay)" },
{ id: "creem", region: "overseas", note: "海外卡支付" },
{ id: "nowpayments", region: "overseas", note: "加密货币" },
{ id: "wx_virtual", region: "cn", note: "微信小程序虚拟支付" },
];
let upstream: { ok: boolean; detail?: string } = { ok: false };
try {
const res = await fetch(`${apiBase}/health`, { cache: "no-store" });
upstream = { ok: res.ok, detail: `HTTP ${res.status}` };
} catch (e) {
upstream = { ok: false, detail: e instanceof Error ? e.message : String(e) };
}
return NextResponse.json({
ok: true,
apiBase,
upstream,
channels,
items: [],
note: "订单明细来自各垂直 + payjsapi;此处先给渠道矩阵与网关探活。电子书订单见 /book/admin。",
});
}

View File

@ -0,0 +1,82 @@
import { NextResponse } from "next/server";
import { requireAdminSession } from "~/lib/admin-auth";
import { createNomadroClient, PORTAL_ROUTES, SDK_VERSION } from "@nomadro/sdk";
import { resolvePocketBaseConfig } from "@nomadro/pb";
import { resolvePayProvider } from "@nomadro/pay";
import { readRemoteConfigFile } from "~/lib/remote-config-store";
async function probe(url: string, timeoutMs = 4000) {
const started = Date.now();
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
const res = await fetch(url, { signal: ctrl.signal, cache: "no-store" });
clearTimeout(t);
return { ok: res.ok, status: res.status, latencyMs: Date.now() - started };
} catch {
return { ok: false, status: 0, latencyMs: Date.now() - started };
}
}
export async function GET() {
if (!(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
}
const client = createNomadroClient();
const pb = resolvePocketBaseConfig();
const pay = resolvePayProvider({ region: "auto", isChinaUser: true });
const [apiHealth, pbHealth, umami, uptime, ntfy, portalHealth, remoteConfig] =
await Promise.all([
client.health(),
probe(`${pb.publicUrl}/api/health`),
probe("https://umami.nomadro.cn"),
probe("https://uptimekuma.nomadro.cn"),
probe("https://ntfy.nomadro.cn/v1/health"),
probe(
`${(process.env.NOMADRO_PUBLIC_ORIGIN || "https://nomadro.cn").replace(/\/$/, "")}/api/health`,
),
readRemoteConfigFile(),
]);
const moduleSummary = Object.fromEntries(
Object.entries(remoteConfig.modules).map(([k, v]) => [
k,
{ enabled: v.enabled !== false, title: v.title },
]),
);
return NextResponse.json({
ok: true,
sdk: SDK_VERSION,
routes: PORTAL_ROUTES,
payHint: pay,
pb: { publicUrl: pb.publicUrl, serverUrl: pb.serverUrl },
health: {
payjsapi: apiHealth,
pocketbase: pbHealth,
umami,
uptimekuma: uptime,
ntfy,
portal: portalHealth,
},
remoteConfig: {
version: remoteConfig.version,
updatedAt: remoteConfig.updatedAt,
flags: remoteConfig.flags,
copy: {
vipPriceFen: remoteConfig.copy.vipPriceFen,
vipCta: remoteConfig.copy.vipCta,
homeBrand: remoteConfig.copy.homeBrand,
},
modules: moduleSummary,
},
verticals: [
{ id: "nav", name: "出海导航", href: "/nav", mini: ["weapp", "tt", "xhs"] },
{ id: "book", name: "电子书", href: "/book", admin: "/book/admin", mini: ["weapp", "tt", "xhs"] },
{ id: "community", name: "社群", href: "/community", mini: ["weapp", "tt", "xhs"] },
{ id: "vip", name: "私域会员", href: "/vip", mini: ["weapp"] },
],
});
}

View File

@ -0,0 +1,16 @@
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import {
ADMIN_COOKIE,
isAdminConfigured,
verifyAdminSession,
} from "~/lib/admin-auth";
export async function GET() {
const jar = await cookies();
const ok = verifyAdminSession(jar.get(ADMIN_COOKIE)?.value);
return NextResponse.json({
ok,
configured: isAdminConfigured(),
});
}

View File

@ -0,0 +1,68 @@
import { NextResponse } from "next/server";
import { requireAdminSession } from "~/lib/admin-auth";
import { resolvePocketBaseConfig } from "@nomadro/pb";
/**
* List users from PocketBase when admin token is configured.
* Env: PB_ADMIN_TOKEN or POCKETBASE_ADMIN_TOKEN (superuser JWT / file-token).
*/
export async function GET(request: Request) {
if (!(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const page = Math.max(1, Number(searchParams.get("page") || 1));
const perPage = Math.min(50, Math.max(1, Number(searchParams.get("perPage") || 20)));
const cfg = resolvePocketBaseConfig();
const token = (
process.env.PB_ADMIN_TOKEN ||
process.env.POCKETBASE_ADMIN_TOKEN ||
""
).trim();
if (!token) {
return NextResponse.json({
ok: true,
source: "stub",
message:
"未配置 PB_ADMIN_TOKEN。可在 PocketBase 超管登录后粘贴 token,或继续用垂直后台。",
items: [],
page,
perPage,
totalItems: 0,
});
}
const url = `${cfg.serverUrl}/api/collections/users/records?page=${page}&perPage=${perPage}&sort=-created`;
try {
const res = await fetch(url, {
headers: { Authorization: token },
cache: "no-store",
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
return NextResponse.json(
{
ok: false,
error: data?.message || `PB ${res.status}`,
source: "pocketbase",
},
{ status: 502 },
);
}
return NextResponse.json({
ok: true,
source: "pocketbase",
items: data.items || [],
page: data.page || page,
perPage: data.perPage || perPage,
totalItems: data.totalItems || 0,
});
} catch (e) {
return NextResponse.json(
{ ok: false, error: e instanceof Error ? e.message : String(e) },
{ status: 502 },
);
}
}

12
app/api/config/route.ts Normal file
View File

@ -0,0 +1,12 @@
import { NextResponse } from "next/server";
import { readRemoteConfigFile } from "~/lib/remote-config-store";
/** Public remote config for portal + miniprogram */
export async function GET() {
const config = await readRemoteConfigFile();
return NextResponse.json({
ok: true,
source: "file",
config,
});
}

25
app/api/health/route.ts Normal file
View File

@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
/** Public health anchor for Uptime-Kuma / Caddy / cron. */
export async function GET() {
return NextResponse.json(
{
ok: true,
service: "nomadro-portal",
ts: new Date().toISOString(),
anchors: {
config: "/api/config",
admin: "/admin",
bookRead: "/book/read#00-preface",
vipEbookRead: "/vip/ebook/read#00-preface",
ops: "/admin/ops",
analytics: "/admin/analytics",
},
},
{
headers: {
"Cache-Control": "no-store",
},
},
);
}

View File

@ -106,16 +106,35 @@ async function createPayOrder(
signal: controller.signal,
}).finally(() => clearTimeout(timeout));
const data = await res.json().catch(() => ({}));
const statusOk = data?.status === "ok" || data?.status === "success" || (res.ok && (data?.xorpay_params || data?.params));
console.log("[pay] createPayOrder 响应 http=%s status=%s hasParams=%s", res.status, data?.status, !!(data?.xorpay_params || data?.params));
const redirectUrl = data?.redirect_url || "";
const statusOk =
data?.status === "ok" ||
data?.status === "success" ||
(res.ok && (data?.xorpay_params || data?.params || redirectUrl));
console.log(
"[pay] createPayOrder 响应 http=%s status=%s hasParams=%s redirect=%s",
res.status,
data?.status,
!!(data?.xorpay_params || data?.params),
!!redirectUrl,
);
if (!res.ok || !statusOk) {
const errMsg = data?.detail || data?.msg || data?.error || "支付创建失败";
console.error("[pay] createPayOrder 失败:", errMsg, "body=", JSON.stringify(data).slice(0, 300));
throw new Error(errMsg);
}
// Overseas: redirect_url only
if (redirectUrl && (data.provider === "creem" || data.provider === "nowpayments")) {
return {
params: { order_id: String(data.order_id || "") },
payUrl: redirectUrl,
redirectUrl,
provider: data.provider as string,
};
}
// xorpay: xorpay_params + xorpay_url | zpay: params + pay_url
const params = (data.xorpay_params ?? data.params) || {};
const payUrl = data.xorpay_url || data.pay_url || "";
const payUrl = data.xorpay_url || data.pay_url || redirectUrl || "";
if (!params || typeof params !== "object" || Object.keys(params).length === 0) {
console.error("[pay] createPayOrder 参数为空 data.keys=", Object.keys(data || {}));
throw new Error("payjsapi 未返回支付参数");
@ -123,6 +142,7 @@ async function createPayOrder(
return {
params: params as Record<string, string>,
payUrl,
redirectUrl: redirectUrl || undefined,
provider: data.provider || "zpay",
};
}
@ -162,9 +182,20 @@ export async function POST(request: NextRequest) {
const device = String(body?.device || "pc");
const wechatNick = String(body?.wechat_nick || body?.nick || body?.user_name || "").trim();
const wechatAvatar = String(body?.wechat_avatar || body?.avatar || "").trim();
// 渠道规则:pc/手机浏览器 -> zpay,仅微信内 -> xorpay
const requestedProvider = String(body?.provider || "").trim().toLowerCase();
// 渠道:显式 provider 优先;否则 pc/H5→zpay,微信内→xorpay;海外 creem/nowpayments 由前端 resolvePayProvider 传入
const effectiveProvider =
device === "wechat" ? "xorpay" : "zpay";
requestedProvider === "creem" ||
requestedProvider === "nowpayments" ||
requestedProvider === "zpay" ||
requestedProvider === "xorpay" ||
requestedProvider === "xpay"
? requestedProvider === "xpay"
? "xorpay"
: requestedProvider
: device === "wechat"
? "xorpay"
: "zpay";
const accept = request.headers.get("accept") || "";
const wantHtml = String(body?.html) === "1" || accept.includes("text/html");
const preferJson = String(body?.prefer_json) === "1";
@ -442,8 +473,8 @@ h2{color:#1e293b;margin:0 0 8px;font-size:1.5rem;}
return NextResponse.json({ ok: false, error: errMsg }, { status: 500 });
}
// xorpay:调用 payh5 获取收银台参数
const { params, payUrl, provider } = await createPayOrder(
// xorpay / creem / nowpayments:调用 payh5 获取收银台参数或跳转 URL
const { params, payUrl, provider, redirectUrl } = await createPayOrder(
apiUrl,
user_id,
wechat_userid || undefined,
@ -455,6 +486,26 @@ h2{color:#1e293b;margin:0 0 8px;font-size:1.5rem;}
effectiveProvider
);
if (redirectUrl && (provider === "creem" || provider === "nowpayments")) {
if (!wantHtml) {
const orderId = String(params?.order_id || "").trim();
const res = NextResponse.json({
ok: true,
redirect_url: redirectUrl,
provider,
order_id: orderId,
});
if (orderId) setPayOrderCookie(res, orderId);
setAnonymousUserCookie(res, request, user_id);
return res;
}
const res = NextResponse.redirect(redirectUrl, 302);
const orderId = String(params?.order_id || "").trim();
if (orderId) setPayOrderCookie(res, orderId);
setAnonymousUserCookie(res, request, user_id);
return res;
}
if (!params || Object.keys(params).length === 0) {
if (wantHtml) {
return new NextResponse(buildErrorHtml("支付参数为空"), {

View File

@ -3,6 +3,8 @@ import { Providers } from "@ebook/components/Providers";
import { getSiteConfig } from "@ebook/lib/site-config.server";
import { getServerFeatures } from "@ebook/lib/features.server";
import { getLocale } from "@ebook/lib/i18n/server";
import { BookRoutesProvider } from "@ebook/components/BookRoutes";
import { ModuleBoundary } from "~/components/module-boundary";
import "@ebook/app/globals.css";
export default async function BookLayout({
@ -15,9 +17,11 @@ export default async function BookLayout({
const f = getServerFeatures();
return (
<ModuleBoundary moduleKey="book">
<div className="ebook-root" data-locale={locale}>
<AntdRegistry>
<Providers locale={locale}>
<BookRoutesProvider cover="/book" home="/">
{f.analytics.enabled ? <AnalyticsLazy /> : null}
{f.ads.enabled && f.ads.clientId ? <AdSenseLazy /> : null}
{children}
@ -29,14 +33,16 @@ export default async function BookLayout({
xHandle={site.brand.xHandle}
/>
) : null}
</BookRoutesProvider>
</Providers>
</AntdRegistry>
<script
dangerouslySetInnerHTML={{
__html: `window.__EBOOK_FEATURES__=${JSON.stringify(f).replace(/</g, "\\u003c")};window.__LOCALE__=${JSON.stringify(locale)};`,
__html: `window.__EBOOK_FEATURES__=${JSON.stringify(f).replace(/</g, "\\u003c")};window.__LOCALE__=${JSON.stringify(locale)};(function(){try{var t=localStorage.getItem("nomadro-theme")||localStorage.getItem("ebook-theme");if(t==="light"||t==="sepia"||t==="dark"){document.documentElement.classList.remove("light","dark","sepia");document.documentElement.classList.add(t);}else{document.documentElement.classList.add("dark");}}catch(e){document.documentElement.classList.add("dark");}})();`,
}}
/>
</div>
</ModuleBoundary>
);
}

View File

@ -5,35 +5,58 @@
@custom-variant dark (&:where(.dark, .dark *));
:root {
/* 日间 = 原紫色封面风 */
--book-bg: #120f1d;
--book-bg-secondary: #1b1630;
--book-surface: rgba(255, 255, 255, 0.72);
--book-surface-strong: rgba(255, 255, 255, 0.86);
--book-soft: rgba(255, 255, 255, 0.08);
--book-border: rgba(255, 255, 255, 0.14);
--book-text: #1e1630;
--book-muted: #6d6286;
--book-text: #f6efff;
--book-muted: #b4a9c8;
--book-accent: #f05a9b;
--book-accent-2: #8b5cf6;
--book-accent-soft: rgba(240, 90, 155, 0.14);
--book-glow-1: rgba(167, 139, 250, 0.28);
--book-glow-2: rgba(244, 114, 182, 0.24);
--book-font-size: 16px;
--book-line-height: 1.7;
--book-font-family: 'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', sans-serif;
--book-font-family: var(--font-noto-sc), 'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', sans-serif;
--reader-max-width: 56rem;
--hub-gradient-text: linear-gradient(135deg, #ff6b6b 0%, #ffe66d 50%, #4ecdc4 100%);
}
.light {
--book-bg: #120f1d;
--book-bg-secondary: #1b1630;
--book-surface: rgba(255, 255, 255, 0.72);
--book-surface-strong: rgba(255, 255, 255, 0.86);
--book-soft: rgba(255, 255, 255, 0.08);
--book-border: rgba(255, 255, 255, 0.14);
--book-text: #f6efff;
--book-muted: #b4a9c8;
--book-accent: #f05a9b;
--book-accent-2: #8b5cf6;
--book-accent-soft: rgba(240, 90, 155, 0.14);
--book-glow-1: rgba(167, 139, 250, 0.28);
--book-glow-2: rgba(244, 114, 182, 0.24);
}
.dark {
--book-bg: #0f0b18;
--book-bg-secondary: #171126;
--book-surface: rgba(28, 22, 45, 0.8);
--book-surface-strong: rgba(33, 26, 53, 0.92);
--book-soft: rgba(255, 255, 255, 0.06);
--book-border: rgba(255, 255, 255, 0.1);
--book-text: #f6efff;
--book-muted: #b4a9c8;
--book-accent: #ff7ab6;
--book-accent-2: #9f7aea;
--book-accent-soft: rgba(255, 122, 182, 0.14);
/* 夜间 = 门户 hub 科技风 */
--book-bg: #0a0e17;
--book-bg-secondary: #111827;
--book-surface: rgba(17, 24, 39, 0.72);
--book-surface-strong: rgba(17, 24, 39, 0.92);
--book-soft: rgba(255, 255, 255, 0.05);
--book-border: rgba(255, 255, 255, 0.08);
--book-text: #f1f5f9;
--book-muted: #94a3b8;
--book-accent: #4ecdc4;
--book-accent-2: #ff6b6b;
--book-accent-soft: rgba(78, 205, 196, 0.14);
--book-glow-1: rgba(255, 107, 107, 0.22);
--book-glow-2: rgba(78, 205, 196, 0.2);
}
.sepia {
@ -62,8 +85,9 @@ html {
font-family: var(--book-font-family);
-webkit-font-smoothing: antialiased;
background-image:
radial-gradient(circle at top, rgba(167, 139, 250, 0.2), transparent 26%),
radial-gradient(circle at 80% 20%, rgba(244, 114, 182, 0.22), transparent 22%),
radial-gradient(circle at top, var(--book-glow-1), transparent 26%),
radial-gradient(circle at 80% 20%, var(--book-glow-2), transparent 22%),
radial-gradient(circle at 40% 100%, rgba(255, 230, 109, 0.08), transparent 28%),
linear-gradient(180deg, var(--book-bg), var(--book-bg-secondary));
isolation: isolate;
}
@ -100,12 +124,23 @@ html {
inset 0 1px 0 rgba(255, 255, 255, 0.14);
}
.dark .book-cover {
background:
radial-gradient(circle at top left, rgba(78, 205, 196, 0.22), transparent 30%),
radial-gradient(circle at bottom right, rgba(255, 107, 107, 0.2), transparent 34%),
linear-gradient(155deg, #0a0e17 0%, #111827 40%, #134e4a 72%, #7f1d1d 100%);
box-shadow:
0 30px 80px rgba(0, 0, 0, 0.45),
0 0 40px rgba(78, 205, 196, 0.15),
inset 0 1px 0 rgba(255, 255, 255, 0.14);
}
.glass-panel {
background: var(--book-surface);
border: 1px solid var(--book-border);
box-shadow:
0 18px 45px rgba(10, 6, 20, 0.18),
inset 0 1px 0 rgba(255, 255, 255, 0.28);
0 18px 45px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.12);
backdrop-filter: blur(18px);
}
@ -759,6 +794,41 @@ html {
background: #f97316;
}
.dark .viral-cover .orb-1 {
background: #ff6b6b;
filter: blur(72px);
opacity: 0.55;
}
.dark .viral-cover .orb-2 {
background: #4ecdc4;
filter: blur(72px);
opacity: 0.5;
}
.dark .viral-cover .orb-3 {
background: #ffe66d;
filter: blur(64px);
opacity: 0.4;
}
.dark .viral-cover-gradient {
background-image: linear-gradient(
to bottom right,
#0a0e17 0%,
#111827 38%,
#134e4a 72%,
#7f1d1d 100%
) !important;
opacity: 0.96;
}
.dark .viral-grid {
background-image:
linear-gradient(rgba(78, 205, 196, 0.08) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 107, 107, 0.06) 1px, transparent 1px);
}
.viral-tag {
display: inline-flex;
padding: 0.35rem 0.75rem;
@ -799,6 +869,66 @@ html {
color: transparent;
}
.dark .viral-title {
background: var(--hub-gradient-text);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
background-size: 200% auto;
animation: book-hub-gradient 4s ease-in-out infinite;
}
@keyframes book-hub-gradient {
0%, 100% { background-position: 0% center; }
50% { background-position: 100% center; }
}
.cover-top-actions {
position: fixed;
top: 18px;
right: 18px;
z-index: 80;
display: inline-flex;
align-items: center;
gap: 8px;
}
.cover-action-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
height: 40px;
min-width: 40px;
padding: 0 14px;
border-radius: 999px;
border: 1px solid rgba(255, 255, 255, 0.45);
background: rgba(10, 8, 22, 0.72);
color: #fff;
font-size: 14px;
font-weight: 700;
letter-spacing: 0.04em;
cursor: pointer;
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(12px);
transition: background 0.2s ease, border-color 0.2s ease, transform 0.15s ease;
}
.cover-action-btn:hover {
background: rgba(18, 12, 36, 0.78);
border-color: rgba(255, 255, 255, 0.55);
}
.dark .cover-action-btn {
background: rgba(10, 14, 23, 0.78);
border-color: rgba(78, 205, 196, 0.35);
}
.dark .cover-action-btn:hover {
background: rgba(17, 24, 39, 0.9);
border-color: rgba(78, 205, 196, 0.55);
}
.viral-subtitle {
margin: 0.75rem 0 0;
font-size: clamp(1rem, 3vw, 1.25rem);
@ -876,7 +1006,7 @@ html {
.viral-book-card-glow {
position: absolute;
inset: -20%;
background: radial-gradient(circle, rgba(236, 72, 153, 0.35), transparent 60%);
background: radial-gradient(circle, rgba(78, 205, 196, 0.32), transparent 60%);
animation: glow-pulse 4s ease-in-out infinite;
}
@ -2120,6 +2250,15 @@ mark.text-highlight,
color: #4c1d95;
}
.dark .viral-free-badge {
background: linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(204, 251, 241, 0.95));
color: #0f766e;
}
.dark .viral-book-card-glow {
background: radial-gradient(circle, rgba(78, 205, 196, 0.32), transparent 60%);
}
.cover-sticky-cta {
position: fixed;
left: 0;
@ -2136,6 +2275,11 @@ mark.text-highlight,
backdrop-filter: blur(12px);
}
.dark .cover-sticky-cta {
background: rgba(10, 14, 23, 0.92);
border-top-color: rgba(255, 255, 255, 0.08);
}
@media (min-width: 768px) {
.cover-sticky-cta {
display: none;
@ -2154,6 +2298,10 @@ mark.text-highlight,
text-decoration: none;
}
.dark .cover-sticky-read {
color: #0f766e;
}
.cover-sticky-meta {
font-size: 0.72rem;
color: rgba(255, 255, 255, 0.55);

View File

@ -33,7 +33,7 @@ export default async function BookLayout({
<div className="ebook-section" data-ebook-root>
<script
dangerouslySetInnerHTML={{
__html: `window.__EBOOK_FEATURES__=${JSON.stringify(f).replace(/</g, "\\u003c")};window.__LOCALE__=${JSON.stringify(locale)};(function(){try{var t=localStorage.getItem("theme");if(t==="light"||t==="sepia"||t==="dark"){document.documentElement.classList.remove("light","dark","sepia");document.documentElement.classList.add(t);}else{document.documentElement.classList.add("dark");}}catch(e){document.documentElement.classList.add("dark");}document.documentElement.style.scrollPaddingTop="0";})();`,
__html: `window.__EBOOK_FEATURES__=${JSON.stringify(f).replace(/</g, "\\u003c")};window.__LOCALE__=${JSON.stringify(locale)};(function(){try{var t=localStorage.getItem("nomadro-theme")||localStorage.getItem("theme");if(t==="light"||t==="sepia"||t==="dark"){document.documentElement.classList.remove("light","dark","sepia");document.documentElement.classList.add(t);}else{document.documentElement.classList.add("dark");}}catch(e){document.documentElement.classList.add("dark");}document.documentElement.style.scrollPaddingTop="0";})();`,
}}
/>
<AntdRegistry>

View File

@ -2,6 +2,7 @@ import { AuthProvider } from "@community/lib/auth";
import { ToastProvider } from "@community/lib/toast";
import { I18nProvider } from "@community/lib/i18n";
import PwaRegister from "@community/components/PwaRegister";
import { ModuleBoundary } from "~/components/module-boundary";
import "@community/app/globals.css";
export default function CommunityLayout({
@ -10,15 +11,17 @@ export default function CommunityLayout({
children: React.ReactNode;
}) {
return (
<div className="community-root">
<I18nProvider>
<AuthProvider>
<ToastProvider>
{children}
<PwaRegister />
</ToastProvider>
</AuthProvider>
</I18nProvider>
</div>
<ModuleBoundary moduleKey="community">
<div className="community-root">
<I18nProvider>
<AuthProvider>
<ToastProvider>
{children}
<PwaRegister />
</ToastProvider>
</AuthProvider>
</I18nProvider>
</div>
</ModuleBoundary>
);
}

View File

@ -1,12 +1,26 @@
@import "tailwindcss";
:root {
:root,
.dark {
--background: #0a0e17;
--foreground: #f1f5f9;
--hub-accent-1: #ff6b6b;
--hub-accent-2: #ffe66d;
--hub-accent-3: #4ecdc4;
--hub-gradient-text: linear-gradient(135deg, #ff6b6b 0%, #ffe66d 50%, #4ecdc4 100%);
--safe-top: env(safe-area-inset-top, 0px);
--safe-bottom: env(safe-area-inset-bottom, 0px);
}
.light {
--background: #f8fafc;
--foreground: #0f172a;
--hub-accent-1: #e11d48;
--hub-accent-2: #d97706;
--hub-accent-3: #0d9488;
--hub-gradient-text: linear-gradient(135deg, #e11d48 0%, #d97706 50%, #0d9488 100%);
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
@ -27,11 +41,40 @@ body {
font-family: var(--font-sans);
-webkit-tap-highlight-color: transparent;
-webkit-font-smoothing: antialiased;
transition: background-color 0.25s ease, color 0.25s ease;
}
.text-gradient {
background: linear-gradient(135deg, #7c3aed 0%, #0891b2 100%);
background: var(--hub-gradient-text);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
/* Portal chrome theme toggle */
.nd-theme-toggle {
display: inline-flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
border-radius: 12px;
border: 1px solid rgba(78, 205, 196, 0.28);
background: rgba(78, 205, 196, 0.1);
color: #4ecdc4;
font-size: 1.05rem;
cursor: pointer;
transition: background 0.2s ease, border-color 0.2s ease, transform 0.15s ease;
}
.nd-theme-toggle:hover {
background: rgba(78, 205, 196, 0.18);
border-color: rgba(78, 205, 196, 0.5);
transform: translateY(-1px);
}
.light .nd-theme-toggle {
border-color: rgba(13, 148, 136, 0.3);
background: rgba(13, 148, 136, 0.1);
color: #0d9488;
}

View File

@ -4,6 +4,7 @@
--hub-bg-card: rgba(17, 24, 39, 0.7);
--hub-bg-glass: rgba(255, 255, 255, 0.05);
--hub-text: #f1f5f9;
--hub-muted: #94a3b8;
--hub-accent-1: #ff6b6b;
--hub-accent-2: #ffe66d;
--hub-accent-3: #4ecdc4;
@ -24,6 +25,23 @@
color: var(--hub-text);
line-height: 1.6;
overflow-x: hidden;
transition: background var(--hub-transition), color var(--hub-transition);
}
html.light .hub-root,
[data-theme="light"] .hub-root {
--hub-bg: #f8fafc;
--hub-bg-card: rgba(255, 255, 255, 0.85);
--hub-bg-glass: rgba(15, 23, 42, 0.04);
--hub-text: #0f172a;
--hub-muted: #64748b;
--hub-accent-1: #e11d48;
--hub-accent-2: #d97706;
--hub-accent-3: #0d9488;
--hub-gradient-text: linear-gradient(135deg, #e11d48 0%, #d97706 50%, #0d9488 100%);
--hub-shadow-glow: 0 0 40px rgba(13, 148, 136, 0.12);
--hub-shadow-card: 0 8px 32px rgba(15, 23, 42, 0.08);
--hub-border: 1px solid rgba(15, 23, 42, 0.08);
}
.hub-root a {
@ -45,7 +63,7 @@
z-index: 9999;
display: grid;
place-items: center;
background: #0a0e17;
background: var(--hub-bg, #0a0e17);
transition: opacity 0.6s ease, visibility 0.6s;
}
@ -102,6 +120,11 @@
border-bottom: var(--hub-border);
}
html.light .hub-navbar.scrolled,
[data-theme="light"] .hub-navbar.scrolled {
background: rgba(248, 250, 252, 0.88);
}
.hub-nav-container {
width: min(1200px, calc(100% - clamp(2rem, 6vw, 5rem)));
margin: 0 auto;
@ -109,6 +132,14 @@
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.hub-nav-actions {
display: flex;
align-items: center;
gap: 8px;
margin-left: auto;
}
.hub-logo {
@ -126,6 +157,48 @@
animation: hub-spin 20s linear infinite;
}
/* Local-dev only shortcuts */
.hub-dev-nav {
display: flex;
align-items: center;
gap: 8px;
}
.hub-dev-link {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 36px;
padding: 0 14px;
border-radius: 10px;
border: 1px solid rgba(78, 205, 196, 0.28);
background: rgba(78, 205, 196, 0.1);
color: #4ecdc4;
font-family: var(--hub-font-display);
font-size: 0.82rem;
font-weight: 700;
letter-spacing: 0.02em;
transition: background var(--hub-transition), border-color var(--hub-transition),
transform var(--hub-transition);
}
.hub-dev-link:hover {
background: rgba(78, 205, 196, 0.18);
border-color: rgba(78, 205, 196, 0.5);
transform: translateY(-1px);
}
.hub-dev-link:nth-child(2) {
border-color: rgba(255, 107, 107, 0.28);
background: rgba(255, 107, 107, 0.1);
color: #ff8a8a;
}
.hub-dev-link:nth-child(2):hover {
background: rgba(255, 107, 107, 0.18);
border-color: rgba(255, 107, 107, 0.5);
}
/* Hero */
.hub-hero {
position: relative;
@ -218,6 +291,16 @@
letter-spacing: -0.02em;
}
.hub-hero-lead {
grid-area: title;
align-self: start;
margin-top: 0.75rem;
max-width: 28rem;
font-size: clamp(0.9rem, 1.6vw, 1.05rem);
color: var(--hub-muted, #94a3b8);
line-height: 1.45;
}
.hub-hero-visual {
grid-area: visual;
position: relative;

View File

@ -4,6 +4,11 @@ import "./hub.css";
import { type Metadata, type Viewport } from "next";
import { Noto_Sans_SC, Outfit } from "next/font/google";
import { LocaleProvider } from "~/components/locale-provider";
import {
ThemeProvider,
themeInitScript,
} from "~/components/theme-provider";
import { SocialFollowPrompt } from "~/components/social-follow";
import { UmamiAnalytics } from "~/components/umami-analytics";
export const viewport: Viewport = {
@ -11,11 +16,15 @@ export const viewport: Viewport = {
initialScale: 1,
maximumScale: 5,
viewportFit: "cover",
themeColor: "#0a0e17",
themeColor: [
{ media: "(prefers-color-scheme: dark)", color: "#0a0e17" },
{ media: "(prefers-color-scheme: light)", color: "#f8fafc" },
{ color: "#0a0e17" },
],
};
export const metadata: Metadata = {
metadataBase: new URL("https://nomadro.com"),
metadataBase: new URL("https://nomadro.cn"),
title: "nomadro",
description: "数字游民入口 · 出海导航 · 数字游民小册 · 旅居社群",
keywords: [
@ -30,7 +39,7 @@ export const metadata: Metadata = {
title: "nomadro",
description: "随处工作,自由生活。出海导航 · 数字游民小册 · 旅居社群",
type: "website",
url: "https://nomadro.com",
url: "https://nomadro.cn",
},
icons: [{ rel: "icon", url: "/favicon.ico" }],
};
@ -55,12 +64,20 @@ export default function RootLayout({
return (
<html
lang="zh-CN"
className={`${outfit.variable} ${notoSansSC.variable}`}
className={`${outfit.variable} ${notoSansSC.variable} dark`}
suppressHydrationWarning
>
<head>
<script dangerouslySetInnerHTML={{ __html: themeInitScript }} />
</head>
<body className="antialiased">
<UmamiAnalytics />
<LocaleProvider>{children}</LocaleProvider>
<ThemeProvider>
<LocaleProvider>
{children}
<SocialFollowPrompt />
</LocaleProvider>
</ThemeProvider>
</body>
</html>
);

View File

@ -1,7 +1,12 @@
"use client";
import NavApp from "@navmini/App";
import { ModuleGate } from "~/components/module-gate";
export default function NavPage() {
return <NavApp />;
return (
<ModuleGate moduleKey="nav">
<NavApp />
</ModuleGate>
);
}

View File

@ -5,6 +5,7 @@ import Link from "next/link";
import { SITE_CONFIG } from "../config/course";
import { isPaid } from "../lib/payment";
import { InstantQaVipModal } from "@vip/app/components/InstantQaVipModal";
import { vipPath } from "@vip/app/lib/vipPath";
const CHAT_URL = "https://chatwoot.hackrobot.cn/livechat?user_id=hackrobot";
@ -26,7 +27,7 @@ export function Footer() {
<Link href="/" className="text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
返回首页
</Link>
<Link href="/vip/cloudphone" className="text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
<Link href={vipPath("/vip/cloudphone")} className="text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
课程首页
</Link>
{paid ? (

View File

@ -7,6 +7,7 @@ import { isPaid } from "../lib/payment";
import { triggerPay } from "@vip/app/lib/triggerPay";
import { ThemeToggle } from "@vip/app/components/ThemeToggle";
import { InstantQaVipModal } from "@vip/app/components/InstantQaVipModal";
import { vipPath } from "@vip/app/lib/vipPath";
export function Header() {
const [paid, setPaid] = useState(false);
@ -22,7 +23,7 @@ export function Header() {
<>
<header className="animate__animated animate__fadeInDown fixed left-0 right-0 top-0 z-50 border-b border-[var(--border)] bg-[var(--background)]/90 backdrop-blur-xl" style={{ animationFillMode: "both" }}>
<div className="mx-auto flex h-12 max-w-6xl items-center justify-between gap-2 px-3 sm:h-14 sm:gap-4 sm:px-4 md:h-16 md:px-6">
<Link href="/vip/cloudphone" className="min-w-0 truncate text-sm font-medium sm:text-base md:text-xl">
<Link href={vipPath("/vip/cloudphone")} className="min-w-0 truncate text-sm font-medium sm:text-base md:text-xl">
{SITE_CONFIG.brand}
</Link>
<div className="flex shrink-0 items-center gap-1.5 sm:gap-3">
@ -60,7 +61,7 @@ export function Header() {
</Link>
{paid ? (
<Link
href="/vip/cloudphone/course/0/0"
href={vipPath("/vip/cloudphone/course/0/0")}
className="hidden rounded-full bg-[var(--accent)] px-3 py-1.5 text-xs font-medium text-[var(--accent-foreground)] transition hover:opacity-90 sm:inline-flex sm:px-4 sm:py-2 sm:text-sm"
>
进入课程 →
@ -76,7 +77,7 @@ export function Header() {
)}
{paid ? (
<Link
href="/vip/cloudphone/course/0/0"
href={vipPath("/vip/cloudphone/course/0/0")}
className="inline-flex rounded-full bg-[var(--accent)] p-2 text-[var(--accent-foreground)] sm:hidden"
aria-label="进入课程"
>

View File

@ -5,6 +5,7 @@ import Link from "next/link";
import { CTA_CONFIG } from "../../config/course";
import { isPaid } from "../../lib/payment";
import { triggerPay } from "@vip/app/lib/triggerPay";
import { vipPath } from "@vip/app/lib/vipPath";
export function CTASection() {
const [paid, setPaid] = useState(false);
@ -37,7 +38,7 @@ export function CTASection() {
</div>
{paid ? (
<Link
href="/vip/cloudphone/course/0/0"
href={vipPath("/vip/cloudphone/course/0/0")}
className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] shadow-lg shadow-[var(--accent)]/25 transition-all duration-300 hover:scale-105 hover:opacity-95 hover:shadow-xl hover:shadow-[var(--accent)]/30 sm:px-10"
>
开始学习 →

View File

@ -6,6 +6,7 @@ import { Section } from "../Section";
import { CURRICULUM_CONFIG } from "../../config/course";
import { canWatchLesson } from "../../lib/payment";
import { isBookmarked, toggleBookmark, getBookmarks, getCompletedLessons } from "../../lib/learning";
import { vipPath } from "@vip/app/lib/vipPath";
export function CurriculumSection() {
const [expanded, setExpanded] = useState<Record<number, boolean>>(() =>
@ -86,7 +87,7 @@ export function CurriculumSection() {
return (
<li key={key}>
<Link
href={`/vip/cloudphone/course/${l.moduleIndex}/${l.lessonIndex}`}
href={vipPath(`/vip/cloudphone/course/${l.moduleIndex}/${l.lessonIndex}`)}
className="flex flex-col gap-1 px-4 py-3 transition hover:bg-[var(--muted)] sm:flex-row sm:items-center sm:justify-between sm:px-5 sm:py-3"
>
<span className="flex items-center gap-2 truncate sm:gap-3">

View File

@ -7,6 +7,7 @@ import { isPaid } from "../../lib/payment";
import { triggerPay } from "@vip/app/lib/triggerPay";
import { getLastWatched, getProgress } from "../../lib/learning";
import { ParticleBackground } from "../ParticleBackground";
import { vipPath } from "@vip/app/lib/vipPath";
const TOTAL_LESSONS = CURRICULUM_CONFIG.modules.reduce((s, m) => s + m.lessons.length, 0);
@ -70,14 +71,14 @@ export function Hero() {
>
{paid && last ? (
<Link
href={`/vip/cloudphone/course/${last.moduleIndex}/${last.lessonIndex}`}
href={vipPath(`/vip/cloudphone/course/${last.moduleIndex}/${last.lessonIndex}`)}
className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-10"
>
继续学习 →
</Link>
) : paid ? (
<Link
href="/vip/cloudphone/course/0/0"
href={vipPath("/vip/cloudphone/course/0/0")}
className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-10"
>
进入课程 →

View File

@ -14,6 +14,7 @@ import { setLastWatched, markCompleted, getCompletedLessons } from "../../../lib
import { CURRICULUM_CONFIG, DOWNLOAD_CONFIG } from "../../../config/course";
import { CLOUDPHONE_COURSE_CONFIG } from "@vip/config/content.config";
import { getPrevNextLesson } from "@vip/lib/content/course-utils";
import { vipPath } from "@vip/app/lib/vipPath";
const TOTAL_LESSONS = CURRICULUM_CONFIG.modules.reduce((s, m) => s + m.lessons.length, 0);
@ -51,7 +52,7 @@ export default function LessonPage() {
<h1 className="mb-4 text-2xl font-bold">章节不存在</h1>
<p className="mb-6 text-[var(--muted-foreground)]">请检查链接或返回课程首页</p>
<Link
href="/vip/cloudphone"
href={vipPath("/vip/cloudphone")}
className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-6 py-3 font-medium text-[var(--accent-foreground)] transition hover:opacity-90"
>
← 返回首页

View File

@ -4,6 +4,7 @@ import { Suspense, useEffect } from "react";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { Header } from "../components";
import { vipPath } from "@vip/app/lib/vipPath";
function PayContent() {
const searchParams = useSearchParams();
@ -41,9 +42,9 @@ function PayContent() {
</Link>
</div>
<p className="mb-4 text-xs text-[var(--muted-foreground)]">
测试:<Link href="/vip/cloudphone/pay?test=ok" className="text-[var(--accent)] underline">点击模拟支付成功</Link>
测试:<Link href={vipPath("/vip/cloudphone/pay?test=ok")} className="text-[var(--accent)] underline">点击模拟支付成功</Link>
</p>
<Link href="/vip/cloudphone" className="text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
<Link href={vipPath("/vip/cloudphone")} className="text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
返回课程首页
</Link>
</main>

View File

@ -1,26 +1,31 @@
/* 电子书阅读器 - 支持深色主题,可复用到 digital/nomadvip/nomadlms */
/* VIP 电子书阅读器 — 深色纸面高对比,不被 github-markdown 白底浅字坑 */
.readerRoot {
min-height: 100vh;
background: #0a0e17;
color: #e8eef7;
}
.readingProgress {
position: fixed;
top: 0;
left: 0;
height: 4px;
background: linear-gradient(90deg, var(--accent) 0%, #00f2fe 100%);
height: 3px;
background: linear-gradient(90deg, #ff6b6b, #ffe66d, #4ecdc4);
z-index: 201;
transition: width 0.15s linear;
border-radius: 0 4px 4px 0;
}
.readingTime {
font-size: 12px;
font-weight: 400;
color: var(--muted-foreground);
color: #94a3b8;
margin-left: 4px;
}
.headerSpacer {
width: 100%;
height: 88px;
height: 56px;
}
.header {
@ -29,28 +34,31 @@
left: 0;
right: 0;
z-index: 100;
height: 88px;
background: var(--card);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border);
height: 56px;
background: rgba(10, 14, 23, 0.92);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.headerLeft {
width: 100px;
width: 48px;
height: 44px;
margin-left: 4px;
display: flex;
align-items: center;
justify-content: center;
color: var(--foreground);
color: #f1f5f9;
cursor: pointer;
border-radius: 10px;
}
.headerLeft:hover {
color: var(--accent);
color: #ffe66d;
background: rgba(255, 255, 255, 0.06);
}
.headerMiddle {
@ -58,52 +66,67 @@
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
font-weight: 600;
color: var(--foreground);
letter-spacing: 2px;
font-size: 15px;
font-weight: 700;
color: #f8fafc;
letter-spacing: 0.04em;
}
.headerRight {
width: 40px;
height: 40px;
padding: 0;
display: flex;
display: inline-flex;
align-items: center;
justify-content: center;
color: var(--accent);
gap: 6px;
min-height: 40px;
min-width: 40px;
padding: 0 12px;
margin-right: 10px;
color: #0a0e17;
cursor: pointer;
margin-right: 8px;
background: var(--accent-muted, rgba(245, 158, 11, 0.15));
border-radius: 50%;
transition: all 0.2s ease;
background: linear-gradient(135deg, #ffe66d, #ff6b6b);
border: none;
border-radius: 999px;
font-weight: 700;
font-size: 13px;
transition: transform 0.15s ease, opacity 0.15s ease;
}
.headerRight:hover {
background: var(--accent-muted, rgba(245, 158, 11, 0.25));
opacity: 0.92;
transform: translateY(-1px);
}
.headerRightActive {
background: var(--accent) !important;
color: var(--accent-foreground) !important;
background: #4ecdc4 !important;
color: #0a0e17 !important;
}
.headerRightText {
display: none;
margin-left: 4px;
display: inline;
}
.chunkEnter {
animation: chunkAppear 0.5s ease-out both;
animation: chunkAppear 0.45s ease-out both;
}
@keyframes chunkAppear {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
from {
opacity: 0;
transform: translateY(12px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.chunkPlaceholder {
background: var(--muted);
background: linear-gradient(
90deg,
rgba(255, 255, 255, 0.04),
rgba(255, 255, 255, 0.1),
rgba(255, 255, 255, 0.04)
);
background-size: 200% 100%;
animation: shimmer 1.8s ease infinite;
border-radius: 12px;
@ -111,52 +134,72 @@
}
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
.backToTop {
position: fixed;
bottom: 120px;
right: 30px;
width: 56px;
height: 56px;
background: var(--card);
backdrop-filter: blur(10px);
border: 1px solid var(--border);
bottom: calc(24px + env(safe-area-inset-bottom));
right: 16px;
width: 48px;
height: 48px;
background: rgba(17, 24, 39, 0.95);
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
cursor: pointer;
z-index: 50;
color: var(--accent);
transition: transform 0.2s, box-shadow 0.2s;
}
.backToTop:hover {
transform: translateY(-2px);
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
color: #ffe66d;
}
.book {
padding: 30px;
max-width: 100%;
padding: 20px 16px 96px;
max-width: 820px;
margin: 0 auto;
min-height: calc(100vh - 56px);
background: transparent;
}
.markdownBody {
/* 强制可读:深色底 + 浅色字,覆盖 github-markdown 白底 */
.markdownBody,
.markdownBody.markdown-body {
font-size: 16px !important;
line-height: 1.85 !important;
color: var(--foreground) !important;
color: #e8eef7 !important;
background-color: transparent !important;
word-wrap: break-word;
box-sizing: border-box;
}
.markdownBody h1,
.markdownBody h2,
.markdownBody h3,
.markdownBody h4,
.markdownBody h5,
.markdownBody h6,
.markdownBody p,
.markdownBody li,
.markdownBody td,
.markdownBody th,
.markdownBody strong,
.markdownBody em,
.markdownBody span {
color: #e8eef7 !important;
}
.markdownBody h1 {
font-size: 24px !important;
font-size: 1.65rem !important;
font-weight: 800;
color: var(--foreground);
margin: 28px 0 10px;
margin: 1.75rem 0 0.75rem;
letter-spacing: 0.02em;
}
.markdownBody h1::after {
@ -164,65 +207,116 @@
display: block;
width: 40px;
height: 3px;
background: linear-gradient(90deg, var(--accent), #00f2fe);
background: linear-gradient(90deg, #ff6b6b, #ffe66d, #4ecdc4);
border-radius: 3px;
margin-top: 8px;
margin-top: 10px;
}
.markdownBody h2 {
font-size: 21px !important;
font-size: 1.3rem !important;
font-weight: 700;
color: var(--foreground);
margin: 22px 0 9px;
padding-bottom: 12px;
border-bottom: 1px solid var(--border);
margin: 1.5rem 0 0.65rem;
padding-bottom: 10px;
border-bottom: 1px solid rgba(255, 255, 255, 0.12);
}
.markdownBody h3 { font-size: 18px !important; font-weight: 600; margin: 18px 0 7px; }
.markdownBody h4, .markdownBody h5, .markdownBody h6 { font-size: 16px !important; margin: 14px 0 6px; }
.markdownBody p { font-size: 16px !important; margin-bottom: 10px; line-height: 1.9; }
.markdownBody h3 {
font-size: 1.1rem !important;
font-weight: 600;
margin: 1.25rem 0 0.5rem;
}
.markdownBody p {
margin-bottom: 0.85rem;
line-height: 1.9;
}
.markdownBody blockquote {
margin: 28px 0;
padding: 20px 24px 20px 30px;
background: var(--muted);
margin: 1.25rem 0;
padding: 14px 16px 14px 18px;
background: rgba(255, 230, 109, 0.08);
border-radius: 0 12px 12px 0;
color: var(--muted-foreground);
border-left: 4px solid var(--accent);
color: #cbd5e1 !important;
border-left: 4px solid #ffe66d;
}
.markdownBody blockquote p {
color: #cbd5e1 !important;
margin-bottom: 0.35rem;
}
.markdownBody pre {
margin: 28px 0;
padding: 28px 24px;
background: var(--background);
border: 1px solid var(--border);
margin: 1.25rem 0;
padding: 16px;
background: #0c1220 !important;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
overflow-x: auto;
}
.markdownBody pre code {
font-family: var(--font-geist-mono), monospace;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px !important;
color: var(--foreground);
color: #e2e8f0 !important;
background: none !important;
}
.markdownBody code {
font-family: var(--font-geist-mono), monospace;
font-size: 14px !important;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.9em !important;
padding: 2px 6px;
background: var(--muted);
color: var(--accent);
background: rgba(255, 230, 109, 0.12) !important;
color: #ffe66d !important;
border-radius: 6px;
}
.markdownBody a { color: var(--accent); }
.markdownBody a:hover { text-decoration: underline; }
.markdownBody img { display: block; margin: 28px auto; max-width: 100%; border-radius: 8px; }
.markdownBody ul, .markdownBody ol { margin: 16px 0; padding-left: 40px; }
.markdownBody table { width: 100%; margin: 28px 0; border-collapse: collapse; border-radius: 8px; }
.markdownBody th { background: var(--muted); font-weight: 600; padding: 16px 20px; border: 1px solid var(--border); }
.markdownBody td { padding: 14px 20px; border: 1px solid var(--border); }
.markdownBody a {
color: #4ecdc4 !important;
}
.markdownBody a:hover {
text-decoration: underline;
}
.markdownBody img {
display: block;
margin: 1.25rem auto;
max-width: 100%;
border-radius: 10px;
}
.markdownBody ul,
.markdownBody ol {
margin: 0.85rem 0;
padding-left: 1.5rem;
color: #e8eef7 !important;
}
.markdownBody table {
width: 100%;
margin: 1.25rem 0;
border-collapse: collapse;
}
.markdownBody th {
background: rgba(255, 255, 255, 0.06);
font-weight: 600;
padding: 12px 14px;
border: 1px solid rgba(255, 255, 255, 0.1);
color: #f8fafc !important;
}
.markdownBody td {
padding: 10px 14px;
border: 1px solid rgba(255, 255, 255, 0.1);
color: #e2e8f0 !important;
}
.markdownBody hr {
border: none;
border-top: 1px solid rgba(255, 255, 255, 0.12);
margin: 1.5rem 0;
}
.drawer {
position: fixed;
@ -231,22 +325,24 @@
bottom: 0;
width: 280px;
max-width: 85vw;
background: var(--card);
border-left: 1px solid var(--border);
box-shadow: -4px 0 24px rgba(0, 0, 0, 0.15);
background: #111827;
border-left: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: -8px 0 32px rgba(0, 0, 0, 0.45);
z-index: 150;
padding-top: 88px;
padding-top: 56px;
overflow-y: auto;
transform: translateX(100%);
transition: transform 0.3s ease;
}
.drawerOpen { transform: translateX(0); }
.drawerOpen {
transform: translateX(0);
}
.drawerMask {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.4);
background: rgba(0, 0, 0, 0.55);
z-index: 140;
opacity: 0;
pointer-events: none;
@ -259,36 +355,39 @@
}
.drawerItem {
padding: 16px 20px;
border-bottom: 1px solid var(--border);
color: var(--foreground);
padding: 14px 18px;
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
color: #e2e8f0;
cursor: pointer;
font-size: 15px;
transition: background 0.15s;
font-size: 14px;
line-height: 1.4;
min-height: 44px;
}
.drawerItem:hover {
background: var(--muted);
background: rgba(255, 255, 255, 0.06);
color: #ffe66d;
}
@media (min-width: 768px) {
.headerSpacer { height: 56px; }
.header { height: 56px; }
.progressBar { top: 56px; }
.headerMiddle { font-size: 18px; }
.headerRight {
width: auto;
height: 34px;
padding: 0 14px;
margin-right: 16px;
border-radius: 17px;
font-size: 13px;
.book {
padding: 28px 32px 96px;
}
.markdownBody {
max-width: 720px;
margin: 0 auto;
}
.markdownBody h1 {
font-size: 1.9rem !important;
}
.markdownBody h2 {
font-size: 1.4rem !important;
}
.drawer {
width: 320px;
}
.backToTop {
right: 28px;
bottom: 36px;
}
.headerRightText { display: inline; }
.book { padding: 30px 60px; }
.markdownBody { max-width: 800px; margin: 0 auto; }
.markdownBody h1 { font-size: 28px !important; }
.markdownBody h2 { font-size: 23px !important; }
.drawer { padding-top: 56px; width: 300px; }
.backToTop { width: 44px; height: 44px; bottom: 40px; right: 40px; }
}

View File

@ -88,6 +88,27 @@ export function EbookViewer({ data, config }: EbookViewerProps) {
return () => window.removeEventListener("scroll", onScroll);
}, [estimatedMin]);
// 深链:/vip/ebook/read#章节id
useEffect(() => {
const hash = decodeURIComponent(window.location.hash.slice(1));
if (!hash) return;
setForceShowAll(true);
const tryScroll = () => {
const el = document.getElementById(hash);
if (!el) return false;
el.scrollIntoView({ behavior: "auto", block: "start" });
return true;
};
if (!tryScroll()) {
const timers = [80, 200, 450, 900, 1600].map((ms) =>
window.setTimeout(() => {
tryScroll();
}, ms),
);
return () => timers.forEach(clearTimeout);
}
}, []);
const handleJump = useCallback((index: number) => {
setForceShowAll(true);
setShowDrawer(false);
@ -99,6 +120,10 @@ export function EbookViewer({ data, config }: EbookViewerProps) {
const targets = h1s.length > 0 ? h1s : h2s;
const el = targets[index] as HTMLElement;
if (el) {
const id = el.id;
if (id) {
history.replaceState(null, "", `#${id}`);
}
try {
el.scrollIntoView({ behavior: "smooth", block: "start" });
} catch {
@ -117,13 +142,13 @@ export function EbookViewer({ data, config }: EbookViewerProps) {
}, []);
return (
<>
<div className={styles.readerRoot}>
<div className={styles.readingProgress} style={{ width: `${readProgress}%` }} />
<div className={styles.headerSpacer} />
<header className={`${styles.header} animate__animated animate__fadeInDown`} style={{ animationFillMode: "both" }}>
<Link href={config.backHref} className={styles.headerLeft} aria-label="返回">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<header className={styles.header}>
<Link href={config.backHref || "/vip/ebook"} className={styles.headerLeft} aria-label="返回封面">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2">
<path d="M15 18l-6-6 6-6" />
</svg>
</Link>
@ -139,7 +164,7 @@ export function EbookViewer({ data, config }: EbookViewerProps) {
onClick={() => setShowDrawer(!showDrawer)}
aria-label="目录"
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2">
<line x1="3" y1="6" x2="21" y2="6" />
<line x1="3" y1="12" x2="21" y2="12" />
<line x1="3" y1="18" x2="21" y2="18" />
@ -195,6 +220,6 @@ export function EbookViewer({ data, config }: EbookViewerProps) {
</svg>
</button>
)}
</>
</div>
);
}

View File

@ -4,6 +4,7 @@
*/
import { CURRICULUM_CONFIG } from "@vip/app/cloudphone/config/course";
import { vipPath } from "@vip/app/lib/vipPath";
/** 视频课程总数:从所有课程配置汇总计算 */
const TOTAL_VIDEOS = CURRICULUM_CONFIG.modules.reduce((s, m) => s + m.lessons.length, 0);
@ -21,14 +22,14 @@ export const TOPICS = [
icon: "📖",
title: "电子书",
desc: "知识沉淀·随时阅读",
href: "/vip/ebook",
href: vipPath("/vip/ebook"),
},
{
id: "cloudphone",
icon: "🎬",
title: "视频教程",
desc: "实战演练·即学即用",
href: "/vip/cloudphone",
href: vipPath("/vip/cloudphone"),
},
{
id: "community",
@ -55,18 +56,18 @@ export const TOPICS_DISPLAY = [
{ id: "tools", icon: "🛒", title: "设备自助下单", desc: "开箱即用", href: "https://store.hackrobot.cn/", locked: true },
] as const;
/** 电子书展示 - 首页展示用 */
/** 电子书展示 — VIP 内 /vip/ebook(与 /book 同 UI,不跳转) */
export const EBOOKS_DISPLAY = [
{ id: "1", title: "数字游民", desc: "地理套利与自动化杠杆", href: "/vip/ebook", free: true },
{ id: "2", title: "云手机", desc: "低成本工作室搭建指南", href: "/vip/ebook/cloudphone", locked: true },
{ id: "1", title: "数字游民", desc: "地理套利与自动化杠杆", href: vipPath("/vip/ebook"), free: true },
{ id: "2", title: "云手机", desc: "低成本工作室搭建指南", href: vipPath("/vip/ebook/cloudphone"), locked: true },
] as const;
/** 视频教程展示(首页),至少 4 个 */
export const VIDEO_COURSES_DISPLAY = [
{ id: "cloudphone", icon: "☁️", title: "云手机", desc: "低成本自建云手机,TikTok/YouTube 无人直播实战指南", href: "/vip/cloudphone" },
{ id: "livestream", icon: "📺", title: "无人直播", desc: "TikTok/YouTube 无人直播,24 小时自动化", href: "/vip/topic/livestream" },
{ id: "indie", icon: "🛠️", title: "独立开发", desc: "从想法到产品,独立开发者全流程指南", href: "/vip/topic/indie" },
{ id: "aiagent", icon: "🤖", title: "AI Agent", desc: "AIGC 与智能体,Vibe Coding 跨界创造", href: "/vip/topic/aiagent" },
{ id: "cloudphone", icon: "☁️", title: "云手机", desc: "低成本自建云手机,TikTok/YouTube 无人直播实战指南", href: vipPath("/vip/cloudphone") },
{ id: "livestream", icon: "📺", title: "无人直播", desc: "TikTok/YouTube 无人直播,24 小时自动化", href: vipPath("/vip/topic/livestream") },
{ id: "indie", icon: "🛠️", title: "独立开发", desc: "从想法到产品,独立开发者全流程指南", href: vipPath("/vip/topic/indie") },
{ id: "aiagent", icon: "🤖", title: "AI Agent", desc: "AIGC 与智能体,Vibe Coding 跨界创造", href: vipPath("/vip/topic/aiagent") },
] as const;
export const COMPARE_ITEMS = [
@ -100,8 +101,8 @@ export const FAQ_ITEMS = [
/** 已登录控制台用 */
export const RECENT_UPDATES = [
{ id: "1", title: "云手机·第3章更新", date: "3月10日", href: "/vip/cloudphone/course/2/0" },
{ id: "2", title: "电子书·地理套利补充", date: "3月8日", href: "/vip/ebook" },
{ id: "1", title: "云手机·第3章更新", date: "3月10日", href: vipPath("/vip/cloudphone/course/2/0") },
{ id: "2", title: "电子书·地理套利补充", date: "3月8日", href: vipPath("/vip/ebook") },
{ id: "3", title: "模板库·RPA 脚本新增", date: "3月5日", href: null },
] as const;
@ -111,7 +112,7 @@ export const COMMUNITY_HIGHLIGHTS = [
] as const;
export const WEEKLY_ACTIONS = [
{ id: "1", text: "完成云手机第2章", href: "/vip/cloudphone/course/1/0", priority: 1 },
{ id: "2", text: "阅读电子书地理套利篇", href: "/vip/ebook", priority: 2 },
{ id: "1", text: "完成云手机第2章", href: vipPath("/vip/cloudphone/course/1/0"), priority: 1 },
{ id: "2", text: "阅读电子书地理套利篇", href: vipPath("/vip/ebook"), priority: 2 },
{ id: "3", text: "加入社群参与讨论", href: "https://qun.hackrobot.cn", priority: 3 },
] as const;

View File

@ -0,0 +1,30 @@
import { ScrollReaderShell } from "@ebook/components/ScrollReaderShell";
import type { Metadata } from "next";
import { VipEbookShell } from "../ebook/VipEbookShell";
import { loadVipEbookAsBook } from "../lib/loadVipEbookBook";
export const dynamic = "force-dynamic";
export const metadata: Metadata = {
title: "阅读 | 数字游民",
description: "数字游民:地理套利与自动化杠杆。",
};
/**
* 与 /book/read 同一套 ScrollReaderShell UI;
* 正文来自 VIP 原 ebook.md(不是游牧代码小册)。
*/
export default function VipEbookReadPage() {
const { book, chapters } = loadVipEbookAsBook();
return (
<VipEbookShell>
<ScrollReaderShell
book={book}
chapters={chapters}
affiliateRules={[]}
adSlots={{ mid: "", end: "" }}
/>
</VipEbookShell>
);
}

View File

@ -0,0 +1,67 @@
import { AntdRegistry } from "@ant-design/nextjs-registry";
import { Providers } from "@ebook/components/Providers";
import { BookRoutesProvider } from "@ebook/components/BookRoutes";
import { getSiteConfig } from "@ebook/lib/site-config.server";
import { getServerFeatures } from "@ebook/lib/features.server";
import { getLocale } from "@ebook/lib/i18n/server";
import "@ebook/app/globals.css";
/** VIP 电子书壳:与 /book layout 同能力,供 /vip/ebook 与阅读器复用(不跳转 /book) */
export async function VipEbookShell({
children,
readPath = "/vip/ebook/read",
}: {
children: React.ReactNode;
readPath?: string;
}) {
const locale = await getLocale();
const site = getSiteConfig();
const f = getServerFeatures();
return (
<div className="ebook-root vip-ebook-root" data-locale={locale}>
<AntdRegistry>
<Providers locale={locale}>
<BookRoutesProvider cover="/vip/ebook" read={readPath} home="/vip">
{f.analytics.enabled ? <AnalyticsLazy /> : null}
{f.ads.enabled && f.ads.clientId ? <AdSenseLazy /> : null}
{children}
{f.feedback.enabled ? (
<FeedbackLazy
title={f.feedback.title}
subtitle={f.feedback.subtitle}
contactEmail={site.brand.contactEmail}
xHandle={site.brand.xHandle}
/>
) : null}
</BookRoutesProvider>
</Providers>
</AntdRegistry>
<script
dangerouslySetInnerHTML={{
__html: `window.__EBOOK_FEATURES__=${JSON.stringify(f).replace(/</g, "\\u003c")};window.__LOCALE__=${JSON.stringify(locale)};(function(){try{var t=localStorage.getItem("nomadro-theme")||localStorage.getItem("ebook-theme");if(t==="light"||t==="sepia"||t==="dark"){document.documentElement.classList.remove("light","dark","sepia");document.documentElement.classList.add(t);}else{document.documentElement.classList.add("dark");}}catch(e){document.documentElement.classList.add("dark");}})();`,
}}
/>
</div>
);
}
function AnalyticsLazy() {
const { AnalyticsProvider } = require("@ebook/components/AnalyticsProvider");
return <AnalyticsProvider />;
}
function AdSenseLazy() {
const { AdSenseScript } = require("@ebook/components/AdSlot");
return <AdSenseScript />;
}
function FeedbackLazy(props: {
title: string;
subtitle: string;
contactEmail: string;
xHandle: string;
}) {
const { FeedbackPanel } = require("@ebook/components/FeedbackPanel");
return <FeedbackPanel {...props} />;
}

View File

@ -0,0 +1,21 @@
import { ScrollReaderShell } from "@ebook/components/ScrollReaderShell";
import { VipEbookShell } from "../VipEbookShell";
import { loadVipEbookAsBook } from "../../lib/loadVipEbookBook";
export const dynamic = "force-dynamic";
/** 与 /vip/ebook/read 相同:ScrollReaderShell + VIP ebook.md */
export default function VipEbookOpenPage() {
const { book, chapters } = loadVipEbookAsBook();
return (
<VipEbookShell>
<ScrollReaderShell
book={book}
chapters={chapters}
affiliateRules={[]}
adSlots={{ mid: "", end: "" }}
/>
</VipEbookShell>
);
}

View File

@ -1,23 +1,35 @@
import { readFileSync } from "fs";
import { parseEbookMarkdown, estimateReadingMinutes } from "@vip/lib/content/ebook";
import { EbookViewer } from "@vip/app/components/content/EbookViewer";
import { EBOOK_CONFIG } from "@vip/config/content.config";
import { resolveVipDataFile } from "@vip/app/lib/resolveVipDataFile";
import type { Metadata } from "next";
import { CoverPage } from "@ebook/components/CoverPage";
import { getSiteConfig, getAdSlot } from "@ebook/lib/site-config.server";
import { getServerFeatures } from "@ebook/lib/features.server";
import { VipEbookShell } from "./VipEbookShell";
import { loadVipEbookAsBook } from "../lib/loadVipEbookBook";
export const metadata = {
export const metadata: Metadata = {
title: "电子书 | 数字游民",
description: "数字游民:地理套利与自动化杠杆,低成本工作室、云手机、无人直播、出海掘金。",
};
export default function EbookPage() {
const mdPath = resolveVipDataFile("ebook.md");
const source = readFileSync(mdPath, "utf-8");
const data = parseEbookMarkdown(source);
const textLen = data.chunks.reduce((s, c) => s + c.html.replace(/<[^>]+>/g, "").length, 0);
const config = {
...EBOOK_CONFIG,
estimatedMinutes: estimateReadingMinutes(textLen),
};
/**
* 封面与 /book 同一套 CoverPage;
* 阅读进 /vip/ebook/read(ScrollReaderShell,正文仍是 ebook.md)。
*/
export default function VipEbookCoverPage() {
const { book, chapters } = loadVipEbookAsBook();
const site = getSiteConfig();
const f = getServerFeatures();
const chapterMinutes = Object.fromEntries(
chapters.map((c) => [c.slug, c.readingMinutes]),
);
return <EbookViewer data={data} config={config} />;
return (
<VipEbookShell>
<CoverPage
book={book}
site={site}
chapterMinutes={chapterMinutes}
coverAdSlot={f.ads.enabled ? getAdSlot("coverSlot") : ""}
/>
</VipEbookShell>
);
}

View File

@ -1,3 +1,6 @@
/**
* 电子书 Markdown 解析 - 共享模块
*/
import { marked } from "marked";
export interface EbookChunk {
@ -12,7 +15,34 @@ export interface EbookData {
export function parseEbookMarkdown(source: string): EbookData {
const html = marked.parse(source, { breaks: true, gfm: true }) as string;
const lazyHtml = html.replace(/<img /g, '<img loading="lazy" decoding="async" ');
let lazyHtml = html.replace(/<img /g, '<img loading="lazy" decoding="async" ');
// 给标题加稳定 id,支持 /vip/ebook/read#章节锚点
const used = new Set<string>();
lazyHtml = lazyHtml.replace(
/<(h[12])(\s[^>]*)?>([\s\S]*?)<\/\1>/gi,
(_m, tag: string, attrs = "", inner: string) => {
if (/\sid\s*=/i.test(attrs || "")) {
return `<${tag}${attrs || ""}>${inner}</${tag}>`;
}
const plain = inner.replace(/<[^>]+>/g, "").trim();
let base =
plain
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\u4e00-\u9fff-]+/g, "")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "")
.slice(0, 80) || "section";
let id = base;
let n = 2;
while (used.has(id)) {
id = `${base}-${n++}`;
}
used.add(id);
return `<${tag}${attrs || ""} id="${id}">${inner}</${tag}>`;
},
);
let rawChunks = lazyHtml.split(/(?=<h1[\s>])/i).filter((c) => c.trim());
if (rawChunks.length <= 1) {
@ -41,3 +71,8 @@ export function parseEbookMarkdown(source: string): EbookData {
return { chunks, headers };
}
/** 估算阅读时间(字/分钟,中文约 300-500) */
export function estimateReadingMinutes(textLength: number, wpm = 400): number {
return Math.max(1, Math.ceil(textLength / wpm));
}

View File

@ -0,0 +1,100 @@
import "server-only";
import { readFileSync } from "fs";
import type { Book, LoadedChapter } from "@ebook/lib/book-types";
import { resolveVipDataFile } from "@vip/app/lib/resolveVipDataFile";
function slugify(title: string, index: number): string {
const plain = title.replace(/[#*_`]/g, "").trim();
// 与 /book 小册习惯对齐:前言 → 00-preface
if (/^前言/.test(plain) || /^preface$/i.test(plain)) return "00-preface";
const base =
plain
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\u4e00-\u9fff-]+/g, "")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "")
.slice(0, 48) || `section-${index}`;
return `${String(index).padStart(2, "0")}-${base}`;
}
function pickEmoji(title: string, index: number): string {
if (/前言|序/.test(title)) return "✈️";
if (/云手机|直播/.test(title)) return "📱";
if (/youtube|yt/i.test(title)) return "📺";
if (/tiktok/i.test(title)) return "🎵";
if (/独立开发|saas|web/i.test(title)) return "🛠️";
if (/vps|服务器|网络|软路由/.test(title)) return "🌐";
if (/赚钱|副业/.test(title)) return "💰";
const pool = ["📖", "✦", "🚀", "💡", "🔥", "🌍", "⚙️"];
return pool[index % pool.length];
}
/**
* 把 VIP 原 ebook.md 拆成与 /book/read 相同的 Book + LoadedChapter 结构,
* 以便直接复用 ScrollReaderShell。
*/
export function loadVipEbookAsBook(): { book: Book; chapters: LoadedChapter[] } {
const mdPath = resolveVipDataFile("ebook.md");
const source = readFileSync(mdPath, "utf-8");
const parts = source.split(/(?=^# )/m).filter((p) => p.trim());
const total = Math.max(parts.length, 1);
const chapters: LoadedChapter[] = (parts.length ? parts : [source]).map((raw, index) => {
const lines = raw.trim().split("\n");
const titleLine = lines[0]?.replace(/^#\s+/, "").trim() || `第 ${index + 1} 章`;
const body = lines.slice(1).join("\n").trim();
const content = body || raw.trim();
const charCount = content.replace(/\s/g, "").length;
const readingMinutes = Math.max(1, Math.round(charCount / 450));
const slug = slugify(titleLine, index);
const emoji = pickEmoji(titleLine, index);
const hook = body
.split("\n")
.map((l) => l.replace(/^>\s?/, "").trim())
.find((l) => l && !l.startsWith("#") && !l.startsWith("!") && !l.startsWith("<"))
?.slice(0, 80) || titleLine;
return {
slug,
title: titleLine,
emoji,
hook,
shareQuote: hook,
content,
index,
readingMinutes,
total,
};
});
const readingMinutes = chapters.reduce((s, c) => s + c.readingMinutes, 0);
const book: Book = {
title: "数字游民",
subtitle: "地理套利与自动化杠杆",
author: "nomadro",
description: "低成本工作室、云手机、无人直播、出海掘金。",
tagline: "在任意城市,过你想要的生活。",
coverGradient: "from-violet-950 via-fuchsia-900 to-orange-900",
readingMinutes,
viralTags: ["数字游民", "云手机", "无人直播", "出海"],
stats: [
{ emoji: "📖", value: String(chapters.length), label: "章" },
{ emoji: "⏱️", value: String(readingMinutes), label: "分钟" },
{ emoji: "☁️", value: "云手机", label: "工作室" },
{ emoji: "💰", value: "出海", label: "掘金" },
],
hooks: chapters.slice(0, 4).map((c) => ({ emoji: c.emoji, text: c.hook })),
chapters: chapters.map(({ slug, title, emoji, hook, shareQuote }) => ({
slug,
title,
emoji,
hook,
shareQuote,
})),
};
return { book, chapters };
}

View File

@ -0,0 +1,17 @@
import { existsSync } from "fs";
import path from "path";
/**
* Resolve VIP content files under portal (apps/nomadvip) or standalone (app/data).
*/
export function resolveVipDataFile(...segments: string[]): string {
const candidates = [
path.join(process.cwd(), "apps", "nomadvip", "app", "data", ...segments),
path.join(process.cwd(), "app", "data", ...segments),
path.join(process.cwd(), "apps", "nomadvip", "app", ...segments),
];
for (const p of candidates) {
if (existsSync(p)) return p;
}
return candidates[0];
}

View File

@ -8,6 +8,8 @@
*/
import { getPayEnv, getDeviceFromEnv } from "@vip/app/lib/payEnv";
import { getPaymentConfig } from "@vip/config/services.config";
import { resolvePayProvider } from "@nomadro/pay";
import { isChinaUser } from "is-china-user";
const ANONYMOUS_USER_COOKIE = "nomadvip_anon_uid";
const ANONYMOUS_USER_COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
@ -161,6 +163,7 @@ function redirectToPayZpay(params: {
type: string;
channel: "alipay" | "wxpay";
device: "pc" | "h5" | "wechat";
provider: string;
}) {
const form = document.createElement("form");
form.method = "POST";
@ -177,7 +180,7 @@ function redirectToPayZpay(params: {
["type", params.type],
["channel", params.channel],
["device", params.device],
["provider", "zpay"],
["provider", params.provider],
["html", "1"],
];
fields.forEach(([k, v]) => {
@ -191,7 +194,7 @@ function redirectToPayZpay(params: {
form.submit();
}
async function redirectToPayZpayH5(
async function redirectToPayH5(
params: {
user_id: string;
wechat_userid?: string;
@ -201,6 +204,7 @@ async function redirectToPayZpayH5(
total_fee: number;
type: string;
channel: "alipay" | "wxpay";
provider: string;
},
onPendingOrder?: (orderId: string) => void
): Promise<string | null> {
@ -210,7 +214,6 @@ async function redirectToPayZpayH5(
body: JSON.stringify({
...params,
device: "h5",
provider: "zpay",
html: "0",
}),
});
@ -263,6 +266,7 @@ function payWechatXorpaySync(params: {
total_fee: number;
type: string;
channel: "alipay" | "wxpay";
provider?: string;
}) {
const form = document.createElement("form");
form.method = "POST";
@ -279,7 +283,7 @@ function payWechatXorpaySync(params: {
["type", params.type],
["channel", params.channel],
["device", "wechat"],
["provider", "xorpay"],
["provider", params.provider || "xorpay"],
["html", "1"],
];
fields.forEach(([k, v]) => {
@ -323,6 +327,17 @@ export async function triggerPay(
if (shouldShowLaunchOverlay) {
showPayLaunchOverlay(profile.displayName, profile.avatar);
}
const china =
typeof window !== "undefined" ? Boolean(isChinaUser()) : true;
const resolved = resolvePayProvider({
isChinaUser: china,
userAgent: typeof navigator !== "undefined" ? navigator.userAgent : undefined,
});
// Backend aliases: xpay → xorpay
const apiProvider =
resolved.provider === "xpay" ? "xorpay" : resolved.provider;
const base = {
user_id: userId,
wechat_userid: wechatUserId || undefined,
@ -331,13 +346,22 @@ export async function triggerPay(
return_url: returnUrl,
total_fee: totalFee,
type: "vip",
channel: "wxpay" as const,
channel: resolved.channel,
provider: apiProvider,
};
// Overseas: always redirect via JSON so Creem/NOWPayments can return checkout URL
if (apiProvider === "creem" || apiProvider === "nowpayments") {
await redirectToPayH5({ ...base, channel: "wxpay" }, onPendingOrder);
return;
}
if (device === "wechat") {
payWechatXorpaySync(base);
} else if (device === "h5") {
await redirectToPayZpayH5(base, onPendingOrder);
await redirectToPayH5(base, onPendingOrder);
} else {
redirectToPayZpay({ ...base, device });
}
}

25
app/vip/lib/vipPath.ts Normal file
View File

@ -0,0 +1,25 @@
/**
* Portal mount prefix for VIP routes.
* Standalone vip.hackrobot.cn: set NEXT_PUBLIC_VIP_BASE_PATH="" (or unset → treated as "").
* Nomadro portal: NEXT_PUBLIC_VIP_BASE_PATH=/vip (default in monorepo).
*/
const RAW =
typeof process !== "undefined"
? process.env.NEXT_PUBLIC_VIP_BASE_PATH
: undefined;
/** Empty string = site root; monorepo portal defaults to /vip */
export const VIP_BASE =
RAW === undefined || RAW === null
? "/vip"
: RAW.replace(/\/$/, "");
export function vipPath(path: string): string {
if (!path || path.startsWith("http") || path.startsWith("#") || path.startsWith("mailto:")) {
return path;
}
const p = path.startsWith("/") ? path : `/${path}`;
if (!VIP_BASE) return p;
if (p === VIP_BASE || p.startsWith(`${VIP_BASE}/`)) return p;
return `${VIP_BASE}${p}`;
}

View File

@ -1,9 +1,14 @@
"use client";
import { ModuleGate } from "~/components/module-gate";
import { HomeClientLoader } from "./HomeClientLoader";
export default function Page() {
export default function VipPage() {
return (
<div className="min-h-screen bg-[var(--background)]">
<HomeClientLoader />
</div>
<ModuleGate moduleKey="vip">
<div className="min-h-screen bg-[var(--background)]">
<HomeClientLoader />
</div>
</ModuleGate>
);
}

View File

@ -19,27 +19,39 @@ type ThemeContextValue = {
const ThemeContext = createContext<ThemeContextValue | null>(null);
const STORAGE_KEY = "nomadvip-theme";
const SHARED_KEY = "nomadro-theme";
const DEFAULT_THEME: ThemeMode = "dark";
function getSystemTheme(): "light" | "dark" {
if (typeof window === "undefined") return "light";
if (typeof window === "undefined") return "dark";
return window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
function resolveMode(mode: ThemeMode): "light" | "dark" {
if (mode === "system") return getSystemTheme();
return mode;
}
function getStoredTheme(): ThemeMode {
if (typeof window === "undefined") return "system";
return (localStorage.getItem(STORAGE_KEY) as ThemeMode) || "system";
if (typeof window === "undefined") return DEFAULT_THEME;
const raw =
(localStorage.getItem(SHARED_KEY) as ThemeMode | null) ||
(localStorage.getItem(STORAGE_KEY) as ThemeMode | null);
if (raw === "light" || raw === "dark" || raw === "system") return raw;
return DEFAULT_THEME;
}
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setThemeState] = useState<ThemeMode>("system");
const [resolvedTheme, setResolvedTheme] = useState<"light" | "dark">("light");
const [theme, setThemeState] = useState<ThemeMode>(DEFAULT_THEME);
const [resolvedTheme, setResolvedTheme] = useState<"light" | "dark">("dark");
const applyTheme = useCallback((mode: "light" | "dark") => {
const root = document.documentElement;
root.classList.remove("light", "dark");
root.classList.add(mode);
root.dataset.theme = mode;
setResolvedTheme(mode);
}, []);
@ -47,9 +59,8 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
(newTheme: ThemeMode) => {
setThemeState(newTheme);
localStorage.setItem(STORAGE_KEY, newTheme);
const resolved =
newTheme === "system" ? getSystemTheme() : newTheme;
applyTheme(resolved);
localStorage.setItem(SHARED_KEY, newTheme);
applyTheme(resolveMode(newTheme));
},
[applyTheme]
);
@ -57,8 +68,7 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
const stored = getStoredTheme();
setThemeState(stored);
const resolved = stored === "system" ? getSystemTheme() : stored;
applyTheme(resolved);
applyTheme(resolveMode(stored));
const media = window.matchMedia("(prefers-color-scheme: dark)");
const handler = () => {

View File

@ -1,10 +1,25 @@
/**
* 主题初始化 - 在 React 水合前执行,避免主题闪烁
* 优先读全局 nomadro-theme,回退 nomadvip-theme;默认夜间
*/
export const themeInitScript = `
(function() {
var theme = localStorage.getItem('nomadvip-theme');
var resolved = theme === 'light' ? 'light' : (theme === 'dark' ? 'dark' : (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'));
document.documentElement.classList.add(resolved);
try {
var theme = localStorage.getItem('nomadro-theme') || localStorage.getItem('nomadvip-theme');
var resolved = theme === 'light'
? 'light'
: (theme === 'dark'
? 'dark'
: (theme === 'system'
? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
: 'dark'));
var root = document.documentElement;
root.classList.remove('light', 'dark');
root.classList.add(resolved);
root.dataset.theme = resolved;
} catch (e) {
document.documentElement.classList.add('dark');
document.documentElement.dataset.theme = 'dark';
}
})();
`;

View File

@ -5,6 +5,7 @@ import Link from "next/link";
import { getTopicCurriculum } from "../config";
import { canWatchLesson, isPaid } from "@vip/app/cloudphone/lib/payment";
import { isBookmarked, toggleBookmark, getBookmarks, getCompletedLessons } from "@vip/app/cloudphone/lib/learning";
import { vipPath } from "@vip/app/lib/vipPath";
type TopicCurriculumProps = {
topicId: string;
@ -165,7 +166,7 @@ export function TopicCurriculum({ topicId }: TopicCurriculumProps) {
</div>
) : (
<Link
href={`/vip/cloudphone/course/${origMod}/${li}`}
href={vipPath(`/vip/cloudphone/course/${origMod}/${li}`)}
className="flex flex-col gap-1 px-4 py-3 transition hover:bg-[var(--muted)]/50 sm:flex-row sm:items-center sm:justify-between sm:px-5 sm:py-3"
>
<span className="flex items-center gap-2 truncate sm:gap-3">

View File

@ -7,6 +7,7 @@ import { getTopicConfig } from "../config";
import { isPaid } from "@vip/app/cloudphone/lib/payment";
import { triggerPay } from "@vip/app/lib/triggerPay";
import { InstantQaVipModal } from "@vip/app/components/InstantQaVipModal";
import { vipPath } from "@vip/app/lib/vipPath";
type TopicHeaderProps = {
topicId: string;
@ -94,7 +95,7 @@ export function TopicHeader({ topicId }: TopicHeaderProps) {
</button>
) : (
<Link
href="/vip/cloudphone/course/0/0"
href={vipPath("/vip/cloudphone/course/0/0")}
className="inline-flex items-center gap-1.5 rounded-full bg-[var(--accent)] px-3 py-1.5 text-xs font-medium text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-4 sm:py-2 sm:text-sm"
>
进入课程 →

View File

@ -8,6 +8,7 @@ import { getLastWatched, getProgress } from "@vip/app/cloudphone/lib/learning";
import { ParticleBackground } from "@vip/app/cloudphone/components/ParticleBackground";
import { triggerPay } from "@vip/app/lib/triggerPay";
import type { TopicPrepVariant } from "./TopicPrepThreeScene";
import { vipPath } from "@vip/app/lib/vipPath";
const TopicPrepThreeScene = dynamic(
() => import("./TopicPrepThreeScene").then((m) => m.TopicPrepThreeScene),
@ -125,7 +126,7 @@ export function TopicHero({ topicId }: TopicHeroProps) {
</button>
) : (
<Link
href={`/vip/cloudphone/course/${last!.moduleIndex}/${last!.lessonIndex}`}
href={vipPath(`/vip/cloudphone/course/${last!.moduleIndex}/${last!.lessonIndex}`)}
className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-10"
>
继续学习 →

View File

@ -13,6 +13,28 @@ function getAvatarLetter(email: string): string {
return local.slice(0, 1).toUpperCase();
}
function LogoIcon() {
return (
<svg className={styles.logoMark} viewBox="0 0 40 40" fill="none" aria-hidden>
<circle cx="20" cy="20" r="18" stroke="url(#vipLogoGrad)" strokeWidth="2.5" />
<path
d="M12 22c4-8 12-8 16 0"
stroke="url(#vipLogoGrad)"
strokeWidth="2"
strokeLinecap="round"
/>
<circle cx="28" cy="14" r="3" fill="url(#vipLogoGrad)" />
<defs>
<linearGradient id="vipLogoGrad" x1="0" y1="0" x2="40" y2="40">
<stop offset="0%" stopColor="#FF6B6B" />
<stop offset="50%" stopColor="#FFE66D" />
<stop offset="100%" stopColor="#4ECDC4" />
</linearGradient>
</defs>
</svg>
);
}
type VipHeaderProps = {
isLoggedIn: boolean;
userName?: string | null;
@ -53,8 +75,9 @@ export function VipHeader({
return (
<header className={styles.header}>
<Link href="/" className={styles.logo}>
🌍 异度星球
<Link href="/" className={styles.logo} aria-label="返回首页">
<LogoIcon />
<span className={styles.logoBrand}>nomadro</span>
</Link>
<nav className={styles.nav}>
<ThemeToggle />
@ -83,14 +106,14 @@ export function VipHeader({
</span>
)}
{open && (
<div className="absolute right-0 top-full z-50 mt-2 min-w-[120px] rounded-lg border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-800">
<span className="block px-4 py-2 text-sm text-slate-600 dark:text-slate-400 truncate max-w-[160px]">
<div className="absolute right-0 top-full z-50 mt-2 min-w-[120px] rounded-lg border border-[var(--border)] bg-[var(--card)] py-1 shadow-lg backdrop-blur-xl">
<span className="block px-4 py-2 text-sm text-[var(--muted-foreground)] truncate max-w-[160px]">
<Copyable text={displayName}>{displayName}</Copyable>
</span>
{isLoggedIn && onLogout && (
<button
onClick={handleLogout}
className="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-slate-700 hover:bg-slate-50 dark:text-slate-300 dark:hover:bg-slate-700"
className="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-[var(--foreground)] hover:bg-[var(--muted)]"
>
退出
</button>

View File

@ -5,6 +5,7 @@ import { getLastWatched, getProgress } from "@vip/app/cloudphone/lib/learning";
import { CURRICULUM_CONFIG } from "@vip/app/cloudphone/config/course";
import { useState, useEffect } from "react";
import styles from "../vip.module.css";
import { vipPath } from "@vip/app/lib/vipPath";
const TOTAL_LESSONS = CURRICULUM_CONFIG.modules.reduce((s, m) => s + m.lessons.length, 0);
@ -28,7 +29,7 @@ export function ContinueLearning() {
<section className={styles.section}>
<h2 className={styles.sectionTitle}>继续学习</h2>
<Link
href="/vip/cloudphone/course/0/0"
href={vipPath("/vip/cloudphone/course/0/0")}
className={`${styles.card} ${styles.btnPrimary}`}
style={{ display: "block", textAlign: "center" }}
>
@ -46,7 +47,7 @@ export function ContinueLearning() {
<section className={styles.section}>
<h2 className={styles.sectionTitle}>继续学习</h2>
<Link
href={`/vip/cloudphone/course/${last.moduleIndex}/${last.lessonIndex}`}
href={vipPath(`/vip/cloudphone/course/${last.moduleIndex}/${last.lessonIndex}`)}
className={styles.card}
style={{
display: "block",

View File

@ -15,14 +15,17 @@ export function LandingHero({ onTitleTap }: LandingHeroProps) {
onClick={onTitleTap}
title="连续点击 10 次切换测试价格"
>
异度星球会员中心
nomadro
</p>
<h1
className={`${styles.heroTitle} animate__animated animate__fadeInDown`}
style={{ animationDelay: "0.2s", animationFillMode: "both" }}
>
<span className={styles.heroTitleAccent}>全模块解锁</span>
<span className={styles.heroTitleRest}> · 持续更新 · 抱团出海</span>
<span className={styles.heroTitleRest}>
<br />
持续更新 · 抱团出海
</span>
</h1>
<p
className={`${styles.heroLead} animate__animated animate__fadeInDown`}

View File

@ -16,6 +16,12 @@
padding: 1rem 1.5rem;
max-width: 1200px;
margin: 0 auto;
position: sticky;
top: 0;
z-index: 40;
backdrop-filter: blur(18px);
background: color-mix(in oklab, var(--background) 82%, transparent);
border-bottom: 1px solid var(--border);
}
@media (max-width: 640px) {
@ -25,14 +31,44 @@
}
.logo {
font-size: 1.25rem;
font-weight: 700;
display: inline-flex;
align-items: center;
gap: 0.5rem;
font-family: var(--font-outfit), var(--font-noto-sc), system-ui, sans-serif;
font-size: 1.15rem;
font-weight: 800;
color: var(--foreground);
text-decoration: none;
letter-spacing: -0.02em;
}
.logoMark {
width: 28px;
height: 28px;
flex-shrink: 0;
}
.logo:hover {
color: var(--hub-accent-3);
}
.logoBrand {
background: var(--hub-gradient-text);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
.logoSep {
color: var(--muted-foreground);
font-weight: 500;
margin: 0 0.15rem;
}
.logoVip {
color: var(--accent);
font-weight: 700;
font-size: 0.95rem;
}
.nav {
@ -171,7 +207,7 @@
height: min(42vw, 380px);
top: -4%;
left: -10%;
background: radial-gradient(circle, rgba(245, 158, 11, 0.38) 0%, transparent 68%);
background: radial-gradient(circle, rgba(255, 107, 107, 0.42) 0%, transparent 68%);
animation: landingOrbA 22s ease-in-out infinite;
}
@ -180,7 +216,7 @@
height: min(48vw, 420px);
top: 10%;
right: -16%;
background: radial-gradient(circle, rgba(245, 158, 11, 0.14) 0%, transparent 72%);
background: radial-gradient(circle, rgba(78, 205, 196, 0.28) 0%, transparent 72%);
animation: landingOrbB 26s ease-in-out infinite;
}
@ -189,12 +225,12 @@
height: min(34vw, 300px);
top: 36%;
left: 14%;
background: radial-gradient(circle, rgba(251, 191, 36, 0.22) 0%, transparent 72%);
background: radial-gradient(circle, rgba(255, 230, 109, 0.26) 0%, transparent 72%);
animation: landingOrbC 19s ease-in-out infinite alternate;
}
.dark .landingOrb:nth-child(2) {
background: radial-gradient(circle, rgba(129, 140, 248, 0.22) 0%, transparent 72%);
background: radial-gradient(circle, rgba(78, 205, 196, 0.32) 0%, transparent 72%);
}
@keyframes landingOrbA {
@ -229,8 +265,8 @@
width: 100%;
height: 100%;
background-image:
linear-gradient(rgba(245, 158, 11, 0.1) 1px, transparent 1px),
linear-gradient(90deg, rgba(245, 158, 11, 0.1) 1px, transparent 1px);
linear-gradient(rgba(78, 205, 196, 0.12) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 107, 107, 0.1) 1px, transparent 1px);
background-size: 52px 52px;
transform-origin: 50% 0%;
transform: rotateX(74deg) translateY(-5%) scale(1.06);
@ -241,8 +277,8 @@
.dark .landingMesh::before {
background-image:
linear-gradient(rgba(245, 158, 11, 0.15) 1px, transparent 1px),
linear-gradient(90deg, rgba(245, 158, 11, 0.15) 1px, transparent 1px);
linear-gradient(rgba(78, 205, 196, 0.16) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 107, 107, 0.12) 1px, transparent 1px);
}
@keyframes landingMeshScroll {
@ -275,17 +311,17 @@
.heroEyebrow {
display: inline-block;
font-size: 0.8125rem;
font-weight: 500;
font-weight: 600;
color: var(--muted-foreground);
padding: 0.4rem 0.95rem;
border-radius: 9999px;
border: 1px solid rgba(245, 158, 11, 0.22);
border: 1px solid rgba(78, 205, 196, 0.28);
margin-bottom: 1rem;
background: rgba(255, 255, 255, 0.5);
background: rgba(255, 255, 255, 0.04);
backdrop-filter: blur(12px) saturate(1.2);
box-shadow:
0 10px 36px rgba(0, 0, 0, 0.07),
0 0 0 1px rgba(255, 255, 255, 0.55) inset;
0 10px 36px rgba(0, 0, 0, 0.2),
0 0 0 1px rgba(255, 255, 255, 0.06) inset;
}
.dark .heroEyebrow {
@ -294,18 +330,26 @@
}
.heroTitle {
font-size: clamp(2rem, 6vw, 3rem);
font-weight: 700;
font-family: var(--font-outfit), var(--font-noto-sc), system-ui, sans-serif;
font-size: clamp(2rem, 6vw, 3.2rem);
font-weight: 800;
margin: 0 0 0.5rem;
letter-spacing: -0.03em;
line-height: 1.18;
}
.heroTitleAccent {
background: linear-gradient(120deg, var(--foreground) 0%, var(--accent) 42%, #fbbf24 100%);
background: var(--hub-gradient-text);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
background-size: 200% auto;
animation: vipGradientShift 4s ease-in-out infinite;
}
@keyframes vipGradientShift {
0%, 100% { background-position: 0% center; }
50% { background-position: 100% center; }
}
.heroTitleRest {
@ -324,28 +368,34 @@
.landingStatCard {
position: relative;
backdrop-filter: blur(12px) saturate(1.15);
background: rgba(255, 255, 255, 0.52);
border-color: rgba(245, 158, 11, 0.2);
backdrop-filter: blur(18px) saturate(1.15);
background: rgba(17, 24, 39, 0.7);
border-color: rgba(255, 255, 255, 0.08);
transition: transform 0.35s ease, box-shadow 0.35s ease, border-color 0.2s;
}
:global(.light) .landingStatCard {
background: rgba(255, 255, 255, 0.72);
border-color: rgba(13, 148, 136, 0.18);
}
.dark .landingStatCard {
background: rgba(255, 255, 255, 0.04);
border-color: rgba(245, 158, 11, 0.24);
background: rgba(17, 24, 39, 0.7);
border-color: rgba(255, 255, 255, 0.08);
}
.landingStatCard:hover {
transform: translateY(-3px) perspective(880px) rotateX(5deg);
transform: translateY(-4px);
border-color: rgba(78, 205, 196, 0.35);
box-shadow:
0 18px 44px rgba(0, 0, 0, 0.1),
0 0 0 1px rgba(245, 158, 11, 0.14);
var(--hub-glow),
0 18px 44px rgba(0, 0, 0, 0.35);
}
.dark .landingStatCard:hover {
box-shadow:
0 22px 52px rgba(0, 0, 0, 0.48),
0 0 0 1px rgba(245, 158, 11, 0.22);
var(--hub-glow),
0 22px 52px rgba(0, 0, 0, 0.48);
}
.statsSection {
@ -1030,7 +1080,7 @@
height: 70%;
background: radial-gradient(
ellipse 70% 80% at 50% 0%,
rgba(245, 158, 11, 0.22),
rgba(78, 205, 196, 0.22),
transparent 65%
);
opacity: 0.85;
@ -1039,12 +1089,24 @@
.ctaCard {
position: relative;
border-radius: 20px;
border-radius: 16px;
padding: 1.75rem 1.5rem 1.65rem;
text-align: center;
background: rgba(255, 255, 255, 0.7);
backdrop-filter: blur(16px) saturate(1.25);
border: 1px solid rgba(245, 158, 11, 0.24);
background:
radial-gradient(90% 70% at 50% -10%, rgba(78, 205, 196, 0.12) 0%, transparent 58%),
radial-gradient(70% 50% at 90% 20%, rgba(255, 107, 107, 0.08) 0%, transparent 55%),
linear-gradient(180deg, rgba(17, 24, 39, 0.92) 0%, rgba(10, 14, 23, 0.96) 100%);
backdrop-filter: blur(18px) saturate(1.25);
border: 1px solid rgba(78, 205, 196, 0.2);
box-shadow:
var(--hub-glow),
0 24px 60px rgba(0, 0, 0, 0.52),
0 0 0 1px rgba(255, 255, 255, 0.04) inset;
}
:global(.light) .ctaCard {
background: rgba(255, 255, 255, 0.85);
border-color: rgba(13, 148, 136, 0.2);
box-shadow:
0 20px 50px rgba(0, 0, 0, 0.08),
0 0 0 1px rgba(255, 255, 255, 0.45) inset;
@ -1052,13 +1114,14 @@
.dark .ctaCard {
background:
radial-gradient(90% 70% at 50% -10%, rgba(251, 191, 36, 0.12) 0%, rgba(251, 191, 36, 0) 58%),
linear-gradient(180deg, #0b1220 0%, #0a0f1a 100%);
border-color: rgba(251, 191, 36, 0.18);
radial-gradient(90% 70% at 50% -10%, rgba(78, 205, 196, 0.12) 0%, transparent 58%),
radial-gradient(70% 50% at 90% 20%, rgba(255, 107, 107, 0.08) 0%, transparent 55%),
linear-gradient(180deg, rgba(17, 24, 39, 0.92) 0%, rgba(10, 14, 23, 0.96) 100%);
border-color: rgba(78, 205, 196, 0.2);
box-shadow:
var(--hub-glow),
0 24px 60px rgba(0, 0, 0, 0.52),
0 0 0 1px rgba(251, 191, 36, 0.08) inset,
0 1px 0 rgba(255, 255, 255, 0.04) inset;
0 0 0 1px rgba(255, 255, 255, 0.04) inset;
}
.dark .ctaGlow {
@ -1071,7 +1134,7 @@
}
.dark .ctaHighlight {
background: linear-gradient(120deg, #f59e0b 0%, #fcd34d 100%);
background: var(--hub-gradient-text);
-webkit-background-clip: text;
background-clip: text;
color: transparent;

View File

@ -12,7 +12,7 @@ from datetime import datetime, timezone
from typing import Any
import httpx
from fastapi import FastAPI, HTTPException
from fastapi import FastAPI, Header, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
@ -201,11 +201,109 @@ async def resolve_pay(body: PayRouteRequest) -> PayRouteResponse:
)
@app.get("/v1/config")
async def get_remote_config() -> dict[str, Any]:
"""前端远程配置;文件缺失时返回内置默认(离线客户端也有同结构兜底)。"""
import json
from pathlib import Path
candidates = [
Path(__file__).resolve().parents[3] / "data" / "remote-config.json",
Path.cwd() / "data" / "remote-config.json",
]
for path in candidates:
try:
if path.is_file():
data = json.loads(path.read_text(encoding="utf-8"))
return {"ok": True, "source": "file", "config": data}
except Exception: # noqa: BLE001
continue
return {
"ok": True,
"source": "default",
"config": {
"version": 1,
"updatedAt": datetime.now(timezone.utc).isoformat(),
"modules": {
"home": {"enabled": True, "title": "首页", "tabLabel": "首页"},
"nav": {"enabled": True, "title": "出海导航", "tabLabel": "导航"},
"book": {"enabled": True, "title": "数字游民小册", "tabLabel": "小册"},
"community": {"enabled": True, "title": "旅居社群", "tabLabel": "社群"},
"destinations": {"enabled": True, "title": "目的地"},
"meetups": {"enabled": True, "title": "活动"},
"vip": {"enabled": True, "title": "私域会员"},
},
"flags": {
"payEnabled": True,
"socialFollow": True,
"offlineBadge": True,
},
"copy": {
"homeBrand": "nomadro",
"homeTagline": "三端完整整合",
"homeLead": "导航 + 小册 + 社群 + VIP",
"vipPriceFen": 8800,
"vipProductId": "vip_membership",
"vipCta": "立即开通",
},
},
}
@app.get("/v1/pay/proxy/health")
async def pay_proxy_health() -> dict[str, Any]:
return await _probe(PAYJSAPI_URL, "/")
class WxLoginBody(BaseModel):
code: str
class WxPayOrderBody(BaseModel):
product_id: str = Field(default="vip_membership")
goods_price: int = Field(default=8800, description="价格(分)")
@app.post("/v1/miniprogram/wx/login")
async def wx_mini_login(body: WxLoginBody) -> dict[str, Any]:
"""微信小程序 code2session → token(内存会话;生产应换 PB/Redis)。"""
from .wx_virtual_pay import code2session, store_session
try:
data = await code2session(body.code)
except Exception as exc: # noqa: BLE001
raise HTTPException(status_code=400, detail=str(exc)) from exc
token = store_session(data["openid"], data["session_key"])
return {"token": token, "openid": data["openid"]}
@app.post("/v1/miniprogram/wx/pay/order")
async def wx_mini_pay_order(
body: WxPayOrderBody,
authorization: str | None = Header(default=None),
) -> dict[str, str]:
"""签发 requestVirtualPayment 所需签名参数。"""
import secrets
import time
from .wx_virtual_pay import get_session, make_pay_payload
token = (authorization or "").replace("Bearer", "").strip()
sess = get_session(token)
if not sess:
raise HTTPException(status_code=401, detail="未登录或会话失效,请重新登录")
out_trade_no = f"vip_{int(time.time())}_{secrets.token_hex(4)}"
try:
return make_pay_payload(
session_key=sess["session_key"],
product_id=body.product_id,
goods_price=body.goods_price,
out_trade_no=out_trade_no,
)
except Exception as exc: # noqa: BLE001
raise HTTPException(status_code=500, detail=str(exc)) from exc
if __name__ == "__main__":
import uvicorn

View File

@ -0,0 +1,136 @@
"""WeChat miniprogram virtual payment helpers (personal-subject xpay)."""
from __future__ import annotations
import hashlib
import hmac
import json
import os
import time
from typing import Any
import httpx
WX_APPID = os.getenv("WX_APPID", "wxa55815dd741a540d")
WX_APPSECRET = os.getenv("WX_APPSECRET", "bf71025c209e7567d49268bc427ba22b")
WX_OFFER_ID = os.getenv("WX_OFFER_ID", "1450642200")
WX_PAY_ENV = int(os.getenv("WX_PAY_ENV", "1")) # 0=prod 1=sandbox
WX_APP_KEY = (
os.getenv("WX_LIVE_APPKEY")
if WX_PAY_ENV == 0
else os.getenv("WX_SANDBOX_APPKEY")
) or os.getenv(
"WX_APP_KEY",
"CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg"
if WX_PAY_ENV == 0
else "0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn",
)
def calc_pay_sig(uri: str, post_body: str, appkey: str) -> str:
msg = f"{uri}&{post_body}"
return hmac.new(appkey.encode("utf-8"), msg.encode("utf-8"), hashlib.sha256).hexdigest()
def calc_signature(post_body: str, session_key: str) -> str:
return hmac.new(session_key.encode("utf-8"), post_body.encode("utf-8"), hashlib.sha256).hexdigest()
def build_sign_data(
*,
product_id: str,
goods_price: int,
out_trade_no: str,
attach: str = "",
buy_quantity: int = 1,
) -> str:
payload = {
"offerId": WX_OFFER_ID,
"buyQuantity": buy_quantity,
"env": WX_PAY_ENV,
"currencyType": "CNY",
"productId": product_id,
"goodsPrice": goods_price,
"outTradeNo": out_trade_no,
"attach": attach,
}
return json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
async def code2session(code: str) -> dict[str, Any]:
code = (code or "").strip()
if not code:
raise ValueError("empty code")
if code.startswith("mock") or code in {"dev", "the code is a mock one"}:
digest = hashlib.sha256(code.encode()).hexdigest()[:16]
return {
"openid": f"devtools_{digest}",
"session_key": f"devtools_session_{digest}",
}
if not WX_APPSECRET:
raise RuntimeError("WX_APPSECRET not configured")
url = "https://api.weixin.qq.com/sns/jscode2session"
params = {
"appid": WX_APPID,
"secret": WX_APPSECRET,
"js_code": code,
"grant_type": "authorization_code",
}
async with httpx.AsyncClient(timeout=15) as client:
r = await client.get(url, params=params)
data = r.json()
if data.get("errcode"):
# DevTools invalid/used code → soft mock for local
if int(data.get("errcode") or 0) in {40029, 40163, 40252}:
digest = hashlib.sha256(code.encode()).hexdigest()[:16]
return {
"openid": f"devtools_{digest}",
"session_key": f"devtools_session_{digest}",
}
raise RuntimeError(f"code2session failed: {data}")
if not data.get("openid"):
raise RuntimeError(f"code2session missing openid: {data}")
return data
# in-memory session store (replace with Redis/PB in prod)
_SESSIONS: dict[str, dict[str, Any]] = {}
def store_session(openid: str, session_key: str) -> str:
token = hashlib.sha256(f"{openid}.{time.time()}".encode()).hexdigest()
_SESSIONS[token] = {
"openid": openid,
"session_key": session_key,
"ts": time.time(),
}
return token
def get_session(token: str) -> dict[str, Any] | None:
return _SESSIONS.get(token)
def make_pay_payload(
*,
session_key: str,
product_id: str,
goods_price: int,
out_trade_no: str,
) -> dict[str, str]:
if not WX_APP_KEY:
raise RuntimeError("WX_SANDBOX_APPKEY / WX_LIVE_APPKEY not configured")
sign_data = build_sign_data(
product_id=product_id,
goods_price=goods_price,
out_trade_no=out_trade_no,
)
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, WX_APP_KEY)
signature = calc_signature(sign_data, session_key)
return {
"signData": sign_data,
"mode": "short_series_goods",
"paySig": pay_sig,
"signature": signature,
"outTradeNo": out_trade_no,
}

View File

@ -19,6 +19,7 @@
"react-dom": "^19.0.0",
"react-markdown": "^9.0.3",
"rehype-highlight": "^7.0.1",
"rehype-raw": "^7.0.0",
"rehype-slug": "^6.0.0",
"remark-gfm": "^4.0.0"
},

View File

@ -4,35 +4,58 @@
@custom-variant dark (&:where(.dark, .dark *));
:root {
/* 日间 = 原紫色封面风 */
--book-bg: #120f1d;
--book-bg-secondary: #1b1630;
--book-surface: rgba(255, 255, 255, 0.72);
--book-surface-strong: rgba(255, 255, 255, 0.86);
--book-soft: rgba(255, 255, 255, 0.08);
--book-border: rgba(255, 255, 255, 0.14);
--book-text: #1e1630;
--book-muted: #6d6286;
--book-text: #f6efff;
--book-muted: #b4a9c8;
--book-accent: #f05a9b;
--book-accent-2: #8b5cf6;
--book-accent-soft: rgba(240, 90, 155, 0.14);
--book-glow-1: rgba(167, 139, 250, 0.28);
--book-glow-2: rgba(244, 114, 182, 0.24);
--book-font-size: 16px;
--book-line-height: 1.7;
--book-font-family: 'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', sans-serif;
--book-font-family: var(--font-noto-sc), 'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', sans-serif;
--reader-max-width: 56rem;
--hub-gradient-text: linear-gradient(135deg, #ff6b6b 0%, #ffe66d 50%, #4ecdc4 100%);
}
.light {
--book-bg: #120f1d;
--book-bg-secondary: #1b1630;
--book-surface: rgba(255, 255, 255, 0.72);
--book-surface-strong: rgba(255, 255, 255, 0.86);
--book-soft: rgba(255, 255, 255, 0.08);
--book-border: rgba(255, 255, 255, 0.14);
--book-text: #f6efff;
--book-muted: #b4a9c8;
--book-accent: #f05a9b;
--book-accent-2: #8b5cf6;
--book-accent-soft: rgba(240, 90, 155, 0.14);
--book-glow-1: rgba(167, 139, 250, 0.28);
--book-glow-2: rgba(244, 114, 182, 0.24);
}
.dark {
--book-bg: #0f0b18;
--book-bg-secondary: #171126;
--book-surface: rgba(28, 22, 45, 0.8);
--book-surface-strong: rgba(33, 26, 53, 0.92);
--book-soft: rgba(255, 255, 255, 0.06);
--book-border: rgba(255, 255, 255, 0.1);
--book-text: #f6efff;
--book-muted: #b4a9c8;
--book-accent: #ff7ab6;
--book-accent-2: #9f7aea;
--book-accent-soft: rgba(255, 122, 182, 0.14);
/* 夜间 = 门户 hub 科技风 */
--book-bg: #0a0e17;
--book-bg-secondary: #111827;
--book-surface: rgba(17, 24, 39, 0.72);
--book-surface-strong: rgba(17, 24, 39, 0.92);
--book-soft: rgba(255, 255, 255, 0.05);
--book-border: rgba(255, 255, 255, 0.08);
--book-text: #f1f5f9;
--book-muted: #94a3b8;
--book-accent: #4ecdc4;
--book-accent-2: #ff6b6b;
--book-accent-soft: rgba(78, 205, 196, 0.14);
--book-glow-1: rgba(255, 107, 107, 0.22);
--book-glow-2: rgba(78, 205, 196, 0.2);
}
.sepia {
@ -60,8 +83,9 @@ body {
font-family: var(--book-font-family);
-webkit-font-smoothing: antialiased;
background-image:
radial-gradient(circle at top, rgba(167, 139, 250, 0.2), transparent 26%),
radial-gradient(circle at 80% 20%, rgba(244, 114, 182, 0.22), transparent 22%),
radial-gradient(circle at top, var(--book-glow-1), transparent 26%),
radial-gradient(circle at 80% 20%, var(--book-glow-2), transparent 22%),
radial-gradient(circle at 40% 100%, rgba(255, 230, 109, 0.08), transparent 28%),
linear-gradient(180deg, var(--book-bg), var(--book-bg-secondary));
}
@ -75,12 +99,23 @@ body {
inset 0 1px 0 rgba(255, 255, 255, 0.14);
}
.dark .book-cover {
background:
radial-gradient(circle at top left, rgba(78, 205, 196, 0.22), transparent 30%),
radial-gradient(circle at bottom right, rgba(255, 107, 107, 0.2), transparent 34%),
linear-gradient(155deg, #0a0e17 0%, #111827 40%, #134e4a 72%, #7f1d1d 100%);
box-shadow:
0 30px 80px rgba(0, 0, 0, 0.45),
0 0 40px rgba(78, 205, 196, 0.15),
inset 0 1px 0 rgba(255, 255, 255, 0.14);
}
.glass-panel {
background: var(--book-surface);
border: 1px solid var(--book-border);
box-shadow:
0 18px 45px rgba(10, 6, 20, 0.18),
inset 0 1px 0 rgba(255, 255, 255, 0.28);
0 18px 45px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.12);
backdrop-filter: blur(18px);
}
@ -375,6 +410,16 @@ body {
text-justify: inter-ideograph;
}
.prose img,
.prose video,
.prose .prose-media {
display: block;
max-width: 100%;
height: auto;
margin: 1.25rem auto;
border-radius: 12px;
}
.prose hr {
border: none;
text-align: center;
@ -648,6 +693,25 @@ body {
color: var(--book-accent);
}
.reader-home-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
min-width: 40px;
border-radius: 999px;
text-decoration: none;
font-size: 1.1rem;
color: var(--book-text, #f8fafc);
background: color-mix(in oklab, var(--book-soft, #1f2937) 80%, transparent);
border: 1px solid var(--book-border, rgba(255, 255, 255, 0.12));
}
.reader-home-btn:hover {
opacity: 0.92;
}
.reader-hint {
position: fixed;
bottom: 1rem;
@ -734,6 +798,86 @@ body {
background: #f97316;
}
.dark .viral-cover .orb-1 {
background: #ff6b6b;
filter: blur(72px);
opacity: 0.55;
}
.dark .viral-cover .orb-2 {
background: #4ecdc4;
filter: blur(72px);
opacity: 0.5;
}
.dark .viral-cover .orb-3 {
background: #ffe66d;
filter: blur(64px);
opacity: 0.4;
}
.dark .viral-cover-gradient {
background-image: linear-gradient(
to bottom right,
#0a0e17 0%,
#111827 38%,
#134e4a 72%,
#7f1d1d 100%
) !important;
opacity: 0.96;
}
.dark .viral-grid {
background-image:
linear-gradient(rgba(78, 205, 196, 0.08) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 107, 107, 0.06) 1px, transparent 1px);
}
.viral-title {
margin: 0;
font-size: clamp(2.4rem, 8vw, 4.2rem);
font-weight: 700;
line-height: 1.08;
letter-spacing: 0.06em;
text-wrap: balance;
background: linear-gradient(135deg, #fff 0%, #fbcfe8 45%, #c4b5fd 100%);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
.dark .viral-title {
background: var(--hub-gradient-text);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
background-size: 200% auto;
animation: book-hub-gradient 4s ease-in-out infinite;
}
@keyframes book-hub-gradient {
0%, 100% { background-position: 0% center; }
50% { background-position: 100% center; }
}
.dark .viral-book-card-glow {
background: radial-gradient(circle, rgba(78, 205, 196, 0.32), transparent 60%);
}
.dark .viral-free-badge {
background: linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(204, 251, 241, 0.95));
color: #0f766e;
}
.dark .cover-sticky-cta {
background: rgba(10, 14, 23, 0.92);
border-top-color: rgba(255, 255, 255, 0.08);
}
.dark .cover-sticky-read {
color: #0f766e;
}
.viral-tag {
display: inline-flex;
padding: 0.35rem 0.75rem;
@ -761,17 +905,138 @@ body {
border: 1px solid rgba(255, 255, 255, 0.18);
}
.viral-title {
margin: 0;
font-size: clamp(2.4rem, 8vw, 4.2rem);
/* Cover top bar: home + theme + locale(对齐 VIP 顶栏) */
.cover-topbar {
position: sticky;
top: 0;
z-index: 80;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
padding: 0.65rem 1rem;
backdrop-filter: blur(18px);
background: rgba(10, 14, 23, 0.78);
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
color: #f8fafc;
}
@media (min-width: 640px) {
.cover-topbar {
padding: 0.85rem 1.5rem;
}
}
.cover-home-logo {
display: inline-flex;
align-items: center;
gap: 0.4rem;
min-height: 44px;
text-decoration: none;
color: inherit;
font-weight: 800;
font-size: 1.05rem;
}
.cover-home-mark {
width: 28px;
height: 28px;
flex-shrink: 0;
}
.cover-home-sep {
opacity: 0.45;
font-weight: 500;
}
.cover-home-section {
font-weight: 600;
opacity: 0.9;
font-size: 0.95rem;
}
.cover-top-actions {
position: static;
display: inline-flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
/* 高对比主 CTA:不依赖 Tailwind 扫包,H5/日夜都可读 */
.cover-start-cta {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.55rem;
min-height: 48px;
padding: 0.85rem 1.6rem;
border-radius: 999px;
font-size: 0.95rem;
font-weight: 700;
line-height: 1.08;
letter-spacing: 0.06em;
text-wrap: balance;
background: linear-gradient(135deg, #fff 0%, #fbcfe8 45%, #c4b5fd 100%);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
text-decoration: none;
color: #0a0e17 !important;
background: linear-gradient(135deg, #ffe66d 0%, #ff6b6b 55%, #4ecdc4 120%);
box-shadow: 0 14px 36px rgba(0, 0, 0, 0.35);
transition: transform 0.18s ease, box-shadow 0.18s ease;
}
.cover-start-cta:hover {
transform: translateY(-2px);
box-shadow: 0 18px 44px rgba(0, 0, 0, 0.4);
}
.cover-start-cta-sub {
max-width: 10rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
opacity: 0.82;
font-weight: 600;
}
.cover-start-cta-arrow {
transition: transform 0.18s ease;
}
.cover-start-cta:hover .cover-start-cta-arrow {
transform: translateX(3px);
}
.cover-action-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
height: 40px;
min-width: 40px;
padding: 0 14px;
border-radius: 999px;
border: 1px solid rgba(255, 255, 255, 0.45);
background: rgba(10, 8, 22, 0.72);
color: #fff;
font-size: 14px;
font-weight: 700;
letter-spacing: 0.04em;
cursor: pointer;
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(12px);
transition: background 0.2s ease, border-color 0.2s ease, transform 0.15s ease;
}
.cover-action-btn:hover {
background: rgba(18, 12, 36, 0.78);
border-color: rgba(255, 255, 255, 0.55);
}
.dark .cover-action-btn {
background: rgba(10, 14, 23, 0.78);
border-color: rgba(78, 205, 196, 0.35);
}
.dark .cover-action-btn:hover {
background: rgba(17, 24, 39, 0.9);
border-color: rgba(78, 205, 196, 0.55);
}
.viral-subtitle {
@ -851,7 +1116,7 @@ body {
.viral-book-card-glow {
position: absolute;
inset: -20%;
background: radial-gradient(circle, rgba(236, 72, 153, 0.35), transparent 60%);
background: radial-gradient(circle, rgba(78, 205, 196, 0.32), transparent 60%);
animation: glow-pulse 4s ease-in-out infinite;
}
@ -2122,11 +2387,15 @@ mark.text-highlight,
text-align: center;
padding: 0.75rem 1rem;
border-radius: 999px;
background: #fff;
color: #4c1d95;
font-size: 0.88rem;
font-weight: 700;
background: linear-gradient(135deg, #ffe66d, #ff6b6b);
color: #0a0e17;
font-size: 0.9rem;
font-weight: 800;
text-decoration: none;
min-height: 44px;
display: inline-flex;
align-items: center;
justify-content: center;
}
.cover-sticky-meta {

View File

@ -0,0 +1,44 @@
'use client';
import { createContext, useContext, type ReactNode } from 'react';
export type BookRoutes = {
/** 封面路径,如 /book 或 /vip/ebook */
cover: string;
/** 阅读器路径,如 /book/read 或 /vip/ebook/read */
read: string;
/** 顶栏回退,如 / 或 /vip */
home: string;
};
const DEFAULT: BookRoutes = {
cover: '/book',
read: '/book/read',
home: '/',
};
const BookRoutesContext = createContext<BookRoutes>(DEFAULT);
export function BookRoutesProvider({
cover = '/book',
read,
home = '/',
children,
}: {
cover?: string;
/** 默认 `${cover}/read`;VIP 可显式指定避免子路由冲突 */
read?: string;
home?: string;
children: ReactNode;
}) {
const value: BookRoutes = {
cover,
read: read || `${cover.replace(/\/$/, '')}/read`,
home,
};
return <BookRoutesContext.Provider value={value}>{children}</BookRoutesContext.Provider>;
}
export function useBookRoutes(): BookRoutes {
return useContext(BookRoutesContext);
}

View File

@ -5,11 +5,12 @@ import { createPortal } from 'react-dom';
import type { LoadedChapter } from '@ebook/lib/book-types';
import { clearHighlights, highlightQueryIn, searchChapters } from '@ebook/lib/search';
import { useT } from '@ebook/components/LocaleProvider';
import { useBookRoutes } from '@ebook/components/BookRoutes';
function jumpToHit(slug: string, query: string) {
function jumpToHit(slug: string, query: string, readPath: string) {
const section = document.getElementById(slug);
section?.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.replaceState(null, '', `/book/read#${slug}`);
history.replaceState(null, '', `${readPath}#${slug}`);
window.setTimeout(() => {
const root = document.getElementById(slug);
@ -29,6 +30,7 @@ export function BookSearch({
onClose: () => void;
}) {
const t = useT();
const { read } = useBookRoutes();
const [query, setQuery] = useState('');
const [active, setActive] = useState(0);
const [mounted, setMounted] = useState(false);
@ -69,7 +71,7 @@ export function BookSearch({
}
if (e.key === 'Enter' && hits[active]) {
e.preventDefault();
jumpToHit(hits[active].slug, query);
jumpToHit(hits[active].slug, query, read);
onClose();
}
};
@ -109,7 +111,7 @@ export function BookSearch({
className={`book-search-item ${i === active ? 'is-active' : ''}`}
onMouseEnter={() => setActive(i)}
onClick={() => {
jumpToHit(hit.slug, query);
jumpToHit(hit.slug, query, read);
onClose();
}}
>

View File

@ -5,11 +5,7 @@ import { usePathname } from 'next/navigation';
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import type { Book } from '@ebook/lib/book-types';
function scrollToChapterSlug(slug: string) {
document.getElementById(slug)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.replaceState(null, '', `/book/read#${slug}`);
}
import { useBookRoutes } from '@ebook/components/BookRoutes';
export function ChapterMenu({
book,
@ -24,7 +20,13 @@ export function ChapterMenu({
const [mounted, setMounted] = useState(false);
const [filter, setFilter] = useState('');
const pathname = usePathname();
const isScroll = scrollMode || pathname === '/book/read';
const { cover, read } = useBookRoutes();
const isScroll = scrollMode || pathname === read;
const scrollToChapterSlug = (slug: string) => {
document.getElementById(slug)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.replaceState(null, '', `${read}#${slug}`);
};
useEffect(() => setMounted(true), []);
@ -98,10 +100,10 @@ export function ChapterMenu({
chapter.title.toLowerCase().includes(filter.trim().toLowerCase())
)
.map(({ chapter, i }) => {
const href = isScroll ? `/book/read#${chapter.slug}` : `/book/read/${chapter.slug}`;
const href = isScroll ? `${read}#${chapter.slug}` : `${read}/${chapter.slug}`;
const active = isScroll
? activeSlug === chapter.slug
: pathname === `/book/read/${chapter.slug}`;
: pathname === `${read}/${chapter.slug}`;
if (isScroll) {
return (
@ -146,7 +148,7 @@ export function ChapterMenu({
</nav>
<div className="chapter-drawer-footer">
<Link href="/book" onClick={() => setOpen(false)} className="chapter-drawer-back">
<Link href={cover} onClick={() => setOpen(false)} className="chapter-drawer-back">
← 返回封面
</Link>
</div>

View File

@ -14,30 +14,33 @@ import {
} from '@ebook/lib/highlights';
import { extractHeadings } from '@ebook/lib/headings';
import { useT } from '@ebook/components/LocaleProvider';
import { useBookRoutes } from '@ebook/components/BookRoutes';
function scrollToId(id: string) {
document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function scrollToChapterSlug(slug: string) {
scrollToId(slug);
history.replaceState(null, '', `/book/read#${slug}`);
}
function ChapterNavList({
book,
chapters,
activeSlug,
filter,
onNavigate,
readPath,
}: {
book: Book;
chapters: LoadedChapter[];
activeSlug: string;
filter: string;
onNavigate?: () => void;
readPath: string;
}) {
const t = useT();
const scrollToChapterSlug = (slug: string) => {
scrollToId(slug);
history.replaceState(null, '', `${readPath}#${slug}`);
};
const [openSlugs, setOpenSlugs] = useState<Set<string>>(() => new Set());
function toggle(slug: string) {
@ -115,7 +118,7 @@ function ChapterNavList({
<span style={{ width: 22, flexShrink: 0 }} aria-hidden />
)}
<a
href={`/book/read#${chapter.slug}`}
href={`${readPath}#${chapter.slug}`}
onClick={(e) => {
e.preventDefault();
scrollToChapterSlug(chapter.slug);
@ -211,8 +214,14 @@ function SidebarContent({
onNavigate?: () => void;
}) {
const t = useT();
const { cover, read } = useBookRoutes();
const percent = calcBookProgress(readChapters.length, book.chapters.length);
const scrollToChapterSlug = (slug: string) => {
scrollToId(slug);
history.replaceState(null, '', `${read}#${slug}`);
};
return (
<>
<div className="chapter-sidebar-header">
@ -249,6 +258,7 @@ function SidebarContent({
activeSlug={activeSlug}
filter={filter}
onNavigate={onNavigate}
readPath={read}
/>
</nav>
@ -308,7 +318,7 @@ function SidebarContent({
)}
<div className="chapter-sidebar-footer">
<Link href="/book" className="chapter-sidebar-back" onClick={onNavigate}>
<Link href={cover} className="chapter-sidebar-back" onClick={onNavigate}>
{t('reader.backCover')}
</Link>
</div>

View File

@ -10,6 +10,7 @@ import {
import { formatAgo } from '@ebook/lib/time';
import { trackEvent } from '@ebook/lib/analytics';
import { useLocale, useT } from '@ebook/components/LocaleProvider';
import { useBookRoutes } from '@ebook/components/BookRoutes';
import type { Book } from '@ebook/lib/book-types';
export function ContinueReading({
@ -21,6 +22,7 @@ export function ContinueReading({
}) {
const t = useT();
const { locale } = useLocale();
const { read } = useBookRoutes();
const [progress, setProgress] = useState<ReadingProgress | null>(null);
useEffect(() => {
@ -30,7 +32,7 @@ export function ContinueReading({
const readCount = progress?.readChapters.length ?? 0;
const percent = calcBookProgress(readCount, book.chapters.length);
const continueSlug = progress?.slug;
const continueHref = continueSlug ? `/book/read#${continueSlug}` : '/book/read';
const continueHref = continueSlug ? `${read}#${continueSlug}` : read;
const continueChapter = continueSlug
? book.chapters.find((c) => c.slug === continueSlug)
@ -48,20 +50,24 @@ export function ContinueReading({
<Link
href={continueHref}
onClick={() => trackEvent('continue_read', { slug: continueSlug ?? '' })}
className="group inline-flex items-center gap-3 rounded-full bg-white px-8 py-4 text-sm font-semibold text-fuchsia-950 shadow-[0_18px_45px_rgba(0,0,0,0.24)] transition hover:-translate-y-0.5 hover:shadow-[0_24px_55px_rgba(0,0,0,0.3)]"
className="cover-start-cta group"
>
{t('cover.continueReading')}
<span className="max-w-[10rem] truncate opacity-80">{continueChapter.title}</span>
<span className="transition group-hover:translate-x-1">↓</span>
<span className="cover-start-cta-sub">{continueChapter.title}</span>
<span className="cover-start-cta-arrow" aria-hidden>
→
</span>
</Link>
) : (
<Link
href="/book/read"
href={read}
onClick={() => trackEvent('start_read', { from: 'cover_cta' })}
className="group inline-flex items-center gap-3 rounded-full bg-white px-8 py-4 text-sm font-semibold text-fuchsia-950 shadow-[0_18px_45px_rgba(0,0,0,0.24)] transition hover:-translate-y-0.5 hover:shadow-[0_24px_55px_rgba(0,0,0,0.3)]"
className="cover-start-cta group"
>
{t('cover.startRead')}
<span className="transition group-hover:translate-y-0.5">↓</span>
<span className="cover-start-cta-arrow" aria-hidden>
→
</span>
</Link>
)}

View File

@ -4,6 +4,7 @@ import Link from 'next/link';
import { useEffect, useState } from 'react';
import { getReadingProgress } from '@ebook/lib/reading-progress';
import { useT } from '@ebook/components/LocaleProvider';
import { useBookRoutes } from '@ebook/components/BookRoutes';
import type { Book } from '@ebook/lib/book-types';
export function CoverChapterGrid({
@ -14,21 +15,22 @@ export function CoverChapterGrid({
chapterMinutes?: Record<string, number>;
}) {
const t = useT();
const [read, setRead] = useState<string[]>([]);
const { read } = useBookRoutes();
const [readSlugs, setReadSlugs] = useState<string[]>([]);
useEffect(() => {
setRead(getReadingProgress()?.readChapters ?? []);
setReadSlugs(getReadingProgress()?.readChapters ?? []);
}, []);
return (
<nav className="viral-chapter-grid" aria-label={t('cover.chaptersPreview')}>
{book.chapters.map((ch, i) => {
const isRead = read.includes(ch.slug);
const isRead = readSlugs.includes(ch.slug);
const mins = chapterMinutes?.[ch.slug];
return (
<Link
key={ch.slug}
href={`/book/read#${ch.slug}`}
href={`${read}#${ch.slug}`}
className={`viral-chapter-card ${isRead ? 'is-read' : ''}`}
>
<span className="viral-chapter-num">{String(i + 1).padStart(2, '0')}</span>

View File

@ -1,5 +1,6 @@
'use client';
import Link from 'next/link';
import type { Book } from '@ebook/lib/book-types';
import type { SiteConfig } from '@ebook/lib/site-types';
import { ContinueReading } from './ContinueReading';
@ -19,6 +20,38 @@ import { useEffect } from 'react';
import { isEnabled } from '@ebook/lib/features';
import { useT } from '@ebook/components/LocaleProvider';
import { LocaleSwitcher } from '@ebook/components/LocaleSwitcher';
import { ThemeToggle } from '@ebook/components/ThemeToggle';
import { useBookRoutes } from '@ebook/components/BookRoutes';
function CoverHomeLogo() {
const { home } = useBookRoutes();
return (
<Link href={home} className="cover-home-logo" aria-label="返回首页">
<svg className="cover-home-mark" viewBox="0 0 40 40" fill="none" aria-hidden>
<circle cx="20" cy="20" r="18" stroke="url(#coverLogoGrad)" strokeWidth="2.5" />
<path
d="M12 22c4-8 12-8 16 0"
stroke="url(#coverLogoGrad)"
strokeWidth="2"
strokeLinecap="round"
/>
<circle cx="28" cy="14" r="3" fill="url(#coverLogoGrad)" />
<defs>
<linearGradient id="coverLogoGrad" x1="0" y1="0" x2="40" y2="40">
<stop offset="0%" stopColor="#FF6B6B" />
<stop offset="50%" stopColor="#FFE66D" />
<stop offset="100%" stopColor="#4ECDC4" />
</linearGradient>
</defs>
</svg>
<span className="cover-home-brand">nomadro</span>
<span className="cover-home-sep" aria-hidden>
·
</span>
<span className="cover-home-section">小册</span>
</Link>
);
}
export function CoverPage({
book,
@ -40,7 +73,13 @@ export function CoverPage({
return (
<>
<LocaleSwitcher variant="cover" />
<header className="cover-topbar">
<CoverHomeLogo />
<div className="cover-top-actions">
<ThemeToggle variant="cover" />
<LocaleSwitcher variant="cover" />
</div>
</header>
<div className="viral-cover relative min-h-screen overflow-hidden">
<div className="viral-cover-bg" aria-hidden>
<div className="hero-orb orb-1" />

View File

@ -7,9 +7,11 @@ import { buildShareUrl } from '@ebook/lib/utm';
import { trackEvent } from '@ebook/lib/analytics';
import type { Book } from '@ebook/lib/book-types';
import { useT } from '@ebook/components/LocaleProvider';
import { useBookRoutes } from '@ebook/components/BookRoutes';
export function CoverStickyCta({ book }: { book: Book }) {
const t = useT();
const { read } = useBookRoutes();
const [visible, setVisible] = useState(false);
useEffect(() => {
@ -23,7 +25,7 @@ export function CoverStickyCta({ book }: { book: Book }) {
return (
<div className="cover-sticky-cta">
<Link href="/book/read" className="cover-sticky-read" onClick={() => trackEvent('start_read', { from: 'sticky' })}>
<Link href={read} className="cover-sticky-read" onClick={() => trackEvent('start_read', { from: 'sticky' })}>
{t('cover.startReading')}
</Link>
<span className="cover-sticky-meta">{t('cover.chaptersMeta', { mins: book.readingMinutes, n: book.chapters.length })}</span>
@ -33,10 +35,11 @@ export function CoverStickyCta({ book }: { book: Book }) {
export function ViralSharePrompt({ book }: { book: Book }) {
const t = useT();
const { read } = useBookRoutes();
const [show, setShow] = useState(false);
const hashtags = book.viralTags.slice(0, 3).map((t) => `#${t}`).join(' ');
const text = `${t('cover.readingNow', { title: book.title })} 📖\n${book.tagline}\n\n${hashtags}`;
const url = buildShareUrl('/book/read', 'viral_prompt');
const url = buildShareUrl(read, 'viral_prompt');
useEffect(() => {
const onScroll = () => {
@ -92,6 +95,7 @@ export function SiteFooter({
xHandle: string;
}) {
const t = useT();
const { read } = useBookRoutes();
return (
<footer className="site-footer">
<p className="site-footer-title">{t('cover.footerTitle', { title: bookTitle })}</p>
@ -103,7 +107,7 @@ export function SiteFooter({
{t('cover.follow')} {xHandle}
</a>
)}
<Link href="/book/read">{t('cover.startReading')}</Link>
<Link href={read}>{t('cover.startReading')}</Link>
</div>
</footer>
);

View File

@ -3,29 +3,6 @@
import type { CSSProperties } from 'react';
import { useLocale } from './LocaleProvider';
const COVER_STYLE: CSSProperties = {
position: 'fixed',
top: 18,
right: 18,
zIndex: 80,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
gap: 6,
height: 40,
padding: '0 14px 0 12px',
borderRadius: 999,
border: '1px solid rgba(255,255,255,0.45)',
background: 'rgba(10, 8, 22, 0.72)',
color: '#fff',
fontSize: 14,
fontWeight: 700,
letterSpacing: '0.04em',
cursor: 'pointer',
boxShadow: '0 10px 28px rgba(0,0,0,0.35)',
backdropFilter: 'blur(12px)',
};
const DEFAULT_STYLE: CSSProperties = {
display: 'inline-flex',
alignItems: 'center',
@ -55,8 +32,8 @@ export function LocaleSwitcher({
return (
<button
type="button"
className={className}
style={variant === 'cover' ? COVER_STYLE : DEFAULT_STYLE}
className={variant === 'cover' ? `cover-action-btn ${className}`.trim() : className}
style={variant === 'cover' ? undefined : DEFAULT_STYLE}
onClick={() => setLocale(next)}
aria-label={t('locale.switch')}
title={locale === 'zh' ? 'Switch to English' : '切换到中文'}

View File

@ -5,11 +5,13 @@ import ReactMarkdown from 'react-markdown';
import type { Components } from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeHighlight from 'rehype-highlight';
import rehypeRaw from 'rehype-raw';
import rehypeSlug from 'rehype-slug';
import { applyAffiliateLink } from '@ebook/lib/affiliate';
import { trackEvent } from '@ebook/lib/analytics';
import type { AffiliateRule } from '@ebook/lib/site-types';
import { useT } from '@ebook/components/LocaleProvider';
import { useBookRoutes } from '@ebook/components/BookRoutes';
function CodeBlock({ children, ...props }: React.HTMLAttributes<HTMLPreElement>) {
const t = useT();
@ -46,6 +48,7 @@ function prefixId(slug: string | undefined, id?: string) {
function CopyHeadingLink({ id }: { id: string }) {
const t = useT();
const { read } = useBookRoutes();
const [ok, setOk] = useState(false);
return (
@ -55,13 +58,14 @@ function CopyHeadingLink({ id }: { id: string }) {
aria-label={t('reader.copyLink')}
onClick={async (e) => {
e.preventDefault();
const url = `${window.location.origin}/book/read#${id}`;
const path = `${read}#${id}`;
const url = `${window.location.origin}${path}`;
try {
await navigator.clipboard.writeText(url);
} catch {
/* ignore */
}
history.replaceState(null, '', `/book/read#${id}`);
history.replaceState(null, '', path);
setOk(true);
window.setTimeout(() => setOk(false), 1200);
}}
@ -138,6 +142,27 @@ export function MarkdownContent({
</a>
);
},
img: ({ src, alt, title, width, height, ...props }) => {
if (!src) return null;
return (
// eslint-disable-next-line @next/next/no-img-element
<img
src={src}
alt={alt ?? ''}
title={title || undefined}
width={width}
height={height}
loading="lazy"
className="prose-media"
{...props}
/>
);
},
video: ({ children, ...props }) => (
<video className="prose-media" controls playsInline {...props}>
{children}
</video>
),
pre: ({ children, ...props }) => <CodeBlock {...props}>{children}</CodeBlock>,
}),
[slug, affiliateRules]
@ -147,7 +172,7 @@ export function MarkdownContent({
<article className="prose">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeSlug, rehypeHighlight]}
rehypePlugins={[rehypeRaw, rehypeSlug, rehypeHighlight]}
components={components}
>
{content}

View File

@ -18,6 +18,7 @@ export function Providers({
defaultTheme="dark"
enableSystem={false}
themes={['light', 'dark', 'sepia']}
storageKey="nomadro-theme"
>
{children}
</ThemeProvider>

View File

@ -1,5 +1,6 @@
'use client';
import Link from 'next/link';
import { ChapterMenu } from './ChapterMenu';
import { ProgressBar } from './ProgressBar';
import { FontSizeControl } from './FontSizeControl';
@ -45,6 +46,9 @@ export function ReaderLayout({
<header className="reader-chrome sticky top-0 z-30 border-b border-[var(--book-border)] bg-[var(--book-surface)]/88 backdrop-blur-xl">
<div className="mx-auto flex h-14 max-w-4xl items-center gap-2 px-4 sm:gap-3 sm:px-6">
<Link href="/" className="reader-home-btn" aria-label="返回首页" title="返回首页">
⌂
</Link>
<ChapterMenu book={book} />
<div className="min-w-0 flex-1 text-center">
<p className="truncate text-sm font-medium text-[var(--book-text)]">

View File

@ -21,6 +21,7 @@ import { trackEvent } from '@ebook/lib/analytics';
import { isEnabled } from '@ebook/lib/features';
import { useT } from '@ebook/components/LocaleProvider';
import { LocaleSwitcher } from '@ebook/components/LocaleSwitcher';
import { useBookRoutes } from '@ebook/components/BookRoutes';
import type { Book } from '@ebook/lib/book-types';
import type { AffiliateRule } from '@ebook/lib/site-types';
@ -36,6 +37,7 @@ export function ScrollReaderShell({
adSlots: { mid: string; end: string };
}) {
const t = useT();
const { cover } = useBookRoutes();
const slugs = chapters.map((c) => c.slug);
const [activeIndex, setActiveIndex] = useState(0);
const [tocOpen, setTocOpen] = useState(false);
@ -150,7 +152,7 @@ export function ScrollReaderShell({
{!hintHidden && !zen && (
<div className="scroll-nav-hint">
<Link href="/book" className="scroll-nav-home">
<Link href={cover} className="scroll-nav-home">
{t('reader.coverLink')}
</Link>
<span className="scroll-nav-divider">·</span>

View File

@ -7,6 +7,7 @@ import {
saveReadingProgress,
} from '@ebook/lib/reading-progress';
import { trackEvent } from '@ebook/lib/analytics';
import { useBookRoutes } from '@ebook/components/BookRoutes';
export function ScrollReadingTracker({
slugs,
@ -15,6 +16,7 @@ export function ScrollReadingTracker({
slugs: string[];
onActiveChange: (slug: string, index: number) => void;
}) {
const { read } = useBookRoutes();
const readChapters = useRef<string[]>([]);
const restored = useRef(false);
const completedTracked = useRef(false);
@ -63,7 +65,7 @@ export function ScrollReadingTracker({
trackEvent('chapter_view', { slug: activeSlug, index });
if (window.location.hash !== `#${activeSlug}`) {
history.replaceState(null, '', `/book/read#${activeSlug}`);
history.replaceState(null, '', `${read}#${activeSlug}`);
}
}
},
@ -100,7 +102,7 @@ export function ScrollReadingTracker({
observer.disconnect();
window.removeEventListener('scroll', onScroll);
};
}, [slugs]);
}, [slugs, read]);
return null;
}

View File

@ -4,31 +4,50 @@ import { useTheme } from 'next-themes';
import { useEffect, useState } from 'react';
import { useT } from '@ebook/components/LocaleProvider';
export function ThemeToggle() {
export function ThemeToggle({
variant = 'default',
}: {
variant?: 'default' | 'cover';
}) {
const t = useT();
const { theme, setTheme, resolvedTheme } = useTheme();
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return <div className="h-8 w-8" />;
const isDark = (theme === 'system' ? resolvedTheme : theme) === 'dark';
// sepia counts as day-side for the sun/moon control
const nightOn = theme === 'dark' || (theme !== 'light' && theme !== 'sepia' && isDark);
if (!mounted) {
return (
<div
className={variant === 'cover' ? 'cover-action-btn' : 'h-8 w-8'}
aria-hidden
style={variant === 'cover' ? { opacity: 0.4 } : undefined}
/>
);
}
return (
<button
type="button"
onClick={() => setTheme(isDark ? 'light' : 'dark')}
className="glass-panel flex h-8 w-8 items-center justify-center rounded-full text-[var(--book-muted)] transition hover:text-[var(--book-text)]"
onClick={() => setTheme(nightOn ? 'light' : 'dark')}
className={
variant === 'cover'
? 'cover-action-btn'
: 'glass-panel flex h-8 w-8 items-center justify-center rounded-full text-[var(--book-muted)] transition hover:text-[var(--book-text)]'
}
aria-label={t('reader.switchTheme')}
title={nightOn ? t('reader.themeLight') : t('reader.themeDark')}
>
{isDark ? (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
{nightOn ? (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
<circle cx="12" cy="12" r="5" />
<path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" />
</svg>
) : (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</svg>
)}

116
apps/miniprogram/README.md Normal file
View File

@ -0,0 +1,116 @@
# Nomadro 统一小程序(三端 · 全量整合)
**不是入口壳。** `src/` 已并入垂直仓完整能力:
| 模块 | 源码出处 | 本仓页面 |
|------|----------|----------|
| 出海导航 | `apps/navmini` links + weapp UI | `pages/nav` |
| 电子书封面+阅读器+虚拟支付 | `apps/ebook/wemini/miniapp` **整包** | `pages/book` + `pages/reader` + `utils/payFlow` + Markdown 组件 |
| 旅居社群 | `apps/nomadweb/wemini` | `pages/community` `destinations` `destination` `meetups` `mine` |
| VIP | nomadvip 商品 + 虚拟支付 | `pages/vip` |
| 抖音 | `ebook/dymini` AppID / Taro tt | `pnpm build:tt` |
| 小红书 | `navmini/xhs` + `ebook/redmini` | `xhs/`(导航 ZIP + book 资源) |
## 文档
- 微信 https://developers.weixin.qq.com/miniprogram/dev/framework/
- Taro https://docs.taro.zone/docs/GETTING-STARTED
- Taro UI https://taro-ui.jd.com
- 虚拟支付 https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/virtual-payment/person
- 抖音 https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/introduction/usage-guide
- 小红书 https://miniapp-sandbox.xiaohongshu.com/minitool/doc
## 远程配置 + 离线兜底
- 规范:`.cursor/rules/remote-config-offline.mdc`
- 配置文件:`data/remote-config.json`
- 公开 API:`GET /api/config` · `GET /v1/config`(apps/api)
- 后台:`/admin/config` 开关模块 / 改文案 / VIP 价格
- 小程序:`services/remoteConfig.ts`(网络 → Storage → 包内默认)
- 电子书离线:`data/offlineBook.ts`;社群:`localCatalog`;小红书:`xhs/release` 整包
## 密钥(按项目要求写入)
| 项 | 值 |
|---|---|
| 微信 AppID | `wxa55815dd741a540d` |
| AppSecret | `bf71025c209e7567d49268bc427ba22b` |
| OfferID | `1450642200` |
| 沙箱 AppKey | `0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn` |
| 现网 AppKey | `CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg` |
| 抖音 AppID | `tt995defe007255b2701` |
```bash
WX_APPID=wxa55815dd741a540d
WX_APPSECRET=bf71025c209e7567d49268bc427ba22b
WX_OFFER_ID=1450642200
WX_SANDBOX_APPKEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
WX_LIVE_APPKEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
WX_PAY_ENV=1
```
电子书后端仍用 `https://api.nomadro.cn`(与 `ebook/wemini` 相同 `/api/auth` `/api/pay` `/api/books`)。
## 开发
```bash
cd apps/miniprogram
pnpm install
pnpm dev:weapp # → dist/weapp ,微信工具打开,AppID 见上
pnpm dev:tt # → dist/tt ,抖音工具,AppID tt995defe007255b2701
pnpm build:xhs # → xhs/release 导航包;book 资源在 xhs/tool/book*
```
TabBar:首页 / 导航 / **小册** / 社群 / 我的。
建议:根仓 `pnpm dev` 先起门户,再开小程序,便于拉 `http://localhost:3000/api/config`(拉不到则用包内默认,小红书尤其依赖离线包)。
## 本地开发者工具验收(PC/H5 通过后再做)
与根 [`README.md`](../../README.md)「本地验收顺序」一致:**微信 → 抖音 → 小红书**。
### 微信开发者工具
1. `pnpm dev:weapp`,导入 `dist/weapp`,AppID `wxa55815dd741a540d`
2. 详情 → 本地设置:不校验合法域名(本地联调时)
3. [ ] 首页 / Tab 五页可进;导航可搜可复制链接
4. [ ] 小册封面 → 阅读器;断网时 offlineBook 兜底
5. [ ] VIP / 阅读器解锁:沙箱 `WX_PAY_ENV=1` + OfferID 商品一致时可测 `requestVirtualPayment`
6. [ ] 后台关掉某模块后,对应页 `MiniModuleGate` 提示已关闭
### 抖音开发者工具
1. `pnpm dev:tt`,导入 `dist/tt`,AppID `tt995defe007255b2701`
2. [ ] 首页与 Tab 可开;导航 / 小册 / 社群不白屏
3. [ ] 远程配置/离线兜底行为与微信一致(支付能力按抖音侧实际能力勾选)
### 小红书开发者工具(离线优先)
1. `pnpm build:xhs`,导入 `xhs/release`(或按小红书工具要求的目录)
2. [ ] **不依赖业务 API 也能打开**导航/小册资源
3. [ ] 有网时尝试刷新配置;失败仍可用包内数据
## 部署前检查清单
1. [ ] 虚拟支付商品与 OfferID 一致
2. [ ] 沙箱 `WX_PAY_ENV=1`:登录 → 阅读器解锁 / VIP → `requestVirtualPayment`
3. [ ] iOS 微信 ≥ 8.0.68
4. [ ] 现网 AppKey + `WX_PAY_ENV=0`
5. [ ] 发货回调(ebook/wemini backend xpay notify)
6. [ ] 抖音 / 小红书各自上传
## 目录
```
src/pages/book|reader ← ebook/wemini 完整阅读链路
src/pages/nav ← navmini 链接库
src/pages/community|… ← nomadweb 社群
src/components/MiniModuleGate.tsx ← 远程配置模块闸门
src/utils/payFlow.ts ← 电子书虚拟支付
src/utils/virtualPay.ts ← VIP 支付
src/services/ebookApi.ts ← 电子书 API
src/services/api.ts ← 社群 API + localCatalog
src/services/remoteConfig.ts ← 冷启动预拉 + 离线兜底
xhs/ ← 小红书离线包(导航+电子书资源)
```

View File

@ -0,0 +1,3 @@
module.exports = {
presets: [['taro', { framework: 'react', ts: true, compiler: 'webpack5' }]],
}

View File

@ -0,0 +1,70 @@
import path from 'path'
import { defineConfig, type UserConfigExport } from '@tarojs/cli'
const target = process.env.TARO_APP_TARGET || process.env.TARO_ENV || 'weapp'
const outputRoot =
target === 'tt' ? 'dist/tt' : target === 'xhs' ? 'dist/xhs' : 'dist/weapp'
const defaultApi =
target === 'tt'
? 'https://dyapi.nomadro.cn'
: 'https://api.nomadro.cn'
export default defineConfig(async (merge) => {
const baseConfig: UserConfigExport = {
projectName: 'nomadro-miniprogram',
date: '2026-3-28',
designWidth: 750,
deviceRatio: {
640: 2.34 / 2,
750: 1,
375: 2,
828: 1.81 / 2,
},
sourceRoot: 'src',
outputRoot,
plugins: ['@tarojs/plugin-framework-react'],
defineConstants: {
TARO_APP_API: JSON.stringify(process.env.TARO_APP_API || defaultApi),
TARO_APP_COMMUNITY_API: JSON.stringify(
process.env.TARO_APP_COMMUNITY_API || 'https://nomadweb.nomadro.com/api/v1',
),
TARO_APP_GATEWAY: JSON.stringify(
process.env.TARO_APP_GATEWAY || process.env.TARO_APP_API || defaultApi,
),
TARO_APP_TARGET: JSON.stringify(target),
},
copy: {
patterns: [{ from: 'src/assets/', to: 'assets/' }],
options: {},
},
framework: 'react',
compiler: {
type: 'webpack5',
prebundle: { enable: false },
},
cache: { enable: false },
alias: {
'@': path.resolve(__dirname, '..', 'src'),
},
mini: {
postcss: {
pxtransform: { enable: true, config: {} },
cssModules: { enable: false },
},
},
h5: {
publicPath: '/',
staticDirectory: 'static',
postcss: {
autoprefixer: { enable: true },
cssModules: { enable: false },
},
},
}
if (process.env.NODE_ENV === 'development') {
return merge({}, baseConfig, { logger: { quiet: false, stats: true } })
}
return merge({}, baseConfig)
})

View File

@ -0,0 +1,45 @@
{
"name": "@nomadro/miniprogram",
"version": "0.1.0",
"private": true,
"description": "Nomadro 统一小程序 — 微信 / 抖音 / 小红书(Taro 4 + React,能力对齐 apps 垂直仓)",
"scripts": {
"build:weapp": "taro build --type weapp",
"dev:weapp": "npm run build:weapp -- --watch",
"build:tt": "cross-env TARO_APP_TARGET=tt taro build --type tt",
"dev:tt": "npm run build:tt -- --watch",
"build:xhs-taro": "cross-env TARO_ENV=weapp TARO_APP_TARGET=xhs taro build --type weapp",
"xhs:sync": "python xhs/scripts/sync_data.py",
"xhs:assemble": "python xhs/scripts/assemble.py",
"xhs:pack": "python xhs/scripts/pack.py",
"build:xhs": "npm run xhs:assemble && npm run xhs:pack",
"dev:all": "echo use: pnpm dev:weapp | pnpm dev:tt | pnpm build:xhs"
},
"browserslist": ["last 3 versions", "Android >= 4.1", "ios >= 8"],
"dependencies": {
"@babel/runtime": "^7.26.0",
"@tarojs/components": "4.0.9",
"@tarojs/helper": "4.0.9",
"@tarojs/plugin-framework-react": "4.0.9",
"@tarojs/plugin-platform-tt": "4.0.9",
"@tarojs/plugin-platform-weapp": "4.0.9",
"@tarojs/react": "4.0.9",
"@tarojs/runtime": "4.0.9",
"@tarojs/shared": "4.0.9",
"@tarojs/taro": "4.0.9",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@babel/core": "^7.26.0",
"@babel/preset-react": "^7.26.3",
"@tarojs/cli": "4.0.9",
"@tarojs/webpack5-runner": "4.0.9",
"@types/react": "^18.3.12",
"babel-preset-taro": "4.0.9",
"cross-env": "^7.0.3",
"sass": "^1.81.0",
"typescript": "^5.6.3",
"webpack": "5.91.0"
}
}

View File

@ -0,0 +1,13 @@
{
"miniprogramRoot": "dist/weapp/",
"projectname": "nomadro-miniprogram",
"description": "Nomadro 统一微信小程序",
"appid": "wxa55815dd741a540d",
"setting": {
"urlCheck": false,
"es6": true,
"minified": true,
"postcss": false
},
"compileType": "miniprogram"
}

View File

@ -0,0 +1,13 @@
{
"miniprogramRoot": "dist/tt/",
"projectname": "nomadro-tt",
"description": "Nomadro 抖音小程序(对齐 apps/ebook/dymini + nomadweb/dymini)",
"appid": "tt995defe007255b2701",
"setting": {
"urlCheck": false,
"es6": true,
"minified": true,
"newFeature": true
},
"compileType": "microApp"
}

View File

@ -0,0 +1,35 @@
export default defineAppConfig({
pages: [
'pages/index/index',
'pages/nav/index',
'pages/community/index',
'pages/mine/index',
'pages/book/index',
'pages/reader/index',
'pages/destinations/index',
'pages/destination/index',
'pages/meetups/index',
'pages/vip/index',
],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#0a0e17',
navigationBarTitleText: 'Nomadro',
navigationBarTextStyle: 'white',
backgroundColor: '#0a0e17',
},
tabBar: {
color: '#8b93a7',
selectedColor: '#4ecdc4',
backgroundColor: '#0c0c0f',
borderStyle: 'black',
list: [
{ pagePath: 'pages/index/index', text: '首页' },
{ pagePath: 'pages/nav/index', text: '导航' },
{ pagePath: 'pages/book/index', text: '小册' },
{ pagePath: 'pages/community/index', text: '社群' },
{ pagePath: 'pages/mine/index', text: '我的' },
],
},
lazyCodeLoading: 'requiredComponents',
})

View File

@ -0,0 +1,6 @@
page {
background: #0a0e17;
color: #f1f5f9;
font-family: 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
box-sizing: border-box;
}

View File

@ -0,0 +1,17 @@
import { type PropsWithChildren } from 'react'
import { useLaunch } from '@tarojs/taro'
import { loadRemoteConfig } from './services/remoteConfig'
import './styles/h5-theme.scss'
import './styles/ebook.scss'
import './app.scss'
function App({ children }: PropsWithChildren) {
useLaunch(() => {
// 冷启动预拉远程配置;失败走包内 DEFAULT(小红书纯前端可用)
void loadRemoteConfig(true)
})
return children
}
export default App

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 794 B

Some files were not shown because too many files have changed in this diff Show More