Add Douyin BMI audit homepage with remote A/B switch.

Ship a health-management BMI home for review, keep the nomad hub as hub, and let admin switch platforms.tt.homeVariant live with track/ntfy; fix tt config fetch to api.nomadro.cn/api/config.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-10-03 02:32:26 -05:00
parent 05b9ab3e33
commit 0e85d71386
30 changed files with 2100 additions and 474 deletions

View File

@ -0,0 +1,175 @@
#!/usr/bin/env python3
"""Deploy Douyin homeVariant A/B: admin SPA + API + seed remote-config."""
from __future__ import annotations
import io
import subprocess
import sys
import tarfile
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REPO = Path(__file__).resolve().parents[3]
ADMIN = REPO / "apps" / "admin"
API_SVC = REPO / "apps" / "api" / "services" / "ebook_svc"
def build_admin() -> Path:
print("building admin SPA (vite only)…", flush=True)
# monorepo 根 @types/react@19 会让 tsc -b 炸;生产只需要 vite bundle
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ADMIN,
shell=True,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
if r.returncode != 0:
print(r.stdout[-2000:] if r.stdout else "")
print(r.stderr[-2000:] if r.stderr else "")
raise SystemExit(f"admin build failed: {r.returncode}")
dist = ADMIN / "dist"
if not dist.is_dir():
raise SystemExit("no apps/admin/dist")
print((r.stdout or "")[-400:], flush=True)
print("build ok", flush=True)
return dist
def rewrite_app_imports(src: Path) -> str:
"""Local monorepo uses ebook_svc.*; production /opt/nomadmini uses app.*."""
text = src.read_text(encoding="utf-8")
return text.replace("ebook_svc.", "app.")
REMOTE_SH = r"""
set -euo pipefail
cd /tmp
rm -rf dy-hv-unpack && mkdir dy-hv-unpack
tar -xzf dy-home-variant.tar.gz -C dy-hv-unpack
echo "==> admin SPA"
sudo rsync -a --delete dy-hv-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
echo "==> API files"
B=/opt/nomadmini/backend/app
sudo cp dy-hv-unpack/api/douyin_admin.py "$B/routers/douyin_admin.py"
sudo cp dy-hv-unpack/api/tt_platform_config.py "$B/services/tt_platform_config.py"
if [ -f dy-hv-unpack/api/track.py ]; then
sudo cp dy-hv-unpack/api/track.py "$B/services/track.py"
fi
sudo chown ubuntu:ubuntu "$B/routers/douyin_admin.py" "$B/services/tt_platform_config.py" "$B/services/track.py" 2>/dev/null || true
echo "==> seed homeVariant (keep live modules/book)"
sudo python3 <<'PY'
import json
from datetime import datetime, timezone
from pathlib import Path
p = Path("/var/www/nomadro.cn/data/remote-config.json")
cfg = json.loads(p.read_text(encoding="utf-8"))
plats = cfg.setdefault("platforms", {})
tt = dict(plats.get("tt") or {})
if tt.get("homeVariant") not in ("bmi", "hub"):
tt["homeVariant"] = "bmi"
print("set homeVariant=bmi")
else:
print("keep homeVariant", tt.get("homeVariant"))
# ensure modules skeleton
mods = tt.setdefault("modules", {})
for key, title in (("nav", "出海导航"), ("book", "数字游民小册"), ("community", "旅居社群")):
if key not in mods or not isinstance(mods[key], dict):
mods[key] = {"enabled": False, "title": title, "tabLabel": title[:2]}
plats["tt"] = tt
cfg["platforms"] = plats
cfg["updatedAt"] = datetime.now(timezone.utc).isoformat()
# backup
bak = p.with_suffix(".json.bak-homevariant")
bak.write_text(p.read_text(encoding="utf-8"), encoding="utf-8")
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
print("tt.homeVariant", tt.get("homeVariant"))
print("tt.mods", {k: (v or {}).get("enabled") for k, v in (tt.get("modules") or {}).items()})
PY
echo "==> restart API"
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
echo "==> smoke"
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/
curl -sk -o /dev/null -w "douyin %{http_code}\n" https://admin.nomadro.cn/douyin
curl -sk -o /dev/null -w "meta_noauth %{http_code}\n" https://admin.nomadro.cn/api/admin/douyin/meta
BODY=$(curl -sk -X POST https://admin.nomadro.cn/api/admin/login \
-H 'Content-Type: application/json' \
-d '{"username":"admin","password":"Xiao4669805"}')
TOKEN=$(echo "$BODY" | python3 -c 'import sys,json; d=json.load(sys.stdin); print(d.get("token") or d.get("access_token") or "")')
echo "token_len=${#TOKEN}"
if [ -n "$TOKEN" ]; then
curl -sk -H "Authorization: Bearer $TOKEN" https://admin.nomadro.cn/api/admin/douyin/config \
| python3 -c 'import sys,json; d=json.load(sys.stdin); c=d.get("config") or {}; print("ok", d.get("ok"), "homeVariant", c.get("homeVariant"), "mods", list((c.get("modules") or {}).keys()))'
fi
# SPA bundle should mention 首页变体 / homeVariant copy
grep -o '首页变体\|Home A / B\|BMI 健康管理\|homeVariant' /www/wwwroot/admin.nomadro.cn/assets/*.js 2>/dev/null | head -8 || true
rm -rf dy-hv-unpack dy-home-variant.tar.gz
echo DONE
"""
def main() -> int:
dist = build_admin()
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
for name, src in (
("api/douyin_admin.py", API_SVC / "routers" / "douyin_admin.py"),
("api/tt_platform_config.py", API_SVC / "services" / "tt_platform_config.py"),
("api/track.py", API_SVC / "services" / "track.py"),
):
data = rewrite_app_imports(src).encode("utf-8")
info = tarfile.TarInfo(name=name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
buf.seek(0)
print(f"pack {buf.getbuffer().nbytes} bytes", flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/dy-home-variant.tar.gz", "wb") as rf:
rf.write(buf.read())
sftp.close()
print("uploaded", flush=True)
_, stdout, _ = c.exec_command(REMOTE_SH, timeout=240, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Diagnose config source mismatch: admin PUT vs public /api/config."""
from __future__ import annotations
import json
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
CMD = r"""
set -e
echo '=== remote-config.json tt ==='
python3 - <<'PY'
import json
from pathlib import Path
for p in [
Path('/var/www/nomadro.cn/data/remote-config.json'),
Path('/opt/nomadmini/backend/data/tt-platform-config.json'),
Path('/opt/nomadmini/data/tt-platform-config.json'),
]:
print('---', p, 'exists', p.exists())
if not p.exists():
continue
try:
d=json.loads(p.read_text(encoding='utf-8'))
except Exception as e:
print('read err', e); continue
tt=(d.get('platforms') or {}).get('tt') if 'platforms' in d else d
if not isinstance(tt, dict):
tt={}
mods=tt.get('modules') or {}
print('homeVariant', tt.get('homeVariant'))
print('mods', {k:(v or {}).get('enabled') for k,v in mods.items()})
print('mtime', p.stat().st_mtime)
PY
echo '=== who serves api.nomadro.cn/api/config ==='
curl -sk https://api.nomadro.cn/api/config | python3 -c 'import sys,json; d=json.load(sys.stdin); print("source", d.get("source")); tt=((d.get("config") or {}).get("platforms") or {}).get("tt") or {}); print("hv", tt.get("homeVariant")); print("mods", {k:(v or {}).get("enabled") for k,v in (tt.get("modules") or {}).items()})'
echo '=== nginx hint ==='
sudo grep -R "api.nomadro.cn\|/api/config" /www/server/panel/vhost/nginx/ /etc/nginx/ 2>/dev/null | head -30 || true
"""
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(CMD, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Diagnose + fix: ensure admin write and public config share same file."""
from __future__ import annotations
import json
import sys
import time
import urllib.request
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASSWD = "82.157.112.245", "ubuntu", "Xiao4669805"
BASE = "https://admin.nomadro.cn"
CMD = r"""
set -e
echo '=== resolve path from API code ==='
cd /opt/nomadmini/backend && .venv/bin/python - <<'PY'
from app.services.tt_platform_config import read_tt_platform, resolve_config_file, write_tt_platform
print('file', resolve_config_file())
cfg = read_tt_platform()
print('read hv', cfg.get('homeVariant'))
print('read mods', {k:(v or {}).get('enabled') for k,v in (cfg.get('modules') or {}).items()})
PY
echo '=== public config ==='
curl -sk https://api.nomadro.cn/api/config | python3 - <<'PY'
import sys, json
d=json.load(sys.stdin)
print('source', d.get('source'))
tt=((d.get('config') or {}).get('platforms') or {}).get('tt') or {}
print('public hv', tt.get('homeVariant'))
print('public mods', {k:(v or {}).get('enabled') for k,v in (tt.get('modules') or {}).items()})
PY
"""
def http(method: str, path: str, token: str | None = None, body: dict | None = None):
data = None if body is None else json.dumps(body).encode()
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWD, timeout=40, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(CMD, timeout=90, get_pty=True)
out = ""
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
chunk = stdout.channel.recv(65536).decode("utf-8", "replace")
out += chunk
print(chunk, end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
chunk = stdout.channel.recv(65536).decode("utf-8", "replace")
out += chunk
print(chunk, end="", flush=True)
c.close()
login = http("POST", "/api/admin/login", body={"username": "admin", "password": "Xiao4669805"})
token = login.get("token") or login.get("access_token")
adm = http("GET", "/api/admin/douyin/config", token=token)
cfg = adm.get("config") or {}
print("admin hv", cfg.get("homeVariant"))
print("admin mods", {k: (v or {}).get("enabled") for k, v in (cfg.get("modules") or {}).items()})
# Force write hub then bmi roundtrip via admin API to prove public follows
print("=== roundtrip hub ===", flush=True)
http("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": "hub"})
time.sleep(1)
pub = json.loads(urllib.request.urlopen("https://api.nomadro.cn/api/config", timeout=20).read().decode())
tt = ((pub.get("config") or {}).get("platforms") or {}).get("tt") or {}
print("public after hub", tt.get("homeVariant"))
print("=== roundtrip bmi ===", flush=True)
http("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": "bmi"})
time.sleep(1)
pub2 = json.loads(urllib.request.urlopen("https://api.nomadro.cn/api/config", timeout=20).read().decode())
tt2 = ((pub2.get("config") or {}).get("platforms") or {}).get("tt") or {}
print("public after bmi", tt2.get("homeVariant"))
ok = tt.get("homeVariant") == "hub" and tt2.get("homeVariant") == "bmi"
print("SYNC_OK" if ok else "SYNC_FAIL")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Probe live douyin admin / API layout on production."""
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
CMD = r"""
set -e
echo "=== systemd ==="
systemctl show nomadmini-api -p WorkingDirectory -p FragmentPath --no-pager 2>/dev/null || true
echo "=== files ==="
ls -la /opt/nomadmini/backend/app/routers/douyin_admin.py /opt/nomadmini/backend/app/services/tt_platform_config.py 2>&1 || true
ls -la /opt/nomadmini/backend/app/main.py 2>&1 || true
echo "=== imports ==="
head -20 /opt/nomadmini/backend/app/routers/douyin_admin.py 2>/dev/null || true
echo "=== homeVariant in py ==="
grep -n homeVariant /opt/nomadmini/backend/app/services/tt_platform_config.py 2>/dev/null || echo no_homeVariant
echo "=== remote-config tt ==="
python3 - <<'PY'
import json
from pathlib import Path
p = Path("/var/www/nomadro.cn/data/remote-config.json")
d = json.loads(p.read_text(encoding="utf-8"))
tt = (d.get("platforms") or {}).get("tt") or {}
print("homeVariant", tt.get("homeVariant"))
mods = tt.get("modules") or {}
print("mods", {k: (v or {}).get("enabled") for k, v in mods.items()})
print("chapters", len(((tt.get("bookContent") or {}).get("chapters") or [])))
PY
"""
def main() -> int:
import sys
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(CMD, timeout=60, get_pty=True)
print(stdout.read().decode("utf-8", "replace"))
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Verify realtime homeVariant PUT + config_change track."""
from __future__ import annotations
import json
import sys
import urllib.request
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
BASE = "https://admin.nomadro.cn"
def req(method: str, path: str, token: str | None = None, body: dict | None = None):
data = None if body is None else json.dumps(body).encode()
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
r = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
with urllib.request.urlopen(r, timeout=25) as resp:
return json.loads(resp.read().decode())
def main() -> int:
login = req("POST", "/api/admin/login", body={"username": "admin", "password": "Xiao4669805"})
token = login.get("token") or login.get("access_token")
if not token:
print("login fail", login)
return 1
before = req("GET", "/api/admin/douyin/config", token=token)
hv = (before.get("config") or {}).get("homeVariant") or "bmi"
print("before", hv)
target = "bmi" if hv == "hub" else "hub"
put = req("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": target})
after = (put.get("config") or {}).get("homeVariant")
print("after", after, "ok", put.get("ok"))
# restore
req("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": hv})
print("restored", hv)
events = req("GET", "/api/admin/track-events?limit=5&name=config_change", token=token)
rows = events.get("events") or events.get("items") or events
if isinstance(rows, dict):
rows = rows.get("events") or []
print("recent config_change count sample", len(rows) if isinstance(rows, list) else type(rows))
if isinstance(rows, list) and rows:
e0 = rows[0]
print("latest", e0.get("name"), e0.get("label"), e0.get("client"))
return 0 if after == target else 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -10,7 +10,8 @@ type Meta = {
const CHECKS = [
'开发者工具导入 apps/miniprogram/tt,AppID 正确',
'首页入口与本后台「入口开关」一致(默认仅小册)',
'过审:首页为 BMI 健康管理(homeVariant=bmi)',
'审核通过后:后台切 hub,门户入口与「入口开关」一致',
'小册可连续竖滑;目录跳章后不弹回封面',
'用户隐私保护协议已声明「剪切板」(导航复制外链)',
'packageBook 分包 ≤2MB;validate:size 通过',

View File

@ -40,7 +40,7 @@ export default function DouyinLayout() {
</nav>
<div className="dy-side-foot">
<p className="dy-hint">只改 platforms.tt:首页入口与小册正文。无道具、无虚拟支付。</p>
<p className="dy-hint">只改 platforms.tt:首页 A/B、入口与小册正文。无道具、无虚拟支付。</p>
<button type="button" className="dy-ghost" onClick={() => nav('/')}>
← 切换平台
</button>

View File

@ -2,7 +2,9 @@ import { useEffect, useMemo, useState } from 'react'
import { api } from '../../api'
type Mod = { enabled: boolean; title: string; tabLabel?: string; note?: string }
type HomeVariant = 'bmi' | 'hub'
type TtCfg = {
homeVariant?: HomeVariant
modules: { nav: Mod; book: Mod; community: Mod }
bookContent: Record<string, unknown>
}
@ -13,20 +15,46 @@ const KEYS = [
{ key: 'community' as const, label: '旅居社群', ico: '🏕️', desc: '社群入口。抖音默认关。' },
]
const VARIANTS: Array<{
key: HomeVariant
label: string
ico: string
desc: string
badge: string
}> = [
{
key: 'bmi',
label: 'B · BMI 健康管理',
ico: '⚖️',
desc: '过审首页:身体质量指数计算、理想体重、本地记录。类目:工具 / 实用工具 / 健康管理。',
badge: '过审用',
},
{
key: 'hub',
label: 'A · 数字游民门户',
ico: '🌐',
desc: '正式首页:出海导航 / 小册 / 旅居社群入口。审核通过后再切回来。',
badge: '正式版',
},
]
function Switch({
checked,
onChange,
label,
disabled,
}: {
checked: boolean
onChange: (v: boolean) => void
label: string
disabled?: boolean
}) {
return (
<label className="dy-switch" title={label}>
<input
type="checkbox"
checked={checked}
disabled={disabled}
onChange={(e) => onChange(e.target.checked)}
aria-label={label}
/>
@ -37,24 +65,31 @@ function Switch({
)
}
function normalize(cfg: TtCfg): TtCfg {
return {
...cfg,
homeVariant: cfg.homeVariant === 'hub' ? 'hub' : 'bmi',
}
}
export default function DouyinModules() {
const [cfg, setCfg] = useState<TtCfg | null>(null)
const [busy, setBusy] = useState(false)
const [dirty, setDirty] = useState(false)
const [msg, setMsg] = useState('')
const [err, setErr] = useState('')
async function load() {
setErr('')
const data = await api<{ config: TtCfg }>('/api/admin/douyin/config')
setCfg(data.config)
setDirty(false)
setCfg(normalize(data.config))
}
useEffect(() => {
load().catch((e) => setErr(e.message || '加载失败'))
}, [])
const variant = cfg?.homeVariant === 'hub' ? 'hub' : 'bmi'
const preview = useMemo(() => {
if (!cfg) return []
return KEYS.map(({ key, label, ico }) => ({
@ -65,26 +100,60 @@ export default function DouyinModules() {
}))
}, [cfg])
async function save() {
/** 点一下立刻写后端(埋点+ntfy 由 API 触发) */
async function persist(patch: { homeVariant?: HomeVariant; modules?: TtCfg['modules'] }, okHint: string) {
if (!cfg) return
setBusy(true)
setMsg('')
setErr('')
const optimistic: TtCfg = {
...cfg,
...(patch.homeVariant ? { homeVariant: patch.homeVariant } : {}),
...(patch.modules ? { modules: patch.modules } : {}),
}
setCfg(optimistic)
try {
const data = await api<{ config: TtCfg }>('/api/admin/douyin/config', {
method: 'PUT',
body: JSON.stringify({ modules: cfg.modules }),
body: JSON.stringify({
homeVariant: optimistic.homeVariant === 'hub' ? 'hub' : 'bmi',
modules: optimistic.modules,
}),
})
setCfg(data.config)
setDirty(false)
setMsg('已保存 · 抖音端下次拉配置生效(可清小程序缓存)')
setCfg(normalize(data.config))
setMsg(okHint)
} catch (e: any) {
setErr(e.message || '保存失败')
await load().catch(() => undefined)
} finally {
setBusy(false)
}
}
async function switchVariant(next: HomeVariant) {
if (!cfg || cfg.homeVariant === next || busy) return
await persist(
{ homeVariant: next },
next === 'bmi'
? '已切换为 B · BMI(已写后端 · ntfy 已推)'
: '已切换为 A · 门户(已写后端 · ntfy 已推)',
)
}
async function toggleModule(key: (typeof KEYS)[number]['key'], enabled: boolean) {
if (!cfg || busy) return
const m = cfg.modules[key]
await persist(
{
modules: {
...cfg.modules,
[key]: { ...m, enabled },
},
},
`${KEYS.find((k) => k.key === key)?.label || key} 已${enabled ? '开启' : '关闭'}`,
)
}
if (!cfg && !err) return <div className="dy-skeleton">加载入口开关…</div>
if (!cfg) return <p className="dy-err dy-toast">{err}</p>
@ -92,16 +161,53 @@ export default function DouyinModules() {
<div>
<header className="dy-head">
<div className="dy-head-copy">
<div className="dy-eyebrow">Home entries</div>
<h1>入口开关</h1>
<p>控制抖音首页「导航 / 小册 / 社群」是否显示。右侧预览会即时跟着变。</p>
<div className="dy-eyebrow">Home A / B · Live</div>
<h1>首页与入口</h1>
<p>
切换即写后端并推 ntfy。小程序前台切回 / 重新打开会立刻拉配置生效。
</p>
</div>
</header>
<div className="dy-panel" style={{ marginBottom: 14 }}>
<h2>首页变体(实时)</h2>
<p className="dy-muted" style={{ marginBottom: 12 }}>
当前:{variant === 'bmi' ? 'B · BMI 健康管理(过审)' : 'A · 数字游民门户(正式)'}
{busy ? ' · 同步中…' : ''}
</p>
<div className="dy-mod-list">
{VARIANTS.map((v) => {
const on = variant === v.key
return (
<div className={`dy-mod${on ? ' is-on' : ''}`} key={v.key}>
<div className="dy-mod-meta">
<div className="dy-mod-ico">{v.ico}</div>
<div className="dy-mod-text">
<strong>
{v.label}
<span className={`dy-mod-badge ${on ? 'on' : 'off'}`}>{on ? '使用中' : v.badge}</span>
</strong>
<span>{v.desc}</span>
</div>
</div>
<button
type="button"
className={on ? 'dy-btn' : 'dy-btn-ghost'}
disabled={on || busy}
onClick={() => void switchVariant(v.key)}
>
{on ? '当前' : busy ? '…' : '切换'}
</button>
</div>
)
})}
</div>
</div>
<div className="dy-preview-wrap">
<div>
<div className="dy-panel" style={{ marginBottom: 0 }}>
<h2>模块显隐</h2>
<h2>模块显隐(仅 A 首页 · 实时)</h2>
<div className="dy-mod-list">
{KEYS.map(({ key, label, ico, desc }) => {
const m = cfg.modules[key]
@ -120,18 +226,9 @@ export default function DouyinModules() {
</div>
<Switch
checked={on}
disabled={busy}
label={`${label}开关`}
onChange={(v) => {
setCfg({
...cfg,
modules: {
...cfg.modules,
[key]: { ...m, enabled: v },
},
})
setDirty(true)
setMsg('')
}}
onChange={(v) => void toggleModule(key, v)}
/>
</div>
)
@ -143,17 +240,38 @@ export default function DouyinModules() {
<div className="dy-phone" aria-hidden>
<div className="dy-phone-notch" />
<div className="dy-phone-screen">
<div className="dy-phone-title">Nomadro · 抖音</div>
<div className="dy-phone-tiles">
{preview.map((p) => (
<div key={p.key} className={`dy-phone-tile ${p.on ? 'on' : 'off'}`}>
<span>{p.ico}</span>
<span>{p.label}</span>
</div>
))}
<div className="dy-phone-title">
{variant === 'bmi' ? 'BMI · 健康管理' : 'Nomadro · 抖音'}
</div>
{variant === 'bmi' ? (
<div className="dy-phone-tiles">
<div className="dy-phone-tile on">
<span>⚖️</span>
<span>BMI 计算</span>
</div>
<div className="dy-phone-tile on">
<span>📏</span>
<span>理想体重</span>
</div>
<div className="dy-phone-tile on">
<span>📝</span>
<span>本地记录</span>
</div>
</div>
) : (
<div className="dy-phone-tiles">
{preview.map((p) => (
<div key={p.key} className={`dy-phone-tile ${p.on ? 'on' : 'off'}`}>
<span>{p.ico}</span>
<span>{p.label}</span>
</div>
))}
</div>
)}
<div className="dy-phone-tabbar">
{preview.filter((p) => p.on).length ? (
{variant === 'bmi' ? (
<span className="on">BMI</span>
) : preview.filter((p) => p.on).length ? (
preview
.filter((p) => p.on)
.map((p, i) => (
@ -174,20 +292,17 @@ export default function DouyinModules() {
{msg ? <span className="dy-ok dy-toast">{msg}</span> : null}
{err ? <span className="dy-err dy-toast">{err}</span> : null}
{!msg && !err ? (
<span className="dy-muted">{dirty ? '有未保存改动' : '当前与线上一致'}</span>
<span className="dy-muted">{busy ? '正在同步后端…' : '切换即生效 · 已与线上同步'}</span>
) : null}
</div>
<div className="dy-actions">
<button
type="button"
className="dy-btn-ghost"
disabled={busy || !dirty}
disabled={busy}
onClick={() => void load().catch((e) => setErr(e.message || '加载失败'))}
>
还原
</button>
<button type="button" className="dy-btn" disabled={busy || !dirty} onClick={() => void save()}>
{busy ? '保存中…' : '保存入口开关'}
刷新
</button>
</div>
</div>

View File

@ -10,6 +10,7 @@ type Meta = {
}
type TtCfg = {
homeVariant?: 'bmi' | 'hub'
modules: Record<string, { enabled: boolean; title: string }>
bookContent: { title: string; chapters: unknown[]; updatedAt?: string }
}
@ -42,6 +43,7 @@ export default function DouyinOverview() {
const mods = cfg?.modules || {}
const onCount = Object.values(mods).filter((m) => m?.enabled).length
const homeVariant = cfg?.homeVariant === 'hub' ? 'hub' : 'bmi'
return (
<div>
@ -49,11 +51,11 @@ export default function DouyinOverview() {
<div className="dy-head-copy">
<div className="dy-eyebrow">Douyin Mini App</div>
<h1>抖音小程序控制台</h1>
<p>只管入口与小册内容。没有道具、没有虚拟支付——和微信后台完全分开。</p>
<p>只管首页 A/B、入口与小册内容。没有道具、没有虚拟支付——和微信后台完全分开。</p>
</div>
<div className="dy-actions">
<Link className="dy-btn" to="/douyin/modules">
调入口开关
调首页 / 入口
</Link>
</div>
</header>
@ -66,7 +68,13 @@ export default function DouyinOverview() {
</div>
</div>
<div className="dy-card">
<strong>首页入口</strong>
<strong>当前首页</strong>
<div className="dy-card-val" style={{ fontSize: 15 }}>
{homeVariant === 'bmi' ? 'B · BMI' : 'A · 门户'}
</div>
</div>
<div className="dy-card">
<strong>门户入口</strong>
<div className="dy-card-val">
{onCount} / 3 <span className="dy-muted">开启</span>
</div>
@ -77,12 +85,6 @@ export default function DouyinOverview() {
{cfg?.bookContent?.title || '…'} · {cfg?.bookContent?.chapters?.length ?? 0} 章
</div>
</div>
<div className="dy-card">
<strong>包体上限</strong>
<div className="dy-card-val" style={{ fontSize: 14 }}>
分包 ≤{meta?.limits.subPackageMB ?? 2}MB
</div>
</div>
</div>
<div className="dy-panel" style={{ marginTop: 14 }}>

View File

@ -7,6 +7,7 @@ from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
from ebook_svc.core.security import require_admin
from ebook_svc.services.track import ingest_events
from ebook_svc.services.tt_platform_config import read_tt_platform, write_tt_platform
router = APIRouter(prefix="/api/admin/douyin", tags=["douyin-admin"])
@ -40,6 +41,7 @@ class BookContent(BaseModel):
class TtPlatformBody(BaseModel):
homeVariant: str | None = None
modules: dict[str, ModuleToggle] | None = None
bookContent: BookContent | None = None
@ -51,12 +53,54 @@ async def get_douyin_config(_: str = Depends(require_admin)) -> dict[str, Any]:
@router.put("/config")
async def put_douyin_config(body: TtPlatformBody, _: str = Depends(require_admin)) -> dict[str, Any]:
before = read_tt_platform()
patch: dict[str, Any] = {}
if body.homeVariant is not None:
if body.homeVariant not in ("bmi", "hub"):
return {"ok": False, "error": "homeVariant must be bmi|hub"}
patch["homeVariant"] = body.homeVariant
if body.modules is not None:
patch["modules"] = {k: v.model_dump() for k, v in body.modules.items()}
if body.bookContent is not None:
patch["bookContent"] = body.bookContent.model_dump()
saved = write_tt_platform(patch)
# 埋点 + ntfy(首页切换 / 入口开关)
old_hv = before.get("homeVariant") or "bmi"
new_hv = saved.get("homeVariant") or "bmi"
changed: list[str] = []
if body.homeVariant is not None and old_hv != new_hv:
changed.append(f"homeVariant {old_hv}→{new_hv}")
if body.modules is not None:
old_mods = before.get("modules") or {}
new_mods = saved.get("modules") or {}
for key in ("nav", "book", "community"):
o = bool((old_mods.get(key) or {}).get("enabled"))
n = bool((new_mods.get(key) or {}).get("enabled"))
if o != n:
changed.append(f"{key}:{'开' if n else '关'}")
if body.bookContent is not None:
changed.append("bookContent")
if changed:
label = " · ".join(changed)[:120]
await ingest_events(
[
{
"name": "config_change",
"page": "admin/douyin",
"label": label,
"props": {
"homeVariant": new_hv,
"from": old_hv,
"changes": ",".join(changed)[:200],
},
}
],
openid=None,
client="admin",
)
return {"ok": True, "config": saved}

View File

@ -33,6 +33,7 @@ NTFY_ALWAYS = {
"access_updated",
"wx_push",
"error",
"config_change",
}
PRIORITY = {
@ -48,6 +49,7 @@ PRIORITY = {
"login_fail": 4,
"wx_push": 4,
"error": 4,
"config_change": 4,
"page_view": 2,
"btn_click": 2,
"app_launch": 3,
@ -75,6 +77,7 @@ TAGS = {
"read_start": "book",
"access_updated": "arrows_counterclockwise",
"wx_push": "incoming_envelope",
"config_change": "gear,loudspeaker",
}
@ -108,6 +111,7 @@ def _title(name: str) -> str:
"access_updated": "权限更新",
"wx_push": "微信推送",
"error": "前端异常",
"config_change": "抖音配置变更",
}
return mapping.get(name, f"埋点 {name}")

View File

@ -29,6 +29,7 @@ _FALLBACK_BOOK: dict[str, Any] = {
}
DEFAULT_TT: dict[str, Any] = {
"homeVariant": "bmi", # 过审默认 BMI;后台可切 hub
"modules": {
"nav": {
"enabled": False,
@ -120,6 +121,9 @@ def _merge_tt(base: dict[str, Any], patch: dict[str, Any] | None) -> dict[str, A
out = deepcopy(base)
if not patch:
return out
hv = patch.get("homeVariant")
if hv in ("bmi", "hub"):
out["homeVariant"] = hv
mods = patch.get("modules") or {}
for key in ("nav", "book", "community"):
if key in mods and isinstance(mods[key], dict):
@ -163,11 +167,20 @@ def read_tt_platform() -> dict[str, Any]:
def write_tt_platform(tt: dict[str, Any]) -> dict[str, Any]:
"""只写 platforms.tt;若目标是门户 remote-config,保留顶层微信/门户 modules。"""
merged = _merge_tt(default_tt_platform(), tt)
# 以现网为底,避免只改小册时冲掉 homeVariant / 入口开关
current = read_tt_platform()
merged = _merge_tt(current, tt)
bc = merged.get("bookContent") or {}
bc["updatedAt"] = datetime.now(timezone.utc).isoformat()
merged["bookContent"] = bc
# 兜底:缺字段时用默认
if merged.get("homeVariant") not in ("bmi", "hub"):
merged["homeVariant"] = "bmi"
for key in ("nav", "book", "community"):
if key not in (merged.get("modules") or {}):
merged.setdefault("modules", {})[key] = default_tt_platform()["modules"][key]
path = resolve_config_file()
path.parent.mkdir(parents=True, exist_ok=True)

View File

@ -9,7 +9,7 @@
| 产物 | `dist/`(gitignore;本地 `pnpm build` 生成) |
| 工程配置 | `project.tt.json`(`miniprogramRoot: ./dist/`) |
| TabBar | **无** |
| 首页 | 三入口;自定义顶栏红标 `nomadro.webp`(与微信同源) |
| 首页 | **A/B**:默认 `homeVariant=bmi`(BMI 健康管理过审);后台可切 `hub` 正式门户 |
| 支付 | 默认关闭 / 离线免费(无微信虚拟支付) |
| 隐私 | `usePrivacyCheck: true`(官方隐私弹窗) |
@ -62,7 +62,7 @@ pnpm build # 生产构建 + copy-static + validate:size
| 运行时 | `FORCE_OFFLINE_BOOK`,不拉线上旧目录 |
| 阅读 | **连续竖滑**:首屏渐进挂载章节(避免一次解析 41 章卡死);目录跳章 `ensureMountedThrough`;全书挂完才出「全书读完」 |
| 滚动 | 目录跳转只用短回钉;用户滑离即停 `pageScrollTo`;跳章锁定期勿增章(否则会抖回封面) |
| 过审 | 首页隐藏「出海导航」入口(配置可开);小册正文不嵌公众号二维码;加群弹窗优先抖音群,稍后再说才出公众号 |
| 过审 | 默认 BMI 首页(健康管理类目);后台 `homeVariant=hub` 切回门户;门户默认隐藏「出海导航」;小册正文不嵌公众号二维码;加群弹窗优先抖音群 |
## 包体积(官方)
@ -77,11 +77,12 @@ pnpm build # 生产构建 + copy-static + validate:size
## 验收
1. [ ] 导入 `tt/`,AppID 正确;`pnpm build` 后预览 `dist/`
2. [ ] 首页两入口(小册 / 社群);红标 logo;顶栏避开状态栏
3. [ ] 导航点链接 → 系统 Modal「复制/关闭」→ 复制成功(后台已声明剪切板)
4. [ ] 小册可连续上下滑;目录跳章后上下滑**不会**弹回封面 / 原地抖
5. [ ] 目录可立刻点;章内无「下一章」条;配图正常显示
6. [ ] 断网仍可打开小册;`validate:size` 通过(`packageBook` ≤2MB)
2. [ ] **过审默认**:首页为 BMI 健康管理(身高/体重/结果/本地记录);无门户入口
3. [ ] 后台将 `homeVariant` 切为 `hub` 后,首页变为门户(导航/小册/社群按开关)
4. [ ] 门户:红标 logo;顶栏避开状态栏;导航复制外链正常
5. [ ] 小册可连续上下滑;目录跳章后上下滑**不会**弹回封面 / 原地抖
6. [ ] 目录可立刻点;章内无「下一章」条;配图正常显示
7. [ ] 断网仍可打开小册;`validate:size` 通过(`packageBook` ≤2MB)
## 禁止

View File

@ -2,6 +2,7 @@
export default defineAppConfig({
pages: [
'pages/index/index',
'pages/hub/index',
'pages/nav/index',
'pages/community/index',
'pages/mine/index',
@ -29,9 +30,9 @@ export default defineAppConfig({
__usePrivacyCheck__: true,
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#0a0e17',
navigationBarTitleText: 'nomadro',
navigationBarBackgroundColor: '#0b0f14',
navigationBarTitleText: 'BMI健康管理',
navigationBarTextStyle: 'white',
backgroundColor: '#0a0e17',
backgroundColor: '#0b0f14',
},
})

View File

@ -4,6 +4,7 @@ import { useLaunch } from '@tarojs/taro'
import { loadRemoteConfig } from './services/remoteConfig'
import { startH5RemLock } from './utils/h5RemLock'
import { applyH5Theme, getStoredH5Theme } from './utils/h5Theme'
import { track } from './utils/track'
// Taro multi-end: theme.h5.ts -> community.scss; theme.ts -> h5-theme.scss
import './styles/theme'
import './styles/ebook.scss'
@ -12,6 +13,7 @@ import './app.scss'
function App({ children }: PropsWithChildren) {
useLaunch(() => {
void loadRemoteConfig(true)
track('app_launch', { page: 'app', label: '打开抖音小程序', immediate: true })
if (process.env.TARO_ENV === 'h5') {
applyH5Theme(getStoredH5Theme())
}

View File

@ -28,7 +28,12 @@ export type TtBookContent = {
updatedAt?: string
}
/** 抖音首页变体:bmi=过审健康工具;hub=正式数字游民门户 */
export type TtHomeVariant = 'bmi' | 'hub'
export type TtPlatformConfig = {
/** 首页 A/B:默认 bmi 过审;后台可切 hub */
homeVariant: TtHomeVariant
modules: {
nav: ModuleToggle
book: ModuleToggle
@ -85,6 +90,8 @@ export const DEFAULT_TT_BOOK_CONTENT: TtBookContent = {
}
export const DEFAULT_TT_PLATFORM: TtPlatformConfig = {
/** 过审默认 BMI;审核通过后后台切 hub */
homeVariant: 'bmi',
modules: {
nav: {
enabled: false,
@ -173,10 +180,15 @@ function mergeTtBookContent(base: TtBookContent, patch?: Partial<TtBookContent>
}
}
function resolveTtHomeVariant(v: unknown, fallback: TtHomeVariant): TtHomeVariant {
return v === 'hub' || v === 'bmi' ? v : fallback
}
export function mergeTtPlatform(partial?: Partial<TtPlatformConfig> | null): TtPlatformConfig {
const base = JSON.parse(JSON.stringify(DEFAULT_TT_PLATFORM)) as TtPlatformConfig
if (!partial) return base
return {
homeVariant: resolveTtHomeVariant(partial.homeVariant, base.homeVariant),
modules: {
nav: mergeModuleToggle(base.modules.nav, partial.modules?.nav),
book: mergeModuleToggle(base.modules.book, partial.modules?.book),
@ -186,6 +198,11 @@ export function mergeTtPlatform(partial?: Partial<TtPlatformConfig> | null): TtP
}
}
/** 抖音当前首页变体 */
export function resolveTtHomeVariantFromConfig(config: NomadroRemoteConfig): TtHomeVariant {
return resolveTtHomeVariant(config.platforms?.tt?.homeVariant, DEFAULT_TT_PLATFORM.homeVariant)
}
export function mergeRemoteConfig(
partial: Partial<NomadroRemoteConfig> | null | undefined,
): NomadroRemoteConfig {

View File

@ -0,0 +1,6 @@
export default definePageConfig({
navigationBarTitleText: 'Nomadro',
navigationStyle: 'custom',
enableShareAppMessage: true,
enableShareTimeline: true,
})

View File

@ -0,0 +1 @@
@import '../index/index.scss';

View File

@ -0,0 +1,39 @@
/**
* 首页 A — 数字游民门户(homeVariant=hub 时启用)
* onShow 强制拉配置,切回 BMI 时立刻 reLaunch
*/
import { useEffect, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import {
getCachedRemoteConfig,
loadRemoteConfig,
} from '@/services/remoteConfig'
import {
resolveTtHomeVariantFromConfig,
type NomadroRemoteConfig,
} from '@/data/remoteConfig.defaults'
import { useNomadroTheme } from '@/utils/h5Theme'
import HubHome from '../index/HubHome'
export default function HubPage() {
const [config, setConfig] = useState<NomadroRemoteConfig>(() => getCachedRemoteConfig())
const theme = useNomadroTheme()
async function syncVariant(force = false) {
const r = await loadRemoteConfig(force)
setConfig(r.config)
if (resolveTtHomeVariantFromConfig(r.config) === 'bmi') {
Taro.reLaunch({ url: '/pages/index/index' })
}
}
useEffect(() => {
void syncVariant(true)
}, [])
useDidShow(() => {
void syncVariant(true)
})
return <HubHome config={config} theme={theme} />
}

View File

@ -0,0 +1,376 @@
/**
* 首页 B — BMI 健康管理(过审默认)
* 干净工具风:原生顶栏、无品牌壳、少卡片。
*/
import { useEffect, useMemo, useState } from 'react'
import { Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
import { applyH5Theme, type H5Theme } from '@/utils/h5Theme'
import { H5Box as Box, H5Txt as Txt } from '@/components/H5Box'
import { trackClick, trackPage } from '@/utils/track'
import './bmi.scss'
const isH5 = process.env.TARO_ENV === 'h5'
const HISTORY_KEY = 'nomadro_bmi_history_v1'
const MAX_HISTORY = 8
type Gender = 'male' | 'female'
type BmiLevel = {
key: string
label: string
tip: string
color: string
min: number
max: number
}
const LEVELS: BmiLevel[] = [
{
key: 'under',
label: '偏瘦',
tip: '可适当增加优质蛋白与规律力量训练,循序渐进增重。',
color: '#38bdf8',
min: 0,
max: 18.5,
},
{
key: 'normal',
label: '正常',
tip: '体重状态良好,保持均衡饮食与每周适度运动即可。',
color: '#34d399',
min: 18.5,
max: 24,
},
{
key: 'over',
label: '超重',
tip: '建议控制精加工饮食,增加有氧与日常步数。',
color: '#fbbf24',
min: 24,
max: 28,
},
{
key: 'obese',
label: '肥胖',
tip: '建议制定可持续减重计划,必要时咨询专业医生。',
color: '#f87171',
min: 28,
max: 99,
},
]
type HistoryItem = {
id: string
bmi: number
heightCm: number
weightKg: number
label: string
at: string
}
function clamp(n: number, min: number, max: number) {
return Math.min(max, Math.max(min, n))
}
function calcBmi(heightCm: number, weightKg: number): number | null {
if (!heightCm || !weightKg || heightCm < 50 || heightCm > 250 || weightKg < 20 || weightKg > 300) {
return null
}
const m = heightCm / 100
return Math.round((weightKg / (m * m)) * 10) / 10
}
function levelOf(bmi: number): BmiLevel {
return LEVELS.find((l) => bmi >= l.min && bmi < l.max) || LEVELS[LEVELS.length - 1]!
}
function idealRange(heightCm: number): { low: number; high: number } | null {
if (heightCm < 50) return null
const m = heightCm / 100
return {
low: Math.round(18.5 * m * m * 10) / 10,
high: Math.round(23.9 * m * m * 10) / 10,
}
}
function estimateBmr(gender: Gender, heightCm: number, weightKg: number): number | null {
if (!heightCm || !weightKg) return null
const base = 10 * weightKg + 6.25 * heightCm - 5 * 28
return Math.round(gender === 'male' ? base + 5 : base - 161)
}
function gaugePercent(bmi: number): number {
return clamp(((bmi - 12) / 24) * 100, 3, 97)
}
function readHistory(): HistoryItem[] {
try {
const raw = Taro.getStorageSync(HISTORY_KEY)
if (!raw) return []
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
return Array.isArray(parsed) ? (parsed as HistoryItem[]) : []
} catch {
return []
}
}
function writeHistory(items: HistoryItem[]) {
try {
Taro.setStorageSync(HISTORY_KEY, JSON.stringify(items.slice(0, MAX_HISTORY)))
} catch {
/* ignore */
}
}
function Stepper({
label,
unit,
value,
min,
max,
step,
onChange,
}: {
label: string
unit: string
value: number
min: number
max: number
step: number
onChange: (n: number) => void
}) {
const bump = (d: number) => onChange(clamp(Math.round((value + d) * 10) / 10, min, max))
return (
<Box className="bmi-row">
<Box className="bmi-row-left">
<Txt className="bmi-row-label">{label}</Txt>
<Txt className="bmi-row-unit">{unit}</Txt>
</Box>
<Box className="bmi-stepper">
<Box className="bmi-step" onClick={() => bump(-step)}>
<Txt>−</Txt>
</Box>
<Input
className="bmi-input"
type="digit"
value={String(value)}
onInput={(e) => {
const n = Number(e.detail.value)
if (!Number.isFinite(n)) return
onChange(clamp(n, min, max))
}}
/>
<Box className="bmi-step" onClick={() => bump(step)}>
<Txt>+</Txt>
</Box>
</Box>
</Box>
)
}
export default function BmiHome({
theme,
}: {
config: NomadroRemoteConfig
theme: H5Theme
}) {
const [height, setHeight] = useState(170)
const [weight, setWeight] = useState(60)
const [gender, setGender] = useState<Gender>('male')
const [history, setHistory] = useState<HistoryItem[]>([])
const [justSaved, setJustSaved] = useState(false)
useEffect(() => {
applyH5Theme(theme)
setHistory(readHistory())
trackPage('pages/index/index', 'BMI首页', { homeVariant: 'bmi' })
}, [theme])
useEffect(() => {
if (!isH5) return
const html = document.documentElement
const prev = html.style.fontSize
const lock = () => {
html.style.fontSize = '16px'
}
lock()
const id = window.setInterval(lock, 500)
window.addEventListener('resize', lock)
return () => {
clearInterval(id)
window.removeEventListener('resize', lock)
html.style.fontSize = prev
}
}, [])
const bmi = useMemo(() => calcBmi(height, weight), [height, weight])
const level = bmi != null ? levelOf(bmi) : null
const ideal = useMemo(() => idealRange(height), [height])
const bmr = useMemo(() => estimateBmr(gender, height, weight), [gender, height, weight])
function saveRecord() {
if (bmi == null || !level) {
Taro.showToast({ title: '请先输入有效身高体重', icon: 'none' })
return
}
trackClick('保存BMI记录', {
bmi,
height,
weight,
gender,
level: level.label,
})
const item: HistoryItem = {
id: `${Date.now()}`,
bmi,
heightCm: height,
weightKg: weight,
label: level.label,
at: new Date().toISOString(),
}
const next = [item, ...history.filter((h) => h.id !== item.id)].slice(0, MAX_HISTORY)
setHistory(next)
writeHistory(next)
setJustSaved(true)
Taro.showToast({ title: '已保存到本机', icon: 'success' })
setTimeout(() => setJustSaved(false), 1400)
}
function clearHistory() {
trackClick('清空BMI记录', { count: history.length })
setHistory([])
writeHistory([])
Taro.showToast({ title: '已清空', icon: 'none' })
}
return (
<Box className={`bmi-page${theme === 'light' ? ' bmi-page--light' : ''}`} data-theme={theme}>
<Box className="bmi-wrap">
<Box className="bmi-head">
<Txt className="bmi-head-kicker">身体质量指数</Txt>
<Txt className="bmi-head-title">算一算你的 BMI</Txt>
</Box>
<Box className="bmi-panel">
<Box className="bmi-seg">
<Box
className={`bmi-seg-item${gender === 'male' ? ' is-on' : ''}`}
onClick={() => {
setGender('male')
trackClick('选择性别', { gender: 'male' })
}}
>
<Txt>男</Txt>
</Box>
<Box
className={`bmi-seg-item${gender === 'female' ? ' is-on' : ''}`}
onClick={() => {
setGender('female')
trackClick('选择性别', { gender: 'female' })
}}
>
<Txt>女</Txt>
</Box>
</Box>
<Stepper label="身高" unit="cm" value={height} min={100} max={230} step={1} onChange={setHeight} />
<Stepper label="体重" unit="kg" value={weight} min={30} max={200} step={0.5} onChange={setWeight} />
</Box>
<Box className="bmi-result">
<Box className="bmi-result-main">
<Box className="bmi-result-left">
<Txt className="bmi-result-k">BMI</Txt>
<Txt className="bmi-result-v" style={level ? { color: level.color } : undefined}>
{bmi != null ? bmi.toFixed(1) : '—'}
</Txt>
</Box>
{level ? (
<Box className="bmi-result-badge" style={{ background: `${level.color}22`, color: level.color }}>
<Txt>{level.label}</Txt>
</Box>
) : null}
</Box>
<Box className="bmi-bar" aria-hidden>
<Box className="bmi-bar-track">
{LEVELS.map((l) => (
<Box key={l.key} className={`bmi-bar-seg bmi-bar-seg--${l.key}`} />
))}
</Box>
{bmi != null ? <Box className="bmi-bar-dot" style={{ left: `${gaugePercent(bmi)}%` }} /> : null}
</Box>
<Box className="bmi-stats">
{ideal ? (
<Box className="bmi-stat">
<Txt className="bmi-stat-k">理想体重</Txt>
<Txt className="bmi-stat-v">
{ideal.low}–{ideal.high} kg
</Txt>
</Box>
) : null}
{bmr != null ? (
<Box className="bmi-stat">
<Txt className="bmi-stat-k">基础代谢</Txt>
<Txt className="bmi-stat-v">{bmr} kcal</Txt>
</Box>
) : null}
</Box>
{level ? <Txt className="bmi-tip">{level.tip}</Txt> : null}
<Box className={`bmi-btn${justSaved ? ' is-ok' : ''}`} onClick={saveRecord}>
<Txt>{justSaved ? '已保存' : '保存本次记录'}</Txt>
</Box>
</Box>
<Box className="bmi-section">
<Txt className="bmi-section-h">参考标准 · 中国成人</Txt>
<Box className="bmi-legend">
{LEVELS.map((l) => (
<Box key={l.key} className={`bmi-legend-row${level?.key === l.key ? ' is-on' : ''}`}>
<Box className="bmi-legend-dot" style={{ background: l.color }} />
<Txt className="bmi-legend-name">{l.label}</Txt>
<Txt className="bmi-legend-range">
{l.key === 'obese' ? '≥ 28' : `${l.min} – ${(l.max - 0.1).toFixed(1)}`}
</Txt>
</Box>
))}
</Box>
</Box>
<Box className="bmi-section">
<Box className="bmi-section-top">
<Txt className="bmi-section-h">本机记录</Txt>
{history.length > 0 ? (
<Box className="bmi-clear" onClick={clearHistory}>
<Txt>清空</Txt>
</Box>
) : null}
</Box>
{history.length === 0 ? (
<Txt className="bmi-empty">还没有记录,算出结果后点保存即可</Txt>
) : (
<Box className="bmi-history">
{history.map((h) => (
<Box key={h.id} className="bmi-history-row">
<Txt className="bmi-history-bmi">{h.bmi.toFixed(1)}</Txt>
<Txt className="bmi-history-meta">
{h.heightCm}cm · {h.weightKg}kg · {h.label}
</Txt>
<Txt className="bmi-history-time">
{h.at.slice(5, 10).replace('-', '/')} {h.at.slice(11, 16)}
</Txt>
</Box>
))}
</Box>
)}
</Box>
<Txt className="bmi-foot">仅供健康参考,不能替代医疗诊断。数据只存在本机。</Txt>
</Box>
</Box>
)
}

View File

@ -0,0 +1,421 @@
/**
* 对齐门户 components/sections/hero.tsx(结构 / PORTALS / 开发快捷入口)
* H5 关键布局用原生 div(Taro View 自定义元素会弄塌 grid/绝对定位)。
*/
/**
* 首页 A — 数字游民门户(审核通过后由后台 homeVariant=hub 启用)
*/
import { useEffect, useMemo, useState, type CSSProperties, type ReactNode } from 'react'
import { View, Text, Image } from '@tarojs/components'
import Taro, { usePageScroll } from '@tarojs/taro'
import { isModuleEnabled } from '@/services/remoteConfig'
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
import { applyH5Theme, type H5Theme } from '@/utils/h5Theme'
import { goPage } from '@/utils/nav'
import { getSafeAreaMetrics } from '@/utils/safeArea'
import { trackClick, trackPage } from '@/utils/track'
import './index.scss'
type PortalId = 'nav' | 'book' | 'community' | 'vip'
type Portal = {
id: PortalId
moduleKey: keyof NomadroRemoteConfig['modules']
emoji: string
name: string
main?: boolean
}
const PORTALS: Portal[] = [
{ id: 'nav', moduleKey: 'nav', emoji: '🧭', name: '出海导航', main: false },
{ id: 'book', moduleKey: 'book', emoji: '📖', name: '数字游民', main: false },
{ id: 'community', moduleKey: 'community', emoji: '🌏', name: '旅居社群', main: true },
]
const INTERNAL_PORTALS: Record<PortalId, string> = {
nav: '/pages/nav/index',
book: '/packageBook/pages/book/index',
community: '/pages/community/index',
vip: '/pages/vip/index',
}
const isH5 = process.env.TARO_ENV === 'h5'
/** 开发快捷入口:默认隐藏 VIP;Admin/Config 仅 H5 开发态 */
const showQuickNav = false
const isDev = process.env.NODE_ENV === 'development'
const LOGO_SVG = `<svg class="hub-logo-icon" viewBox="0 0 40 40" fill="none" aria-hidden="true">
<circle cx="20" cy="20" r="18" stroke="#f06664" stroke-width="2.5"/>
<path d="M12 22c4-8 12-8 16 0" stroke="#f06664" stroke-width="2" stroke-linecap="round"/>
<circle cx="28" cy="14" r="3" fill="#f06664"/>
</svg>`
const GLOBE_SVG = `<svg class="hub-globe-svg" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<defs>
<radialGradient id="hubGlobeGlow" cx="50%" cy="50%" r="50%">
<stop offset="0%" stop-color="#4ECDC4" stop-opacity="0.3"/>
<stop offset="100%" stop-color="#4ECDC4" stop-opacity="0"/>
</radialGradient>
<linearGradient id="hubOrbitGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#FF6B6B"/>
<stop offset="100%" stop-color="#4ECDC4"/>
</linearGradient>
</defs>
<circle cx="200" cy="200" r="160" fill="url(#hubGlobeGlow)"/>
<circle cx="200" cy="200" r="120" fill="none" stroke="rgba(78,205,196,0.2)" stroke-width="1"/>
<circle cx="200" cy="200" r="90" fill="none" stroke="rgba(78,205,196,0.15)" stroke-width="1"/>
<ellipse class="hub-orbit-ring" cx="200" cy="200" rx="120" ry="40" fill="none" stroke="rgba(78,205,196,0.3)" stroke-width="1.5"/>
<ellipse class="hub-orbit-ring hub-orbit-ring-2" cx="200" cy="200" rx="40" ry="120" fill="none" stroke="rgba(255,107,107,0.3)" stroke-width="1.5"/>
<path class="hub-continent" d="M160 140 Q180 130 200 135 Q220 128 240 140 Q250 155 245 170 Q235 185 220 190 Q200 195 185 188 Q165 180 160 165 Z" fill="rgba(78,205,196,0.4)"/>
<path class="hub-continent" d="M130 210 Q145 200 160 215 Q155 235 140 240 Q125 235 130 210 Z" fill="rgba(78,205,196,0.3)"/>
<path class="hub-continent" d="M250 200 Q270 195 280 210 Q275 230 260 235 Q245 228 250 200 Z" fill="rgba(78,205,196,0.35)"/>
<circle class="hub-pulse-dot" cx="180" cy="155" r="5" fill="#FF6B6B"/>
<circle class="hub-pulse-dot" cx="260" cy="215" r="5" fill="#FFE66D"/>
<circle class="hub-pulse-dot" cx="145" cy="225" r="5" fill="#4ECDC4"/>
<path class="hub-flight-path" d="M180 155 Q220 140 260 215" fill="none" stroke="url(#hubOrbitGrad)" stroke-width="2" stroke-dasharray="6 4"/>
</svg>`
function goPath(path: string) {
goPage(path)
}
function openDevLink(kind: 'vip' | 'admin' | 'config') {
if (kind === 'vip') {
goPath('/pages/vip/index')
return
}
if (isH5 && typeof window !== 'undefined') {
const origin = window.location.origin.includes('10086')
? 'http://localhost:3000'
: window.location.origin
const href = kind === 'admin' ? `${origin}/admin` : `${origin}/admin/config`
window.open(href, '_blank', 'noopener,noreferrer')
return
}
Taro.showToast({
title: kind === 'admin' ? '请用门户 /admin' : '请用门户 /admin/config',
icon: 'none',
})
}
/** H5 用原生标签,避开 taro-view-core 默认 inline */
function Box({
className,
id,
children,
onClick,
html,
style,
'aria-hidden': ariaHidden,
'aria-label': ariaLabel,
'data-theme': dataTheme,
}: {
className?: string
id?: string
children?: ReactNode
onClick?: () => void
html?: string
style?: CSSProperties
'aria-hidden'?: boolean
'aria-label'?: string
'data-theme'?: string
}) {
if (isH5) {
return (
<div
id={id}
className={className}
style={style}
onClick={onClick}
aria-hidden={ariaHidden}
aria-label={ariaLabel}
data-theme={dataTheme}
dangerouslySetInnerHTML={html ? { __html: html } : undefined}
>
{html ? undefined : children}
</div>
)
}
return (
<View
id={id}
className={className}
style={style}
onClick={onClick}
data-theme={dataTheme}
dangerouslySetInnerHTML={html ? { __html: html } : undefined}
>
{html ? undefined : children}
</View>
)
}
function Txt({ className, children }: { className?: string; children?: ReactNode }) {
if (isH5) return <span className={className}>{children}</span>
return <Text className={className}>{children}</Text>
}
export default function HubHome({
config,
theme,
}: {
config: NomadroRemoteConfig
theme: H5Theme
}) {
const [navScrolled, setNavScrolled] = useState(false)
useEffect(() => {
applyH5Theme(theme)
trackPage('pages/hub/index', '门户首页', { homeVariant: 'hub' })
}, [theme])
// H5:锁 16px,并干掉 Taro flexible 脚本改根字号
useEffect(() => {
if (!isH5) return
const html = document.documentElement
const prev = html.style.fontSize
const lock = () => {
html.style.fontSize = '16px'
}
lock()
const id = window.setInterval(lock, 500)
window.addEventListener('resize', lock)
return () => {
clearInterval(id)
window.removeEventListener('resize', lock)
html.style.fontSize = prev
}
}, [])
usePageScroll((e) => {
setNavScrolled(e.scrollTop > 24)
})
useEffect(() => {
if (!isH5) return
const onScroll = () => {
setNavScrolled(window.scrollY > 24)
}
window.addEventListener('scroll', onScroll, { passive: true })
onScroll()
return () => window.removeEventListener('scroll', onScroll)
}, [])
useEffect(() => {
if (!isH5) return
const host = document.getElementById('particle-canvas-host')
if (!host) return
let canvas = host.querySelector('canvas') as HTMLCanvasElement | null
if (!canvas) {
canvas = document.createElement('canvas')
canvas.id = 'particle-canvas'
canvas.className = 'hub-particle-canvas'
canvas.setAttribute('aria-hidden', 'true')
host.appendChild(canvas)
}
const ctx = canvas.getContext('2d')
if (!ctx) return
let particles: { x: number; y: number; r: number; vx: number; vy: number; a: number }[] = []
let w = 0
let h = 0
let raf = 0
let running = true
const resize = () => {
w = canvas!.width = window.innerWidth
h = canvas!.height = window.innerHeight
const n = Math.min(60, Math.floor((w * h) / 22000))
particles = Array.from({ length: n }, () => ({
x: Math.random() * w,
y: Math.random() * h,
r: Math.random() * 1.6 + 0.4,
vx: (Math.random() - 0.5) * 0.3,
vy: (Math.random() - 0.5) * 0.3,
a: Math.random() * 0.4 + 0.15,
}))
}
const draw = () => {
if (!running) return
ctx.clearRect(0, 0, w, h)
particles.forEach((p, i) => {
p.x += p.vx
p.y += p.vy
if (p.x < 0 || p.x > w) p.vx *= -1
if (p.y < 0 || p.y > h) p.vy *= -1
ctx.beginPath()
ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2)
ctx.fillStyle = `rgba(255,255,255,${p.a})`
ctx.fill()
for (let j = i + 1; j < particles.length; j++) {
const q = particles[j]!
const d = Math.hypot(p.x - q.x, p.y - q.y)
if (d < 110) {
ctx.beginPath()
ctx.moveTo(p.x, p.y)
ctx.lineTo(q.x, q.y)
ctx.strokeStyle = `rgba(78,205,196,${0.16 * (1 - d / 110)})`
ctx.stroke()
}
}
})
raf = requestAnimationFrame(draw)
}
resize()
draw()
window.addEventListener('resize', resize)
return () => {
running = false
cancelAnimationFrame(raf)
window.removeEventListener('resize', resize)
}
}, [])
const cfg = config
const portals = PORTALS.filter((p) => isModuleEnabled(cfg, p.moduleKey))
const brand = cfg.copy.homeBrand || 'nomadro'
const safe = useMemo(() => getSafeAreaMetrics(), [])
const rootSafeStyle = {
['--safe-status-bar' as string]: `${safe.statusBarHeight}px`,
['--safe-nav-bar' as string]: `${safe.navBarHeight}px`,
['--safe-menu-pad' as string]: `${safe.menuRightPad}px`,
['--safe-header' as string]: `${safe.headerHeight}px`,
} as CSSProperties
return (
<Box
className={`hub-root${theme === 'light' ? ' hub-root--light' : ''}${!isH5 ? ' hub-root--mini' : ''}`}
data-theme={theme}
style={rootSafeStyle}
>
{isH5 ? <Box id="particle-canvas-host" className="hub-particle-canvas" /> : null}
<Box
className={`hub-navbar${navScrolled ? ' scrolled' : ''}`}
id="navbar"
style={
!isH5
? {
paddingTop: safe.statusBarHeight,
height: 'auto',
}
: undefined
}
>
<Box
className="hub-nav-container"
style={
!isH5
? {
height: safe.navBarHeight,
paddingRight: safe.menuRightPad,
}
: undefined
}
>
<Box className="hub-logo" onClick={() => goPath('/pages/hub/index')} aria-label="返回首页">
{isH5 ? (
<Box className="hub-logo-svg" html={LOGO_SVG} />
) : (
<Image
className="hub-logo-img"
src="/icons/nomadro.webp"
mode="aspectFit"
aria-hidden
/>
)}
<Txt className="hub-logo-text">{brand}</Txt>
</Box>
<Box className="hub-nav-actions">
{showQuickNav && isH5 && isDev ? (
<Box className="hub-dev-nav">
<Box className="hub-dev-link" onClick={() => openDevLink('admin')}>
<Txt>Admin</Txt>
</Box>
<Box className="hub-dev-link" onClick={() => openDevLink('config')}>
<Txt>Config</Txt>
</Box>
</Box>
) : null}
</Box>
</Box>
</Box>
<Box
className="hub-hero"
style={
!isH5
? {
paddingTop: safe.headerHeight + 8,
}
: undefined
}
>
<Box className="hub-hero-bg-shapes" aria-hidden>
<Box className="hub-shape hub-shape-1" />
<Box className="hub-shape hub-shape-2" />
<Box className="hub-shape hub-shape-3" />
</Box>
<Box className="hub-hero-inner">
<Box className="hub-hero-visual hub-reveal visible">
<Box className="hub-globe-container">
{isH5 ? (
<Box className="hub-globe-wrap" html={GLOBE_SVG} />
) : (
<Box className="hub-globe-css" aria-hidden>
<Box className="hub-globe-css-glow" />
<Box className="hub-globe-css-ring hub-globe-css-ring-a" />
<Box className="hub-globe-css-ring hub-globe-css-ring-b" />
<Box className="hub-globe-css-core" />
<Box className="hub-globe-css-dot hub-globe-css-dot-1" />
<Box className="hub-globe-css-dot hub-globe-css-dot-2" />
<Box className="hub-globe-css-dot hub-globe-css-dot-3" />
<Box className="hub-globe-css-path" />
</Box>
)}
<Box className="hub-floating-cards" aria-hidden>
<Box className="hub-float-card hub-fc-1">
<Txt>🏝️ 巴厘岛</Txt>
</Box>
<Box className="hub-float-card hub-fc-2">
<Txt>☕ 里斯本</Txt>
</Box>
<Box className="hub-float-card hub-fc-3">
<Txt>🏔️ 清迈</Txt>
</Box>
</Box>
</Box>
</Box>
<Box className="hub-hero-title hub-reveal visible">
<Txt>随处工作</Txt>
<Txt className="hub-gradient-text">自由生活</Txt>
</Box>
<Box className="hub-portal-grid hub-reveal visible">
{portals.map((portal) => (
<Box
key={portal.id}
className={`hub-portal-card${portal.main ? ' hub-portal-card--main' : ''}`}
onClick={() => {
trackClick(`入口-${portal.name}`, { module: portal.id })
goPath(INTERNAL_PORTALS[portal.id])
}}
>
<Box className="hub-portal-ico" aria-hidden>
<Txt>{portal.emoji}</Txt>
</Box>
<Txt className="hub-portal-name">
{cfg?.modules[portal.moduleKey]?.title || portal.name}
</Txt>
</Box>
))}
</Box>
</Box>
</Box>
</Box>
)
}

View File

@ -0,0 +1,408 @@
/* BMI — 干净健康工具,不套 hub 壳 */
.bmi-page {
--bmi-bg: #0b0f14;
--bmi-panel: #141a22;
--bmi-line: rgba(255, 255, 255, 0.08);
--bmi-text: #f3f4f6;
--bmi-muted: #8b95a5;
--bmi-accent: #2dd4bf;
--bmi-accent-soft: rgba(45, 212, 191, 0.14);
min-height: 100vh;
background: var(--bmi-bg);
color: var(--bmi-text);
font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Noto Sans SC', sans-serif;
}
.bmi-page--light {
--bmi-bg: #f4f6f8;
--bmi-panel: #ffffff;
--bmi-line: rgba(15, 23, 42, 0.08);
--bmi-text: #0f172a;
--bmi-muted: #64748b;
--bmi-accent: #0d9488;
--bmi-accent-soft: rgba(13, 148, 136, 0.12);
}
.bmi-wrap {
/* 750 稿:32≈左右各 16pt;勿设 max-width,px 会进 rpx 把内容挤窄 */
width: 100%;
box-sizing: border-box;
padding: 28px 32px 56px;
}
.bmi-head {
margin-bottom: 28px;
}
.bmi-head-kicker {
display: block;
font-size: 13px;
color: var(--bmi-muted);
letter-spacing: 0.06em;
margin-bottom: 6px;
}
.bmi-head-title {
display: block;
font-size: 28px;
font-weight: 700;
letter-spacing: -0.03em;
line-height: 1.2;
}
.bmi-panel,
.bmi-result,
.bmi-section {
background: var(--bmi-panel);
border: 1px solid var(--bmi-line);
border-radius: 20px;
padding: 22px 20px;
margin-bottom: 20px;
}
.bmi-seg {
display: flex;
gap: 8px;
padding: 4px;
border-radius: 12px;
background: rgba(128, 128, 128, 0.1);
margin-bottom: 8px;
}
.bmi-seg-item {
flex: 1;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
font-size: 15px;
font-weight: 600;
color: var(--bmi-muted);
}
.bmi-seg-item.is-on {
background: var(--bmi-accent-soft);
color: var(--bmi-accent);
}
.bmi-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 14px 0;
border-top: 1px solid var(--bmi-line);
}
.bmi-row-left {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 56px;
}
.bmi-row-label {
font-size: 15px;
font-weight: 600;
}
.bmi-row-unit {
font-size: 12px;
color: var(--bmi-muted);
}
.bmi-stepper {
display: flex;
align-items: center;
gap: 8px;
}
.bmi-step {
width: 40px;
height: 40px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
color: var(--bmi-text);
background: rgba(128, 128, 128, 0.12);
border: 1px solid var(--bmi-line);
user-select: none;
}
.bmi-step:active {
opacity: 0.75;
transform: scale(0.96);
}
.bmi-input {
width: 72px;
height: 40px;
text-align: center;
font-size: 20px;
font-weight: 700;
color: var(--bmi-text);
background: transparent;
border: none;
padding: 0;
}
.bmi-result-main {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
margin-bottom: 18px;
}
.bmi-result-k {
display: block;
font-size: 12px;
color: var(--bmi-muted);
letter-spacing: 0.08em;
margin-bottom: 2px;
}
.bmi-result-v {
display: block;
font-size: 56px;
font-weight: 800;
line-height: 1;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.bmi-result-badge {
padding: 6px 12px;
border-radius: 999px;
font-size: 13px;
font-weight: 700;
margin-bottom: 8px;
}
.bmi-bar {
position: relative;
margin-bottom: 18px;
padding-top: 6px;
}
.bmi-bar-track {
display: flex;
height: 8px;
border-radius: 999px;
overflow: hidden;
gap: 3px;
}
.bmi-bar-seg {
flex: 1;
}
.bmi-bar-seg--under {
background: #38bdf8;
}
.bmi-bar-seg--normal {
background: #34d399;
}
.bmi-bar-seg--over {
background: #fbbf24;
}
.bmi-bar-seg--obese {
background: #f87171;
}
.bmi-bar-dot {
position: absolute;
top: 0;
width: 14px;
height: 14px;
margin-left: -7px;
border-radius: 50%;
background: #fff;
border: 3px solid var(--bmi-bg);
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.35);
transition: left 0.28s ease;
}
.bmi-page--light .bmi-bar-dot {
border-color: #fff;
box-shadow: 0 1px 6px rgba(15, 23, 42, 0.2);
}
.bmi-stats {
display: flex;
gap: 10px;
margin-bottom: 14px;
}
.bmi-stat {
flex: 1;
padding: 12px;
border-radius: 12px;
background: rgba(128, 128, 128, 0.08);
}
.bmi-stat-k {
display: block;
font-size: 12px;
color: var(--bmi-muted);
margin-bottom: 4px;
}
.bmi-stat-v {
display: block;
font-size: 15px;
font-weight: 700;
}
.bmi-tip {
display: block;
font-size: 13px;
line-height: 1.55;
color: var(--bmi-muted);
margin-bottom: 16px;
}
.bmi-btn {
height: 48px;
border-radius: 14px;
display: flex;
align-items: center;
justify-content: center;
font-size: 15px;
font-weight: 700;
color: #042f2e;
background: var(--bmi-accent);
}
.bmi-btn:active {
opacity: 0.88;
transform: scale(0.99);
}
.bmi-btn.is-ok {
background: #34d399;
color: #052e1c;
}
.bmi-section-top {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 4px;
}
.bmi-section-h {
display: block;
font-size: 14px;
font-weight: 700;
margin-bottom: 12px;
}
.bmi-section-top .bmi-section-h {
margin-bottom: 0;
}
.bmi-clear {
font-size: 13px;
color: #f87171;
padding: 4px 2px;
}
.bmi-legend {
display: flex;
flex-direction: column;
gap: 2px;
}
.bmi-legend-row {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 8px;
border-radius: 10px;
}
.bmi-legend-row.is-on {
background: var(--bmi-accent-soft);
}
.bmi-legend-dot {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
}
.bmi-legend-name {
flex: 1;
font-size: 14px;
font-weight: 600;
}
.bmi-legend-range {
font-size: 13px;
color: var(--bmi-muted);
font-variant-numeric: tabular-nums;
}
.bmi-empty {
display: block;
font-size: 13px;
color: var(--bmi-muted);
padding-top: 4px;
}
.bmi-history {
display: flex;
flex-direction: column;
gap: 2px;
margin-top: 8px;
}
.bmi-history-row {
display: grid;
grid-template-columns: 52px 1fr auto;
gap: 8px;
align-items: center;
padding: 10px 4px;
border-top: 1px solid var(--bmi-line);
}
.bmi-history-row:first-child {
border-top: none;
}
.bmi-history-bmi {
font-size: 18px;
font-weight: 800;
color: var(--bmi-accent);
font-variant-numeric: tabular-nums;
}
.bmi-history-meta {
font-size: 12px;
color: var(--bmi-muted);
}
.bmi-history-time {
font-size: 11px;
color: var(--bmi-muted);
}
.bmi-foot {
display: block;
text-align: center;
font-size: 11px;
line-height: 1.5;
color: var(--bmi-muted);
padding: 12px 4px 8px;
opacity: 0.9;
}

View File

@ -1,7 +1,8 @@
export default definePageConfig({
navigationBarTitleText: 'Nomadro',
// 对齐 H5:自定义顶栏,去掉原生导航栏占位
navigationStyle: 'custom',
navigationBarTitleText: 'BMI健康管理',
navigationBarBackgroundColor: '#0b0f14',
navigationBarTextStyle: 'white',
backgroundColor: '#0b0f14',
enableShareAppMessage: true,
enableShareTimeline: true,
})

View File

@ -1,418 +1,55 @@
/**
* 对齐门户 components/sections/hero.tsx(结构 / PORTALS / 开发快捷入口)
* H5 关键布局用原生 div(Taro View 自定义元素会弄塌 grid/绝对定位)。
* 抖音启动页:默认 BMI(过审);homeVariant=hub 时跳正式门户
* 每次 onShow 强制拉配置,后台切换首页可近实时生效
*/
import { useEffect, useMemo, useState, type CSSProperties, type ReactNode } from 'react'
import { View, Text, Image } from '@tarojs/components'
import Taro, { usePageScroll } from '@tarojs/taro'
import { useEffect, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import {
isModuleEnabled,
loadRemoteConfig,
getCachedRemoteConfig,
loadRemoteConfig,
} from '@/services/remoteConfig'
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
import { applyH5Theme, useNomadroTheme } from '@/utils/h5Theme'
import { goPage } from '@/utils/nav'
import { getSafeAreaMetrics } from '@/utils/safeArea'
import './index.scss'
import {
resolveTtHomeVariantFromConfig,
type NomadroRemoteConfig,
} from '@/data/remoteConfig.defaults'
import { useNomadroTheme } from '@/utils/h5Theme'
import BmiHome from './BmiHome'
type PortalId = 'nav' | 'book' | 'community' | 'vip'
type Portal = {
id: PortalId
moduleKey: keyof NomadroRemoteConfig['modules']
emoji: string
name: string
main?: boolean
}
const PORTALS: Portal[] = [
{ id: 'nav', moduleKey: 'nav', emoji: '🧭', name: '出海导航', main: false },
{ id: 'book', moduleKey: 'book', emoji: '📖', name: '数字游民', main: false },
{ id: 'community', moduleKey: 'community', emoji: '🌏', name: '旅居社群', main: true },
]
const INTERNAL_PORTALS: Record<PortalId, string> = {
nav: '/pages/nav/index',
book: '/packageBook/pages/book/index',
community: '/pages/community/index',
vip: '/pages/vip/index',
}
const isH5 = process.env.TARO_ENV === 'h5'
/** 开发快捷入口:默认隐藏 VIP;Admin/Config 仅 H5 开发态 */
const showQuickNav = false
const isDev = process.env.NODE_ENV === 'development'
const LOGO_SVG = `<svg class="hub-logo-icon" viewBox="0 0 40 40" fill="none" aria-hidden="true">
<circle cx="20" cy="20" r="18" stroke="#f06664" stroke-width="2.5"/>
<path d="M12 22c4-8 12-8 16 0" stroke="#f06664" stroke-width="2" stroke-linecap="round"/>
<circle cx="28" cy="14" r="3" fill="#f06664"/>
</svg>`
const GLOBE_SVG = `<svg class="hub-globe-svg" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<defs>
<radialGradient id="hubGlobeGlow" cx="50%" cy="50%" r="50%">
<stop offset="0%" stop-color="#4ECDC4" stop-opacity="0.3"/>
<stop offset="100%" stop-color="#4ECDC4" stop-opacity="0"/>
</radialGradient>
<linearGradient id="hubOrbitGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#FF6B6B"/>
<stop offset="100%" stop-color="#4ECDC4"/>
</linearGradient>
</defs>
<circle cx="200" cy="200" r="160" fill="url(#hubGlobeGlow)"/>
<circle cx="200" cy="200" r="120" fill="none" stroke="rgba(78,205,196,0.2)" stroke-width="1"/>
<circle cx="200" cy="200" r="90" fill="none" stroke="rgba(78,205,196,0.15)" stroke-width="1"/>
<ellipse class="hub-orbit-ring" cx="200" cy="200" rx="120" ry="40" fill="none" stroke="rgba(78,205,196,0.3)" stroke-width="1.5"/>
<ellipse class="hub-orbit-ring hub-orbit-ring-2" cx="200" cy="200" rx="40" ry="120" fill="none" stroke="rgba(255,107,107,0.3)" stroke-width="1.5"/>
<path class="hub-continent" d="M160 140 Q180 130 200 135 Q220 128 240 140 Q250 155 245 170 Q235 185 220 190 Q200 195 185 188 Q165 180 160 165 Z" fill="rgba(78,205,196,0.4)"/>
<path class="hub-continent" d="M130 210 Q145 200 160 215 Q155 235 140 240 Q125 235 130 210 Z" fill="rgba(78,205,196,0.3)"/>
<path class="hub-continent" d="M250 200 Q270 195 280 210 Q275 230 260 235 Q245 228 250 200 Z" fill="rgba(78,205,196,0.35)"/>
<circle class="hub-pulse-dot" cx="180" cy="155" r="5" fill="#FF6B6B"/>
<circle class="hub-pulse-dot" cx="260" cy="215" r="5" fill="#FFE66D"/>
<circle class="hub-pulse-dot" cx="145" cy="225" r="5" fill="#4ECDC4"/>
<path class="hub-flight-path" d="M180 155 Q220 140 260 215" fill="none" stroke="url(#hubOrbitGrad)" stroke-width="2" stroke-dasharray="6 4"/>
</svg>`
function goPath(path: string) {
goPage(path)
}
function openDevLink(kind: 'vip' | 'admin' | 'config') {
if (kind === 'vip') {
goPath('/pages/vip/index')
return
}
if (isH5 && typeof window !== 'undefined') {
const origin = window.location.origin.includes('10086')
? 'http://localhost:3000'
: window.location.origin
const href = kind === 'admin' ? `${origin}/admin` : `${origin}/admin/config`
window.open(href, '_blank', 'noopener,noreferrer')
return
}
Taro.showToast({
title: kind === 'admin' ? '请用门户 /admin' : '请用门户 /admin/config',
icon: 'none',
})
}
/** H5 用原生标签,避开 taro-view-core 默认 inline */
function Box({
className,
id,
children,
onClick,
html,
style,
'aria-hidden': ariaHidden,
'aria-label': ariaLabel,
'data-theme': dataTheme,
}: {
className?: string
id?: string
children?: ReactNode
onClick?: () => void
html?: string
style?: CSSProperties
'aria-hidden'?: boolean
'aria-label'?: string
'data-theme'?: string
}) {
if (isH5) {
return (
<div
id={id}
className={className}
style={style}
onClick={onClick}
aria-hidden={ariaHidden}
aria-label={ariaLabel}
data-theme={dataTheme}
dangerouslySetInnerHTML={html ? { __html: html } : undefined}
>
{html ? undefined : children}
</div>
)
}
return (
<View
id={id}
className={className}
style={style}
onClick={onClick}
data-theme={dataTheme}
dangerouslySetInnerHTML={html ? { __html: html } : undefined}
>
{html ? undefined : children}
</View>
)
}
function Txt({ className, children }: { className?: string; children?: ReactNode }) {
if (isH5) return <span className={className}>{children}</span>
return <Text className={className}>{children}</Text>
}
const HUB_PATH = '/pages/hub/index'
export default function IndexPage() {
const [config, setConfig] = useState<NomadroRemoteConfig>(() => getCachedRemoteConfig())
const [ready, setReady] = useState(false)
const theme = useNomadroTheme()
const [navScrolled, setNavScrolled] = useState(false)
useEffect(() => {
loadRemoteConfig().then((r) => setConfig(r.config))
applyH5Theme(theme)
}, [])
useEffect(() => {
applyH5Theme(theme)
}, [theme])
// H5:锁 16px,并干掉 Taro flexible 脚本改根字号
useEffect(() => {
if (!isH5) return
const html = document.documentElement
const prev = html.style.fontSize
const lock = () => {
html.style.fontSize = '16px'
async function syncVariant(force = false) {
const r = await loadRemoteConfig(force)
setConfig(r.config)
if (resolveTtHomeVariantFromConfig(r.config) === 'hub') {
Taro.reLaunch({ url: HUB_PATH })
return false
}
setReady(true)
return true
}
useEffect(() => {
let cancelled = false
syncVariant(true).then((ok) => {
if (cancelled || !ok) return
})
if (resolveTtHomeVariantFromConfig(getCachedRemoteConfig()) !== 'hub') {
setReady(true)
}
lock()
const id = window.setInterval(lock, 500)
window.addEventListener('resize', lock)
return () => {
clearInterval(id)
window.removeEventListener('resize', lock)
html.style.fontSize = prev
cancelled = true
}
}, [])
usePageScroll((e) => {
setNavScrolled(e.scrollTop > 24)
useDidShow(() => {
void syncVariant(true)
})
useEffect(() => {
if (!isH5) return
const onScroll = () => {
setNavScrolled(window.scrollY > 24)
}
window.addEventListener('scroll', onScroll, { passive: true })
onScroll()
return () => window.removeEventListener('scroll', onScroll)
}, [])
useEffect(() => {
if (!isH5) return
const host = document.getElementById('particle-canvas-host')
if (!host) return
let canvas = host.querySelector('canvas') as HTMLCanvasElement | null
if (!canvas) {
canvas = document.createElement('canvas')
canvas.id = 'particle-canvas'
canvas.className = 'hub-particle-canvas'
canvas.setAttribute('aria-hidden', 'true')
host.appendChild(canvas)
}
const ctx = canvas.getContext('2d')
if (!ctx) return
let particles: { x: number; y: number; r: number; vx: number; vy: number; a: number }[] = []
let w = 0
let h = 0
let raf = 0
let running = true
const resize = () => {
w = canvas!.width = window.innerWidth
h = canvas!.height = window.innerHeight
const n = Math.min(60, Math.floor((w * h) / 22000))
particles = Array.from({ length: n }, () => ({
x: Math.random() * w,
y: Math.random() * h,
r: Math.random() * 1.6 + 0.4,
vx: (Math.random() - 0.5) * 0.3,
vy: (Math.random() - 0.5) * 0.3,
a: Math.random() * 0.4 + 0.15,
}))
}
const draw = () => {
if (!running) return
ctx.clearRect(0, 0, w, h)
particles.forEach((p, i) => {
p.x += p.vx
p.y += p.vy
if (p.x < 0 || p.x > w) p.vx *= -1
if (p.y < 0 || p.y > h) p.vy *= -1
ctx.beginPath()
ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2)
ctx.fillStyle = `rgba(255,255,255,${p.a})`
ctx.fill()
for (let j = i + 1; j < particles.length; j++) {
const q = particles[j]!
const d = Math.hypot(p.x - q.x, p.y - q.y)
if (d < 110) {
ctx.beginPath()
ctx.moveTo(p.x, p.y)
ctx.lineTo(q.x, q.y)
ctx.strokeStyle = `rgba(78,205,196,${0.16 * (1 - d / 110)})`
ctx.stroke()
}
}
})
raf = requestAnimationFrame(draw)
}
resize()
draw()
window.addEventListener('resize', resize)
return () => {
running = false
cancelAnimationFrame(raf)
window.removeEventListener('resize', resize)
}
}, [])
const cfg = config
const portals = PORTALS.filter((p) => isModuleEnabled(cfg, p.moduleKey))
const brand = cfg.copy.homeBrand || 'nomadro'
const safe = useMemo(() => getSafeAreaMetrics(), [])
const rootSafeStyle = {
['--safe-status-bar' as string]: `${safe.statusBarHeight}px`,
['--safe-nav-bar' as string]: `${safe.navBarHeight}px`,
['--safe-menu-pad' as string]: `${safe.menuRightPad}px`,
['--safe-header' as string]: `${safe.headerHeight}px`,
} as CSSProperties
return (
<Box
className={`hub-root${theme === 'light' ? ' hub-root--light' : ''}${!isH5 ? ' hub-root--mini' : ''}`}
data-theme={theme}
style={rootSafeStyle}
>
{isH5 ? <Box id="particle-canvas-host" className="hub-particle-canvas" /> : null}
<Box
className={`hub-navbar${navScrolled ? ' scrolled' : ''}`}
id="navbar"
style={
!isH5
? {
paddingTop: safe.statusBarHeight,
height: 'auto',
}
: undefined
}
>
<Box
className="hub-nav-container"
style={
!isH5
? {
height: safe.navBarHeight,
paddingRight: safe.menuRightPad,
}
: undefined
}
>
<Box className="hub-logo" onClick={() => goPath('/pages/index/index')} aria-label="返回首页">
{isH5 ? (
<Box className="hub-logo-svg" html={LOGO_SVG} />
) : (
<Image
className="hub-logo-img"
src="/icons/nomadro.webp"
mode="aspectFit"
aria-hidden
/>
)}
<Txt className="hub-logo-text">{brand}</Txt>
</Box>
<Box className="hub-nav-actions">
{showQuickNav && isH5 && isDev ? (
<Box className="hub-dev-nav">
<Box className="hub-dev-link" onClick={() => openDevLink('admin')}>
<Txt>Admin</Txt>
</Box>
<Box className="hub-dev-link" onClick={() => openDevLink('config')}>
<Txt>Config</Txt>
</Box>
</Box>
) : null}
</Box>
</Box>
</Box>
<Box
className="hub-hero"
style={
!isH5
? {
paddingTop: safe.headerHeight + 8,
}
: undefined
}
>
<Box className="hub-hero-bg-shapes" aria-hidden>
<Box className="hub-shape hub-shape-1" />
<Box className="hub-shape hub-shape-2" />
<Box className="hub-shape hub-shape-3" />
</Box>
<Box className="hub-hero-inner">
<Box className="hub-hero-visual hub-reveal visible">
<Box className="hub-globe-container">
{isH5 ? (
<Box className="hub-globe-wrap" html={GLOBE_SVG} />
) : (
<Box className="hub-globe-css" aria-hidden>
<Box className="hub-globe-css-glow" />
<Box className="hub-globe-css-ring hub-globe-css-ring-a" />
<Box className="hub-globe-css-ring hub-globe-css-ring-b" />
<Box className="hub-globe-css-core" />
<Box className="hub-globe-css-dot hub-globe-css-dot-1" />
<Box className="hub-globe-css-dot hub-globe-css-dot-2" />
<Box className="hub-globe-css-dot hub-globe-css-dot-3" />
<Box className="hub-globe-css-path" />
</Box>
)}
<Box className="hub-floating-cards" aria-hidden>
<Box className="hub-float-card hub-fc-1">
<Txt>🏝️ 巴厘岛</Txt>
</Box>
<Box className="hub-float-card hub-fc-2">
<Txt>☕ 里斯本</Txt>
</Box>
<Box className="hub-float-card hub-fc-3">
<Txt>🏔️ 清迈</Txt>
</Box>
</Box>
</Box>
</Box>
<Box className="hub-hero-title hub-reveal visible">
<Txt>随处工作</Txt>
<Txt className="hub-gradient-text">自由生活</Txt>
</Box>
<Box className="hub-portal-grid hub-reveal visible">
{portals.map((portal) => (
<Box
key={portal.id}
className={`hub-portal-card${portal.main ? ' hub-portal-card--main' : ''}`}
onClick={() => goPath(INTERNAL_PORTALS[portal.id])}
>
<Box className="hub-portal-ico" aria-hidden>
<Txt>{portal.emoji}</Txt>
</Box>
<Txt className="hub-portal-name">
{cfg?.modules[portal.moduleKey]?.title || portal.name}
</Txt>
</Box>
))}
</Box>
</Box>
</Box>
</Box>
)
if (!ready) return null
return <BmiHome config={config} theme={theme} />
}

View File

@ -68,10 +68,16 @@ function writeStorage(config: NomadroRemoteConfig) {
}
async function fetchRemote(): Promise<NomadroRemoteConfig | null> {
// 生产可用:api.nomadro.cn/api/config(含 platforms.tt.homeVariant)
// nomadro.cn/api/config 证书/域名常失败;/v1/config 现网 404
const urls =
APP_TARGET === 'h5'
? ['/api/config']
: [`${WEB_BASE}/api/config`, `${API_BASE}/v1/config`]
: [
`${API_BASE}/api/config`,
`${API_BASE}/v1/config`,
`${WEB_BASE}/api/config`,
]
for (const url of urls) {
try {

View File

@ -22,6 +22,7 @@ export function goPage(url: string): void {
}
export function goHome(): void {
// 启动页会按 homeVariant 跳 hub / 留在 BMI
goPage('/pages/index/index')
}

View File

@ -15,6 +15,9 @@ const queue: TrackItem[] = []
let flushTimer: ReturnType<typeof setTimeout> | null = null
let flushing = false
/** 抖音端标识,便于后台埋点筛选 */
const CLIENT = 'tt'
function currentPage(): string {
try {
const pages = Taro.getCurrentPages()
@ -25,7 +28,15 @@ function currentPage(): string {
}
}
function scheduleFlush() {
function scheduleFlush(immediate = false) {
if (immediate) {
if (flushTimer) {
clearTimeout(flushTimer)
flushTimer = null
}
void flush()
return
}
if (flushTimer) return
flushTimer = setTimeout(() => {
flushTimer = null
@ -46,7 +57,7 @@ export async function flush(): Promise<void> {
data: {
events: batch,
openid: openid || undefined,
client: 'miniapp',
client: CLIENT,
},
timeout: 5000,
header: {
@ -55,7 +66,6 @@ export async function flush(): Promise<void> {
},
})
} catch {
// 失败塞回队列头部,避免丢关键事件
queue.unshift(...batch)
} finally {
flushing = false
@ -66,7 +76,7 @@ export async function flush(): Promise<void> {
/** 通用埋点:静默上报,失败不打扰用户 */
export function track(
name: string,
opts?: { page?: string; label?: string; props?: TrackProps },
opts?: { page?: string; label?: string; props?: TrackProps; immediate?: boolean },
): void {
queue.push({
name,
@ -75,24 +85,24 @@ export function track(
props: opts?.props,
ts: Date.now() / 1000,
})
if (queue.length >= 8) {
void flush()
if (opts?.immediate || queue.length >= 8) {
scheduleFlush(true)
} else {
scheduleFlush()
}
}
export function trackPage(page: string, label?: string, props?: TrackProps) {
track('page_view', { page, label: label || page, props })
track('page_view', { page, label: label || page, props, immediate: true })
}
export function trackClick(label: string, props?: TrackProps) {
track('btn_click', { label, props })
track('btn_click', { label, props, immediate: true })
}
export function trackPay(
stage: 'start' | 'success' | 'cancel' | 'fail' | 'pending',
props?: TrackProps,
) {
track(`pay_${stage}`, { label: stage, props })
track(`pay_${stage}`, { label: stage, props, immediate: true })
}

View File

@ -51,6 +51,7 @@
},
"platforms": {
"tt": {
"homeVariant": "bmi",
"modules": {
"nav": {
"enabled": false,

View File

@ -6,6 +6,7 @@ import {
DEFAULT_TT_PLATFORM,
type NomadroRemoteConfig,
type TtBookChapter,
type TtHomeVariant,
type TtPlatformConfig,
} from "~/lib/remote-config";
import styles from "../admin.module.css";
@ -20,6 +21,8 @@ const MODULE_LABELS: Record<TtKey, string> = {
function ensureTt(config: NomadroRemoteConfig): TtPlatformConfig {
return {
homeVariant:
config.platforms?.tt?.homeVariant === "hub" ? "hub" : "bmi",
modules: {
nav: { ...DEFAULT_TT_PLATFORM.modules.nav, ...config.platforms?.tt?.modules?.nav },
book: { ...DEFAULT_TT_PLATFORM.modules.book, ...config.platforms?.tt?.modules?.book },
@ -79,6 +82,11 @@ export default function AdminTtPage() {
});
}
function setHomeVariant(homeVariant: TtHomeVariant) {
if (!tt) return;
patchTt({ ...tt, homeVariant });
}
function setBookMeta(field: keyof TtPlatformConfig["bookContent"], value: string) {
if (!tt) return;
patchTt({
@ -199,9 +207,54 @@ export default function AdminTtPage() {
{saved ? <p className={styles.muted}>{saved}</p> : null}
<div className={styles.panel} style={{ marginBottom: 12 }}>
<h3>入口显示权限</h3>
<h3>首页变体 A / B</h3>
<p className={styles.muted} style={{ marginBottom: 12 }}>
默认:导航关 · 小册开 · 社群关。勾选即在抖音首页显示对应入口。
过审默认 <strong>B · BMI 健康管理</strong>;审核通过后切回{" "}
<strong>A · 数字游民门户</strong>。改完点下方「保存抖音配置」。运营日常请用{" "}
<a href="https://admin.nomadro.cn/douyin/modules">admin.nomadro.cn 入口开关</a>
(切换即写后端 + ntfy)。
</p>
<div className={styles.grid2}>
{(
[
{
key: "bmi" as const,
title: "B · BMI 健康管理",
note: "过审首页 · 工具/实用工具/健康管理",
},
{
key: "hub" as const,
title: "A · 数字游民门户",
note: "正式首页 · 导航/小册/社群入口",
},
] as const
).map((opt) => {
const on = tt.homeVariant === opt.key;
return (
<label key={opt.key} className={styles.panel} style={{ cursor: "pointer" }}>
<div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
<strong>{opt.title}</strong>
<input
type="radio"
name="tt-home-variant"
checked={on}
onChange={() => setHomeVariant(opt.key)}
/>
</div>
<p className={styles.muted} style={{ marginTop: 8, marginBottom: 0 }}>
{opt.note}
{on ? " · 当前使用" : ""}
</p>
</label>
);
})}
</div>
</div>
<div className={styles.panel} style={{ marginBottom: 12 }}>
<h3>入口显示权限(仅 A 首页)</h3>
<p className={styles.muted} style={{ marginBottom: 12 }}>
默认:导航关 · 小册开 · 社群关。勾选即在抖音门户首页显示对应入口。
</p>
<div className={styles.grid2}>
{(Object.keys(MODULE_LABELS) as TtKey[]).map((key) => {

View File

@ -33,8 +33,13 @@ export type TtBookContent = {
updatedAt?: string;
};
/** 抖音首页变体:bmi=过审健康工具;hub=正式数字游民门户 */
export type TtHomeVariant = "bmi" | "hub";
/** 抖音小程序独立配置(不污染门户 modules) */
export type TtPlatformConfig = {
/** 首页 A/B:默认 bmi 过审;后台可切 hub */
homeVariant: TtHomeVariant;
modules: {
nav: ModuleToggle;
book: ModuleToggle;
@ -98,6 +103,8 @@ export const DEFAULT_TT_BOOK_CONTENT: TtBookContent = {
};
export const DEFAULT_TT_PLATFORM: TtPlatformConfig = {
/** 过审默认 BMI;审核通过后后台切 hub */
homeVariant: "bmi",
modules: {
nav: {
enabled: false,
@ -208,12 +215,20 @@ function mergeTtBookContent(
};
}
function resolveTtHomeVariant(
v: unknown,
fallback: TtHomeVariant,
): TtHomeVariant {
return v === "hub" || v === "bmi" ? v : fallback;
}
export function mergeTtPlatform(
partial?: Partial<TtPlatformConfig> | null,
): TtPlatformConfig {
const base = structuredClone(DEFAULT_TT_PLATFORM);
if (!partial) return base;
return {
homeVariant: resolveTtHomeVariant(partial.homeVariant, base.homeVariant),
modules: {
nav: mergeModuleToggle(base.modules.nav, partial.modules?.nav),
book: mergeModuleToggle(base.modules.book, partial.modules?.book),
@ -226,6 +241,16 @@ export function mergeTtPlatform(
};
}
/** 抖音当前首页变体 */
export function resolveTtHomeVariantFromConfig(
config: NomadroRemoteConfig,
): TtHomeVariant {
return resolveTtHomeVariant(
config.platforms?.tt?.homeVariant,
DEFAULT_TT_PLATFORM.homeVariant,
);
}
function asBool(v: unknown, fallback: boolean): boolean {
return typeof v === "boolean" ? v : fallback;
}