Ship social selfie face-check, avatar UX by device, blog/admin, and notify polish.
Add InsightFace/OpenCV challenge upload, PC vs mobile capture branching, and fix avatar persistence into roster/profile pages. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
ffa456afdf
commit
5271aabc98
@ -199,7 +199,7 @@ pnpm dev:api
|
||||
|
||||
与旅居社群 `/community` **完全独立**:门户 `src/modules/social` + `src/app/social`;后端 `social_svc`(前缀 `/api/social/v1`,库文件 `data/social/social.db` 或 `SOCIAL_DB_PATH`);`SOCIAL_ENABLED=false` 或挂载失败不影响 ebook / community / pay。门户首页主入口为「游民社区」;旅居社群仍保留。增量部署见 [`deploy/social/README.md`](deploy/social/README.md)。
|
||||
|
||||
**加入流程(`/social/join`)**:支付成功 → `?step=profile` 完善资料(PC 双栏 + 实时名片;H5 全宽)→ 完成。本地 `joinFlow` 标记;开发可跳过支付。**头像**:`POST /api/social/v1/upload` → 美国机 SeaweedFS(`s3.nomadro.com`,与 community 共用 `S3_*`);失败落本地 `/api/social/v1/files/avatar/*`。资料草稿挂载后再读 localStorage,避免 SSR hydration 不一致。
|
||||
**加入流程(`/social/join`)**:支付成功 → `?step=profile` 完善资料(PC 双栏 + 实时名片;H5 全宽)→ 完成。本地 `joinFlow` 标记;开发可跳过支付。**头像**:`POST /api/social/v1/upload` → 美国机 SeaweedFS(`s3.nomadro.com`,与 community 共用 `S3_*`);失败落本地 `/api/social/v1/files/avatar/*`。资料草稿挂载后再读 localStorage,避免 SSR hydration 不一致。**人脸门禁**(默认开):头像需**单人正脸**;优先 InsightFace 检测 + RGB 活体。**现场自拍核验**(推荐):`POST /api/social/v1/avatar/challenge` 收正脸+转头两帧,校验同人 embedding + 转头幅度后再存头像。关检测:`SOCIAL_AVATAR_FACE_CHECK=false`;关活体:`SOCIAL_AVATAR_LIVENESS=false`。
|
||||
|
||||
**地理发现**:`/social/map`、`/social/places`;内部 API `GET /api/social/v1/map/cities`。对外标准面:`/api/public/v1`(OpenAPI / SDK / MCP / Skill,见 [`docs/public-api.md`](docs/public-api.md))。**默认发版 `.com`(美国机)**;`.cn` 独立同步。
|
||||
|
||||
|
||||
@ -145,9 +145,10 @@ app.include_router(vip_library_admin.router)
|
||||
app.include_router(vip_library_public.router)
|
||||
app.include_router(weapp_switches_admin.router)
|
||||
app.include_router(social_ops_admin.router)
|
||||
from ebook_svc.routers import social_ugc_admin, community_admin # noqa: E402
|
||||
from ebook_svc.routers import social_ugc_admin, social_blog_admin, community_admin # noqa: E402
|
||||
|
||||
app.include_router(social_ugc_admin.router)
|
||||
app.include_router(social_blog_admin.router)
|
||||
app.include_router(community_admin.router)
|
||||
app.include_router(shop_admin.router)
|
||||
app.include_router(memo_admin.router)
|
||||
|
||||
@ -21,3 +21,6 @@ requests
|
||||
minio
|
||||
opencv-python-headless
|
||||
rapidocr-onnxruntime
|
||||
# Avatar face gate (preferred). OpenCV Haar remains fallback if import fails.
|
||||
onnxruntime
|
||||
insightface
|
||||
|
||||
@ -85,11 +85,13 @@ app.include_router(nav_admin.router)
|
||||
from ebook_svc.routers import weapp_switches_admin # noqa: E402
|
||||
from ebook_svc.routers import social_ops_admin # noqa: E402
|
||||
from ebook_svc.routers import social_ugc_admin # noqa: E402
|
||||
from ebook_svc.routers import social_blog_admin # noqa: E402
|
||||
from ebook_svc.routers import community_admin # noqa: E402
|
||||
|
||||
app.include_router(weapp_switches_admin.router)
|
||||
app.include_router(social_ops_admin.router)
|
||||
app.include_router(social_ugc_admin.router)
|
||||
app.include_router(social_blog_admin.router)
|
||||
app.include_router(community_admin.router)
|
||||
# 运营:ntfy 状态 / 试推(admin.nomadro.com)
|
||||
from ebook_svc.routers import ops_admin # noqa: E402
|
||||
|
||||
42
apps/api/services/ebook_svc/routers/social_blog_admin.py
Normal file
42
apps/api/services/ebook_svc/routers/social_blog_admin.py
Normal file
@ -0,0 +1,42 @@
|
||||
"""admin.nomadro.com · Nomad Blog 运营(AdSense / 显隐 / 置顶)"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ebook_svc.core.security import require_admin
|
||||
from ebook_svc.services import social_blog_ops as blog
|
||||
|
||||
router = APIRouter(prefix="/api/admin/social/blog", tags=["social-blog-admin"])
|
||||
|
||||
|
||||
class BlogOpsPatch(BaseModel):
|
||||
featuredSlug: str | None = None
|
||||
hiddenSlugs: list[str] | None = None
|
||||
hideSlug: str | None = None
|
||||
showSlug: str | None = None
|
||||
note: str | None = None
|
||||
heroLead: str | None = None
|
||||
moduleEnabled: bool | None = None
|
||||
adsenseEnabled: bool | None = None
|
||||
adsenseClientId: str | None = None
|
||||
adsensePublisherId: str | None = None
|
||||
adsenseSlotBlogMid: str | None = None
|
||||
adsenseSlotBlogEnd: str | None = None
|
||||
|
||||
|
||||
@router.get("/overview")
|
||||
async def get_overview(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
return blog.overview()
|
||||
|
||||
|
||||
@router.get("/posts")
|
||||
async def get_posts(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
return blog.list_posts()
|
||||
|
||||
|
||||
@router.patch("/ops")
|
||||
async def patch_ops(body: BlogOpsPatch, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
return blog.patch_ops(body.model_dump(exclude_none=True))
|
||||
229
apps/api/services/ebook_svc/services/social_blog_ops.py
Normal file
229
apps/api/services/ebook_svc/services/social_blog_ops.py
Normal file
@ -0,0 +1,229 @@
|
||||
"""Nomad Blog ops — remote-config 深合并;文章列表从门户 RSS/公开 API 拉取。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
from ebook_svc.services.tt_platform_config import resolve_config_file
|
||||
|
||||
PORTAL = os.getenv("PORTAL_PUBLIC_URL", "https://nomadro.com").rstrip("/")
|
||||
|
||||
|
||||
def _read_raw() -> dict[str, Any]:
|
||||
path = resolve_config_file()
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
return raw if isinstance(raw, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _write_raw(out: dict[str, Any]) -> None:
|
||||
from ebook_svc.services.weapp_switches import _write_raw as write_rc
|
||||
|
||||
write_rc(out)
|
||||
|
||||
|
||||
def _ops_from_raw(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
copy = raw.get("copy") if isinstance(raw.get("copy"), dict) else {}
|
||||
ops = copy.get("socialBlogOps") if isinstance(copy.get("socialBlogOps"), dict) else {}
|
||||
hidden = ops.get("hiddenSlugs")
|
||||
if not isinstance(hidden, list):
|
||||
hidden = []
|
||||
return {
|
||||
"featuredSlug": str(ops.get("featuredSlug") or ""),
|
||||
"hiddenSlugs": [str(x) for x in hidden if str(x).strip()],
|
||||
"note": str(ops.get("note") or ""),
|
||||
"heroLead": str(ops.get("heroLead") or ""),
|
||||
}
|
||||
|
||||
|
||||
def _module_flags(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
modules = raw.get("modules") if isinstance(raw.get("modules"), dict) else {}
|
||||
blog = modules.get("socialBlog") if isinstance(modules.get("socialBlog"), dict) else {}
|
||||
flags = raw.get("flags") if isinstance(raw.get("flags"), dict) else {}
|
||||
return {
|
||||
"moduleEnabled": blog.get("enabled", True) is not False,
|
||||
"adsenseEnabled": bool(flags.get("adsenseEnabled")),
|
||||
"adsenseClientId": str(flags.get("adsenseClientId") or ""),
|
||||
"adsensePublisherId": str(flags.get("adsensePublisherId") or ""),
|
||||
"adsenseSlotBlogMid": str(flags.get("adsenseSlotBlogMid") or ""),
|
||||
"adsenseSlotBlogEnd": str(flags.get("adsenseSlotBlogEnd") or ""),
|
||||
}
|
||||
|
||||
|
||||
def _fetch_posts() -> list[dict[str, Any]]:
|
||||
"""Prefer public JSON; fall back to RSS."""
|
||||
urls = [
|
||||
f"{PORTAL}/api/public/v1/social/blog",
|
||||
f"{PORTAL}/social/blog/rss.xml",
|
||||
]
|
||||
for url in urls:
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={"User-Agent": "nomadro-admin-blog/1.0", "Accept": "*/*"},
|
||||
method="GET",
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=12) as res:
|
||||
body = res.read()
|
||||
ctype = (res.headers.get("Content-Type") or "").lower()
|
||||
if "json" in ctype or url.endswith("/blog"):
|
||||
data = json.loads(body.decode("utf-8", "replace"))
|
||||
items = data.get("items") if isinstance(data, dict) else None
|
||||
if isinstance(items, list):
|
||||
out = []
|
||||
for it in items:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
slug = str(it.get("slug") or "").strip()
|
||||
if not slug:
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"slug": slug,
|
||||
"title": str(it.get("title") or slug),
|
||||
"description": str(it.get("description") or ""),
|
||||
"date": str(it.get("date") or ""),
|
||||
"tags": it.get("tags") if isinstance(it.get("tags"), list) else [],
|
||||
"wordCount": int(it.get("wordCount") or 0),
|
||||
"readingMinutes": int(it.get("readingMinutes") or 0),
|
||||
"locale": str(it.get("locale") or "en"),
|
||||
"url": f"{PORTAL}/social/blog/{slug}",
|
||||
}
|
||||
)
|
||||
return out
|
||||
# RSS
|
||||
root = ET.fromstring(body)
|
||||
items = []
|
||||
for item in root.findall(".//item"):
|
||||
link = (item.findtext("link") or "").strip()
|
||||
title = (item.findtext("title") or "").strip()
|
||||
desc = (item.findtext("description") or "").strip()
|
||||
date = (item.findtext("pubDate") or "").strip()
|
||||
m = re.search(r"/social/blog/([^/?#]+)", link)
|
||||
slug = m.group(1) if m else ""
|
||||
if not slug:
|
||||
continue
|
||||
items.append(
|
||||
{
|
||||
"slug": slug,
|
||||
"title": title or slug,
|
||||
"description": desc,
|
||||
"date": date,
|
||||
"tags": [],
|
||||
"wordCount": 0,
|
||||
"readingMinutes": 0,
|
||||
"locale": "en",
|
||||
"url": link or f"{PORTAL}/social/blog/{slug}",
|
||||
}
|
||||
)
|
||||
if items:
|
||||
return items
|
||||
except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError, ValueError, ET.ParseError):
|
||||
continue
|
||||
return []
|
||||
|
||||
|
||||
def overview() -> dict[str, Any]:
|
||||
raw = _read_raw()
|
||||
ops = _ops_from_raw(raw)
|
||||
flags = _module_flags(raw)
|
||||
posts = _fetch_posts()
|
||||
visible = [p for p in posts if p["slug"] not in set(ops["hiddenSlugs"])]
|
||||
return {
|
||||
"ok": True,
|
||||
"portal": PORTAL,
|
||||
"liveUrl": f"{PORTAL}/social/blog",
|
||||
"aboutUrl": f"{PORTAL}/social/blog/about",
|
||||
"privacyUrl": f"{PORTAL}/social/privacy",
|
||||
"adsTxtUrl": f"{PORTAL}/ads.txt",
|
||||
"rssUrl": f"{PORTAL}/social/blog/rss.xml",
|
||||
"sitemapUrl": f"{PORTAL}/social/sitemap.xml",
|
||||
"counts": {
|
||||
"posts": len(posts),
|
||||
"visible": len(visible),
|
||||
"hidden": len(ops["hiddenSlugs"]),
|
||||
},
|
||||
"ops": ops,
|
||||
**flags,
|
||||
"version": raw.get("version"),
|
||||
"updatedAt": raw.get("updatedAt"),
|
||||
}
|
||||
|
||||
|
||||
def list_posts() -> dict[str, Any]:
|
||||
raw = _read_raw()
|
||||
ops = _ops_from_raw(raw)
|
||||
hidden = set(ops["hiddenSlugs"])
|
||||
featured = ops["featuredSlug"]
|
||||
posts = _fetch_posts()
|
||||
for p in posts:
|
||||
p["hidden"] = p["slug"] in hidden
|
||||
p["featured"] = bool(featured) and p["slug"] == featured
|
||||
# featured first, then date desc-ish (already from source)
|
||||
posts.sort(key=lambda x: (not x["featured"], x.get("hidden", False), x.get("date") or ""), reverse=False)
|
||||
posts.sort(key=lambda x: (0 if x["featured"] else 1, 1 if x["hidden"] else 0))
|
||||
return {"ok": True, "items": posts, "total": len(posts), "ops": ops}
|
||||
|
||||
|
||||
def patch_ops(body: dict[str, Any]) -> dict[str, Any]:
|
||||
raw = _read_raw()
|
||||
out = dict(raw) if raw else {"version": 1, "modules": {}, "flags": {}, "copy": {}}
|
||||
copy = dict(out.get("copy") or {})
|
||||
ops = _ops_from_raw(out)
|
||||
|
||||
if "featuredSlug" in body:
|
||||
ops["featuredSlug"] = str(body.get("featuredSlug") or "").strip()
|
||||
if "note" in body:
|
||||
ops["note"] = str(body.get("note") or "")[:500]
|
||||
if "heroLead" in body:
|
||||
ops["heroLead"] = str(body.get("heroLead") or "")[:400]
|
||||
if "hiddenSlugs" in body and isinstance(body["hiddenSlugs"], list):
|
||||
ops["hiddenSlugs"] = [str(x).strip() for x in body["hiddenSlugs"] if str(x).strip()]
|
||||
if "hideSlug" in body:
|
||||
slug = str(body.get("hideSlug") or "").strip()
|
||||
if slug and slug not in ops["hiddenSlugs"]:
|
||||
ops["hiddenSlugs"].append(slug)
|
||||
if "showSlug" in body:
|
||||
slug = str(body.get("showSlug") or "").strip()
|
||||
ops["hiddenSlugs"] = [s for s in ops["hiddenSlugs"] if s != slug]
|
||||
|
||||
copy["socialBlogOps"] = ops
|
||||
out["copy"] = copy
|
||||
|
||||
# optional module / adsense flags in same patch
|
||||
modules = dict(out.get("modules") or {})
|
||||
flags = dict(out.get("flags") or {})
|
||||
if "moduleEnabled" in body:
|
||||
base = modules.get("socialBlog") if isinstance(modules.get("socialBlog"), dict) else {}
|
||||
modules["socialBlog"] = {
|
||||
**base,
|
||||
"enabled": bool(body["moduleEnabled"]),
|
||||
"title": base.get("title") or "Nomad Blog",
|
||||
"tabLabel": base.get("tabLabel") or "Blog",
|
||||
}
|
||||
out["modules"] = modules
|
||||
for key in (
|
||||
"adsenseEnabled",
|
||||
"adsenseClientId",
|
||||
"adsensePublisherId",
|
||||
"adsenseSlotBlogMid",
|
||||
"adsenseSlotBlogEnd",
|
||||
):
|
||||
if key in body:
|
||||
if key == "adsenseEnabled":
|
||||
flags[key] = bool(body[key])
|
||||
else:
|
||||
flags[key] = str(body.get(key) or "").strip()
|
||||
out["flags"] = flags
|
||||
|
||||
_write_raw(out)
|
||||
return overview()
|
||||
@ -27,6 +27,7 @@ MODULE_KEYS = (
|
||||
"book",
|
||||
"community",
|
||||
"social",
|
||||
"socialBlog",
|
||||
"vip",
|
||||
"destinations",
|
||||
"meetups",
|
||||
@ -44,6 +45,12 @@ DEFAULT_MODULES: dict[str, dict[str, Any]] = {
|
||||
"tabLabel": "社区",
|
||||
"note": "Taro 原生 pages/social · 开关不碰业务库",
|
||||
},
|
||||
"socialBlog": {
|
||||
"enabled": True,
|
||||
"title": "Nomad Blog",
|
||||
"tabLabel": "Blog",
|
||||
"note": "/social/blog · EN long-form · AdSense",
|
||||
},
|
||||
"vip": {"enabled": False, "title": "会员中心"},
|
||||
"destinations": {"enabled": True, "title": "目的地"},
|
||||
"meetups": {"enabled": True, "title": "活动"},
|
||||
@ -152,6 +159,12 @@ def read_weapp_switches() -> dict[str, Any]:
|
||||
),
|
||||
"memoTrialBrowse": flags_raw.get("memoTrialBrowse", True) is not False,
|
||||
"joinGroupWechat": flags_raw.get("joinGroupWechat", True) is not False,
|
||||
# AdSense: default off until publisher approval
|
||||
"adsenseEnabled": bool(flags_raw.get("adsenseEnabled")),
|
||||
"adsenseClientId": str(flags_raw.get("adsenseClientId") or ""),
|
||||
"adsensePublisherId": str(flags_raw.get("adsensePublisherId") or ""),
|
||||
"adsenseSlotBlogMid": str(flags_raw.get("adsenseSlotBlogMid") or ""),
|
||||
"adsenseSlotBlogEnd": str(flags_raw.get("adsenseSlotBlogEnd") or ""),
|
||||
},
|
||||
"copy": {
|
||||
"homeBrand": str(copy_raw.get("homeBrand") or "nomadro"),
|
||||
@ -217,6 +230,16 @@ def write_weapp_switches(patch: dict[str, Any]) -> dict[str, Any]:
|
||||
flags["joinGroupAction"] = (
|
||||
"vip" if fp["joinGroupAction"] == "vip" else "popup"
|
||||
)
|
||||
if "adsenseEnabled" in fp:
|
||||
flags["adsenseEnabled"] = bool(fp["adsenseEnabled"])
|
||||
for ak in (
|
||||
"adsenseClientId",
|
||||
"adsensePublisherId",
|
||||
"adsenseSlotBlogMid",
|
||||
"adsenseSlotBlogEnd",
|
||||
):
|
||||
if ak in fp and fp[ak] is not None:
|
||||
flags[ak] = str(fp[ak]).strip()
|
||||
|
||||
if isinstance(patch.get("copy"), dict):
|
||||
cp = patch["copy"]
|
||||
|
||||
33314
apps/api/services/social_svc/assets/haarcascade_frontalface_default.xml
Normal file
33314
apps/api/services/social_svc/assets/haarcascade_frontalface_default.xml
Normal file
File diff suppressed because it is too large
Load Diff
451
apps/api/services/social_svc/face_check.py
Normal file
451
apps/api/services/social_svc/face_check.py
Normal file
@ -0,0 +1,451 @@
|
||||
"""Avatar face gate — detect + optional InsightFace RGB liveness.
|
||||
|
||||
Env:
|
||||
SOCIAL_AVATAR_FACE_CHECK on|off (default on for purpose=avatar)
|
||||
SOCIAL_AVATAR_FACE_ENGINE auto|insightface|opencv (default auto)
|
||||
SOCIAL_AVATAR_FACE_STRICT fail closed when no engine (default off)
|
||||
SOCIAL_AVATAR_FACE_MIN min faces (default 1)
|
||||
SOCIAL_AVATAR_FACE_MAX max faces (default 1 — reject group photos)
|
||||
SOCIAL_AVATAR_LIVENESS on|off (default on; InsightFace addon)
|
||||
SOCIAL_AVATAR_LIVENESS_THRESHOLD 0..1 (default 0.5)
|
||||
SOCIAL_AVATAR_INSIGHTFACE_MODEL buffalo_l|buffalo_sc (default buffalo_l)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
log = logging.getLogger("social_svc.face_check")
|
||||
|
||||
_lock = threading.Lock()
|
||||
_insight_app = None
|
||||
_insight_failed = False
|
||||
_insight_liveness = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class FaceCheckResult:
|
||||
ok: bool
|
||||
faces: int
|
||||
engine: str
|
||||
detail: str = ""
|
||||
is_live: bool | None = None
|
||||
live_score: float | None = None
|
||||
|
||||
|
||||
def _env_bool(name: str, default: bool) -> bool:
|
||||
raw = (os.getenv(name) or "").strip().lower()
|
||||
if not raw:
|
||||
return default
|
||||
return raw in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def face_check_enabled(purpose: str) -> bool:
|
||||
if (purpose or "").strip().lower() not in {"avatar", "roster", "profile"}:
|
||||
return False
|
||||
return _env_bool("SOCIAL_AVATAR_FACE_CHECK", True)
|
||||
|
||||
|
||||
def _engine_pref() -> str:
|
||||
return (os.getenv("SOCIAL_AVATAR_FACE_ENGINE") or "auto").strip().lower()
|
||||
|
||||
|
||||
def _min_faces() -> int:
|
||||
try:
|
||||
return max(1, int(os.getenv("SOCIAL_AVATAR_FACE_MIN") or "1"))
|
||||
except ValueError:
|
||||
return 1
|
||||
|
||||
|
||||
def _max_faces() -> int:
|
||||
try:
|
||||
return max(_min_faces(), int(os.getenv("SOCIAL_AVATAR_FACE_MAX") or "1"))
|
||||
except ValueError:
|
||||
return 1
|
||||
|
||||
|
||||
def _liveness_on() -> bool:
|
||||
return _env_bool("SOCIAL_AVATAR_LIVENESS", True)
|
||||
|
||||
|
||||
def _liveness_threshold() -> float:
|
||||
try:
|
||||
v = float(os.getenv("SOCIAL_AVATAR_LIVENESS_THRESHOLD") or "0.5")
|
||||
except ValueError:
|
||||
v = 0.5
|
||||
return min(0.99, max(0.05, v))
|
||||
|
||||
|
||||
def _decode_bgr(data: bytes):
|
||||
arr = np.frombuffer(data, dtype=np.uint8)
|
||||
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
|
||||
return img
|
||||
|
||||
|
||||
def _providers() -> list[str]:
|
||||
providers = ["CPUExecutionProvider"]
|
||||
try:
|
||||
from onnxruntime import get_available_providers
|
||||
|
||||
avail = set(get_available_providers())
|
||||
if "CUDAExecutionProvider" in avail:
|
||||
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
|
||||
except Exception:
|
||||
pass
|
||||
return providers
|
||||
|
||||
|
||||
def _get_insightface():
|
||||
global _insight_app, _insight_failed, _insight_liveness
|
||||
if _insight_failed:
|
||||
return None
|
||||
if _insight_app is not None:
|
||||
return _insight_app
|
||||
with _lock:
|
||||
if _insight_failed:
|
||||
return None
|
||||
if _insight_app is not None:
|
||||
return _insight_app
|
||||
try:
|
||||
from insightface.app import FaceAnalysis
|
||||
|
||||
name = (os.getenv("SOCIAL_AVATAR_INSIGHTFACE_MODEL") or "buffalo_l").strip()
|
||||
providers = _providers()
|
||||
want_live = _liveness_on()
|
||||
addons: tuple[str, ...] = ("liveness",) if want_live else ()
|
||||
try:
|
||||
app = FaceAnalysis(
|
||||
name=name,
|
||||
providers=providers,
|
||||
addons=addons,
|
||||
liveness_mode="normal",
|
||||
liveness_threshold=_liveness_threshold(),
|
||||
)
|
||||
_insight_liveness = bool(addons) and "liveness" in app.addons
|
||||
except Exception as live_exc:
|
||||
# Model package without addon download — fall back to detection only
|
||||
log.warning("insightface liveness init failed, detection-only: %s", live_exc)
|
||||
app = FaceAnalysis(name=name, providers=providers)
|
||||
_insight_liveness = False
|
||||
ctx_id = 0 if providers[0].startswith("CUDA") else -1
|
||||
app.prepare(ctx_id=ctx_id, det_size=(640, 640))
|
||||
_insight_app = app
|
||||
log.info(
|
||||
"insightface ready model=%s providers=%s liveness=%s",
|
||||
name,
|
||||
providers,
|
||||
_insight_liveness,
|
||||
)
|
||||
return _insight_app
|
||||
except Exception as exc:
|
||||
_insight_failed = True
|
||||
log.warning("insightface unavailable: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _analyze_insightface(img) -> FaceCheckResult:
|
||||
app = _get_insightface()
|
||||
if app is None:
|
||||
raise RuntimeError("insightface not loaded")
|
||||
faces = app.get(img) or []
|
||||
n = len(faces)
|
||||
need = _min_faces()
|
||||
cap = _max_faces()
|
||||
if n < need:
|
||||
return FaceCheckResult(
|
||||
ok=False,
|
||||
faces=n,
|
||||
engine="insightface",
|
||||
detail="未检测到人脸,请上传本人清晰正脸照片",
|
||||
)
|
||||
if n > cap:
|
||||
return FaceCheckResult(
|
||||
ok=False,
|
||||
faces=n,
|
||||
engine="insightface",
|
||||
detail="请只上传一张本人正脸(不要合影)",
|
||||
)
|
||||
|
||||
face = faces[0]
|
||||
is_live = None
|
||||
live_score = None
|
||||
live = getattr(face, "liveness", None)
|
||||
if live is not None:
|
||||
is_live = getattr(live, "is_live", None)
|
||||
try:
|
||||
live_score = float(getattr(live, "live_score", None) or getattr(live, "score", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
live_score = None
|
||||
status = getattr(live, "status", None)
|
||||
reason = getattr(live, "reason", None) or ""
|
||||
if is_live is False:
|
||||
return FaceCheckResult(
|
||||
ok=False,
|
||||
faces=n,
|
||||
engine="insightface+liveness",
|
||||
detail="未通过真人检测,请用前置摄像头现场自拍(勿用网图/截图)",
|
||||
is_live=False,
|
||||
live_score=live_score,
|
||||
)
|
||||
if status == "input_rejected":
|
||||
return FaceCheckResult(
|
||||
ok=False,
|
||||
faces=n,
|
||||
engine="insightface+liveness",
|
||||
detail=str(reason) or "人脸区域不足,请靠近镜头、露出完整正脸再拍",
|
||||
is_live=False,
|
||||
live_score=live_score,
|
||||
)
|
||||
|
||||
if _liveness_on() and _insight_liveness and is_live is not True:
|
||||
# Addon loaded but face missing live flag — treat as fail-closed
|
||||
return FaceCheckResult(
|
||||
ok=False,
|
||||
faces=n,
|
||||
engine="insightface+liveness",
|
||||
detail="真人检测未完成,请重新自拍一张正脸",
|
||||
is_live=False,
|
||||
live_score=live_score,
|
||||
)
|
||||
|
||||
engine = "insightface+liveness" if is_live is True else "insightface"
|
||||
return FaceCheckResult(
|
||||
ok=True,
|
||||
faces=n,
|
||||
engine=engine,
|
||||
is_live=is_live,
|
||||
live_score=live_score,
|
||||
)
|
||||
|
||||
|
||||
def _haar_cascade_path() -> str:
|
||||
from pathlib import Path
|
||||
|
||||
bundled = (
|
||||
Path(__file__).resolve().parent
|
||||
/ "assets"
|
||||
/ "haarcascade_frontalface_default.xml"
|
||||
)
|
||||
if bundled.is_file():
|
||||
return str(bundled)
|
||||
data_dir = getattr(getattr(cv2, "data", None), "haarcascades", "") or ""
|
||||
candidate = data_dir + "haarcascade_frontalface_default.xml"
|
||||
if data_dir and Path(candidate).is_file():
|
||||
return candidate
|
||||
raise RuntimeError("haar cascade xml not found (bundle assets/)")
|
||||
|
||||
|
||||
def _count_opencv(img) -> int:
|
||||
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
gray = cv2.equalizeHist(gray)
|
||||
cascade = cv2.CascadeClassifier(_haar_cascade_path())
|
||||
if cascade.empty():
|
||||
raise RuntimeError("opencv haar cascade missing")
|
||||
h, w = gray.shape[:2]
|
||||
max_side = 960
|
||||
if max(h, w) > max_side:
|
||||
scale = max_side / float(max(h, w))
|
||||
gray = cv2.resize(gray, (int(w * scale), int(h * scale)))
|
||||
faces = cascade.detectMultiScale(
|
||||
gray,
|
||||
scaleFactor=1.1,
|
||||
minNeighbors=5,
|
||||
minSize=(48, 48),
|
||||
flags=cv2.CASCADE_SCALE_IMAGE,
|
||||
)
|
||||
return len(faces)
|
||||
|
||||
|
||||
def check_face(data: bytes) -> FaceCheckResult:
|
||||
"""Return face / liveness result; does not raise for soft failures."""
|
||||
img = _decode_bgr(data)
|
||||
if img is None or img.size == 0:
|
||||
return FaceCheckResult(ok=False, faces=0, engine="none", detail="无法解码图片")
|
||||
|
||||
pref = _engine_pref()
|
||||
engines: list[str] = []
|
||||
if pref == "insightface":
|
||||
engines = ["insightface"]
|
||||
elif pref == "opencv":
|
||||
engines = ["opencv"]
|
||||
else:
|
||||
engines = ["insightface", "opencv"]
|
||||
|
||||
last_err = ""
|
||||
for eng in engines:
|
||||
try:
|
||||
if eng == "insightface":
|
||||
return _analyze_insightface(img)
|
||||
|
||||
n = _count_opencv(img)
|
||||
need = _min_faces()
|
||||
cap = _max_faces()
|
||||
if n < need:
|
||||
return FaceCheckResult(
|
||||
ok=False,
|
||||
faces=n,
|
||||
engine="opencv",
|
||||
detail="未检测到人脸,请上传本人清晰正脸照片",
|
||||
)
|
||||
if n > cap:
|
||||
return FaceCheckResult(
|
||||
ok=False,
|
||||
faces=n,
|
||||
engine="opencv",
|
||||
detail="请只上传一张本人正脸(不要合影)",
|
||||
)
|
||||
# OpenCV cannot prove liveness — require InsightFace when liveness enforced
|
||||
if _liveness_on() and _env_bool("SOCIAL_AVATAR_LIVENESS_REQUIRE", True):
|
||||
return FaceCheckResult(
|
||||
ok=False,
|
||||
faces=n,
|
||||
engine="opencv",
|
||||
detail="请用摄像头现场自拍以完成真人验证",
|
||||
)
|
||||
return FaceCheckResult(ok=True, faces=n, engine="opencv")
|
||||
except Exception as exc:
|
||||
last_err = str(exc)
|
||||
log.warning("face engine %s failed: %s", eng, exc)
|
||||
continue
|
||||
|
||||
if _env_bool("SOCIAL_AVATAR_FACE_STRICT", False):
|
||||
return FaceCheckResult(
|
||||
ok=False,
|
||||
faces=0,
|
||||
engine="none",
|
||||
detail=f"人脸检测不可用: {last_err or 'no engine'}",
|
||||
)
|
||||
log.warning("face check skipped (no engine); allowing upload")
|
||||
return FaceCheckResult(ok=True, faces=-1, engine="skipped", detail=last_err)
|
||||
|
||||
|
||||
def assert_avatar_has_face(data: bytes) -> FaceCheckResult:
|
||||
"""Raise ValueError when check fails."""
|
||||
result = check_face(data)
|
||||
if not result.ok:
|
||||
raise ValueError(result.detail or "未检测到人脸")
|
||||
return result
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChallengeResult:
|
||||
ok: bool
|
||||
detail: str = ""
|
||||
similarity: float | None = None
|
||||
yaw_delta: float | None = None
|
||||
front: FaceCheckResult | None = None
|
||||
turn: FaceCheckResult | None = None
|
||||
|
||||
|
||||
def _cosine(a, b) -> float:
|
||||
a = np.asarray(a, dtype=np.float32).ravel()
|
||||
b = np.asarray(b, dtype=np.float32).ravel()
|
||||
denom = float(np.linalg.norm(a) * np.linalg.norm(b) + 1e-9)
|
||||
return float(np.dot(a, b) / denom)
|
||||
|
||||
|
||||
def _yaw_proxy(kps) -> float:
|
||||
"""Nose offset vs eye midpoint, normalized by eye distance (≈ yaw proxy)."""
|
||||
pts = np.asarray(kps, dtype=np.float32)
|
||||
if pts.shape[0] < 3:
|
||||
return 0.0
|
||||
le, re, nose = pts[0], pts[1], pts[2]
|
||||
mid_x = (float(le[0]) + float(re[0])) * 0.5
|
||||
eye_w = abs(float(re[0]) - float(le[0])) + 1e-6
|
||||
return (float(nose[0]) - mid_x) / eye_w
|
||||
|
||||
|
||||
def _extract_face_features(data: bytes):
|
||||
"""Return (FaceCheckResult, embedding|None, yaw|None)."""
|
||||
img = _decode_bgr(data)
|
||||
if img is None or img.size == 0:
|
||||
return (
|
||||
FaceCheckResult(ok=False, faces=0, engine="none", detail="无法解码图片"),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
# Prefer insightface for embeddings; also runs liveness when enabled
|
||||
try:
|
||||
app = _get_insightface()
|
||||
if app is None:
|
||||
raise RuntimeError("insightface not loaded")
|
||||
faces = app.get(img) or []
|
||||
base = _analyze_insightface(img)
|
||||
if not base.ok or not faces:
|
||||
return base, None, None
|
||||
face = faces[0]
|
||||
emb = getattr(face, "normed_embedding", None)
|
||||
if emb is None:
|
||||
emb = getattr(face, "embedding", None)
|
||||
yaw = _yaw_proxy(getattr(face, "kps", None)) if getattr(face, "kps", None) is not None else None
|
||||
return base, emb, yaw
|
||||
except Exception as exc:
|
||||
log.warning("challenge feature extract failed: %s", exc)
|
||||
# Fall back to presence-only (no identity match)
|
||||
presence = check_face(data)
|
||||
return presence, None, None
|
||||
|
||||
|
||||
def verify_pose_challenge(front_bytes: bytes, turn_bytes: bytes) -> ChallengeResult:
|
||||
"""Two-frame selfie: same person + measurable head turn + face/liveness gates."""
|
||||
front, emb_a, yaw_a = _extract_face_features(front_bytes)
|
||||
if not front.ok:
|
||||
return ChallengeResult(ok=False, detail=front.detail or "正脸核验失败", front=front)
|
||||
|
||||
turn, emb_b, yaw_b = _extract_face_features(turn_bytes)
|
||||
if not turn.ok:
|
||||
return ChallengeResult(
|
||||
ok=False,
|
||||
detail=turn.detail or "转头照核验失败",
|
||||
front=front,
|
||||
turn=turn,
|
||||
)
|
||||
|
||||
sim = None
|
||||
if emb_a is not None and emb_b is not None:
|
||||
sim = _cosine(emb_a, emb_b)
|
||||
min_sim = 0.32
|
||||
try:
|
||||
min_sim = float(os.getenv("SOCIAL_AVATAR_CHALLENGE_MIN_SIM") or "0.32")
|
||||
except ValueError:
|
||||
pass
|
||||
if sim < min_sim:
|
||||
return ChallengeResult(
|
||||
ok=False,
|
||||
detail="两张照片不是同一个人,请本人连续自拍完成核验",
|
||||
similarity=sim,
|
||||
front=front,
|
||||
turn=turn,
|
||||
)
|
||||
|
||||
yaw_delta = None
|
||||
if yaw_a is not None and yaw_b is not None:
|
||||
yaw_delta = abs(float(yaw_a) - float(yaw_b))
|
||||
min_yaw = 0.06
|
||||
try:
|
||||
min_yaw = float(os.getenv("SOCIAL_AVATAR_CHALLENGE_MIN_YAW") or "0.06")
|
||||
except ValueError:
|
||||
pass
|
||||
if yaw_delta < min_yaw:
|
||||
return ChallengeResult(
|
||||
ok=False,
|
||||
detail="转头幅度不够,请稍微左右转头后再拍第二张",
|
||||
similarity=sim,
|
||||
yaw_delta=yaw_delta,
|
||||
front=front,
|
||||
turn=turn,
|
||||
)
|
||||
|
||||
return ChallengeResult(
|
||||
ok=True,
|
||||
detail="",
|
||||
similarity=sim,
|
||||
yaw_delta=yaw_delta,
|
||||
front=front,
|
||||
turn=turn,
|
||||
)
|
||||
@ -18,6 +18,15 @@ from social_svc.config import (
|
||||
|
||||
log = logging.getLogger("social_svc.realtime")
|
||||
|
||||
_http: httpx.AsyncClient | None = None
|
||||
|
||||
|
||||
def _client() -> httpx.AsyncClient:
|
||||
global _http
|
||||
if _http is None or _http.is_closed:
|
||||
_http = httpx.AsyncClient(timeout=3.0)
|
||||
return _http
|
||||
|
||||
|
||||
def channel_name(channel_id: str) -> str:
|
||||
cid = (channel_id or "").strip() or "lobby"
|
||||
@ -58,16 +67,15 @@ async def _publish(channel_id: str, data: dict[str, Any]) -> bool:
|
||||
url = CENTRIFUGO_API_URL.rstrip("/") + "/publish"
|
||||
body = {"channel": channel_name(channel_id), "data": data}
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=3.0) as client:
|
||||
res = await client.post(
|
||||
url,
|
||||
headers={"X-API-Key": CENTRIFUGO_API_KEY, "Content-Type": "application/json"},
|
||||
json=body,
|
||||
)
|
||||
if res.status_code >= 400:
|
||||
log.warning("centrifugo publish %s: %s", res.status_code, res.text[:200])
|
||||
return False
|
||||
return True
|
||||
res = await _client().post(
|
||||
url,
|
||||
headers={"X-API-Key": CENTRIFUGO_API_KEY, "Content-Type": "application/json"},
|
||||
json=body,
|
||||
)
|
||||
if res.status_code >= 400:
|
||||
log.warning("centrifugo publish %s: %s", res.status_code, res.text[:200])
|
||||
return False
|
||||
return True
|
||||
except Exception as e: # pragma: no cover
|
||||
log.warning("centrifugo publish failed: %s", e)
|
||||
return False
|
||||
|
||||
@ -173,8 +173,7 @@ def get_messages(
|
||||
items = store.list_messages(
|
||||
channel_id, limit, since=since, before=before, q=q
|
||||
)
|
||||
desc = store.channel_desc(channel_id)
|
||||
return {"items": items, "seq": desc["seq"]}
|
||||
return {"items": items, "seq": store.channel_seq(channel_id)}
|
||||
|
||||
|
||||
async def _publish_msg(channel_id: str, saved: dict[str, Any]) -> None:
|
||||
@ -358,7 +357,10 @@ async def upload_media(
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
"""Guest-friendly image upload → SeaweedFS S3 (fallback local)."""
|
||||
"""Guest-friendly image upload → SeaweedFS S3 (fallback local).
|
||||
|
||||
Avatar / roster / profile: optional face presence gate (InsightFace → OpenCV).
|
||||
"""
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
ctype = (file.content_type or "").lower()
|
||||
if not ctype.startswith("image/"):
|
||||
@ -367,26 +369,97 @@ async def upload_media(
|
||||
if not raw:
|
||||
raise HTTPException(status_code=400, detail="空文件")
|
||||
max_avatar = min(SOCIAL_UPLOAD_MAX_BYTES, 8 * 1024 * 1024)
|
||||
purpose_norm = (purpose or "avatar")[:40]
|
||||
|
||||
def persist():
|
||||
from social_svc.face_check import assert_avatar_has_face, face_check_enabled
|
||||
from social_svc.s3_upload import upload_bytes
|
||||
|
||||
return upload_bytes(
|
||||
face_meta = None
|
||||
if face_check_enabled(purpose_norm):
|
||||
face_meta = assert_avatar_has_face(raw)
|
||||
|
||||
uploaded = upload_bytes(
|
||||
raw,
|
||||
filename=file.filename or "avatar.jpg",
|
||||
content_type=file.content_type or "image/jpeg",
|
||||
purpose=(purpose or "avatar")[:40],
|
||||
purpose=purpose_norm,
|
||||
guest_id=peer,
|
||||
max_size=max_avatar,
|
||||
)
|
||||
return uploaded, face_meta
|
||||
|
||||
try:
|
||||
result = await run_in_threadpool(persist)
|
||||
result, face_meta = await run_in_threadpool(persist)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=503, detail=f"上传失败: {exc}") from exc
|
||||
|
||||
payload = {
|
||||
"ok": True,
|
||||
"success": True,
|
||||
"url": result.url,
|
||||
"object_key": result.object_key,
|
||||
"size": result.size,
|
||||
"content_type": result.content_type,
|
||||
"storage": result.storage,
|
||||
}
|
||||
if face_meta is not None:
|
||||
face_payload = {
|
||||
"ok": face_meta.ok,
|
||||
"faces": face_meta.faces,
|
||||
"engine": face_meta.engine,
|
||||
}
|
||||
if face_meta.is_live is not None:
|
||||
face_payload["is_live"] = face_meta.is_live
|
||||
if face_meta.live_score is not None:
|
||||
face_payload["live_score"] = face_meta.live_score
|
||||
payload["face"] = face_payload
|
||||
return payload
|
||||
|
||||
|
||||
@router.post("/avatar/challenge")
|
||||
async def avatar_pose_challenge(
|
||||
front: UploadFile = File(...),
|
||||
turn: UploadFile = File(...),
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
"""Two-frame live selfie: same identity + head-turn + face/liveness, then store front as avatar."""
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
front_raw = await front.read()
|
||||
turn_raw = await turn.read()
|
||||
if not front_raw or not turn_raw:
|
||||
raise HTTPException(status_code=400, detail="空文件")
|
||||
max_avatar = min(SOCIAL_UPLOAD_MAX_BYTES, 8 * 1024 * 1024)
|
||||
if len(front_raw) > max_avatar or len(turn_raw) > max_avatar:
|
||||
raise HTTPException(status_code=400, detail="图片过大")
|
||||
|
||||
def work():
|
||||
from social_svc.face_check import verify_pose_challenge
|
||||
from social_svc.s3_upload import upload_bytes
|
||||
|
||||
challenge = verify_pose_challenge(front_raw, turn_raw)
|
||||
if not challenge.ok:
|
||||
raise ValueError(challenge.detail or "真人核验失败")
|
||||
uploaded = upload_bytes(
|
||||
front_raw,
|
||||
filename=front.filename or "avatar-front.jpg",
|
||||
content_type=front.content_type or "image/jpeg",
|
||||
purpose="avatar",
|
||||
guest_id=peer,
|
||||
max_size=max_avatar,
|
||||
)
|
||||
return uploaded, challenge
|
||||
|
||||
try:
|
||||
result, challenge = await run_in_threadpool(work)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=503, detail=f"核验失败: {exc}") from exc
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"success": True,
|
||||
@ -395,6 +468,20 @@ async def upload_media(
|
||||
"size": result.size,
|
||||
"content_type": result.content_type,
|
||||
"storage": result.storage,
|
||||
"challenge": {
|
||||
"similarity": challenge.similarity,
|
||||
"yaw_delta": challenge.yaw_delta,
|
||||
"front": {
|
||||
"faces": challenge.front.faces if challenge.front else 0,
|
||||
"engine": challenge.front.engine if challenge.front else "",
|
||||
"is_live": challenge.front.is_live if challenge.front else None,
|
||||
},
|
||||
"turn": {
|
||||
"faces": challenge.turn.faces if challenge.turn else 0,
|
||||
"engine": challenge.turn.engine if challenge.turn else "",
|
||||
"is_live": challenge.turn.is_live if challenge.turn else None,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -40,11 +40,17 @@ def s3_enabled() -> bool:
|
||||
)
|
||||
|
||||
|
||||
_boto = None
|
||||
|
||||
|
||||
def _client():
|
||||
global _boto
|
||||
if _boto is not None:
|
||||
return _boto
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
|
||||
return boto3.client(
|
||||
_boto = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=_env("S3_ENDPOINT", default="http://127.0.0.1:8333").rstrip("/"),
|
||||
aws_access_key_id=_env(
|
||||
@ -54,6 +60,7 @@ def _client():
|
||||
region_name=_env("S3_REGION", default="us-east-1"),
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
|
||||
)
|
||||
return _boto
|
||||
|
||||
|
||||
def _object_key(filename: str, purpose: str, guest_id: str) -> str:
|
||||
@ -89,9 +96,19 @@ def upload_bytes(
|
||||
if len(data) > max_size:
|
||||
raise ValueError(f"file too large (max {max_size // 1024 // 1024}MB)")
|
||||
|
||||
ctype = content_type or mimetypes.guess_type(filename or "")[0] or "image/jpeg"
|
||||
guessed = mimetypes.guess_type(filename or "")[0] or ""
|
||||
ctype = (content_type or "").strip().lower() or guessed or "image/jpeg"
|
||||
# Browser FormData Blob parts often arrive as application/octet-stream
|
||||
if not ctype.startswith("image/"):
|
||||
raise ValueError("only images allowed")
|
||||
suffix = Path(filename or "").suffix.lower()
|
||||
if suffix in {".jpg", ".jpeg", ".png", ".webp", ".gif"} or guessed.startswith(
|
||||
"image/"
|
||||
):
|
||||
ctype = guessed if guessed.startswith("image/") else (
|
||||
"image/jpeg" if suffix in {".jpg", ".jpeg", ""} else f"image/{suffix[1:]}"
|
||||
)
|
||||
else:
|
||||
raise ValueError("only images allowed")
|
||||
|
||||
key = _object_key(filename, purpose, guest_id)
|
||||
|
||||
@ -99,16 +116,8 @@ def upload_bytes(
|
||||
bucket = _env("S3_BUCKET", default="nomadweb")
|
||||
client = _client()
|
||||
try:
|
||||
try:
|
||||
client.put_object(
|
||||
Bucket=bucket,
|
||||
Key=key,
|
||||
Body=data,
|
||||
ContentType=ctype,
|
||||
ACL="public-read",
|
||||
)
|
||||
except Exception:
|
||||
client.put_object(Bucket=bucket, Key=key, Body=data, ContentType=ctype)
|
||||
# SeaweedFS often rejects canned ACL — skip ACL for lower latency
|
||||
client.put_object(Bucket=bucket, Key=key, Body=data, ContentType=ctype)
|
||||
return UploadResult(
|
||||
url=public_url_for_key(key),
|
||||
object_key=key,
|
||||
|
||||
@ -33,12 +33,17 @@ def _now() -> str:
|
||||
|
||||
|
||||
@contextmanager
|
||||
def db() -> Iterator[sqlite3.Connection]:
|
||||
def db(*, commit: bool = True) -> Iterator[sqlite3.Connection]:
|
||||
SOCIAL_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = _connect(SOCIAL_DB_PATH)
|
||||
try:
|
||||
try:
|
||||
conn.execute("PRAGMA busy_timeout=5000")
|
||||
except Exception:
|
||||
pass
|
||||
yield conn
|
||||
conn.commit()
|
||||
if commit:
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
@ -46,7 +51,13 @@ def db() -> Iterator[sqlite3.Connection]:
|
||||
conn.close()
|
||||
|
||||
|
||||
_DB_READY = False
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
global _DB_READY
|
||||
if _DB_READY:
|
||||
return
|
||||
with db() as conn:
|
||||
conn.executescript(
|
||||
"""
|
||||
@ -169,6 +180,7 @@ def init_db() -> None:
|
||||
"""
|
||||
)
|
||||
_backfill_seq(conn)
|
||||
_DB_READY = True
|
||||
try:
|
||||
from . import geo_pb
|
||||
|
||||
@ -286,10 +298,25 @@ def _get_message_row(conn: sqlite3.Connection, msg_id: str) -> sqlite3.Row | Non
|
||||
return _get_message(conn, msg_id)
|
||||
|
||||
|
||||
def channel_seq(channel_id: str) -> int:
|
||||
"""Latest message seq for a channel (cheap; no presence / read marks)."""
|
||||
init_db()
|
||||
with db(commit=False) as conn:
|
||||
meta = conn.execute(
|
||||
"SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,)
|
||||
).fetchone()
|
||||
if meta:
|
||||
return max(0, int(meta["next_seq"]) - 1)
|
||||
row = conn.execute(
|
||||
"SELECT MAX(seq) AS m FROM messages WHERE channel_id = ?", (channel_id,)
|
||||
).fetchone()
|
||||
return int(row["m"] or 0)
|
||||
|
||||
|
||||
def channel_desc(channel_id: str, guest_id: str | None = None) -> dict[str, Any]:
|
||||
"""Tinode-like topic desc: latest seq + caller's recv/read watermarks."""
|
||||
init_db()
|
||||
with db() as conn:
|
||||
with db(commit=False) as conn:
|
||||
meta = conn.execute(
|
||||
"SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,)
|
||||
).fetchone()
|
||||
@ -335,7 +362,7 @@ def list_messages(
|
||||
"""History with Tinode-style seq cursors (since exclusive, before exclusive)."""
|
||||
lim = max(1, min(int(limit or 100), 500))
|
||||
needle = (q or "").strip()[:80]
|
||||
with db() as conn:
|
||||
with db(commit=False) as conn:
|
||||
if needle:
|
||||
like = f"%{needle}%"
|
||||
rows = conn.execute(
|
||||
|
||||
@ -9,6 +9,8 @@ import Events from './pages/Events'
|
||||
import Orders from './pages/Orders'
|
||||
import Users from './pages/Users'
|
||||
import Ntfy from './pages/Ntfy'
|
||||
import Social from './pages/Social'
|
||||
import Blog from './pages/Blog'
|
||||
import LaneHub, { type LaneKey } from './pages/LaneHub'
|
||||
|
||||
/**
|
||||
@ -57,6 +59,8 @@ export default function App() {
|
||||
>
|
||||
<Route index element={<LaneHome />} />
|
||||
<Route path="switches" element={<Switches />} />
|
||||
<Route path="social" element={<Social />} />
|
||||
<Route path="blog" element={<Blog />} />
|
||||
<Route path="events" element={<Events />} />
|
||||
<Route path="orders" element={<Orders />} />
|
||||
<Route path="users" element={<Users />} />
|
||||
|
||||
@ -15,6 +15,8 @@ function laneNav(lane: LaneKey): NavItem[] {
|
||||
return [
|
||||
{ to: p, end: true, ico: '◈', label: '模块总览' },
|
||||
{ to: `${p}/switches`, ico: '⏻', label: '动态开关' },
|
||||
{ to: `${p}/social`, ico: '💕', label: '游民社区' },
|
||||
{ to: `${p}/blog`, ico: '📝', label: 'Nomad Blog' },
|
||||
{ to: `${p}/events`, ico: '📊', label: '埋点' },
|
||||
{ to: `${p}/orders`, ico: '🧾', label: '订单' },
|
||||
{ to: `${p}/users`, ico: '👥', label: '用户' },
|
||||
|
||||
442
apps/com/admin/src/pages/Blog.tsx
Normal file
442
apps/com/admin/src/pages/Blog.tsx
Normal file
@ -0,0 +1,442 @@
|
||||
/**
|
||||
* Nomad Blog 运营台 — 文章显隐/置顶 · AdSense · 模块开关
|
||||
* 内容 SoT 仍是仓库 Markdown;本页管线上运营与广告展示。
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { api } from '../api/client'
|
||||
|
||||
type Overview = {
|
||||
ok?: boolean
|
||||
portal?: string
|
||||
liveUrl?: string
|
||||
aboutUrl?: string
|
||||
privacyUrl?: string
|
||||
adsTxtUrl?: string
|
||||
rssUrl?: string
|
||||
sitemapUrl?: string
|
||||
counts?: { posts?: number; visible?: number; hidden?: number }
|
||||
ops?: {
|
||||
featuredSlug?: string
|
||||
hiddenSlugs?: string[]
|
||||
note?: string
|
||||
heroLead?: string
|
||||
}
|
||||
moduleEnabled?: boolean
|
||||
adsenseEnabled?: boolean
|
||||
adsenseClientId?: string
|
||||
adsensePublisherId?: string
|
||||
adsenseSlotBlogMid?: string
|
||||
adsenseSlotBlogEnd?: string
|
||||
version?: number
|
||||
updatedAt?: string
|
||||
}
|
||||
|
||||
type Post = {
|
||||
slug: string
|
||||
title: string
|
||||
description?: string
|
||||
date?: string
|
||||
tags?: string[]
|
||||
wordCount?: number
|
||||
readingMinutes?: number
|
||||
url?: string
|
||||
hidden?: boolean
|
||||
featured?: boolean
|
||||
}
|
||||
|
||||
type TabKey = 'posts' | 'adsense' | 'module'
|
||||
|
||||
const TABS: Array<{ key: TabKey; label: string }> = [
|
||||
{ key: 'posts', label: '文章' },
|
||||
{ key: 'adsense', label: 'AdSense' },
|
||||
{ key: 'module', label: '模块 / 文案' },
|
||||
]
|
||||
|
||||
export default function Blog() {
|
||||
const [tab, setTab] = useState<TabKey>('posts')
|
||||
const [ov, setOv] = useState<Overview | null>(null)
|
||||
const [posts, setPosts] = useState<Post[]>([])
|
||||
const [q, setQ] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [busy, setBusy] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [draft, setDraft] = useState({
|
||||
adsenseClientId: '',
|
||||
adsensePublisherId: '',
|
||||
adsenseSlotBlogMid: '',
|
||||
adsenseSlotBlogEnd: '',
|
||||
heroLead: '',
|
||||
note: '',
|
||||
})
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
try {
|
||||
const [overview, list] = await Promise.all([
|
||||
api<Overview>('/api/admin/social/blog/overview'),
|
||||
api<{ items?: Post[] }>('/api/admin/social/blog/posts'),
|
||||
])
|
||||
setOv(overview)
|
||||
setPosts(Array.isArray(list.items) ? list.items : [])
|
||||
setDraft({
|
||||
adsenseClientId: overview.adsenseClientId || '',
|
||||
adsensePublisherId: overview.adsensePublisherId || '',
|
||||
adsenseSlotBlogMid: overview.adsenseSlotBlogMid || '',
|
||||
adsenseSlotBlogEnd: overview.adsenseSlotBlogEnd || '',
|
||||
heroLead: overview.ops?.heroLead || '',
|
||||
note: overview.ops?.note || '',
|
||||
})
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '加载失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
async function patch(body: Record<string, unknown>, okHint: string) {
|
||||
setBusy(okHint)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const next = await api<Overview>('/api/admin/social/blog/ops', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
setOv(next)
|
||||
setMsg(okHint)
|
||||
const list = await api<{ items?: Post[] }>('/api/admin/social/blog/posts')
|
||||
setPosts(Array.isArray(list.items) ? list.items : [])
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '保存失败')
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const needle = q.trim().toLowerCase()
|
||||
if (!needle) return posts
|
||||
return posts.filter((p) =>
|
||||
`${p.title} ${p.slug} ${(p.tags || []).join(' ')}`.toLowerCase().includes(needle),
|
||||
)
|
||||
}, [posts, q])
|
||||
|
||||
const adsReady =
|
||||
Boolean(ov?.adsenseClientId) &&
|
||||
(Boolean(ov?.adsenseSlotBlogMid) || Boolean(ov?.adsenseSlotBlogEnd))
|
||||
|
||||
return (
|
||||
<div className="com-page com-blog-admin">
|
||||
<header className="com-page-head com-page-head-row">
|
||||
<div>
|
||||
<h1>Nomad Blog</h1>
|
||||
<p>
|
||||
管理 <code>/social/blog</code>:文章显隐、置顶、AdSense 与模块开关。正文仍在仓库 Markdown(Tina
|
||||
式 Git SoT)。
|
||||
</p>
|
||||
<div className="com-chip-row">
|
||||
<span className={`com-chip${ov?.moduleEnabled ? ' com-chip-ok' : ''}`}>
|
||||
模块 {ov?.moduleEnabled ? '开' : '关'}
|
||||
</span>
|
||||
<span className={`com-chip${ov?.adsenseEnabled ? ' com-chip-ok' : ''}`}>
|
||||
AdSense {ov?.adsenseEnabled ? '展示中' : '关闭'}
|
||||
</span>
|
||||
{ov?.version != null ? <span className="com-chip">v{ov.version}</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="com-blog-head-actions">
|
||||
{ov?.liveUrl ? (
|
||||
<a className="com-btn com-btn-ghost" href={ov.liveUrl} target="_blank" rel="noreferrer">
|
||||
打开博客 ↗
|
||||
</a>
|
||||
) : null}
|
||||
<button type="button" className="com-btn com-btn-ghost" onClick={() => void load()} disabled={!!busy}>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
|
||||
<div className="com-stat-grid com-stat-grid-4">
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">文章</span>
|
||||
<strong>{ov?.counts?.posts ?? '—'}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">可见</span>
|
||||
<strong>{ov?.counts?.visible ?? '—'}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">隐藏</span>
|
||||
<strong>{ov?.counts?.hidden ?? '—'}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">广告就绪</span>
|
||||
<strong>{adsReady ? '是' : '否'}</strong>
|
||||
<span className="com-stat-note">{adsReady ? 'client + slot' : '先填 clientId / slot'}</span>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div className="com-blog-quicklinks">
|
||||
{(
|
||||
[
|
||||
['线上博客', ov?.liveUrl],
|
||||
['About', ov?.aboutUrl],
|
||||
['Privacy', ov?.privacyUrl],
|
||||
['ads.txt', ov?.adsTxtUrl],
|
||||
['RSS', ov?.rssUrl],
|
||||
['Sitemap', ov?.sitemapUrl],
|
||||
] as const
|
||||
).map(([label, href]) =>
|
||||
href ? (
|
||||
<a key={label} href={href} target="_blank" rel="noreferrer" className="com-blog-quick">
|
||||
{label}
|
||||
</a>
|
||||
) : null,
|
||||
)}
|
||||
</div>
|
||||
|
||||
<nav className="com-tabs" aria-label="博客运营">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
className={`com-tab${tab === t.key ? ' is-on' : ''}`}
|
||||
onClick={() => setTab(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{tab === 'posts' ? (
|
||||
<section className="com-panel">
|
||||
<div className="com-panel-head">
|
||||
<div>
|
||||
<h2>文章列表</h2>
|
||||
<p>置顶 / 隐藏写入 remote-config;改标题正文请在仓库 Markdown。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="com-toolbar">
|
||||
<input
|
||||
className="com-input"
|
||||
placeholder="搜标题 / slug / 标签"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
/>
|
||||
<span className="com-muted">{filtered.length} 篇</span>
|
||||
</div>
|
||||
{loading && !posts.length ? (
|
||||
<p className="com-muted">加载中…</p>
|
||||
) : !filtered.length ? (
|
||||
<p className="com-muted">暂无文章(确认门户 /api/public/v1/social/blog 可访问)</p>
|
||||
) : (
|
||||
<div className="com-blog-cards">
|
||||
{filtered.map((p) => (
|
||||
<article
|
||||
key={p.slug}
|
||||
className={`com-blog-card${p.featured ? ' is-featured' : ''}${p.hidden ? ' is-hidden' : ''}`}
|
||||
>
|
||||
<div className="com-blog-card-top">
|
||||
<div className="com-chip-row">
|
||||
{p.featured ? <span className="com-chip com-chip-ok">置顶</span> : null}
|
||||
{p.hidden ? <span className="com-chip">已隐藏</span> : null}
|
||||
<span className="com-chip">{p.date || '—'}</span>
|
||||
</div>
|
||||
<a href={p.url || '#'} target="_blank" rel="noreferrer" className="com-blog-card-link">
|
||||
预览
|
||||
</a>
|
||||
</div>
|
||||
<h3>{p.title}</h3>
|
||||
<p>{p.description || p.slug}</p>
|
||||
<div className="com-blog-card-meta">
|
||||
<code>{p.slug}</code>
|
||||
{p.readingMinutes ? <span>{p.readingMinutes} min</span> : null}
|
||||
{p.wordCount ? <span>{p.wordCount} words</span> : null}
|
||||
</div>
|
||||
<div className="com-blog-card-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn com-btn-ghost com-btn-sm"
|
||||
disabled={!!busy || p.featured}
|
||||
onClick={() => void patch({ featuredSlug: p.slug }, `已置顶 ${p.slug}`)}
|
||||
>
|
||||
置顶
|
||||
</button>
|
||||
{p.hidden ? (
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn com-btn-ghost com-btn-sm"
|
||||
disabled={!!busy}
|
||||
onClick={() => void patch({ showSlug: p.slug }, `已显示 ${p.slug}`)}
|
||||
>
|
||||
显示
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn com-btn-danger com-btn-sm"
|
||||
disabled={!!busy}
|
||||
onClick={() => void patch({ hideSlug: p.slug }, `已隐藏 ${p.slug}`)}
|
||||
>
|
||||
隐藏
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{tab === 'adsense' ? (
|
||||
<section className="com-panel">
|
||||
<div className="com-panel-head">
|
||||
<div>
|
||||
<h2>Google AdSense</h2>
|
||||
<p>审过前保持关闭。开启后仅英文长文页插位。</p>
|
||||
</div>
|
||||
<label className="com-switch" title="AdSense">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(ov?.adsenseEnabled)}
|
||||
disabled={!!busy}
|
||||
onChange={(e) =>
|
||||
void patch(
|
||||
{ adsenseEnabled: e.target.checked },
|
||||
e.target.checked ? 'AdSense 已开启' : 'AdSense 已关闭',
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span className="com-switch-track">
|
||||
<span className="com-switch-thumb" />
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="com-form-grid">
|
||||
{(
|
||||
[
|
||||
['adsenseClientId', 'clientId (ca-pub-…)'],
|
||||
['adsensePublisherId', 'ads.txt publisher (pub-…)'],
|
||||
['adsenseSlotBlogMid', '文中 slot'],
|
||||
['adsenseSlotBlogEnd', '文末 slot'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<label key={key} className="com-field">
|
||||
<span>{label}</span>
|
||||
<input
|
||||
value={draft[key]}
|
||||
disabled={!!busy}
|
||||
onChange={(e) => setDraft((d) => ({ ...d, [key]: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="com-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={!!busy}
|
||||
onClick={() =>
|
||||
void patch(
|
||||
{
|
||||
adsenseClientId: draft.adsenseClientId.trim(),
|
||||
adsensePublisherId: draft.adsensePublisherId.trim(),
|
||||
adsenseSlotBlogMid: draft.adsenseSlotBlogMid.trim(),
|
||||
adsenseSlotBlogEnd: draft.adsenseSlotBlogEnd.trim(),
|
||||
},
|
||||
'AdSense 配置已保存',
|
||||
)
|
||||
}
|
||||
>
|
||||
保存 AdSense
|
||||
</button>
|
||||
</div>
|
||||
<ul className="com-list" style={{ marginTop: 16 }}>
|
||||
<li>申请期:模块开、广告关、政策页齐全、持续发英文长文</li>
|
||||
<li>
|
||||
过审后:填 client / slot → 开展示 → 更新根目录 <code>ads.txt</code>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{tab === 'module' ? (
|
||||
<section className="com-panel">
|
||||
<div className="com-panel-head">
|
||||
<div>
|
||||
<h2>模块与运营文案</h2>
|
||||
<p>关闭 modules.socialBlog 可隐藏入口(需门户读配置)。</p>
|
||||
</div>
|
||||
<label className="com-switch" title="socialBlog">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={ov?.moduleEnabled !== false}
|
||||
disabled={!!busy}
|
||||
onChange={(e) =>
|
||||
void patch(
|
||||
{ moduleEnabled: e.target.checked },
|
||||
e.target.checked ? 'Blog 模块已开' : 'Blog 模块已关',
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span className="com-switch-track">
|
||||
<span className="com-switch-thumb" />
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="com-form-grid">
|
||||
<label className="com-field">
|
||||
<span>运营备注(仅后台)</span>
|
||||
<input
|
||||
value={draft.note}
|
||||
disabled={!!busy}
|
||||
onChange={(e) => setDraft((d) => ({ ...d, note: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="com-field">
|
||||
<span>Hero 导语覆盖(可选)</span>
|
||||
<input
|
||||
value={draft.heroLead}
|
||||
disabled={!!busy}
|
||||
onChange={(e) => setDraft((d) => ({ ...d, heroLead: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="com-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={!!busy}
|
||||
onClick={() =>
|
||||
void patch(
|
||||
{ note: draft.note, heroLead: draft.heroLead },
|
||||
'文案已保存',
|
||||
)
|
||||
}
|
||||
>
|
||||
保存文案
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn com-btn-ghost"
|
||||
disabled={!!busy || !ov?.ops?.featuredSlug}
|
||||
onClick={() => void patch({ featuredSlug: '' }, '已取消置顶')}
|
||||
>
|
||||
清除置顶
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -4,10 +4,31 @@ export default function Docs() {
|
||||
<header className="com-page-head">
|
||||
<div>
|
||||
<h1>部署说明</h1>
|
||||
<p>源码与发布目标都与 .cn 隔离。</p>
|
||||
<p>源码与发布目标都与 .cn 隔离;本后台只服务 admin.nomadro.com(美国 VPS)。</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="com-panel">
|
||||
<h2>能力一览</h2>
|
||||
<ul className="com-list">
|
||||
<li>
|
||||
<code>/cn</code> · <code>/intl</code> — 受众模块总览与本轨开关
|
||||
</li>
|
||||
<li>
|
||||
<code>…/switches</code> — 页面 / flag / VIP / 文案(remote-config)
|
||||
</li>
|
||||
<li>
|
||||
<code>…/social</code> — 游民社区 UGC(聊天 / 花名册 / 评价 / 接单 / 反馈)
|
||||
</li>
|
||||
<li>
|
||||
<code>…/blog</code> — Nomad Blog(文章显隐 / 置顶 / AdSense)
|
||||
</li>
|
||||
<li>
|
||||
<code>…/events</code> · <code>…/orders</code> · <code>…/users</code> · <code>…/ntfy</code>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section className="com-panel">
|
||||
<h2>本地</h2>
|
||||
<pre className="com-pre">{`pnpm install
|
||||
@ -21,10 +42,15 @@ pnpm build:admin-com`}</pre>
|
||||
<li>
|
||||
静态产物:<code>apps/com/admin/dist</code> → 美国 VPS · <code>admin.nomadro.com</code>
|
||||
</li>
|
||||
<li>
|
||||
API:<code>api.nomadro.com</code>(含 <code>/api/admin/social/ugc/*</code>)
|
||||
</li>
|
||||
<li>
|
||||
发版:<code>python apps/admin/deploy/_deploy_admin_com_us.py</code>
|
||||
</li>
|
||||
<li>
|
||||
勿发布到 <code>/www/wwwroot/admin.nomadro.cn</code>(那是 .cn 微信/抖音后台)
|
||||
</li>
|
||||
<li>门户 Next 若在美国机,与仓库根 <code>src/</code> 的 .cn 部署分开构建、分开进程</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@ -130,8 +130,22 @@ export default function LaneHub({ lane }: { lane: LaneKey }) {
|
||||
const L = cfg?.[lane]
|
||||
const other: LaneKey = lane === 'cn' ? 'intl' : 'cn'
|
||||
|
||||
const [stats, setStats] = useState<Record<string, number> | null>(null)
|
||||
const [socialCounts, setSocialCounts] = useState<Record<string, number> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
api<Record<string, number>>('/api/admin/stats')
|
||||
.then(setStats)
|
||||
.catch(() => setStats(null))
|
||||
api<{ counts?: Record<string, number> }>('/api/admin/social/ugc/overview')
|
||||
.then((d) => setSocialCounts(d.counts || null))
|
||||
.catch(() => setSocialCounts(null))
|
||||
}, [lane])
|
||||
|
||||
const tools = [
|
||||
{ to: `/${lane}/switches`, ico: '⏻', title: '动态开关', desc: '页面 / flag / VIP 入口' },
|
||||
{ to: `/${lane}/social`, ico: '💕', title: '游民社区', desc: '聊天 / 花名册 / 反馈审核' },
|
||||
{ to: `/${lane}/blog`, ico: '📝', title: 'Nomad Blog', desc: '文章显隐 / AdSense / 置顶' },
|
||||
{ to: `/${lane}/events`, ico: '📊', title: '埋点', desc: '本轨相关行为回放' },
|
||||
{ to: `/${lane}/orders`, ico: '🧾', title: '订单', desc: '支付与发货' },
|
||||
{ to: `/${lane}/users`, ico: '👥', title: '用户', desc: '解锁与干预' },
|
||||
@ -165,6 +179,27 @@ export default function LaneHub({ lane }: { lane: LaneKey }) {
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
|
||||
{(stats || socialCounts) && (
|
||||
<div className="com-stat-grid" style={{ marginBottom: 18 }}>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">已付订单</span>
|
||||
<strong>{stats?.paid_orders ?? '—'}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">用户</span>
|
||||
<strong>{stats?.users ?? '—'}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">社群聊天</span>
|
||||
<strong>{socialCounts?.messages ?? '—'}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">花名册</span>
|
||||
<strong>{socialCounts?.roster ?? '—'}</strong>
|
||||
</article>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="com-hub-grid" style={{ marginBottom: 18 }}>
|
||||
{tools.map((t) => (
|
||||
<Link key={t.to} to={t.to} className="com-hub com-hub-primary">
|
||||
|
||||
394
apps/com/admin/src/pages/Social.tsx
Normal file
394
apps/com/admin/src/pages/Social.tsx
Normal file
@ -0,0 +1,394 @@
|
||||
/**
|
||||
* 游民社区 UGC — 直连 social.db(与 nomadro-social 同库)
|
||||
* overview / 聊天 / 花名册 / 评价 / 接单申请 / 反馈 / 目录
|
||||
*/
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { api } from '../api/client'
|
||||
|
||||
type Overview = {
|
||||
path?: string
|
||||
exists?: boolean
|
||||
writable?: boolean
|
||||
bytes?: number
|
||||
counts?: {
|
||||
messages?: number
|
||||
roster?: number
|
||||
reviews?: number
|
||||
gigApps?: number
|
||||
gig_apps?: number
|
||||
feedback?: number
|
||||
}
|
||||
}
|
||||
|
||||
type TabKey = 'messages' | 'roster' | 'reviews' | 'gigs' | 'feedback' | 'catalog'
|
||||
|
||||
const TABS: Array<{ key: TabKey; label: string }> = [
|
||||
{ key: 'messages', label: '聊天' },
|
||||
{ key: 'roster', label: '花名册' },
|
||||
{ key: 'reviews', label: '咖啡馆评价' },
|
||||
{ key: 'gigs', label: '接单申请' },
|
||||
{ key: 'feedback', label: '反馈' },
|
||||
{ key: 'catalog', label: '目录配置' },
|
||||
]
|
||||
|
||||
function fmtTime(v: unknown) {
|
||||
if (!v) return '—'
|
||||
const s = String(v)
|
||||
if (/^\d+$/.test(s)) {
|
||||
const n = Number(s)
|
||||
return new Date(n < 1e12 ? n * 1000 : n).toLocaleString('zh-CN', { hour12: false })
|
||||
}
|
||||
return s.slice(0, 19).replace('T', ' ')
|
||||
}
|
||||
|
||||
function short(v: unknown, n = 48) {
|
||||
const s = String(v ?? '')
|
||||
return s.length <= n ? s || '—' : `${s.slice(0, n)}…`
|
||||
}
|
||||
|
||||
export default function Social() {
|
||||
const [tab, setTab] = useState<TabKey>('messages')
|
||||
const [overview, setOverview] = useState<Overview | null>(null)
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [q, setQ] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [busyId, setBusyId] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [err, setErr] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [catalogJson, setCatalogJson] = useState('')
|
||||
|
||||
const loadOverview = useCallback(async () => {
|
||||
const data = await api<Overview>('/api/admin/social/ugc/overview')
|
||||
setOverview(data)
|
||||
}, [])
|
||||
|
||||
const loadList = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
try {
|
||||
if (tab === 'catalog') {
|
||||
const data = await api<{ catalogs?: Record<string, unknown> }>(
|
||||
'/api/admin/social/ugc/catalog',
|
||||
)
|
||||
setCatalogJson(JSON.stringify(data.catalogs || {}, null, 2))
|
||||
setItems([])
|
||||
setTotal(0)
|
||||
return
|
||||
}
|
||||
const path =
|
||||
tab === 'messages'
|
||||
? `/api/admin/social/ugc/messages?limit=80&q=${encodeURIComponent(q)}`
|
||||
: tab === 'roster'
|
||||
? `/api/admin/social/ugc/roster?limit=80&q=${encodeURIComponent(q)}`
|
||||
: tab === 'reviews'
|
||||
? `/api/admin/social/ugc/reviews?limit=80`
|
||||
: tab === 'gigs'
|
||||
? `/api/admin/social/ugc/gig-apps?limit=80`
|
||||
: `/api/admin/social/ugc/feedback?limit=80`
|
||||
const data = await api<{ items?: Record<string, unknown>[]; total?: number }>(path)
|
||||
setItems(Array.isArray(data.items) ? data.items : [])
|
||||
setTotal(Number(data.total || 0))
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '加载失败')
|
||||
setItems([])
|
||||
setTotal(0)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [tab, q])
|
||||
|
||||
useEffect(() => {
|
||||
loadOverview().catch((e: Error) => setErr(e.message || '概览失败'))
|
||||
}, [loadOverview])
|
||||
|
||||
useEffect(() => {
|
||||
void loadList()
|
||||
}, [loadList])
|
||||
|
||||
async function removeRow(kind: TabKey, id: string) {
|
||||
if (kind === 'catalog' || !id || !window.confirm(`确认删除这条 ${kind} 记录?不可恢复。`)) return
|
||||
setBusyId(id)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const path =
|
||||
kind === 'messages'
|
||||
? `/api/admin/social/ugc/messages/${encodeURIComponent(id)}`
|
||||
: kind === 'roster'
|
||||
? `/api/admin/social/ugc/roster/${encodeURIComponent(id)}`
|
||||
: kind === 'reviews'
|
||||
? `/api/admin/social/ugc/reviews/${encodeURIComponent(id)}`
|
||||
: kind === 'gigs'
|
||||
? `/api/admin/social/ugc/gig-apps/${encodeURIComponent(id)}`
|
||||
: `/api/admin/social/ugc/feedback/${encodeURIComponent(id)}`
|
||||
await api(path, { method: 'DELETE' })
|
||||
setMsg('已删除')
|
||||
await loadList()
|
||||
await loadOverview().catch(() => undefined)
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '删除失败')
|
||||
} finally {
|
||||
setBusyId('')
|
||||
}
|
||||
}
|
||||
|
||||
async function saveCatalog() {
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const parsed = JSON.parse(catalogJson) as Record<string, unknown>
|
||||
await api('/api/admin/social/ugc/catalog', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(parsed),
|
||||
})
|
||||
setMsg('目录已保存(remote-config 深合并)')
|
||||
await loadList()
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '目录保存失败(检查 JSON)')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const counts = overview?.counts || {}
|
||||
|
||||
return (
|
||||
<div className="com-page">
|
||||
<header className="com-page-head com-page-head-row">
|
||||
<div>
|
||||
<h1>游民社区</h1>
|
||||
<p>
|
||||
管理 <code>/social</code> UGC:聊天、花名册、评价、接单申请、反馈与目录。库文件与{' '}
|
||||
<code>nomadro-social</code> 同源。
|
||||
</p>
|
||||
<div className="com-chip-row">
|
||||
<span className={`com-chip${overview?.exists ? ' com-chip-ok' : ''}`}>
|
||||
DB {overview?.exists ? '在线' : '缺失'}
|
||||
</span>
|
||||
{overview?.writable === false ? <span className="com-chip">只读</span> : null}
|
||||
{overview?.path ? (
|
||||
<span className="com-chip" title={overview.path}>
|
||||
{short(overview.path, 36)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn com-btn-ghost"
|
||||
onClick={() => {
|
||||
void loadOverview()
|
||||
void loadList()
|
||||
}}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
|
||||
<div className="com-stat-grid">
|
||||
{(
|
||||
[
|
||||
['聊天', counts.messages],
|
||||
['花名册', counts.roster],
|
||||
['评价', counts.reviews],
|
||||
['接单', counts.gigApps ?? counts.gig_apps],
|
||||
['反馈', counts.feedback],
|
||||
] as const
|
||||
).map(([label, n]) => (
|
||||
<article key={label} className="com-stat">
|
||||
<span className="com-stat-label">{label}</span>
|
||||
<strong>{n ?? '—'}</strong>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<nav className="com-tabs" aria-label="UGC 分类">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
className={`com-tab${tab === t.key ? ' is-on' : ''}`}
|
||||
onClick={() => {
|
||||
setTab(t.key)
|
||||
setQ('')
|
||||
}}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{tab === 'catalog' ? (
|
||||
<section className="com-panel">
|
||||
<div className="com-panel-head">
|
||||
<div>
|
||||
<h2>socialCatalogs</h2>
|
||||
<p>meetups / gigs / cafes / roster / ebooks / videos(JSON)</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={busy}
|
||||
onClick={() => void saveCatalog()}
|
||||
>
|
||||
{busy ? '保存中…' : '保存目录'}
|
||||
</button>
|
||||
</div>
|
||||
<textarea
|
||||
className="com-pre"
|
||||
style={{ width: '100%', minHeight: 360, resize: 'vertical', fontFamily: 'ui-monospace, monospace' }}
|
||||
value={catalogJson}
|
||||
onChange={(e) => setCatalogJson(e.target.value)}
|
||||
spellCheck={false}
|
||||
/>
|
||||
</section>
|
||||
) : (
|
||||
<>
|
||||
{(tab === 'messages' || tab === 'roster') && (
|
||||
<div className="com-toolbar">
|
||||
<input
|
||||
className="com-input"
|
||||
placeholder={tab === 'messages' ? '搜正文 / 昵称' : '搜名字 / 城市 / 技能'}
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void loadList()
|
||||
}}
|
||||
/>
|
||||
<button type="button" className="com-btn com-btn-ghost" onClick={() => void loadList()}>
|
||||
搜索
|
||||
</button>
|
||||
<span className="com-muted">共 {total || items.length} 条</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<section className="com-panel com-table-wrap">
|
||||
{loading && !items.length ? (
|
||||
<p className="com-muted">加载中…</p>
|
||||
) : !items.length ? (
|
||||
<p className="com-muted">暂无数据</p>
|
||||
) : (
|
||||
<table className="com-table">
|
||||
<thead>
|
||||
{tab === 'messages' ? (
|
||||
<tr>
|
||||
<th>频道</th>
|
||||
<th>作者</th>
|
||||
<th>内容</th>
|
||||
<th>时间</th>
|
||||
<th />
|
||||
</tr>
|
||||
) : null}
|
||||
{tab === 'roster' ? (
|
||||
<tr>
|
||||
<th>名字</th>
|
||||
<th>城市</th>
|
||||
<th>标题</th>
|
||||
<th>更新</th>
|
||||
<th />
|
||||
</tr>
|
||||
) : null}
|
||||
{tab === 'reviews' ? (
|
||||
<tr>
|
||||
<th>咖啡馆</th>
|
||||
<th>作者</th>
|
||||
<th>分</th>
|
||||
<th>评语</th>
|
||||
<th />
|
||||
</tr>
|
||||
) : null}
|
||||
{tab === 'gigs' ? (
|
||||
<tr>
|
||||
<th>Gig</th>
|
||||
<th>姓名</th>
|
||||
<th>联系</th>
|
||||
<th>备注</th>
|
||||
<th />
|
||||
</tr>
|
||||
) : null}
|
||||
{tab === 'feedback' ? (
|
||||
<tr>
|
||||
<th>类型</th>
|
||||
<th>内容</th>
|
||||
<th>联系</th>
|
||||
<th>时间</th>
|
||||
<th />
|
||||
</tr>
|
||||
) : null}
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((row) => {
|
||||
const id = String(
|
||||
row.id || row.messageId || row.guestId || row.guest_id || '',
|
||||
)
|
||||
return (
|
||||
<tr key={id || JSON.stringify(row).slice(0, 40)}>
|
||||
{tab === 'messages' ? (
|
||||
<>
|
||||
<td>{String(row.channelId || row.channel_id || '—')}</td>
|
||||
<td>{String(row.author || '—')}</td>
|
||||
<td title={String(row.text || '')}>{short(row.text, 56)}</td>
|
||||
<td>{fmtTime(row.at || row.created_at || row.createdAt)}</td>
|
||||
</>
|
||||
) : null}
|
||||
{tab === 'roster' ? (
|
||||
<>
|
||||
<td>{String(row.name || '—')}</td>
|
||||
<td>{String(row.city || '—')}</td>
|
||||
<td>{short(row.title, 28)}</td>
|
||||
<td>{fmtTime(row.updatedAt || row.updated_at)}</td>
|
||||
</>
|
||||
) : null}
|
||||
{tab === 'reviews' ? (
|
||||
<>
|
||||
<td>{String(row.cafeId || row.cafe_id || '—')}</td>
|
||||
<td>{String(row.author || '—')}</td>
|
||||
<td>{String(row.score ?? '—')}</td>
|
||||
<td>{short(row.text, 40)}</td>
|
||||
</>
|
||||
) : null}
|
||||
{tab === 'gigs' ? (
|
||||
<>
|
||||
<td>{String(row.gigId || row.gig_id || '—')}</td>
|
||||
<td>{String(row.name || '—')}</td>
|
||||
<td>{short(row.contact, 24)}</td>
|
||||
<td>{short(row.note, 32)}</td>
|
||||
</>
|
||||
) : null}
|
||||
{tab === 'feedback' ? (
|
||||
<>
|
||||
<td>{String(row.kind || '—')}</td>
|
||||
<td>{short(row.text, 48)}</td>
|
||||
<td>{short(row.contact, 20)}</td>
|
||||
<td>{fmtTime(row.created_at || row.createdAt || row.at)}</td>
|
||||
</>
|
||||
) : null}
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn com-btn-danger com-btn-sm"
|
||||
disabled={!id || busyId === id}
|
||||
onClick={() => void removeRow(tab, id)}
|
||||
>
|
||||
{busyId === id ? '…' : '删除'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -16,6 +16,11 @@ type SwitchesCfg = {
|
||||
joinGroupAction: 'popup' | 'vip'
|
||||
memoTrialBrowse?: boolean
|
||||
joinGroupWechat?: boolean
|
||||
adsenseEnabled?: boolean
|
||||
adsenseClientId?: string
|
||||
adsensePublisherId?: string
|
||||
adsenseSlotBlogMid?: string
|
||||
adsenseSlotBlogEnd?: string
|
||||
}
|
||||
copy: {
|
||||
homeBrand: string
|
||||
@ -23,6 +28,7 @@ type SwitchesCfg = {
|
||||
homeLead: string
|
||||
vipCta: string
|
||||
wechatOaName?: string
|
||||
xHandle?: string
|
||||
memoUnlockCta?: string
|
||||
}
|
||||
vipEntries: Record<string, boolean>
|
||||
@ -51,6 +57,7 @@ const PAGE_MODS = [
|
||||
{ key: 'book', label: '数字游民小册', ico: '📕', desc: '小册阅读' },
|
||||
{ key: 'community', label: '旅居社群', ico: '🏕️', desc: '社群入口' },
|
||||
{ key: 'social', label: '游民社区', ico: '💕', desc: '社交大厅;关则拦截入口' },
|
||||
{ key: 'socialBlog', label: 'Nomad Blog', ico: '📝', desc: '/social/blog 英文长文 · AdSense' },
|
||||
{ key: 'vip', label: 'VIP 中心', ico: '👑', desc: '会员落地;关则加群改弹引导' },
|
||||
{ key: 'destinations', label: '目的地', ico: '📍', desc: '目的地列表' },
|
||||
{ key: 'meetups', label: '活动', ico: '📅', desc: '活动入口' },
|
||||
@ -105,6 +112,7 @@ export default function Switches() {
|
||||
homeTagline: '',
|
||||
homeLead: '',
|
||||
vipCta: '',
|
||||
xHandle: '',
|
||||
})
|
||||
|
||||
const load = useCallback(async () => {
|
||||
@ -116,6 +124,7 @@ export default function Switches() {
|
||||
homeTagline: data.copy?.homeTagline || '',
|
||||
homeLead: data.copy?.homeLead || '',
|
||||
vipCta: data.copy?.vipCta || '',
|
||||
xHandle: data.copy?.xHandle || 'noamdcna',
|
||||
})
|
||||
}, [])
|
||||
|
||||
@ -138,6 +147,7 @@ export default function Switches() {
|
||||
homeTagline: data.copy?.homeTagline || '',
|
||||
homeLead: data.copy?.homeLead || '',
|
||||
vipCta: data.copy?.vipCta || '',
|
||||
xHandle: data.copy?.xHandle || 'noamdcna',
|
||||
})
|
||||
setMsg(okHint)
|
||||
} catch (e: unknown) {
|
||||
@ -251,6 +261,11 @@ export default function Switches() {
|
||||
{ key: 'payEnabled', label: '支付总开关', desc: '关闭后隐藏付费 CTA' },
|
||||
{ key: 'socialFollow', label: '关注引导', desc: '公众号 / X 关注弹窗' },
|
||||
{ key: 'offlineBadge', label: '离线角标', desc: '展示「本地数据」提示' },
|
||||
{
|
||||
key: 'adsenseEnabled',
|
||||
label: 'AdSense 展示',
|
||||
desc: '审过前务必关;开后需填 clientId + slot',
|
||||
},
|
||||
] as const
|
||||
).map((f) => {
|
||||
const on = Boolean(cfg.flags[f.key])
|
||||
@ -291,6 +306,29 @@ export default function Switches() {
|
||||
<option value="popup">弹窗</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="com-form-grid" style={{ marginTop: 16 }}>
|
||||
{(
|
||||
[
|
||||
['adsenseClientId', 'AdSense clientId (ca-pub-…)'],
|
||||
['adsensePublisherId', 'ads.txt publisher (pub-…)'],
|
||||
['adsenseSlotBlogMid', '文中 slot'],
|
||||
['adsenseSlotBlogEnd', '文末 slot'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<label key={key} className="com-field">
|
||||
<span>{label}</span>
|
||||
<input
|
||||
disabled={busy}
|
||||
defaultValue={String(cfg.flags[key] || '')}
|
||||
onBlur={(e) => {
|
||||
const v = e.target.value.trim()
|
||||
if (v === String(cfg.flags[key] || '')) return
|
||||
void patch({ flags: { [key]: v } }, `${label} 已保存`)
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
@ -335,6 +373,7 @@ export default function Switches() {
|
||||
['homeTagline', '副标题'],
|
||||
['homeLead', '导语'],
|
||||
['vipCta', 'VIP CTA'],
|
||||
['xHandle', 'X 账号(intl 关注,如 noamdcna)'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<label key={key} className="com-field">
|
||||
|
||||
@ -475,6 +475,14 @@ input {
|
||||
}
|
||||
|
||||
.com-btn,
|
||||
.com-btn-danger {
|
||||
background: rgba(239, 68, 68, 0.14);
|
||||
border: 1px solid rgba(239, 68, 68, 0.4);
|
||||
color: #fca5a5;
|
||||
}
|
||||
.com-btn-danger:hover:not(:disabled) {
|
||||
background: rgba(239, 68, 68, 0.28);
|
||||
}
|
||||
.com-btn-ghost,
|
||||
.com-btn-sm {
|
||||
min-height: 44px;
|
||||
@ -1126,3 +1134,110 @@ button.com-chip.is-on,
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
/* Nomad Blog admin */
|
||||
.com-stat-grid-4 {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
.com-blog-head-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.com-blog-quicklinks {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin: 0 0 18px;
|
||||
}
|
||||
.com-blog-quick {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 36px;
|
||||
padding: 0 12px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
font-size: 13px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
transition: border-color 0.2s, color 0.2s;
|
||||
}
|
||||
.com-blog-quick:hover {
|
||||
color: #fff;
|
||||
border-color: rgba(245, 158, 11, 0.45);
|
||||
}
|
||||
.com-blog-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
.com-blog-card {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
padding: 16px;
|
||||
background: rgba(20, 20, 24, 0.72);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
transition: border-color 0.2s, transform 0.2s;
|
||||
}
|
||||
.com-blog-card:hover {
|
||||
border-color: rgba(245, 158, 11, 0.35);
|
||||
}
|
||||
.com-blog-card.is-featured {
|
||||
border-color: rgba(52, 211, 153, 0.45);
|
||||
box-shadow: 0 0 0 1px rgba(52, 211, 153, 0.12);
|
||||
}
|
||||
.com-blog-card.is-hidden {
|
||||
opacity: 0.62;
|
||||
}
|
||||
.com-blog-card-top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
}
|
||||
.com-blog-card-link {
|
||||
color: var(--accent-2, #f59e0b);
|
||||
font-size: 12px;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.com-blog-card h3 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
line-height: 1.35;
|
||||
font-family: var(--font-display);
|
||||
}
|
||||
.com-blog-card > p {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.com-blog-card-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 12px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.com-blog-card-meta code {
|
||||
color: var(--accent-2, #f59e0b);
|
||||
}
|
||||
.com-blog-card-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.com-stat-grid-4 {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.com-blog-cards {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@ -64,6 +64,8 @@ const nextConfig: NextConfig = {
|
||||
remotePatterns: [
|
||||
{ protocol: "https", hostname: "**.nomadro.cn" },
|
||||
{ protocol: "https", hostname: "**.nomadro.com" },
|
||||
{ protocol: "https", hostname: "s3.nomadro.com" },
|
||||
{ protocol: "https", hostname: "api.dicebear.com" },
|
||||
],
|
||||
},
|
||||
transpilePackages: ["@nomadro/pay", "@nomadro/pb", "@nomadro/sdk"],
|
||||
|
||||
5
public/ads.txt
Normal file
5
public/ads.txt
Normal file
@ -0,0 +1,5 @@
|
||||
# Google AdSense — replace pub-XXXXXXXXXXXXXXXX with your publisher ID after approval.
|
||||
# Format: google.com, pub-XXXXXXXXXXXXXXXX, DIRECT, f08c47fec0942fa0
|
||||
# Keep this file at https://nomadro.com/ads.txt (site root).
|
||||
# Placeholder line commented until remote-config adsensePublisherId is set:
|
||||
# google.com, pub-PLACEHOLDER, DIRECT, f08c47fec0942fa0
|
||||
38
src/app/api/public/v1/social/blog/route.ts
Normal file
38
src/app/api/public/v1/social/blog/route.ts
Normal file
@ -0,0 +1,38 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { listBlogPosts } from "@social/lib/blog/catalog";
|
||||
import {
|
||||
assertPublicKey,
|
||||
jsonOk,
|
||||
optionsOk,
|
||||
} from "~/lib/public-api/http";
|
||||
|
||||
export async function OPTIONS(req: NextRequest) {
|
||||
return optionsOk(req);
|
||||
}
|
||||
|
||||
/** Public blog catalog — admin + SEO tools; AdSense-friendly indexable metadata */
|
||||
export async function GET(req: NextRequest) {
|
||||
const denied = assertPublicKey(req);
|
||||
if (denied) return denied;
|
||||
const locale = (req.nextUrl.searchParams.get("locale") || "en").trim();
|
||||
const items = listBlogPosts({
|
||||
locale: locale === "all" ? "all" : locale === "zh" ? "zh" : "en",
|
||||
}).map((p) => ({
|
||||
slug: p.slug,
|
||||
title: p.title,
|
||||
description: p.description,
|
||||
date: p.date,
|
||||
tags: p.tags,
|
||||
wordCount: p.wordCount,
|
||||
readingMinutes: p.readingMinutes,
|
||||
locale: p.locale,
|
||||
author: p.author,
|
||||
url: `https://nomadro.com/social/blog/${p.slug}`,
|
||||
}));
|
||||
return jsonOk(req, {
|
||||
ok: true,
|
||||
total: items.length,
|
||||
items,
|
||||
pagePath: "/social/blog",
|
||||
});
|
||||
}
|
||||
67
src/app/social/blog/[slug]/page.tsx
Normal file
67
src/app/social/blog/[slug]/page.tsx
Normal file
@ -0,0 +1,67 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import BlogPostClient from "@social/components/blog/BlogPostClient";
|
||||
import { getBlogPost, listBlogPosts, listBlogSlugs } from "@social/lib/blog/catalog";
|
||||
import { resolveBlogAdSense } from "@social/lib/blog/adsense";
|
||||
import { blogPostingJsonLd } from "@social/lib/blog/jsonld";
|
||||
import { readRemoteConfigFile } from "~/lib/remote-config-store";
|
||||
|
||||
type Props = { params: Promise<{ slug: string }> };
|
||||
|
||||
export async function generateStaticParams() {
|
||||
return listBlogSlugs().map((slug) => ({ slug }));
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const { slug } = await params;
|
||||
const post = getBlogPost(slug);
|
||||
if (!post) return { title: "Not found" };
|
||||
const url = `https://nomadro.com/social/blog/${post.slug}`;
|
||||
return {
|
||||
title: `${post.title} | Nomadro Blog`,
|
||||
description: post.description,
|
||||
alternates: { canonical: url },
|
||||
openGraph: {
|
||||
title: post.title,
|
||||
description: post.description,
|
||||
url,
|
||||
type: "article",
|
||||
publishedTime: post.date,
|
||||
modifiedTime: post.updated || post.date,
|
||||
authors: [post.author || "Nomadro"],
|
||||
tags: post.tags,
|
||||
siteName: "Nomadro",
|
||||
},
|
||||
twitter: {
|
||||
card: "summary_large_image",
|
||||
title: post.title,
|
||||
description: post.description,
|
||||
},
|
||||
robots: { index: true, follow: true },
|
||||
};
|
||||
}
|
||||
|
||||
export default async function SocialBlogPostPage({ params }: Props) {
|
||||
const { slug } = await params;
|
||||
const post = getBlogPost(slug);
|
||||
if (!post) notFound();
|
||||
|
||||
const related = listBlogPosts({ locale: post.locale })
|
||||
.filter((p) => p.slug !== post.slug)
|
||||
.filter((p) => p.tags.some((t) => post.tags.includes(t)))
|
||||
.slice(0, 3);
|
||||
|
||||
const config = await readRemoteConfigFile().catch(() => null);
|
||||
const adsense = resolveBlogAdSense(config);
|
||||
const jsonLd = blogPostingJsonLd(post);
|
||||
|
||||
return (
|
||||
<>
|
||||
<script
|
||||
type="application/ld+json"
|
||||
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
|
||||
/>
|
||||
<BlogPostClient post={post} related={related} adsense={adsense} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
58
src/app/social/blog/about/page.tsx
Normal file
58
src/app/social/blog/about/page.tsx
Normal file
@ -0,0 +1,58 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import SiteShell from "@social/components/SiteShell";
|
||||
import { SocialFooter } from "@social/components/SocialNavigation";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "About the Nomad Blog | Nomadro",
|
||||
description:
|
||||
"Who publishes Nomadro’s nomad blog, what we write about, and how advertising may appear after approval.",
|
||||
alternates: { canonical: "https://nomadro.com/social/blog/about" },
|
||||
robots: { index: true, follow: true },
|
||||
};
|
||||
|
||||
export default function SocialBlogAboutPage() {
|
||||
return (
|
||||
<SiteShell title="About" editorial>
|
||||
<article className="sblog-page sblog-article">
|
||||
<header className="sblog-hero">
|
||||
<p className="sblog-eyebrow">Publisher</p>
|
||||
<h1>About this blog</h1>
|
||||
<p className="sblog-lead">
|
||||
Nomadro publishes practical English guides for digital nomads on{" "}
|
||||
<strong>nomadro.com</strong>. We also run community tools under{" "}
|
||||
<Link href={socialPath("/")}>/social</Link> so readers can meet people,
|
||||
not only consume posts.
|
||||
</p>
|
||||
</header>
|
||||
<div className="sblog-prose">
|
||||
<h2>What we write</h2>
|
||||
<p>
|
||||
Field notes on housing, coworking, budgets, time zones, privacy, and
|
||||
making friends in a new city. Articles are original, edited for clarity,
|
||||
and meant to be useful offline as well as online.
|
||||
</p>
|
||||
<h2>Advertising</h2>
|
||||
<p>
|
||||
We may show Google AdSense units on long English articles after the
|
||||
publisher account is approved. Until then, ads stay disabled via remote
|
||||
configuration. Content always comes first; ads never replace the article.
|
||||
</p>
|
||||
<h2>Contact</h2>
|
||||
<p>
|
||||
Questions or corrections: use{" "}
|
||||
<Link href={socialPath("/feedback")}>Feedback</Link>. Privacy details
|
||||
live on the <Link href={socialPath("/privacy")}>Privacy</Link> page.
|
||||
</p>
|
||||
</div>
|
||||
<nav className="sblog-policy-row">
|
||||
<Link href={socialPath("/blog")}>Blog</Link>
|
||||
<Link href={socialPath("/privacy")}>Privacy</Link>
|
||||
<Link href={socialPath("/feedback")}>Contact</Link>
|
||||
</nav>
|
||||
<SocialFooter />
|
||||
</article>
|
||||
</SiteShell>
|
||||
);
|
||||
}
|
||||
35
src/app/social/blog/page.tsx
Normal file
35
src/app/social/blog/page.tsx
Normal file
@ -0,0 +1,35 @@
|
||||
import type { Metadata } from "next";
|
||||
import BlogListClient from "@social/components/blog/BlogListClient";
|
||||
import { listBlogPosts } from "@social/lib/blog/catalog";
|
||||
import { blogListJsonLd } from "@social/lib/blog/jsonld";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Nomad Blog | Nomadro",
|
||||
description:
|
||||
"English field notes for digital nomads: cities, cafés, remote work, budgets, and meeting people on the road.",
|
||||
alternates: { canonical: "https://nomadro.com/social/blog" },
|
||||
openGraph: {
|
||||
title: "Nomad Blog | Nomadro",
|
||||
description:
|
||||
"Practical guides for remote work and slow travel. Content-first — ads off until AdSense approval.",
|
||||
url: "https://nomadro.com/social/blog",
|
||||
type: "website",
|
||||
siteName: "Nomadro",
|
||||
},
|
||||
robots: { index: true, follow: true },
|
||||
};
|
||||
|
||||
export default function SocialBlogPage() {
|
||||
const posts = listBlogPosts({ locale: "en", adsenseReadyOnly: false });
|
||||
const jsonLd = blogListJsonLd(posts);
|
||||
|
||||
return (
|
||||
<>
|
||||
<script
|
||||
type="application/ld+json"
|
||||
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
|
||||
/>
|
||||
<BlogListClient posts={posts} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
37
src/app/social/blog/rss.xml/route.ts
Normal file
37
src/app/social/blog/rss.xml/route.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import { listBlogPosts } from "@social/lib/blog/catalog";
|
||||
|
||||
const SITE = "https://nomadro.com";
|
||||
|
||||
export async function GET() {
|
||||
const posts = listBlogPosts({ locale: "en" });
|
||||
const items = posts
|
||||
.map(
|
||||
(p) => `
|
||||
<item>
|
||||
<title><![CDATA[${p.title}]]></title>
|
||||
<link>${SITE}/social/blog/${p.slug}</link>
|
||||
<guid>${SITE}/social/blog/${p.slug}</guid>
|
||||
<pubDate>${new Date(p.date).toUTCString()}</pubDate>
|
||||
<description><![CDATA[${p.description}]]></description>
|
||||
</item>`,
|
||||
)
|
||||
.join("");
|
||||
|
||||
const xml = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rss version="2.0">
|
||||
<channel>
|
||||
<title>Nomadro Nomad Blog</title>
|
||||
<link>${SITE}/social/blog</link>
|
||||
<description>English field notes for digital nomads</description>
|
||||
<language>en-us</language>
|
||||
${items}
|
||||
</channel>
|
||||
</rss>`;
|
||||
|
||||
return new Response(xml, {
|
||||
headers: {
|
||||
"Content-Type": "application/rss+xml; charset=utf-8",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -12,6 +12,7 @@ import "@social/app/motion.css";
|
||||
import "@social/app/depth.css";
|
||||
import "@social/app/vivid.css";
|
||||
import "@social/app/h5.css";
|
||||
import "@social/app/blog.css";
|
||||
import SocialExperience from "@social/components/SocialExperience";
|
||||
|
||||
export const metadata = {
|
||||
|
||||
78
src/app/social/privacy/page.tsx
Normal file
78
src/app/social/privacy/page.tsx
Normal file
@ -0,0 +1,78 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import SiteShell from "@social/components/SiteShell";
|
||||
import { SocialFooter } from "@social/components/SocialNavigation";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Privacy | Nomadro Social",
|
||||
description:
|
||||
"How Nomadro handles data on /social, cookies, analytics, and advertising (including Google AdSense when enabled).",
|
||||
alternates: { canonical: "https://nomadro.com/social/privacy" },
|
||||
robots: { index: true, follow: true },
|
||||
};
|
||||
|
||||
/** AdSense reviewers look for a clear Privacy Policy with ads/cookies disclosure */
|
||||
export default function SocialPrivacyPage() {
|
||||
return (
|
||||
<SiteShell title="Privacy" editorial>
|
||||
<article className="sblog-page sblog-article">
|
||||
<header className="sblog-hero">
|
||||
<p className="sblog-eyebrow">Legal</p>
|
||||
<h1>Privacy Policy</h1>
|
||||
<p className="sblog-lead">
|
||||
Last updated: 4 November 2026. This page covers nomadro.com social
|
||||
surfaces including <code>/social</code> and the Nomad Blog.
|
||||
</p>
|
||||
</header>
|
||||
<div className="sblog-prose">
|
||||
<h2>Who we are</h2>
|
||||
<p>
|
||||
Nomadro operates nomadro.com. Contact us via{" "}
|
||||
<Link href={socialPath("/feedback")}>Feedback</Link> for privacy
|
||||
requests.
|
||||
</p>
|
||||
<h2>Data we process</h2>
|
||||
<p>
|
||||
Account or profile details you submit (for example display name, city,
|
||||
or join flow fields), messages you post in community tools, technical
|
||||
logs needed to keep the service running, and optional analytics events.
|
||||
</p>
|
||||
<h2>Cookies, analytics, and advertising</h2>
|
||||
<p>
|
||||
We may use cookies or similar technologies for session continuity,
|
||||
preference storage, and traffic analytics. After Google AdSense
|
||||
approval, advertising cookies may be used by Google and partners to
|
||||
serve and measure ads on eligible pages. You can control cookies through
|
||||
your browser settings. Where required by law, we will present a consent
|
||||
mechanism before non‑essential advertising cookies.
|
||||
</p>
|
||||
<p>
|
||||
Third‑party ad partners may collect data subject to their own policies
|
||||
(for example Google’s advertising policies). See also our{" "}
|
||||
<Link href={socialPath("/blog/about")}>About</Link> page for how ads
|
||||
relate to editorial content.
|
||||
</p>
|
||||
<h2>Your choices</h2>
|
||||
<p>
|
||||
You may request access or deletion of account‑linked data via Feedback.
|
||||
You may refuse non‑essential cookies where a banner is shown. Blocking
|
||||
ads does not remove your ability to read blog articles.
|
||||
</p>
|
||||
<h2>International visitors</h2>
|
||||
<p>
|
||||
nomadro.com primarily serves an international audience. Data may be
|
||||
processed on servers outside your country. We take reasonable measures
|
||||
to protect information in transit (HTTPS) and at rest.
|
||||
</p>
|
||||
</div>
|
||||
<nav className="sblog-policy-row">
|
||||
<Link href={socialPath("/blog")}>Blog</Link>
|
||||
<Link href={socialPath("/blog/about")}>About</Link>
|
||||
<Link href={socialPath("/feedback")}>Contact</Link>
|
||||
</nav>
|
||||
<SocialFooter />
|
||||
</article>
|
||||
</SiteShell>
|
||||
);
|
||||
}
|
||||
35
src/app/social/sitemap.ts
Normal file
35
src/app/social/sitemap.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { listBlogPosts } from "@social/lib/blog/catalog";
|
||||
|
||||
const SITE = "https://nomadro.com";
|
||||
|
||||
export default function sitemap(): MetadataRoute.Sitemap {
|
||||
const posts = listBlogPosts({ locale: "all" });
|
||||
const staticRoutes: MetadataRoute.Sitemap = [
|
||||
{
|
||||
url: `${SITE}/social/blog`,
|
||||
lastModified: new Date(),
|
||||
changeFrequency: "weekly",
|
||||
priority: 0.8,
|
||||
},
|
||||
{
|
||||
url: `${SITE}/social/blog/about`,
|
||||
lastModified: new Date(),
|
||||
changeFrequency: "monthly",
|
||||
priority: 0.6,
|
||||
},
|
||||
{
|
||||
url: `${SITE}/social/privacy`,
|
||||
lastModified: new Date(),
|
||||
changeFrequency: "monthly",
|
||||
priority: 0.7,
|
||||
},
|
||||
];
|
||||
const postRoutes = posts.map((p) => ({
|
||||
url: `${SITE}/social/blog/${p.slug}`,
|
||||
lastModified: new Date(p.updated || p.date),
|
||||
changeFrequency: "monthly" as const,
|
||||
priority: 0.7,
|
||||
}));
|
||||
return [...staticRoutes, ...postRoutes];
|
||||
}
|
||||
@ -12,7 +12,19 @@ import styles from "./social-follow.module.css";
|
||||
|
||||
const SHOW_DELAY_MS = 4500;
|
||||
|
||||
const X_URL = "https://x.com/nomadro";
|
||||
/** Intl follow SoT — overridable via remote-config copy.xHandle */
|
||||
export const DEFAULT_X_HANDLE = "noamdcna";
|
||||
|
||||
export function xProfileUrl(handle: string = DEFAULT_X_HANDLE) {
|
||||
const h = handle.replace(/^@/, "").trim() || DEFAULT_X_HANDLE;
|
||||
return `https://x.com/${h}`;
|
||||
}
|
||||
|
||||
export function formatXHandle(handle: string = DEFAULT_X_HANDLE) {
|
||||
const h = handle.replace(/^@/, "").trim() || DEFAULT_X_HANDLE;
|
||||
return `@${h}`;
|
||||
}
|
||||
|
||||
/** Public WeChat OA QR — replace asset when brand QR updates */
|
||||
export const WECHAT_OA_QR = "/wechat-oa-qr.png";
|
||||
|
||||
@ -159,6 +171,7 @@ export function SocialFollowPrompt() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [mode, setMode] = useState<Mode>("wechat");
|
||||
const [meta, setMeta] = useState<JoinMeta>(DEFAULT_META);
|
||||
const [xHandle, setXHandle] = useState(DEFAULT_X_HANDLE);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
@ -198,6 +211,7 @@ export function SocialFollowPrompt() {
|
||||
flags?.joinGroupDouyin === true,
|
||||
};
|
||||
setMeta(m);
|
||||
setXHandle(String(copy.xHandle || DEFAULT_X_HANDLE));
|
||||
// 关注渠道完全由 audience 模块决定
|
||||
if (channel === "x") setMode("x");
|
||||
else if (channel === "wechat") {
|
||||
@ -300,7 +314,7 @@ export function SocialFollowPrompt() {
|
||||
) : (
|
||||
<a
|
||||
className={styles.cta}
|
||||
href={X_URL}
|
||||
href={xProfileUrl(xHandle)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
data-track="follow_x"
|
||||
@ -309,7 +323,7 @@ export function SocialFollowPrompt() {
|
||||
dismiss();
|
||||
}}
|
||||
>
|
||||
<span aria-hidden>𝕏</span> Follow @nomadro
|
||||
<span aria-hidden>𝕏</span> Follow {formatXHandle(xHandle)}
|
||||
</a>
|
||||
)}
|
||||
|
||||
|
||||
@ -108,6 +108,8 @@ export type NomadroRemoteConfig = {
|
||||
community: ModuleToggle;
|
||||
/** 游民社区(社交垂直;可拆独立域) */
|
||||
social: ModuleToggle;
|
||||
/** /social/blog — AdSense 友好英文长文;关则隐藏入口 */
|
||||
socialBlog?: ModuleToggle;
|
||||
vip: ModuleToggle;
|
||||
meetups: ModuleToggle;
|
||||
destinations: ModuleToggle;
|
||||
@ -131,6 +133,17 @@ export type NomadroRemoteConfig = {
|
||||
/** 加群点击:popup=弹窗;vip=跳会员页。本地默认 vip */
|
||||
joinGroupAction: "popup" | "vip";
|
||||
offlineBadge: boolean;
|
||||
/**
|
||||
* Google AdSense master switch for /social/blog.
|
||||
* Keep false until publisher approval — content-first review.
|
||||
*/
|
||||
adsenseEnabled?: boolean;
|
||||
/** ca-pub-xxxxxxxxxxxxxxxx */
|
||||
adsenseClientId?: string;
|
||||
/** ads.txt publisher id pub-xxxxxxxx(可与 client 同源) */
|
||||
adsensePublisherId?: string;
|
||||
adsenseSlotBlogMid?: string;
|
||||
adsenseSlotBlogEnd?: string;
|
||||
};
|
||||
/**
|
||||
* 受众分轨(.com 国际优先;中文用户特殊对待)。
|
||||
@ -150,6 +163,8 @@ export type NomadroRemoteConfig = {
|
||||
vipProductId: string;
|
||||
vipCta: string;
|
||||
wechatOaName?: string;
|
||||
/** X / Twitter handle for intl follow CTA (without or with @) */
|
||||
xHandle?: string;
|
||||
joinGroupDouyinHint?: string;
|
||||
joinGroupDouyinQr?: string;
|
||||
/** 游民社区落地页;/admin/config 可编辑,客户端有默认文案兜底。 */
|
||||
@ -191,6 +206,11 @@ export type NomadroRemoteConfig = {
|
||||
socialWayTeam?: string;
|
||||
socialPayJoinLabel?: string;
|
||||
socialOaJoinLabel?: string;
|
||||
/** AdSense 文案位兜底(优先 flags) */
|
||||
adsenseClientId?: string;
|
||||
adsensePublisherId?: string;
|
||||
adsenseSlotBlogMid?: string;
|
||||
adsenseSlotBlogEnd?: string;
|
||||
};
|
||||
/** 导航页分类 / 链接(后台可增删改隐) */
|
||||
navContent?: NavContent;
|
||||
@ -387,6 +407,12 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
|
||||
tabLabel: "社区",
|
||||
note: "门户 /social · 可拆独立域",
|
||||
},
|
||||
socialBlog: {
|
||||
enabled: true,
|
||||
title: "Nomad Blog",
|
||||
tabLabel: "Blog",
|
||||
note: "/social/blog · EN long-form · AdSense",
|
||||
},
|
||||
destinations: { enabled: true, title: "目的地" },
|
||||
meetups: { enabled: true, title: "活动" },
|
||||
vip: { enabled: false, title: "会员中心", note: "deep link only" },
|
||||
@ -400,6 +426,11 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
|
||||
joinGroupDouyin: false,
|
||||
joinGroupAction: "popup",
|
||||
offlineBadge: false,
|
||||
adsenseEnabled: false,
|
||||
adsenseClientId: "",
|
||||
adsensePublisherId: "",
|
||||
adsenseSlotBlogMid: "",
|
||||
adsenseSlotBlogEnd: "",
|
||||
},
|
||||
audience: {
|
||||
defaultLane: "intl",
|
||||
@ -428,6 +459,7 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
|
||||
vipProductId: "tiktok",
|
||||
vipCta: "立即加入 · ¥88",
|
||||
wechatOaName: "异度世界",
|
||||
xHandle: "noamdcna",
|
||||
joinGroupDouyinHint: "打开抖音搜群「数字游民」或扫码进群",
|
||||
joinGroupDouyinQr: "",
|
||||
socialEyebrow: "自由生活,同频相遇",
|
||||
@ -664,6 +696,23 @@ export function mergeRemoteConfig(
|
||||
joinGroupDouyin: asBool(pf.joinGroupDouyin, base.flags.joinGroupDouyin),
|
||||
joinGroupAction: joinAction,
|
||||
offlineBadge: asBool(pf.offlineBadge, base.flags.offlineBadge),
|
||||
adsenseEnabled: asBool(pf.adsenseEnabled, base.flags.adsenseEnabled ?? false),
|
||||
adsenseClientId:
|
||||
typeof pf.adsenseClientId === "string"
|
||||
? pf.adsenseClientId
|
||||
: base.flags.adsenseClientId || "",
|
||||
adsensePublisherId:
|
||||
typeof pf.adsensePublisherId === "string"
|
||||
? pf.adsensePublisherId
|
||||
: base.flags.adsensePublisherId || "",
|
||||
adsenseSlotBlogMid:
|
||||
typeof pf.adsenseSlotBlogMid === "string"
|
||||
? pf.adsenseSlotBlogMid
|
||||
: base.flags.adsenseSlotBlogMid || "",
|
||||
adsenseSlotBlogEnd:
|
||||
typeof pf.adsenseSlotBlogEnd === "string"
|
||||
? pf.adsenseSlotBlogEnd
|
||||
: base.flags.adsenseSlotBlogEnd || "",
|
||||
},
|
||||
audience: mergeAudienceConfig(base.audience, partial.audience),
|
||||
copy: { ...base.copy, ...(partial.copy || {}) },
|
||||
|
||||
@ -11,7 +11,7 @@ export type { SiteConfig, AffiliateRule } from './site-types';
|
||||
const defaults: SiteConfig = {
|
||||
brand: {
|
||||
name: 'Ebook',
|
||||
xHandle: '',
|
||||
xHandle: 'noamdcna',
|
||||
contactEmail: '',
|
||||
},
|
||||
share: {
|
||||
|
||||
@ -10,7 +10,7 @@ export type { SiteConfig, AffiliateRule } from './site-types';
|
||||
const defaults: SiteConfig = {
|
||||
brand: {
|
||||
name: 'Ebook',
|
||||
xHandle: '',
|
||||
xHandle: 'noamdcna',
|
||||
contactEmail: '',
|
||||
},
|
||||
share: {
|
||||
|
||||
@ -1,22 +1,68 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Bell } from "lucide-react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useId,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
import { notifyApi } from "../lib/api";
|
||||
import { categoryLabel } from "../lib/categories";
|
||||
import type { NotifyMessage } from "../lib/types";
|
||||
import "./notifications.css";
|
||||
|
||||
const SUB = "guest";
|
||||
const POLL_MS = 45_000;
|
||||
const PREVIEW_LIMIT = 8;
|
||||
|
||||
function resolveHref(m: NotifyMessage) {
|
||||
const raw = m.href || m.cta_url || "";
|
||||
if (!raw) return socialPath("/notifications");
|
||||
if (raw.startsWith("http") || raw.startsWith("/social")) return raw;
|
||||
if (raw.startsWith("/")) return socialPath(raw.replace(/^\/social/, "") || "/");
|
||||
return socialPath(`/${raw}`);
|
||||
}
|
||||
|
||||
function formatWhen(iso: string, zh: boolean) {
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return iso;
|
||||
const diff = Date.now() - d.getTime();
|
||||
if (diff < 60_000) return zh ? "刚刚" : "Just now";
|
||||
if (diff < 3_600_000) {
|
||||
const m = Math.floor(diff / 60_000);
|
||||
return zh ? `${m} 分钟前` : `${m}m ago`;
|
||||
}
|
||||
if (diff < 86_400_000) {
|
||||
const h = Math.floor(diff / 3_600_000);
|
||||
return zh ? `${h} 小时前` : `${h}h ago`;
|
||||
}
|
||||
return d.toLocaleDateString(zh ? "zh-CN" : "en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
}
|
||||
|
||||
export default function NotifyBell({ onNavigate }: { onNavigate?: () => void }) {
|
||||
const { locale } = useSocialI18n();
|
||||
const zh = locale === "zh";
|
||||
const [unread, setUnread] = useState(0);
|
||||
const router = useRouter();
|
||||
const panelId = useId();
|
||||
const wrapRef = useRef<HTMLDivElement>(null);
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [unread, setUnread] = useState(0);
|
||||
const [messages, setMessages] = useState<NotifyMessage[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
|
||||
const refreshUnread = useCallback(async () => {
|
||||
try {
|
||||
const res = await notifyApi.unread(SUB);
|
||||
setUnread(res.unread || 0);
|
||||
@ -25,16 +71,92 @@ export default function NotifyBell({ onNavigate }: { onNavigate?: () => void })
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadPreview = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setErr(null);
|
||||
try {
|
||||
const res = await notifyApi.inbox(SUB);
|
||||
setMessages((res.messages || []).slice(0, PREVIEW_LIMIT));
|
||||
setUnread(res.unread || 0);
|
||||
} catch (e) {
|
||||
setErr(e instanceof Error ? e.message : String(e));
|
||||
setMessages([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
const t = window.setInterval(() => void refresh(), POLL_MS);
|
||||
const onFocus = () => void refresh();
|
||||
void refreshUnread();
|
||||
const t = window.setInterval(() => void refreshUnread(), POLL_MS);
|
||||
const onFocus = () => void refreshUnread();
|
||||
window.addEventListener("focus", onFocus);
|
||||
return () => {
|
||||
window.clearInterval(t);
|
||||
window.removeEventListener("focus", onFocus);
|
||||
};
|
||||
}, [refresh]);
|
||||
}, [refreshUnread]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
void loadPreview();
|
||||
}, [open, loadPreview]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
setOpen(false);
|
||||
buttonRef.current?.focus();
|
||||
}
|
||||
};
|
||||
const onPointer = (event: PointerEvent) => {
|
||||
if (!wrapRef.current?.contains(event.target as Node)) {
|
||||
setOpen(false);
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
window.addEventListener("pointerdown", onPointer);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey);
|
||||
window.removeEventListener("pointerdown", onPointer);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
function toggle() {
|
||||
setOpen((v) => !v);
|
||||
}
|
||||
|
||||
function closeAndNavigate() {
|
||||
setOpen(false);
|
||||
onNavigate?.();
|
||||
}
|
||||
|
||||
async function openItem(m: NotifyMessage) {
|
||||
if (!m.read) {
|
||||
try {
|
||||
await notifyApi.patchMessage(m.id, { read: true });
|
||||
setUnread((n) => Math.max(0, n - 1));
|
||||
setMessages((list) =>
|
||||
list.map((item) => (item.id === m.id ? { ...item, read: true } : item)),
|
||||
);
|
||||
} catch {
|
||||
/* still navigate */
|
||||
}
|
||||
}
|
||||
closeAndNavigate();
|
||||
router.push(resolveHref(m));
|
||||
}
|
||||
|
||||
async function markAll() {
|
||||
try {
|
||||
await notifyApi.markAllRead(SUB);
|
||||
setUnread(0);
|
||||
setMessages((list) => list.map((m) => ({ ...m, read: true })));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
const label =
|
||||
unread > 0
|
||||
@ -46,18 +168,98 @@ export default function NotifyBell({ onNavigate }: { onNavigate?: () => void })
|
||||
: "Notifications";
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={socialPath("/notifications")}
|
||||
className="nav-icon-btn nav-notify-bell"
|
||||
aria-label={label}
|
||||
onClick={onNavigate}
|
||||
>
|
||||
<Bell size={17} />
|
||||
{unread > 0 && (
|
||||
<em className="nav-notify-badge" aria-hidden>
|
||||
{unread > 99 ? "99+" : unread}
|
||||
</em>
|
||||
)}
|
||||
</Link>
|
||||
<div className={`nav-notify-wrap${open ? " is-open" : ""}`} ref={wrapRef}>
|
||||
<button
|
||||
ref={buttonRef}
|
||||
type="button"
|
||||
className="nav-icon-btn nav-notify-bell"
|
||||
aria-label={label}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
aria-controls={panelId}
|
||||
onClick={toggle}
|
||||
>
|
||||
<Bell size={17} />
|
||||
{unread > 0 && (
|
||||
<em className="nav-notify-badge" aria-hidden>
|
||||
{unread > 99 ? "99+" : unread}
|
||||
</em>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<div
|
||||
id={panelId}
|
||||
className="nav-notify-panel"
|
||||
role="dialog"
|
||||
aria-label={zh ? "通知预览" : "Notification preview"}
|
||||
>
|
||||
<header className="nav-notify-panel-head">
|
||||
<strong>{zh ? "通知" : "Notifications"}</strong>
|
||||
<button
|
||||
type="button"
|
||||
className="nav-notify-text-btn"
|
||||
disabled={unread === 0}
|
||||
onClick={() => void markAll()}
|
||||
>
|
||||
{zh ? "全部已读" : "Mark all read"}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="nav-notify-panel-body">
|
||||
{loading && !messages.length ? (
|
||||
<p className="nav-notify-empty">{zh ? "加载中…" : "Loading…"}</p>
|
||||
) : null}
|
||||
{err ? <p className="nav-notify-error">{err}</p> : null}
|
||||
{!loading && !err && !messages.length ? (
|
||||
<p className="nav-notify-empty">
|
||||
{zh ? "暂无通知" : "No notifications"}
|
||||
</p>
|
||||
) : null}
|
||||
<ul className="nav-notify-list">
|
||||
{messages.map((m) => (
|
||||
<li key={m.id}>
|
||||
<button
|
||||
type="button"
|
||||
className={`nav-notify-item${m.read ? "" : " is-unread"}`}
|
||||
onClick={() => void openItem(m)}
|
||||
>
|
||||
<span className="nav-notify-item-meta">
|
||||
<span className={`ntf-pill ${m.category}`}>
|
||||
{categoryLabel(m.category, zh)}
|
||||
</span>
|
||||
<time dateTime={m.created_at}>
|
||||
{formatWhen(m.created_at, zh)}
|
||||
</time>
|
||||
</span>
|
||||
<span className="nav-notify-item-title">{m.subject}</span>
|
||||
{m.body ? (
|
||||
<span className="nav-notify-item-body">{m.body}</span>
|
||||
) : null}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<footer className="nav-notify-panel-foot">
|
||||
<Link
|
||||
href={socialPath("/notifications")}
|
||||
className="nav-notify-view-all"
|
||||
onClick={closeAndNavigate}
|
||||
>
|
||||
{zh ? "查看全部" : "View all"}
|
||||
</Link>
|
||||
<Link
|
||||
href={socialPath("/notifications/settings")}
|
||||
className="nav-notify-text-btn"
|
||||
onClick={closeAndNavigate}
|
||||
>
|
||||
{zh ? "设置" : "Settings"}
|
||||
</Link>
|
||||
</footer>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -247,7 +247,12 @@
|
||||
transform: translateX(20px);
|
||||
}
|
||||
|
||||
/* bell */
|
||||
/* bell + preview popover */
|
||||
.nav-notify-wrap {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
.nav-notify-bell {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
@ -270,3 +275,183 @@
|
||||
text-align: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.nav-notify-panel {
|
||||
--nt-amber: #f59e0b;
|
||||
--nt-ink: #f4f4f5;
|
||||
--nt-muted: rgba(244, 244, 245, 0.68);
|
||||
--nt-line: rgba(255, 255, 255, 0.1);
|
||||
position: absolute;
|
||||
top: calc(100% + 10px);
|
||||
right: 0;
|
||||
z-index: 1300;
|
||||
width: min(22.5rem, calc(100vw - 1.5rem));
|
||||
max-height: min(28rem, calc(100dvh - 6.5rem));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: 16px;
|
||||
border: 1px solid var(--nt-line);
|
||||
background: color-mix(in srgb, #0c0c0f 92%, #1a1a22);
|
||||
backdrop-filter: blur(20px);
|
||||
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.45);
|
||||
overflow: hidden;
|
||||
font-family: "DM Sans", system-ui, sans-serif;
|
||||
color: var(--nt-ink);
|
||||
animation: nav-notify-in 0.16s ease-out;
|
||||
}
|
||||
@keyframes nav-notify-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.nav-notify-panel-head,
|
||||
.nav-notify-panel-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem 0.9rem;
|
||||
border-bottom: 1px solid var(--nt-line);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.nav-notify-panel-foot {
|
||||
border-bottom: 0;
|
||||
border-top: 1px solid var(--nt-line);
|
||||
}
|
||||
.nav-notify-panel-head strong {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 750;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
.nav-notify-text-btn {
|
||||
appearance: none;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--nt-muted);
|
||||
font: inherit;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
min-height: 36px;
|
||||
padding: 0 0.35rem;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
}
|
||||
.nav-notify-text-btn:hover:not(:disabled) {
|
||||
color: var(--nt-amber);
|
||||
}
|
||||
.nav-notify-text-btn:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.nav-notify-view-all {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 40px;
|
||||
padding: 0 0.85rem;
|
||||
border-radius: 999px;
|
||||
background: var(--nt-amber);
|
||||
color: #0c0c0f;
|
||||
font-size: 0.84rem;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
.nav-notify-view-all:hover {
|
||||
filter: brightness(1.05);
|
||||
}
|
||||
|
||||
.nav-notify-panel-body {
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.nav-notify-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0.25rem 0;
|
||||
}
|
||||
.nav-notify-item {
|
||||
display: grid;
|
||||
gap: 0.2rem;
|
||||
width: 100%;
|
||||
padding: 0.75rem 0.9rem;
|
||||
border: 0;
|
||||
border-bottom: 1px solid color-mix(in srgb, #fff 5%, transparent);
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
min-height: 44px;
|
||||
}
|
||||
.nav-notify-item:last-child {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.nav-notify-item:hover {
|
||||
background: color-mix(in srgb, #f59e0b 8%, transparent);
|
||||
}
|
||||
.nav-notify-item.is-unread {
|
||||
box-shadow: inset 3px 0 0 var(--nt-amber);
|
||||
background: color-mix(in srgb, #f59e0b 5%, transparent);
|
||||
}
|
||||
.nav-notify-item-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.35rem 0.5rem;
|
||||
font-size: 0.72rem;
|
||||
color: var(--nt-muted);
|
||||
}
|
||||
.nav-notify-item-title {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 650;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.nav-notify-item-body {
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.4;
|
||||
color: var(--nt-muted);
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
.nav-notify-empty,
|
||||
.nav-notify-error {
|
||||
margin: 0;
|
||||
padding: 1.25rem 0.9rem;
|
||||
font-size: 0.88rem;
|
||||
color: var(--nt-muted);
|
||||
text-align: center;
|
||||
}
|
||||
.nav-notify-error {
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
html.light .nav-notify-panel,
|
||||
html[data-theme="light"] .nav-notify-panel {
|
||||
--nt-ink: #18181b;
|
||||
--nt-muted: rgba(24, 24, 27, 0.62);
|
||||
--nt-line: rgba(24, 24, 27, 0.1);
|
||||
background: color-mix(in srgb, #fff 94%, #f4f4f5);
|
||||
box-shadow: 0 18px 40px rgba(15, 23, 42, 0.14);
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.nav-notify-panel {
|
||||
position: fixed;
|
||||
top: calc(var(--nav-height, 72px) + 8px);
|
||||
right: 0.75rem;
|
||||
left: 0.75rem;
|
||||
bottom: auto;
|
||||
width: auto;
|
||||
max-height: min(68dvh, calc(100dvh - 9rem - env(safe-area-inset-bottom, 0px)));
|
||||
border-radius: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
49
src/modules/social-content/blog/coworking-vs-cafe.md
Normal file
49
src/modules/social-content/blog/coworking-vs-cafe.md
Normal file
@ -0,0 +1,49 @@
|
||||
---
|
||||
title: "Coworking vs Café: Where Digital Nomads Actually Get Work Done"
|
||||
description: "Compare noise, power, community, and cost so you stop romanticizing laptops next to espresso machines."
|
||||
date: "2026-10-18"
|
||||
tags: [coworking, cafe, productivity, remote-work]
|
||||
locale: en
|
||||
author: Nomadro
|
||||
---
|
||||
|
||||
The laptop‑in‑café photo is marketing. Your calendar is reality. Choosing between coworking and cafés is less about vibe and more about power outlets, bathroom access, and whether you can take a call without whispering.
|
||||
|
||||
## When cafés win
|
||||
|
||||
Cafés win for short bursts: email, light editing, waiting between meetings. They are cheap social signals—you are around people without committing to a membership. Good cafés have steady Wi‑Fi, multiple plugs, and staff who do not hate remote workers.
|
||||
|
||||
They fail when you need long focus, private calls, or eight‑hour days. Buying three drinks to rent a table is neither kind nor sustainable.
|
||||
|
||||
## When coworking wins
|
||||
|
||||
Coworking wins for recurring deep work, phone booths, printers, and meeting locals who also ship. Day passes help you test a city. Monthly desks make sense if you stay three weeks or more.
|
||||
|
||||
Watch for “community theater”: endless events that steal evenings. Pick spaces with quiet zones and clear call etiquette.
|
||||
|
||||
## A simple decision matrix
|
||||
|
||||
Ask four questions each morning:
|
||||
|
||||
1. Do I have back‑to‑back calls?
|
||||
2. Do I need more than three hours of focus?
|
||||
3. Is my housing desk usable today?
|
||||
4. Do I want to meet someone new this week?
|
||||
|
||||
Calls and long focus → coworking or apartment. Light tasks and ambient energy → café. Meeting people → coworking event or a scheduled coffeechat, not hovering near the pastry case.
|
||||
|
||||
## Etiquette that keeps doors open
|
||||
|
||||
Use headphones. Cap café sessions. Tip fairly. Do not film strangers for content. In coworking, clean the booth after calls and book rooms instead of colonizing sofas.
|
||||
|
||||
## Hybrid pattern that works on the road
|
||||
|
||||
Many nomads use apartment mornings, coworking midweek, and one café afternoon for lighter tasks. That mix protects focus and still creates chance encounters.
|
||||
|
||||
If a city only offers loud cafés and expensive coworking, treat that as data for your next destination—not a personal failure. Tools like Nomadro’s city notes and map pins help you spot café clusters and meetup density before you book the flight.
|
||||
|
||||
## Extra field notes
|
||||
|
||||
Write down what surprised you in the first seventy-two hours: noise, heat, grocery access, SIM friction, and whether you can take a call without leaving the apartment. Those notes beat generic city rankings. Revisit them before you extend a lease or buy a nonrefundable coworking month.
|
||||
|
||||
If energy is low, shrink the plan: one deep-work block, one short walk, one message to a real person. Momentum returns faster from tiny completions than from ambitious itineraries you abandon by Wednesday.
|
||||
46
src/modules/social-content/blog/first-month-digital-nomad.md
Normal file
46
src/modules/social-content/blog/first-month-digital-nomad.md
Normal file
@ -0,0 +1,46 @@
|
||||
---
|
||||
title: "Your First Month as a Digital Nomad: A Practical Field Guide"
|
||||
description: "A grounded checklist for visas, housing, routines, and meeting people in a new city without burning out in week two."
|
||||
date: "2026-10-12"
|
||||
tags: [nomad, beginners, routine, housing]
|
||||
locale: en
|
||||
author: Nomadro
|
||||
---
|
||||
|
||||
Starting a nomadic life sounds romantic until the SIM card fails, the Airbnb host cancels, and you realize you have not spoken to anyone real in five days. This guide is for that first month—the stretch where systems matter more than aesthetics.
|
||||
|
||||
## Decide what “good enough” looks like
|
||||
|
||||
Before you leave, write three non‑negotiables: sleep quality, work hours overlap with clients, and a weekly social touchpoint. Everything else is negotiable. Nomads who skip this step often optimize for cheap flights and then wonder why their work and mood collapse.
|
||||
|
||||
A useful rule: if a city fails two of your three non‑negotiables for more than ten days, leave. Staying out of sunk‑cost guilt is a skill. Write the rule on a note in your phone so you do not negotiate with yourself at 1 a.m.
|
||||
|
||||
## Visas and money before aesthetics
|
||||
|
||||
Confirm entry rules, proof of funds, and outbound tickets if required. Keep digital and paper copies of passport pages. Set up a backup card and a low‑friction way to receive payments. Pretty cafés do not replace a working bank app.
|
||||
|
||||
If you invoice internationally, test one full payment cycle before you travel. Many first‑month disasters are delayed payouts, not delayed trains. Keep a small cash buffer for SIM cards, transit cards, and deposits that only accept local currency.
|
||||
|
||||
## Housing: optimize for sleep and desk, not Instagram
|
||||
|
||||
For month one, prefer a place with a real desk, reliable Wi‑Fi, and blackout curtains over a rooftop pool. Ask hosts for a speed test screenshot and a quiet‑hours note. Plan a backup café within a fifteen‑minute walk for days the router dies.
|
||||
|
||||
Month one is research. Month two is when you hunt longer stays and local leases. Photograph the meter and inventory on day one so deposit negotiations stay factual.
|
||||
|
||||
## Build a weekday rhythm that survives jet lag
|
||||
|
||||
Protect a fixed morning block for deep work before exploring. Put social time on the calendar like a meeting: Tuesday coworking, Thursday community dinner, Saturday walk. Open calendars reduce loneliness more than “I’ll see what happens.”
|
||||
|
||||
Hydration, daylight, and a short walk after lunch prevent the 3 p.m. crash that eats remote workers alive. If your clients sit in another hemisphere, shift the deep‑work block to match overlap instead of copying your home‑country schedule blindly.
|
||||
|
||||
## Meet people without performing
|
||||
|
||||
Introduce yourself with what you are building or learning, not a polished personal brand. Ask one specific question about the city. Follow up once. Nomadro’s map, chat rooms, and coffeechat booking exist so you can turn “maybe later” into a real hello.
|
||||
|
||||
Safety still matters: meet first in public places, tell a friend where you are, and keep financial details offline. Friendship grows from repeated low‑stakes contact, not from one intense night out.
|
||||
|
||||
## What to track after thirty days
|
||||
|
||||
Keep a short log: sleep score, billable hours, number of real conversations, money spent versus plan. Patterns beat vibes. If conversations are zero, change the city or change your outreach—not your self‑talk alone.
|
||||
|
||||
Also note what drained you: commute noise, humidity, bad desks, or too many shallow events. The next booking should reflect those notes. The first month is not about becoming a perfect nomad. It is about proving you can work, rest, and meet people in motion. Do that, and the next city gets easier.
|
||||
42
src/modules/social-content/blog/meet-people-new-city.md
Normal file
42
src/modules/social-content/blog/meet-people-new-city.md
Normal file
@ -0,0 +1,42 @@
|
||||
---
|
||||
title: "How to Meet People in a New City Without Feeling Weird"
|
||||
description: "Concrete scripts, weekly habits, and safety notes for digital nomads who want friends—not just followers."
|
||||
date: "2026-10-25"
|
||||
tags: [community, friendship, safety, meetups]
|
||||
locale: en
|
||||
author: Nomadro
|
||||
---
|
||||
|
||||
Loneliness on the road is common and fixable. The fix is not “be more extroverted.” It is designing small, repeatable contact points so social energy does not depend on mood.
|
||||
|
||||
## Replace hope with a weekly quota
|
||||
|
||||
Set a humble quota: three real conversations per week. A conversation means names exchanged and a next step, even if the next step is “see you at Thursday coworking.” Tracking a quota turns vague longing into a checklist.
|
||||
|
||||
## Scripts that do not sound like networking
|
||||
|
||||
Try: “I just arrived—what’s one place locals actually like that isn’t on the tourist list?” Or: “I’m working on X this month; curious what you’re building.” Offer a tiny reciprocity: a map pin, a SIM tip, a café recommendation.
|
||||
|
||||
Avoid interviewing people like a podcast host. Share one vulnerable but low‑stakes detail about your week.
|
||||
|
||||
## Choose containers, not crowds
|
||||
|
||||
Large parties are hard if you are jet‑lagged. Prefer containers: language exchange tables, hiking groups, coworking lunches, volunteer shifts, sports drop‑ins. Containers give you a role so you are not inventing small talk from zero.
|
||||
|
||||
On Nomadro you can browse people nearby, join group chat, or book a short coffeechat so the first meeting has a clear start and end.
|
||||
|
||||
## Safety without paranoia
|
||||
|
||||
Meet first in public places. Tell a friend where you are. Keep financial details offline. Trust pattern recognition: people who rush intimacy or push private transfers are a no.
|
||||
|
||||
## What to do when it feels awkward
|
||||
|
||||
Awkward is information, not failure. Shorten the hangout. Suggest a walk. Follow up once, then release. Consistency beats intensity—showing up weekly compounds faster than one heroic night out.
|
||||
|
||||
After two weeks, review: where did conversations happen, and which invitations you ignored. Adjust the calendar, not your personality. Cities reward people who keep gentle pressure on the social surface.
|
||||
|
||||
## Extra field notes
|
||||
|
||||
Write down what surprised you in the first seventy-two hours: noise, heat, grocery access, SIM friction, and whether you can take a call without leaving the apartment. Those notes beat generic city rankings. Revisit them before you extend a lease or buy a nonrefundable coworking month.
|
||||
|
||||
If energy is low, shrink the plan: one deep-work block, one short walk, one message to a real person. Momentum returns faster from tiny completions than from ambitious itineraries you abandon by Wednesday.
|
||||
40
src/modules/social-content/blog/nomad-privacy-basics.md
Normal file
40
src/modules/social-content/blog/nomad-privacy-basics.md
Normal file
@ -0,0 +1,40 @@
|
||||
---
|
||||
title: "Privacy Basics for Digital Nomads (and Why Sites Ask for Cookies)"
|
||||
description: "Practical privacy habits on public Wi‑Fi, plus a plain‑English note on ads, analytics, and consent for readers of nomadro.com."
|
||||
date: "2026-11-04"
|
||||
tags: [privacy, security, adsense, trust]
|
||||
locale: en
|
||||
author: Nomadro
|
||||
---
|
||||
|
||||
Traveling light with a laptop means your data travels too. This piece covers personal hygiene on the road and how publisher sites—including Nomadro—talk about ads and cookies without jargon theater.
|
||||
|
||||
## Personal device hygiene
|
||||
|
||||
Prefer reputable VPNs on untrusted networks. Keep OS and browser updates on. Use a password manager and unique passwords. Avoid banking on café Wi‑Fi without extra protection. Lock your screen in coworking spaces.
|
||||
|
||||
Do not photograph boarding passes or ID pages into public chats. Blur faces when you share café photos if companions did not consent.
|
||||
|
||||
## Accounts and location sharing
|
||||
|
||||
Review which apps always track location. Share live location with friends for safety meetings, then turn it off. Separate “content” accounts from financial email where practical.
|
||||
|
||||
## How ads and analytics relate to readers
|
||||
|
||||
Many independent sites fund writing with advertising networks such as Google AdSense. Those networks may use cookies or similar technologies to measure views and, where allowed, personalize ads. Analytics tools help publishers understand which guides are useful.
|
||||
|
||||
You can usually control cookies via browser settings and, where required by law, via consent banners. Blocking ads is your choice; publishers may ask supporters to tip or subscribe instead.
|
||||
|
||||
## What Nomadro commits to on policy pages
|
||||
|
||||
We publish Privacy and About pages so you can see who runs the site, how to contact us, and how advertising may appear after approval. Blog articles stay readable first—ads, when enabled, should not replace the article.
|
||||
|
||||
If something feels off—misleading labels, accidental personal data in a form—email or use the feedback channel. Trust is part of the product for a community built around meeting real people.
|
||||
|
||||
Stay curious, stay kind online, and treat public networks as public. Good privacy habits make slow travel safer; clear publisher policies make the web more honest for everyone reading along.
|
||||
|
||||
## Extra field notes
|
||||
|
||||
Write down what surprised you in the first seventy-two hours: noise, heat, grocery access, SIM friction, and whether you can take a call without leaving the apartment. Those notes beat generic city rankings. Revisit them before you extend a lease or buy a nonrefundable coworking month.
|
||||
|
||||
If energy is low, shrink the plan: one deep-work block, one short walk, one message to a real person. Momentum returns faster from tiny completions than from ambitious itineraries you abandon by Wednesday.
|
||||
42
src/modules/social-content/blog/remote-work-timezones.md
Normal file
42
src/modules/social-content/blog/remote-work-timezones.md
Normal file
@ -0,0 +1,42 @@
|
||||
---
|
||||
title: "Remote Work Across Time Zones: Protect Focus and Friendships"
|
||||
description: "Overlap windows, async rituals, and city choices that keep clients happy without deleting your evenings."
|
||||
date: "2026-11-01"
|
||||
tags: [remote-work, timezone, clients, productivity]
|
||||
locale: en
|
||||
author: Nomadro
|
||||
---
|
||||
|
||||
Timezone math is the quiet boss of nomad life. Ignore it and you will either miss standups or miss dinner with new friends. Design overlap on purpose.
|
||||
|
||||
## Map your non‑negotiable overlap
|
||||
|
||||
List the meetings you cannot move. Convert them to the destination’s local time before you book housing. If the only affordable neighborhood forces 5 a.m. calls every day, that city is expensive in sleep currency.
|
||||
|
||||
A two‑hour daily overlap with your core team is often enough if async writing is strong.
|
||||
|
||||
## Async that clients trust
|
||||
|
||||
Send end‑of‑day notes with decisions, blockers, and next actions. Record short loom‑style updates when tone matters. Agree on response SLAs so nobody expects midnight replies.
|
||||
|
||||
Clear async reduces the urge to live permanently in “always online” mode—which destroys the reason you traveled.
|
||||
|
||||
## Guard deep work like rent
|
||||
|
||||
Block a morning deep‑work window and treat it as a meeting with yourself. Put social plans after that block. Friends who only appear at 11 a.m. cafés will adapt if you propose evening walks instead.
|
||||
|
||||
## City selection with timezone as a filter
|
||||
|
||||
East Asia may suit US evening clients; Europe may suit US mornings. Southeast Asia is flexible but can punish East Coast US standups. Write the filter into your destination shortlist instead of discovering it after signing a monthly lease.
|
||||
|
||||
## Energy, not just clocks
|
||||
|
||||
Late dinners and early calls stack. Cap late nights before heavy meeting days. Use light exposure and consistent wake times so your body clock lands faster.
|
||||
|
||||
Nomadro’s community features help you schedule coffeechats inside your overlap free time—so meeting people does not silently delete billable hours. When work and friendship share a calendar, both survive the next flight.
|
||||
|
||||
## Extra field notes
|
||||
|
||||
Write down what surprised you in the first seventy-two hours: noise, heat, grocery access, SIM friction, and whether you can take a call without leaving the apartment. Those notes beat generic city rankings. Revisit them before you extend a lease or buy a nonrefundable coworking month.
|
||||
|
||||
If energy is low, shrink the plan: one deep-work block, one short walk, one message to a real person. Momentum returns faster from tiny completions than from ambitious itineraries you abandon by Wednesday.
|
||||
44
src/modules/social-content/blog/slow-travel-budget.md
Normal file
44
src/modules/social-content/blog/slow-travel-budget.md
Normal file
@ -0,0 +1,44 @@
|
||||
---
|
||||
title: "Slow Travel Budgets for Nomads Who Hate Spreadsheet Drama"
|
||||
description: "A lightweight money system for multi‑month stays: housing ratios, buffers, and when to leave a city early."
|
||||
date: "2026-11-03"
|
||||
tags: [budget, slow-travel, housing, money]
|
||||
locale: en
|
||||
author: Nomadro
|
||||
---
|
||||
|
||||
Slow travel only feels free when money is boring. The goal is a system light enough to update on your phone in ten minutes a week.
|
||||
|
||||
## The 50 / 30 / 20 road version
|
||||
|
||||
Think in three buckets tailored to mobility: housing + utilities (aim under half of monthly spend), living + transport, and buffer + fun. Buffer is not optional—visas, dental, laptop repair, and sudden flights happen.
|
||||
|
||||
If housing alone eats sixty percent for more than a month, the city is telling you something.
|
||||
|
||||
## Monthly stay math beats nightly rates
|
||||
|
||||
Nightly hotels look fine until laundry and kitchen access disappear. Monthly apartments or coliving often win after day twelve. Always ask what is included: cleaning, AC electricity, tourist tax, deposits.
|
||||
|
||||
Photograph the inventory list when you move in. Deposit fights are a tax on optimism.
|
||||
|
||||
## Track five numbers, not fifty categories
|
||||
|
||||
Weekly: housing paid, food, transport, work tools, “everything else.” If “everything else” spikes, investigate once—not with shame, with curiosity. Many spikes are social FOMO, not logistics.
|
||||
|
||||
## Leave criteria tied to money and mood
|
||||
|
||||
Pre‑commit: if buffer drops below X, or sleep is bad for ten nights, or you have had zero meaningful conversations for two weeks, you reassess. Leaving early is a budget tool, not failure.
|
||||
|
||||
## Income hygiene while moving
|
||||
|
||||
Separate tax set‑asides. Keep one month of runway in a liquid account. Test ATM access before you need cash urgently.
|
||||
|
||||
Use community intel—cafés with fair prices, coworking day passes, city threads—to avoid tourist markups. Nomadro’s places and map notes are useful when locals and nomads share real costs instead of glossy averages.
|
||||
|
||||
Slow travel is not cheap by default. It is calm when your money system is calm. Make the spreadsheet dull so the city can be interesting.
|
||||
|
||||
## Extra field notes
|
||||
|
||||
Write down what surprised you in the first seventy-two hours: noise, heat, grocery access, SIM friction, and whether you can take a call without leaving the apartment. Those notes beat generic city rankings. Revisit them before you extend a lease or buy a nonrefundable coworking month.
|
||||
|
||||
If energy is low, shrink the plan: one deep-work block, one short walk, one message to a real person. Momentum returns faster from tiny completions than from ambitious itineraries you abandon by Wednesday.
|
||||
@ -22,6 +22,7 @@
|
||||
- **全站动效**:`SocialExperience` / `experience.css` 提供星点连线、鼠标柔光、漂移光晕、卡片聚光和页面入场;`interaction.css` / `studio.css` 提供声波、会前雷达、名片透视与书封动效。动效可切为轻量,系统减少动态效果设置优先;离开页面或标签页隐藏时清理/暂停动画。
|
||||
- **视觉终态层**:`depth.css` + `vivid.css` 统一玻璃导航、快捷轨、约会进度、聊天跳转最新、咖啡馆主从、Meetup 雷达、触控 ≥44px;子页 `SocialQuickRail` 横向跳转。
|
||||
- **H5(≤900px)**:`app/h5.css` **最后加载**;Ways 竖列表(群组聊天优先)、底栏「聊天」在「认识」左侧、滑卡/composer/加入 sheet 避开 dock + safe-area。
|
||||
- **聊天性能**(不影响视觉):WS 连通后停 since 轮询;消息内存态 + 防抖写本地末 80 条;空 poll 不刷 read note。
|
||||
|
||||
## 子页面与交互边界
|
||||
|
||||
|
||||
603
src/modules/social/app/blog.css
Normal file
603
src/modules/social/app/blog.css
Normal file
@ -0,0 +1,603 @@
|
||||
/* /social/blog — editorial reading plane (AdSense: content first, clear hierarchy) */
|
||||
|
||||
.social-editorial {
|
||||
--nav-height: 72px;
|
||||
--sblog-index-max: 58rem;
|
||||
--sblog-article-max: 42rem;
|
||||
position: relative;
|
||||
min-height: 100dvh;
|
||||
}
|
||||
|
||||
.social-experience:has(.social-editorial) .social-fx-control {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.social-editorial::before {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
background:
|
||||
radial-gradient(ellipse 70% 45% at 50% -10%, rgba(78, 205, 196, 0.1), transparent 55%),
|
||||
radial-gradient(ellipse 40% 30% at 90% 20%, rgba(255, 107, 107, 0.06), transparent 50%);
|
||||
}
|
||||
|
||||
.social-editorial-frame {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
width: 100%;
|
||||
max-width: none;
|
||||
margin: 0;
|
||||
padding: calc(var(--nav-height) + 20px) clamp(1rem, 3vw, 2rem) 5.5rem;
|
||||
box-sizing: border-box;
|
||||
min-height: 100dvh;
|
||||
}
|
||||
|
||||
.social-editorial .social-main--editorial {
|
||||
width: 100%;
|
||||
max-width: none;
|
||||
margin: 0 auto;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.sblog-page {
|
||||
width: 100%;
|
||||
max-width: var(--sblog-article-max);
|
||||
margin: 0 auto;
|
||||
padding: 0 0 1.5rem;
|
||||
}
|
||||
|
||||
.sblog-page.sblog-index {
|
||||
max-width: var(--sblog-index-max);
|
||||
}
|
||||
|
||||
.sblog-hero {
|
||||
margin-bottom: 1.35rem;
|
||||
}
|
||||
|
||||
.sblog-eyebrow {
|
||||
margin: 0 0 0.55rem;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: color-mix(in srgb, var(--muted, #94a3b8) 92%, #fff);
|
||||
}
|
||||
|
||||
.sblog-eyebrow a {
|
||||
color: inherit;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
.sblog-hero h1 {
|
||||
margin: 0 0 0.7rem;
|
||||
font-size: clamp(1.85rem, 5vw, 2.45rem);
|
||||
line-height: 1.15;
|
||||
letter-spacing: -0.03em;
|
||||
font-weight: 720;
|
||||
}
|
||||
|
||||
.sblog-lead {
|
||||
margin: 0;
|
||||
font-size: 1.08rem;
|
||||
line-height: 1.55;
|
||||
color: var(--muted, #94a3b8);
|
||||
max-width: 36rem;
|
||||
}
|
||||
|
||||
.sblog-count {
|
||||
margin: 0.85rem 0 0;
|
||||
font-size: 0.82rem;
|
||||
color: var(--muted, #64748b);
|
||||
}
|
||||
|
||||
.sblog-meta {
|
||||
margin: 0.85rem 0 0;
|
||||
font-size: 0.88rem;
|
||||
color: var(--muted, #94a3b8);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem 0.45rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.sblog-inline-tag {
|
||||
display: inline-block;
|
||||
padding: 0.12rem 0.45rem;
|
||||
border-radius: 999px;
|
||||
font-size: 0.75rem;
|
||||
background: color-mix(in srgb, currentColor 9%, transparent);
|
||||
}
|
||||
|
||||
.sblog-tags {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
gap: 0.45rem;
|
||||
margin: 0 0 1.35rem;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 0.25rem;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.sblog-tags::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.sblog-tag {
|
||||
appearance: none;
|
||||
flex: 0 0 auto;
|
||||
border: 1px solid color-mix(in srgb, currentColor 16%, transparent);
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 0.78rem;
|
||||
line-height: 1.2;
|
||||
padding: 0.45rem 0.85rem;
|
||||
border-radius: 999px;
|
||||
min-height: 40px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sblog-tag.is-on {
|
||||
background: color-mix(in srgb, #2dd4bf 22%, transparent);
|
||||
border-color: color-mix(in srgb, #2dd4bf 45%, transparent);
|
||||
color: #ecfeff;
|
||||
}
|
||||
|
||||
.sblog-featured {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.45rem;
|
||||
margin: 0 0 1.75rem;
|
||||
padding: 1.25rem 0 1.45rem;
|
||||
border-bottom: 1px solid color-mix(in srgb, currentColor 14%, transparent);
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
transition: opacity 0.18s ease;
|
||||
}
|
||||
|
||||
.sblog-featured:hover {
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
.sblog-featured-kicker {
|
||||
font-size: 0.7rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: #2dd4bf;
|
||||
}
|
||||
|
||||
.sblog-featured time,
|
||||
.sblog-featured em {
|
||||
font-size: 0.82rem;
|
||||
font-style: normal;
|
||||
color: var(--muted, #94a3b8);
|
||||
}
|
||||
|
||||
.sblog-featured strong {
|
||||
font-size: clamp(1.25rem, 3.5vw, 1.55rem);
|
||||
line-height: 1.3;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.sblog-featured-desc {
|
||||
font-size: 1rem;
|
||||
line-height: 1.5;
|
||||
color: var(--muted, #94a3b8);
|
||||
}
|
||||
|
||||
.sblog-featured:hover strong {
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.sblog-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.sblog-card-link {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
height: 100%;
|
||||
padding: 1.05rem 0;
|
||||
border-bottom: 1px solid color-mix(in srgb, currentColor 10%, transparent);
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.sblog-card-link time,
|
||||
.sblog-card-link em {
|
||||
font-size: 0.8rem;
|
||||
font-style: normal;
|
||||
color: var(--muted, #94a3b8);
|
||||
}
|
||||
|
||||
.sblog-card-link strong {
|
||||
font-size: 1.08rem;
|
||||
line-height: 1.35;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.sblog-card-link span {
|
||||
font-size: 0.94rem;
|
||||
line-height: 1.45;
|
||||
color: var(--muted, #94a3b8);
|
||||
}
|
||||
|
||||
.sblog-card-link:hover strong {
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.sblog-article .sblog-hero {
|
||||
padding-bottom: 1.15rem;
|
||||
margin-bottom: 1.5rem;
|
||||
border-bottom: 1px solid color-mix(in srgb, currentColor 12%, transparent);
|
||||
}
|
||||
|
||||
.sblog-prose {
|
||||
font-size: 1.08rem;
|
||||
line-height: 1.75;
|
||||
}
|
||||
|
||||
.sblog-prose h2 {
|
||||
margin: 2rem 0 0.7rem;
|
||||
font-size: 1.38rem;
|
||||
line-height: 1.28;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.sblog-prose h3 {
|
||||
margin: 1.45rem 0 0.5rem;
|
||||
font-size: 1.12rem;
|
||||
}
|
||||
|
||||
.sblog-prose p,
|
||||
.sblog-prose ul,
|
||||
.sblog-prose ol {
|
||||
margin: 0 0 1.05rem;
|
||||
}
|
||||
|
||||
.sblog-prose li {
|
||||
margin: 0.28rem 0;
|
||||
}
|
||||
|
||||
.sblog-prose a {
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
color: #5eead4;
|
||||
}
|
||||
|
||||
.sblog-prose code {
|
||||
font-size: 0.9em;
|
||||
padding: 0.1em 0.35em;
|
||||
border-radius: 4px;
|
||||
background: color-mix(in srgb, currentColor 8%, transparent);
|
||||
}
|
||||
|
||||
.sblog-table-wrap {
|
||||
overflow-x: auto;
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
.sblog-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.92rem;
|
||||
}
|
||||
|
||||
.sblog-table th,
|
||||
.sblog-table td {
|
||||
border: 1px solid color-mix(in srgb, currentColor 14%, transparent);
|
||||
padding: 0.45rem 0.6rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.sblog-ad {
|
||||
margin: 1.85rem 0;
|
||||
padding: 0.85rem 0.25rem;
|
||||
border-top: 1px dashed color-mix(in srgb, currentColor 16%, transparent);
|
||||
border-bottom: 1px dashed color-mix(in srgb, currentColor 16%, transparent);
|
||||
min-height: 100px;
|
||||
background: color-mix(in srgb, #fff 3%, transparent);
|
||||
}
|
||||
|
||||
.sblog-ad-label {
|
||||
margin: 0 0 0.45rem;
|
||||
font-size: 0.68rem;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--muted, #94a3b8);
|
||||
}
|
||||
|
||||
.sblog-related {
|
||||
margin: 2.75rem 0 1rem;
|
||||
padding-top: 1.35rem;
|
||||
border-top: 1px solid color-mix(in srgb, currentColor 12%, transparent);
|
||||
}
|
||||
|
||||
.sblog-related h2 {
|
||||
margin: 0 0 0.75rem;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.sblog-related ul {
|
||||
margin: 0;
|
||||
padding-left: 1.1rem;
|
||||
}
|
||||
|
||||
.sblog-related li {
|
||||
margin: 0.4rem 0;
|
||||
}
|
||||
|
||||
.sblog-policy-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.85rem 1.15rem;
|
||||
margin: 2.25rem 0 1rem;
|
||||
padding-top: 1.15rem;
|
||||
border-top: 1px solid color-mix(in srgb, currentColor 10%, transparent);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.sblog-policy-row a {
|
||||
color: var(--muted, #94a3b8);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
.sblog-empty {
|
||||
color: var(--muted, #94a3b8);
|
||||
}
|
||||
|
||||
.social-editorial .social-workspace-footer {
|
||||
max-width: none;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
padding: 0 0 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.social-editorial {
|
||||
--nav-height: 64px;
|
||||
}
|
||||
|
||||
.social-editorial-frame {
|
||||
padding: calc(var(--nav-height) + 12px) 1rem calc(5.5rem + env(safe-area-inset-bottom, 0px));
|
||||
}
|
||||
|
||||
.sblog-hero h1 {
|
||||
font-size: clamp(1.65rem, 7vw, 2.1rem);
|
||||
}
|
||||
|
||||
.sblog-lead {
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 901px) {
|
||||
.social-editorial .social-mobile-dock {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.social-editorial-frame {
|
||||
padding-top: calc(var(--nav-height) + 28px);
|
||||
padding-bottom: 4rem;
|
||||
}
|
||||
|
||||
.sblog-featured {
|
||||
padding: 1.5rem 1.35rem 1.65rem;
|
||||
margin-inline: -1.35rem;
|
||||
border: 1px solid color-mix(in srgb, currentColor 12%, transparent);
|
||||
border-radius: 18px;
|
||||
background: color-mix(in srgb, #fff 3.5%, transparent);
|
||||
}
|
||||
|
||||
.sblog-featured strong {
|
||||
font-size: clamp(1.4rem, 2.2vw, 1.75rem);
|
||||
}
|
||||
|
||||
.sblog-featured:hover strong {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.sblog-featured:hover {
|
||||
border-color: color-mix(in srgb, #4ecdc4 28%, transparent);
|
||||
}
|
||||
|
||||
.sblog-list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
column-gap: 2rem;
|
||||
row-gap: 0;
|
||||
}
|
||||
|
||||
.sblog-list > li {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.sblog-card-link {
|
||||
padding: 1.15rem 0 1.25rem;
|
||||
}
|
||||
|
||||
.sblog-tag {
|
||||
min-height: 40px;
|
||||
}
|
||||
|
||||
.sblog-related-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.75rem 1.5rem;
|
||||
}
|
||||
|
||||
.sblog-hero--index {
|
||||
margin-bottom: 1.75rem;
|
||||
}
|
||||
|
||||
.sblog-toolbar {
|
||||
max-width: 28rem;
|
||||
}
|
||||
}
|
||||
|
||||
.sblog-progress {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 3px;
|
||||
z-index: 1200;
|
||||
pointer-events: none;
|
||||
background: transparent;
|
||||
}
|
||||
.sblog-progress > span {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #ff6b6b, #4ecdc4);
|
||||
transition: width 0.12s linear;
|
||||
}
|
||||
.sblog-toolbar { margin: 0 0 0.85rem; }
|
||||
.sblog-search input {
|
||||
width: 100%;
|
||||
min-height: 44px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid color-mix(in srgb, currentColor 14%, transparent);
|
||||
background: color-mix(in srgb, #fff 4%, transparent);
|
||||
color: inherit;
|
||||
padding: 0.7rem 0.95rem;
|
||||
font: inherit;
|
||||
}
|
||||
.sblog-search input:focus {
|
||||
outline: 2px solid color-mix(in srgb, #4ecdc4 45%, transparent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.sblog-dot {
|
||||
display: inline-block;
|
||||
width: 3px;
|
||||
height: 3px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
opacity: 0.45;
|
||||
margin: 0 0.35rem;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.sblog-hero-glow {
|
||||
position: absolute;
|
||||
inset: -20% -10% auto;
|
||||
height: 180px;
|
||||
background: radial-gradient(ellipse at top, rgba(78, 205, 196, 0.14), transparent 70%);
|
||||
pointer-events: none;
|
||||
z-index: -1;
|
||||
}
|
||||
.sblog-hero--index, .sblog-hero--article { position: relative; }
|
||||
.sblog-featured-top, .sblog-card-top, .sblog-featured-foot, .sblog-card-foot, .sblog-meta-row, .sblog-actions, .sblog-cta-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.45rem 0.75rem;
|
||||
}
|
||||
.sblog-featured-foot, .sblog-card-foot, .sblog-meta-row { justify-content: space-between; }
|
||||
.sblog-go {
|
||||
font-size: 0.82rem;
|
||||
font-weight: 650;
|
||||
color: #4ecdc4;
|
||||
}
|
||||
.sblog-pill {
|
||||
font-size: 0.72rem;
|
||||
padding: 0.15rem 0.5rem;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, #4ecdc4 16%, transparent);
|
||||
color: #99f6e4;
|
||||
}
|
||||
.sblog-empty-box {
|
||||
padding: 1.5rem 0;
|
||||
color: var(--muted, #94a3b8);
|
||||
}
|
||||
.sblog-text-btn, .sblog-ghost-btn {
|
||||
appearance: none;
|
||||
border: 1px solid color-mix(in srgb, currentColor 16%, transparent);
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
min-height: 36px;
|
||||
padding: 0.35rem 0.75rem;
|
||||
border-radius: 999px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.sblog-toc {
|
||||
margin: 0 0 1.5rem;
|
||||
padding: 0.9rem 1rem;
|
||||
border-radius: 14px;
|
||||
border: 1px solid color-mix(in srgb, currentColor 12%, transparent);
|
||||
background: color-mix(in srgb, #fff 3%, transparent);
|
||||
}
|
||||
.sblog-toc p {
|
||||
margin: 0 0 0.45rem;
|
||||
font-size: 0.75rem;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--muted, #94a3b8);
|
||||
}
|
||||
.sblog-toc ol {
|
||||
margin: 0;
|
||||
padding-left: 1.1rem;
|
||||
}
|
||||
.sblog-toc li { margin: 0.3rem 0; }
|
||||
.sblog-cta {
|
||||
margin: 2.5rem 0 1rem;
|
||||
padding: 1.25rem 0 0;
|
||||
border-top: 1px solid color-mix(in srgb, currentColor 12%, transparent);
|
||||
}
|
||||
.sblog-cta h2 { margin: 0 0 0.35rem; font-size: 1.15rem; }
|
||||
.sblog-cta p { margin: 0 0 0.9rem; color: var(--muted, #94a3b8); }
|
||||
.sblog-cta-primary, .sblog-cta-secondary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 44px;
|
||||
padding: 0 1rem;
|
||||
border-radius: 999px;
|
||||
text-decoration: none;
|
||||
font-weight: 650;
|
||||
}
|
||||
.sblog-cta-primary {
|
||||
background: #ff7b75;
|
||||
color: #0a0e17;
|
||||
}
|
||||
.sblog-cta-secondary {
|
||||
border: 1px solid color-mix(in srgb, currentColor 18%, transparent);
|
||||
color: inherit;
|
||||
}
|
||||
.sblog-related-grid {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.sblog-related-grid a {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
padding: 0.85rem 0;
|
||||
border-bottom: 1px solid color-mix(in srgb, currentColor 10%, transparent);
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
}
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0,0,0,0);
|
||||
border: 0;
|
||||
}
|
||||
@ -374,11 +374,14 @@
|
||||
gap: 14px;
|
||||
}
|
||||
.social-join-avatar-btn {
|
||||
position: relative;
|
||||
flex: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 72px;
|
||||
height: 72px;
|
||||
min-width: 72px;
|
||||
min-height: 72px;
|
||||
padding: 0;
|
||||
border-radius: 22px;
|
||||
border: 1px dashed rgba(255, 255, 255, 0.22);
|
||||
@ -392,10 +395,33 @@
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.social-join-avatar-btn:disabled {
|
||||
opacity: 0.6;
|
||||
.social-join-avatar-btn:disabled,
|
||||
.social-join-avatar-btn.is-busy {
|
||||
opacity: 0.85;
|
||||
cursor: wait;
|
||||
}
|
||||
.social-join-avatar-btn.is-error {
|
||||
border-color: rgba(251, 113, 133, 0.85);
|
||||
border-style: solid;
|
||||
box-shadow: 0 0 0 3px rgba(251, 113, 133, 0.18);
|
||||
}
|
||||
.social-join-avatar-spin {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
margin: auto;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid rgba(255, 255, 255, 0.25);
|
||||
border-top-color: #f59e0b;
|
||||
animation: social-join-spin 0.7s linear infinite;
|
||||
background: rgba(8, 12, 18, 0.35);
|
||||
}
|
||||
@keyframes social-join-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
.social-join-avatar-row strong {
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
@ -408,8 +434,44 @@
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.social-join-avatar-err {
|
||||
margin: 6px 0 0 !important;
|
||||
color: #fb7185 !important;
|
||||
font-size: 0.82rem !important;
|
||||
font-weight: 650;
|
||||
line-height: 1.35 !important;
|
||||
}
|
||||
.social-join-avatar-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 10px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.social-join-avatar-action {
|
||||
appearance: none;
|
||||
min-height: 36px;
|
||||
padding: 0 0.75rem;
|
||||
border-radius: 999px;
|
||||
border: 1px solid color-mix(in srgb, #f59e0b 45%, transparent);
|
||||
background: color-mix(in srgb, #f59e0b 14%, transparent);
|
||||
color: #fbbf24;
|
||||
font: inherit;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 650;
|
||||
cursor: pointer;
|
||||
}
|
||||
.social-join-avatar-action.is-ghost {
|
||||
border-color: rgba(255, 255, 255, 0.16);
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.72);
|
||||
}
|
||||
.social-join-avatar-action:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: wait;
|
||||
}
|
||||
.social-join-avatar-clear {
|
||||
margin-top: 6px;
|
||||
margin-top: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
@ -418,6 +480,185 @@
|
||||
font-size: 0.8rem;
|
||||
font-weight: 650;
|
||||
cursor: pointer;
|
||||
min-height: 36px;
|
||||
}
|
||||
|
||||
/* Live selfie challenge modal */
|
||||
/* Portaled to document.body — escape join-desk transform/overflow clipping */
|
||||
.social-selfie-root {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 10050;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 16px;
|
||||
isolation: isolate;
|
||||
}
|
||||
.social-selfie-backdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border: 0;
|
||||
background: rgba(0, 0, 0, 0.72);
|
||||
cursor: pointer;
|
||||
}
|
||||
.social-selfie-card {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
width: min(420px, 100%);
|
||||
max-height: min(92vh, 720px);
|
||||
overflow: auto;
|
||||
border-radius: 20px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
background: #0c0c0f;
|
||||
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.55);
|
||||
padding: 14px 14px 16px;
|
||||
}
|
||||
.social-selfie-loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
margin: 0;
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
font-size: 0.88rem;
|
||||
font-weight: 650;
|
||||
pointer-events: none;
|
||||
}
|
||||
.social-join-avatar-row[data-capture-ready="false"] .social-join-avatar-actions {
|
||||
opacity: 0.55;
|
||||
}
|
||||
.social-join-avatar-row[data-device="mobile"] .social-join-avatar-btn {
|
||||
width: 72px;
|
||||
height: 72px;
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.social-selfie-root {
|
||||
padding: 0;
|
||||
place-items: end stretch;
|
||||
}
|
||||
.social-selfie-card {
|
||||
width: 100%;
|
||||
max-height: 92vh;
|
||||
border-radius: 20px 20px 0 0;
|
||||
padding-bottom: max(16px, env(safe-area-inset-bottom));
|
||||
}
|
||||
}
|
||||
.social-selfie-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.social-selfie-head strong {
|
||||
font-size: 0.98rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
.social-selfie-close {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 0;
|
||||
border-radius: 12px;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.social-selfie-stage {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 16px;
|
||||
aspect-ratio: 1;
|
||||
background: #111;
|
||||
}
|
||||
.social-selfie-video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
transform: scaleX(-1);
|
||||
}
|
||||
.social-selfie-oval {
|
||||
position: absolute;
|
||||
inset: 12% 16%;
|
||||
border: 2px dashed rgba(245, 158, 11, 0.7);
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 999px rgba(0, 0, 0, 0.35);
|
||||
pointer-events: none;
|
||||
}
|
||||
.social-selfie-count {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: 4rem;
|
||||
font-weight: 800;
|
||||
color: #fff;
|
||||
text-shadow: 0 8px 24px rgba(0, 0, 0, 0.6);
|
||||
pointer-events: none;
|
||||
}
|
||||
.social-selfie-tip {
|
||||
margin: 12px 0 6px;
|
||||
color: rgba(255, 255, 255, 0.72);
|
||||
font-size: 0.88rem;
|
||||
text-align: center;
|
||||
}
|
||||
.social-selfie-steps {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
margin: 0 0 10px;
|
||||
font-size: 0.78rem;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
.social-selfie-steps .is-on {
|
||||
color: #fbbf24;
|
||||
font-weight: 700;
|
||||
}
|
||||
.social-selfie-steps .is-done {
|
||||
color: #34d399;
|
||||
}
|
||||
.social-selfie-err {
|
||||
margin: 0 0 10px;
|
||||
color: #fb7185;
|
||||
font-size: 0.84rem;
|
||||
font-weight: 650;
|
||||
text-align: center;
|
||||
}
|
||||
.social-selfie-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
justify-content: center;
|
||||
}
|
||||
.social-selfie-cta,
|
||||
.social-selfie-cancel {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
min-height: 44px;
|
||||
padding: 0 1rem;
|
||||
border-radius: 999px;
|
||||
font: inherit;
|
||||
font-size: 0.88rem;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
.social-selfie-cta {
|
||||
border: 0;
|
||||
background: #f59e0b;
|
||||
color: #0c0c0f;
|
||||
}
|
||||
.social-selfie-cta:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: wait;
|
||||
}
|
||||
.social-selfie-cancel {
|
||||
border: 1px solid rgba(255, 255, 255, 0.14);
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.75);
|
||||
}
|
||||
.social-join-live-meter {
|
||||
display: grid;
|
||||
|
||||
@ -1244,6 +1244,43 @@
|
||||
margin-top: 30px;
|
||||
font-size: 9px;
|
||||
}
|
||||
.social-home-footer-bottom {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px 20px;
|
||||
}
|
||||
.social-home-follow-row {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px 14px;
|
||||
}
|
||||
.social-home-follow-row a {
|
||||
font-size: 12px;
|
||||
font-weight: 650;
|
||||
color: var(--text-muted, #94a3b8);
|
||||
text-decoration: none;
|
||||
min-height: 36px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
.social-home-follow-row a:hover {
|
||||
color: var(--text-primary, #f4f4f5);
|
||||
}
|
||||
.social-home-follow-x {
|
||||
padding: 0 12px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid color-mix(in srgb, #f59e0b 45%, transparent);
|
||||
color: #f59e0b !important;
|
||||
background: color-mix(in srgb, #f59e0b 10%, transparent);
|
||||
gap: 6px;
|
||||
}
|
||||
.social-home-follow-x:hover {
|
||||
background: color-mix(in srgb, #f59e0b 18%, transparent);
|
||||
color: #fbbf24 !important;
|
||||
}
|
||||
|
||||
.connection-video-dialog {
|
||||
position: fixed;
|
||||
|
||||
166
src/modules/social/app/shell-tokens.css
Normal file
166
src/modules/social/app/shell-tokens.css
Normal file
@ -0,0 +1,166 @@
|
||||
/* Slim shell tokens + nav base — replaces @community/app/globals.css on /social */
|
||||
:root {
|
||||
--bg-primary: #0a0e17;
|
||||
--bg-secondary: #111827;
|
||||
--bg-card: rgba(17, 24, 39, 0.7);
|
||||
--bg-glass: rgba(255, 255, 255, 0.05);
|
||||
--text-primary: #f1f5f9;
|
||||
--text-secondary: #94a3b8;
|
||||
--text-muted: #64748b;
|
||||
--accent-1: #ff6b6b;
|
||||
--accent-2: #ffe66d;
|
||||
--accent-3: #4ecdc4;
|
||||
--accent-4: #4ecdc4;
|
||||
--gradient-main: linear-gradient(135deg, #ff6b6b, #ffe66d, #4ecdc4);
|
||||
--gradient-text: linear-gradient(135deg, #ff6b6b 0%, #ffe66d 50%, #4ecdc4 100%);
|
||||
--shadow-glow: 0 0 40px rgba(78, 205, 196, 0.15);
|
||||
--shadow-card: 0 8px 32px rgba(0, 0, 0, 0.3);
|
||||
--border-glass: 1px solid rgba(255, 255, 255, 0.08);
|
||||
--radius-sm: 8px;
|
||||
--radius-md: 16px;
|
||||
--radius-lg: 24px;
|
||||
--radius-xl: 32px;
|
||||
--font-display: var(--font-outfit), "PingFang SC", "Hiragino Sans GB",
|
||||
"Microsoft YaHei", "Noto Sans SC", sans-serif;
|
||||
--font-body: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei",
|
||||
"Noto Sans SC", var(--font-outfit), sans-serif;
|
||||
--nav-height: 72px;
|
||||
--transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
[data-theme="light"] {
|
||||
--bg-primary: #f8fafc;
|
||||
--bg-secondary: #ffffff;
|
||||
--bg-card: rgba(255, 255, 255, 0.85);
|
||||
--bg-glass: rgba(0, 0, 0, 0.03);
|
||||
--text-primary: #0f172a;
|
||||
--text-secondary: #475569;
|
||||
--text-muted: #94a3b8;
|
||||
--shadow-glow: 0 0 40px rgba(78, 205, 196, 0.1);
|
||||
--shadow-card: 0 8px 32px rgba(0, 0, 0, 0.08);
|
||||
--border-glass: 1px solid rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.community-root.social-skin {
|
||||
min-height: 100dvh;
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
font-family: var(--font-body);
|
||||
}
|
||||
|
||||
.navbar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: var(--nav-height);
|
||||
z-index: 1000;
|
||||
transition: all var(--transition);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.navbar.scrolled {
|
||||
background: rgba(10, 14, 23, 0.85);
|
||||
backdrop-filter: blur(20px);
|
||||
border-bottom: var(--border-glass);
|
||||
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
[data-theme="light"] .navbar.scrolled {
|
||||
background: rgba(248, 250, 252, 0.9);
|
||||
}
|
||||
|
||||
.nav-container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 0 24px;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.nav-container > .logo {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.nav-container > .nav-links {
|
||||
flex: 1;
|
||||
justify-content: center;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.logo {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-family: var(--font-display);
|
||||
font-weight: 800;
|
||||
font-size: 1.35rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.logo span {
|
||||
background: linear-gradient(135deg, #ff6b6b, #ffe66d, #4ecdc4);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.logo-icon {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.nav-links a {
|
||||
padding: 8px 16px;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
transition: all var(--transition);
|
||||
}
|
||||
|
||||
.nav-links a:hover {
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-glass);
|
||||
}
|
||||
|
||||
.mobile-menu-btn {
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.mobile-menu-btn span {
|
||||
display: block;
|
||||
width: 24px;
|
||||
height: 2px;
|
||||
background: var(--text-primary);
|
||||
border-radius: 2px;
|
||||
transition: all 0.3s ease;
|
||||
transform-origin: center;
|
||||
}
|
||||
|
||||
.mobile-menu-btn.open span:nth-child(1) {
|
||||
transform: translateY(7px) rotate(45deg);
|
||||
}
|
||||
|
||||
.mobile-menu-btn.open span:nth-child(2) {
|
||||
opacity: 0;
|
||||
transform: scaleX(0);
|
||||
}
|
||||
|
||||
.mobile-menu-btn.open span:nth-child(3) {
|
||||
transform: translateY(-7px) rotate(-45deg);
|
||||
}
|
||||
@ -75,6 +75,22 @@
|
||||
margin-bottom: 24px;
|
||||
box-shadow: 0 0 35px #4ecdc411;
|
||||
}
|
||||
.social-profile-face {
|
||||
width: 88px;
|
||||
height: 88px;
|
||||
margin-bottom: 24px;
|
||||
border-radius: 22px;
|
||||
overflow: hidden;
|
||||
border: 1px solid #4ecdc443;
|
||||
box-shadow: 0 0 35px #4ecdc411;
|
||||
background: #0c0c0f;
|
||||
}
|
||||
.social-profile-face img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.social-profile-passport .social-page-kicker {
|
||||
font-size: 8px;
|
||||
letter-spacing: 0.18em;
|
||||
|
||||
292
src/modules/social/components/AvatarSelfieModal.tsx
Normal file
292
src/modules/social/components/AvatarSelfieModal.tsx
Normal file
@ -0,0 +1,292 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Camera, X } from "lucide-react";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
|
||||
type Step = "front" | "turn" | "done";
|
||||
|
||||
export default function AvatarSelfieModal({
|
||||
open,
|
||||
onClose,
|
||||
onCaptured,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onCaptured: (front: Blob, turn: Blob) => void | Promise<void>;
|
||||
}) {
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const streamRef = useRef<MediaStream | null>(null);
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [step, setStep] = useState<Step>("front");
|
||||
const [frontBlob, setFrontBlob] = useState<Blob | null>(null);
|
||||
const [err, setErr] = useState("");
|
||||
const [countdown, setCountdown] = useState<number | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [previewReady, setPreviewReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
let cancelled = false;
|
||||
setStep("front");
|
||||
setFrontBlob(null);
|
||||
setErr("");
|
||||
setCountdown(null);
|
||||
setBusy(false);
|
||||
setPreviewReady(false);
|
||||
|
||||
const attach = async (stream: MediaStream) => {
|
||||
streamRef.current = stream;
|
||||
const video = videoRef.current;
|
||||
if (!video) return;
|
||||
video.srcObject = stream;
|
||||
video.muted = true;
|
||||
video.playsInline = true;
|
||||
const onReady = () => {
|
||||
if (!cancelled) setPreviewReady(true);
|
||||
};
|
||||
video.addEventListener("loadedmetadata", onReady, { once: true });
|
||||
video.addEventListener("playing", onReady, { once: true });
|
||||
try {
|
||||
await video.play();
|
||||
onReady();
|
||||
} catch {
|
||||
/* autoplay may need metadata first */
|
||||
}
|
||||
};
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
// Desktop USB cams often break with facingMode:"user" → black frames
|
||||
let stream: MediaStream;
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: false,
|
||||
video: { width: { ideal: 1280 }, height: { ideal: 720 } },
|
||||
});
|
||||
} catch {
|
||||
stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: false,
|
||||
video: true,
|
||||
});
|
||||
}
|
||||
if (cancelled) {
|
||||
stream.getTracks().forEach((t) => t.stop());
|
||||
return;
|
||||
}
|
||||
// Wait a tick so portal video node is mounted
|
||||
await new Promise((r) => requestAnimationFrame(() => r(undefined)));
|
||||
if (cancelled) {
|
||||
stream.getTracks().forEach((t) => t.stop());
|
||||
return;
|
||||
}
|
||||
await attach(stream);
|
||||
// Retry attach if ref wasn't ready
|
||||
if (!cancelled && videoRef.current && videoRef.current.srcObject !== stream) {
|
||||
await attach(stream);
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
setErr(socialTx("无法打开摄像头,请允许权限或改用相册"));
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
const video = videoRef.current;
|
||||
if (video) video.srcObject = null;
|
||||
streamRef.current?.getTracks().forEach((t) => t.stop());
|
||||
streamRef.current = null;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
async function snap(): Promise<Blob | null> {
|
||||
const video = videoRef.current;
|
||||
if (!video || video.readyState < 2) return null;
|
||||
const w = video.videoWidth || 640;
|
||||
const h = video.videoHeight || 640;
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return null;
|
||||
ctx.translate(w, 0);
|
||||
ctx.scale(-1, 1);
|
||||
ctx.drawImage(video, 0, 0, w, h);
|
||||
return await new Promise((resolve) => {
|
||||
canvas.toBlob((b) => resolve(b), "image/jpeg", 0.92);
|
||||
});
|
||||
}
|
||||
|
||||
function startCountdown(next: () => void) {
|
||||
if (busy || countdown !== null) return;
|
||||
setErr("");
|
||||
let n = 3;
|
||||
setCountdown(n);
|
||||
const timer = window.setInterval(() => {
|
||||
n -= 1;
|
||||
if (n <= 0) {
|
||||
window.clearInterval(timer);
|
||||
setCountdown(null);
|
||||
next();
|
||||
} else {
|
||||
setCountdown(n);
|
||||
}
|
||||
}, 700);
|
||||
}
|
||||
|
||||
async function captureFront() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const blob = await snap();
|
||||
if (!blob) {
|
||||
setErr(socialTx("拍照失败,请重试"));
|
||||
return;
|
||||
}
|
||||
setFrontBlob(blob);
|
||||
setStep("turn");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function captureTurn() {
|
||||
if (!frontBlob) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const blob = await snap();
|
||||
if (!blob) {
|
||||
setErr(socialTx("拍照失败,请重试"));
|
||||
return;
|
||||
}
|
||||
setStep("done");
|
||||
await onCaptured(frontBlob, blob);
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setStep("turn");
|
||||
setErr(
|
||||
e instanceof Error && e.message
|
||||
? socialTx(e.message) || e.message
|
||||
: socialTx("真人核验失败,请重试"),
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!open || !mounted) return null;
|
||||
|
||||
const tip =
|
||||
step === "front"
|
||||
? socialTx("正对镜头,脸放进圈内")
|
||||
: step === "turn"
|
||||
? socialTx("请稍微转头(左右任一方向)再拍")
|
||||
: socialTx("核验中…");
|
||||
|
||||
const node = (
|
||||
<div
|
||||
className="social-selfie-root"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={socialTx("现场自拍核验")}
|
||||
data-preview-ready={previewReady ? "true" : "false"}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="social-selfie-backdrop"
|
||||
aria-label={socialTx("关闭")}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<div className="social-selfie-card">
|
||||
<header className="social-selfie-head">
|
||||
<strong>{socialTx("现场自拍核验")}</strong>
|
||||
<button
|
||||
type="button"
|
||||
className="social-selfie-close"
|
||||
onClick={onClose}
|
||||
aria-label={socialTx("关闭")}
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</header>
|
||||
<div className="social-selfie-stage">
|
||||
<video
|
||||
ref={videoRef}
|
||||
className="social-selfie-video"
|
||||
playsInline
|
||||
muted
|
||||
autoPlay
|
||||
controls={false}
|
||||
/>
|
||||
<div className="social-selfie-guide" aria-hidden>
|
||||
<i className="social-selfie-oval" />
|
||||
</div>
|
||||
{!previewReady && !err ? (
|
||||
<p className="social-selfie-loading">{socialTx("正在打开摄像头…")}</p>
|
||||
) : null}
|
||||
{countdown !== null ? (
|
||||
<span className="social-selfie-count">{countdown}</span>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="social-selfie-tip">{tip}</p>
|
||||
<p className="social-selfie-steps">
|
||||
<span className={step === "front" ? "is-on" : "is-done"}>
|
||||
1. {socialTx("正脸")}
|
||||
</span>
|
||||
<span
|
||||
className={
|
||||
step === "turn" ? "is-on" : step === "done" ? "is-done" : ""
|
||||
}
|
||||
>
|
||||
2. {socialTx("转头")}
|
||||
</span>
|
||||
</p>
|
||||
{err ? (
|
||||
<p className="social-selfie-err" role="alert">
|
||||
{err}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="social-selfie-actions">
|
||||
{step === "front" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="social-selfie-cta"
|
||||
disabled={busy || countdown !== null || !previewReady}
|
||||
onClick={() => startCountdown(() => void captureFront())}
|
||||
>
|
||||
<Camera size={16} />
|
||||
{socialTx("拍正脸")}
|
||||
</button>
|
||||
) : null}
|
||||
{step === "turn" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="social-selfie-cta"
|
||||
disabled={busy || countdown !== null || !previewReady}
|
||||
onClick={() => startCountdown(() => void captureTurn())}
|
||||
>
|
||||
<Camera size={16} />
|
||||
{socialTx("拍转头")}
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="social-selfie-cancel"
|
||||
onClick={onClose}
|
||||
disabled={busy}
|
||||
>
|
||||
{socialTx("取消")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return createPortal(node, document.body);
|
||||
}
|
||||
@ -19,9 +19,11 @@ import {
|
||||
import { WechatOaModal } from "~/components/social-follow";
|
||||
import SiteShell from "./SiteShell";
|
||||
import JoinPayModal from "./JoinPayModal";
|
||||
import AvatarSelfieModal from "./AvatarSelfieModal";
|
||||
import { PageIntro } from "./SocialUI";
|
||||
import { useSocialConfig } from "./SocialExperience";
|
||||
import { socialApi } from "@social/lib/api";
|
||||
import { useCaptureCapability } from "@social/lib/useCaptureCapability";
|
||||
import {
|
||||
JOIN_EDUCATION_OPTIONS,
|
||||
JOIN_GENDER_OPTIONS,
|
||||
@ -304,15 +306,43 @@ function JoinStepMark({ active }: { active: 2 | 3 }) {
|
||||
|
||||
function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
const { locale } = useSocialI18n();
|
||||
const capture = useCaptureCapability();
|
||||
const nameRef = useRef<HTMLInputElement>(null);
|
||||
const avatarInputRef = useRef<HTMLInputElement>(null);
|
||||
const captureInputRef = useRef<HTMLInputElement>(null);
|
||||
// Empty seed for SSR — hydrate from localStorage after mount (avoids mismatch).
|
||||
const [draft, setDraft] = useState<JoinProfileDraft>(EMPTY_JOIN_PROFILE);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [avatarBusy, setAvatarBusy] = useState(false);
|
||||
const [avatarErr, setAvatarErr] = useState("");
|
||||
const [selfieOpen, setSelfieOpen] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
const lock = useRef(false);
|
||||
|
||||
const openPrimaryCapture = () => {
|
||||
if (capture.mode === "live-modal") {
|
||||
setSelfieOpen(true);
|
||||
return;
|
||||
}
|
||||
if (capture.mode === "native-capture") {
|
||||
captureInputRef.current?.click();
|
||||
return;
|
||||
}
|
||||
avatarInputRef.current?.click();
|
||||
};
|
||||
|
||||
const avatarHint = (() => {
|
||||
if (avatarBusy) return socialTx("检测人脸并上传中…");
|
||||
if (!capture.ready) return socialTx("检测设备中…");
|
||||
if (capture.mode === "live-modal") {
|
||||
return socialTx("电脑已检测到摄像头:建议现场预览自拍(正脸 + 微转头)");
|
||||
}
|
||||
if (capture.mode === "native-capture") {
|
||||
return socialTx("手机可调用前置摄像头拍照核验;也可从相册选");
|
||||
}
|
||||
return socialTx("当前无可用摄像头,请从相册上传清晰正脸");
|
||||
})();
|
||||
|
||||
useEffect(() => {
|
||||
const saved = loadJson<Partial<JoinProfileDraft>>(
|
||||
"join-profile",
|
||||
@ -350,32 +380,102 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
|
||||
const onAvatarPick = async (file: File | null) => {
|
||||
if (!file || avatarBusy) return;
|
||||
if (!file.type.startsWith("image/")) {
|
||||
setErr(socialTx("请选择图片文件"));
|
||||
const mime = (file.type || "").toLowerCase();
|
||||
const okMime =
|
||||
!mime ||
|
||||
mime.startsWith("image/") ||
|
||||
/\.(jpe?g|png|webp|gif)$/i.test(file.name);
|
||||
if (!okMime) {
|
||||
setAvatarErr(socialTx("请选择图片文件"));
|
||||
return;
|
||||
}
|
||||
if (file.size > 8 * 1024 * 1024) {
|
||||
setErr(socialTx("头像不能超过 8MB"));
|
||||
setAvatarErr(socialTx("头像不能超过 8MB"));
|
||||
return;
|
||||
}
|
||||
setAvatarBusy(true);
|
||||
setAvatarErr("");
|
||||
setErr("");
|
||||
// Instant local preview while uploading
|
||||
// Instant local preview while uploading / face-checking
|
||||
const localUrl = URL.createObjectURL(file);
|
||||
update("avatar", localUrl);
|
||||
setDraft((current) => ({ ...current, avatar: localUrl }));
|
||||
try {
|
||||
const uploaded = await socialApi.uploadAvatar(file, "avatar");
|
||||
if (!uploaded?.url) throw new Error("no url");
|
||||
update("avatar", uploaded.url);
|
||||
const url = (uploaded?.url || "").trim();
|
||||
if (!url) throw new Error(socialTx("头像上传失败"));
|
||||
setDraft((current) => {
|
||||
const next = { ...current, avatar: url };
|
||||
saveJson("join-profile", next);
|
||||
const roster = loadJson<SocialRosterProfile>("roster", {
|
||||
name: "",
|
||||
title: "",
|
||||
city: "",
|
||||
phone: "",
|
||||
linktree: "",
|
||||
skills: "",
|
||||
bio: "",
|
||||
avatar: "",
|
||||
});
|
||||
saveJson("roster", { ...roster, avatar: url });
|
||||
return next;
|
||||
});
|
||||
setAvatarErr("");
|
||||
requestAnimationFrame(() => URL.revokeObjectURL(localUrl));
|
||||
} catch (e) {
|
||||
update("avatar", "");
|
||||
setErr(
|
||||
e instanceof Error
|
||||
? e.message.slice(0, 120) || socialTx("头像上传失败")
|
||||
: socialTx("头像上传失败"),
|
||||
);
|
||||
} finally {
|
||||
setDraft((current) => ({ ...current, avatar: "" }));
|
||||
URL.revokeObjectURL(localUrl);
|
||||
const raw =
|
||||
e instanceof Error ? e.message.slice(0, 160).trim() : "";
|
||||
const msg =
|
||||
raw && !/^upload failed|^no url|^上传失败 HTTP/i.test(raw)
|
||||
? socialTx(raw)
|
||||
: socialTx("头像上传失败");
|
||||
setAvatarErr(msg || socialTx("头像上传失败"));
|
||||
} finally {
|
||||
setAvatarBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onSelfieChallenge = async (front: Blob, turn: Blob) => {
|
||||
setAvatarBusy(true);
|
||||
setAvatarErr("");
|
||||
setErr("");
|
||||
const preview = URL.createObjectURL(front);
|
||||
setDraft((current) => ({ ...current, avatar: preview }));
|
||||
try {
|
||||
const uploaded = await socialApi.uploadAvatarChallenge(front, turn);
|
||||
const url = (uploaded?.url || "").trim();
|
||||
if (!url) throw new Error(socialTx("头像上传失败"));
|
||||
// Persist immediately so later profile / discovery pages keep the face.
|
||||
setDraft((current) => {
|
||||
const next = { ...current, avatar: url };
|
||||
saveJson("join-profile", next);
|
||||
const roster = loadJson<SocialRosterProfile>("roster", {
|
||||
name: "",
|
||||
title: "",
|
||||
city: "",
|
||||
phone: "",
|
||||
linktree: "",
|
||||
skills: "",
|
||||
bio: "",
|
||||
avatar: "",
|
||||
});
|
||||
saveJson("roster", { ...roster, avatar: url });
|
||||
return next;
|
||||
});
|
||||
setAvatarErr("");
|
||||
// Revoke blob only after remote URL is committed (avoids blank <img>)
|
||||
requestAnimationFrame(() => URL.revokeObjectURL(preview));
|
||||
} catch (e) {
|
||||
setDraft((current) => ({ ...current, avatar: "" }));
|
||||
URL.revokeObjectURL(preview);
|
||||
const raw =
|
||||
e instanceof Error ? e.message.slice(0, 160).trim() : "";
|
||||
setAvatarErr(
|
||||
raw ? socialTx(raw) || raw : socialTx("真人核验失败,请重试"),
|
||||
);
|
||||
throw e instanceof Error ? e : new Error(socialTx("真人核验失败,请重试"));
|
||||
} finally {
|
||||
setAvatarBusy(false);
|
||||
}
|
||||
};
|
||||
@ -604,14 +704,35 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
void onAvatarPick(file);
|
||||
}}
|
||||
/>
|
||||
{/* Mobile native camera — capture=user opens front camera sheet */}
|
||||
<input
|
||||
ref={captureInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="user"
|
||||
className="social-join-file-input"
|
||||
tabIndex={-1}
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0] || null;
|
||||
e.target.value = "";
|
||||
void onAvatarPick(file);
|
||||
}}
|
||||
/>
|
||||
<fieldset disabled={busy} className="social-fieldset social-join-fields">
|
||||
<p className="social-join-section">{socialTx("基本信息")}</p>
|
||||
<div className="social-join-avatar-row social-join-span-2">
|
||||
<div
|
||||
className="social-join-avatar-row social-join-span-2"
|
||||
data-capture-mode={capture.mode}
|
||||
data-capture-ready={capture.ready ? "true" : "false"}
|
||||
data-device={capture.isMobile ? "mobile" : "pc"}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="social-join-avatar-btn"
|
||||
disabled={avatarBusy}
|
||||
onClick={() => avatarInputRef.current?.click()}
|
||||
className={`social-join-avatar-btn${avatarErr ? " is-error" : ""}${avatarBusy ? " is-busy" : ""}`}
|
||||
disabled={avatarBusy || !capture.ready}
|
||||
aria-busy={avatarBusy}
|
||||
aria-invalid={Boolean(avatarErr) || undefined}
|
||||
onClick={openPrimaryCapture}
|
||||
>
|
||||
{draft.avatar ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
@ -619,23 +740,64 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
) : (
|
||||
<Camera size={22} />
|
||||
)}
|
||||
{avatarBusy ? (
|
||||
<span className="social-join-avatar-spin" aria-hidden />
|
||||
) : null}
|
||||
</button>
|
||||
<div>
|
||||
<strong>{socialTx("头像")}</strong>
|
||||
<p>
|
||||
{avatarBusy
|
||||
? socialTx("上传中…")
|
||||
: socialTx("点选上传,存到 s3.nomadro.com")}
|
||||
</p>
|
||||
{draft.avatar && !draft.avatar.startsWith("blob:") ? (
|
||||
<p>{avatarHint}</p>
|
||||
{avatarErr ? (
|
||||
<p className="social-join-avatar-err" role="alert">
|
||||
{avatarErr}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="social-join-avatar-actions">
|
||||
{capture.mode === "live-modal" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="social-join-avatar-action"
|
||||
disabled={avatarBusy || !capture.ready}
|
||||
onClick={() => setSelfieOpen(true)}
|
||||
>
|
||||
{socialTx("电脑摄像头自拍")}
|
||||
</button>
|
||||
) : null}
|
||||
{capture.mode === "native-capture" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="social-join-avatar-action"
|
||||
disabled={avatarBusy || !capture.ready}
|
||||
onClick={() => captureInputRef.current?.click()}
|
||||
>
|
||||
{socialTx("打开前置摄像头")}
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="social-join-avatar-clear"
|
||||
onClick={() => update("avatar", "")}
|
||||
className={`social-join-avatar-action${
|
||||
capture.mode === "album-only" ? "" : " is-ghost"
|
||||
}`}
|
||||
disabled={avatarBusy}
|
||||
onClick={() => avatarInputRef.current?.click()}
|
||||
>
|
||||
{socialTx("移除头像")}
|
||||
{capture.mode === "album-only"
|
||||
? socialTx("从相册上传正脸")
|
||||
: socialTx("从相册选")}
|
||||
</button>
|
||||
) : null}
|
||||
{draft.avatar && !draft.avatar.startsWith("blob:") ? (
|
||||
<button
|
||||
type="button"
|
||||
className="social-join-avatar-clear"
|
||||
onClick={() => {
|
||||
setAvatarErr("");
|
||||
update("avatar", "");
|
||||
}}
|
||||
>
|
||||
{socialTx("移除头像")}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<label className="social-join-span-2">
|
||||
@ -799,6 +961,13 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
{capture.mode === "live-modal" ? (
|
||||
<AvatarSelfieModal
|
||||
open={selfieOpen}
|
||||
onClose={() => setSelfieOpen(false)}
|
||||
onCaptured={onSelfieChallenge}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@ -26,6 +26,12 @@ import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
import { useAudienceRoster } from "@social/lib/useAudienceRoster";
|
||||
import { useSocialConfig } from "./SocialExperience";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
import {
|
||||
DEFAULT_X_HANDLE,
|
||||
formatXHandle,
|
||||
xProfileUrl,
|
||||
} from "~/components/social-follow";
|
||||
import { trackFollow } from "~/lib/analytics/track";
|
||||
|
||||
const DEFAULT_PROMO =
|
||||
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4";
|
||||
@ -66,12 +72,12 @@ export default function HomeClient() {
|
||||
useEffect(() => {
|
||||
const root = document.querySelector(".social-home");
|
||||
if (!root) return;
|
||||
const observer = new IntersectionObserver(
|
||||
const reveal = new IntersectionObserver(
|
||||
(entries) =>
|
||||
entries.forEach((e) => {
|
||||
if (e.isIntersecting) {
|
||||
e.target.classList.add("visible");
|
||||
observer.unobserve(e.target);
|
||||
reveal.unobserve(e.target);
|
||||
}
|
||||
}),
|
||||
{ threshold: 0.06, rootMargin: "0px 0px -24px 0px" },
|
||||
@ -79,21 +85,12 @@ export default function HomeClient() {
|
||||
const scan = () => {
|
||||
root
|
||||
.querySelectorAll(".reveal:not(.visible)")
|
||||
.forEach((el) => observer.observe(el));
|
||||
.forEach((el) => reveal.observe(el));
|
||||
};
|
||||
scan();
|
||||
root.setAttribute("data-home-motion", "ready");
|
||||
const t = window.setTimeout(scan, 400);
|
||||
return () => {
|
||||
window.clearTimeout(t);
|
||||
observer.disconnect();
|
||||
root.removeAttribute("data-home-motion");
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const root = document.querySelector(".social-home");
|
||||
if (!root) return;
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
entries.forEach((entry) => {
|
||||
@ -105,7 +102,12 @@ export default function HomeClient() {
|
||||
root
|
||||
.querySelectorAll("section[id]:not(#hero)")
|
||||
.forEach((section) => observer.observe(section));
|
||||
return () => observer.disconnect();
|
||||
return () => {
|
||||
window.clearTimeout(t);
|
||||
reveal.disconnect();
|
||||
observer.disconnect();
|
||||
root.removeAttribute("data-home-motion");
|
||||
};
|
||||
}, []);
|
||||
|
||||
const onPanelPointerMove = (event: PointerEvent<HTMLDivElement>) => {
|
||||
@ -617,12 +619,30 @@ export default function HomeClient() {
|
||||
<Link href="/">{socialTx("门户首页")}</Link>
|
||||
<Link href="/community">{socialTx("旅居社群")}</Link>
|
||||
<Link href="/book">{socialTx("数字游民小册")}</Link>
|
||||
<Link href={socialPath("/blog")}>{socialTx("博客")}</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="footer-bottom">
|
||||
<div className="footer-bottom social-home-footer-bottom">
|
||||
<p suppressHydrationWarning>
|
||||
© {new Date().getFullYear()} nomadro · 游民社区
|
||||
</p>
|
||||
<div className="social-home-follow-row">
|
||||
<Link href={socialPath("/blog")}>{socialTx("博客")}</Link>
|
||||
<a
|
||||
className="social-home-follow-x"
|
||||
href={xProfileUrl(DEFAULT_X_HANDLE)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={() =>
|
||||
trackFollow("click", {
|
||||
channel: "x",
|
||||
place: "social_home_footer",
|
||||
})
|
||||
}
|
||||
>
|
||||
<span aria-hidden>𝕏</span> Follow {formatXHandle()}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
@ -4,6 +4,7 @@ import { useEffect, useRef, useState, type FormEvent } from "react";
|
||||
import Link from "next/link";
|
||||
import { ArrowUpRight, Check, Globe2, MapPin, Sparkles } from "lucide-react";
|
||||
import SiteShell from "./SiteShell";
|
||||
import SocialAvatar from "./SocialAvatar";
|
||||
import { PageIntro } from "./SocialUI";
|
||||
import { socialApi } from "@social/lib/api";
|
||||
import { useLocalState } from "@social/lib/useLocalState";
|
||||
@ -25,6 +26,7 @@ const EMPTY: SocialRosterProfile = {
|
||||
linktree: "",
|
||||
skills: "",
|
||||
bio: "",
|
||||
avatar: "",
|
||||
};
|
||||
const FIELDS = [
|
||||
{
|
||||
@ -93,8 +95,13 @@ export default function ProfileStudio() {
|
||||
!loadJson<SocialRosterProfile>("roster", EMPTY).updatedAt
|
||||
) {
|
||||
const next = { ...EMPTY };
|
||||
for (const key of Object.keys(EMPTY) as (keyof typeof EMPTY)[])
|
||||
for (const key of Object.keys(EMPTY) as (keyof typeof EMPTY)[]) {
|
||||
next[key] = response.item[key] || "";
|
||||
}
|
||||
// Keep a locally verified selfie if server row has no avatar yet
|
||||
const localAvatar =
|
||||
loadJson<SocialRosterProfile>("roster", EMPTY).avatar || "";
|
||||
if (!next.avatar && localAvatar) next.avatar = localAvatar;
|
||||
setProfile(next);
|
||||
setSync("synced");
|
||||
}
|
||||
@ -254,9 +261,15 @@ export default function ProfileStudio() {
|
||||
<div className="social-passport-pattern" aria-hidden="true">
|
||||
<Globe2 size={170} strokeWidth={0.5} />
|
||||
</div>
|
||||
<div className="social-profile-monogram">
|
||||
{profile.name.trim().slice(0, 1) || "N"}
|
||||
</div>
|
||||
{profile.avatar?.trim() ? (
|
||||
<div className="social-profile-face">
|
||||
<SocialAvatar src={profile.avatar.trim()} size={88} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="social-profile-monogram">
|
||||
{profile.name.trim().slice(0, 1) || "N"}
|
||||
</div>
|
||||
)}
|
||||
<span className="social-page-kicker">{socialTx("先看看效果")}</span>
|
||||
<h2>{profile.name.trim() || "你的名字"}</h2>
|
||||
<p>{profile.title || "你在做什么"}</p>
|
||||
|
||||
@ -18,11 +18,14 @@ import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
import { SocialMobileDock } from "./SocialNavigation";
|
||||
import SocialQuickRail from "./SocialQuickRail";
|
||||
import SocialBrandLogo from "./SocialBrandLogo";
|
||||
|
||||
export default function SiteShell({
|
||||
children,
|
||||
title,
|
||||
home = false,
|
||||
immersive = false,
|
||||
/** Blog / policy pages — content-first, no QuickRail (AdSense readability) */
|
||||
editorial = false,
|
||||
onJoin,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
@ -30,6 +33,7 @@ export default function SiteShell({
|
||||
home?: boolean;
|
||||
/** Full-bleed pages (map) — no quick rail / dense workspace chrome */
|
||||
immersive?: boolean;
|
||||
editorial?: boolean;
|
||||
onJoin?: () => void;
|
||||
}) {
|
||||
const { t } = useSocialI18n();
|
||||
@ -249,6 +253,27 @@ export default function SiteShell({
|
||||
);
|
||||
}
|
||||
|
||||
if (editorial) {
|
||||
return (
|
||||
<div className="social-flow social-root social-workspace social-editorial">
|
||||
<a className="connection-skip-link" href="#social-main">
|
||||
{t.skipToMain}
|
||||
</a>
|
||||
{nav}
|
||||
<div className="social-editorial-frame">
|
||||
<main
|
||||
className="social-main social-main--editorial"
|
||||
id="social-main"
|
||||
data-page={title || t.brand}
|
||||
>
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
<SocialMobileDock />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="social-flow social-root social-workspace social-workspace-dense">
|
||||
<a className="connection-skip-link" href="#social-main">
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
import Image from "next/image";
|
||||
|
||||
/** Unoptimized keeps external profile images compatible with configured/offline sources. */
|
||||
/** Unoptimized keeps external/profile/API avatar URLs working offline & cross-host. */
|
||||
export default function SocialAvatar({
|
||||
src,
|
||||
size,
|
||||
@ -12,9 +12,35 @@ export default function SocialAvatar({
|
||||
size: number;
|
||||
lazy?: boolean;
|
||||
}) {
|
||||
const url = (src || "").trim();
|
||||
// Relative social API / blob: use plain <img> — next/image remotePatterns skip these.
|
||||
if (
|
||||
!url ||
|
||||
url.startsWith("/api/") ||
|
||||
url.startsWith("blob:") ||
|
||||
url.startsWith("data:")
|
||||
) {
|
||||
return (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={url || "/icons/nomadro.webp"}
|
||||
alt=""
|
||||
width={size}
|
||||
height={size}
|
||||
loading={lazy ? "lazy" : "eager"}
|
||||
decoding="async"
|
||||
style={{ width: size, height: size, objectFit: "cover" }}
|
||||
onError={(event) => {
|
||||
const img = event.currentTarget;
|
||||
if (!img.src.endsWith("/icons/nomadro.webp"))
|
||||
img.src = "/icons/nomadro.webp";
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Image
|
||||
src={src}
|
||||
src={url}
|
||||
alt=""
|
||||
width={size}
|
||||
height={size}
|
||||
|
||||
@ -134,7 +134,7 @@ export default function SocialExperience({
|
||||
() => localizeSocialConfig(config, locale),
|
||||
[config, locale],
|
||||
);
|
||||
const [immersive, setImmersive] = useLocalState("immersive-fx-v2", true);
|
||||
const [immersive, setImmersive] = useLocalState("immersive-fx-v3", true);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const root = rootRef.current;
|
||||
|
||||
@ -10,6 +10,12 @@ import {
|
||||
House,
|
||||
MessageCircle,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
DEFAULT_X_HANDLE,
|
||||
formatXHandle,
|
||||
xProfileUrl,
|
||||
} from "~/components/social-follow";
|
||||
import { trackFollow } from "~/lib/analytics/track";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
|
||||
@ -64,19 +70,28 @@ export function SocialMobileDock() {
|
||||
}
|
||||
|
||||
export function SocialFooter() {
|
||||
const { t } = useSocialI18n();
|
||||
const { t, locale } = useSocialI18n();
|
||||
const zh = locale === "zh";
|
||||
|
||||
return (
|
||||
<footer className="social-workspace-footer">
|
||||
<span>{t.footerTagline}</span>
|
||||
<div>
|
||||
<Link href={socialPath("/date")}>{t.landing.socialWayDate}</Link>
|
||||
<Link href={socialPath("/blog")}>{zh ? "博客" : "Blog"}</Link>
|
||||
<Link href={socialPath("/blog/about")}>About</Link>
|
||||
<Link href={socialPath("/privacy")}>Privacy</Link>
|
||||
<Link href={socialPath("/feedback")}>
|
||||
{t.navGroups.find((g) => g.id === "together")?.items.find((i) => i.href === "/feedback")?.label || "Feedback"}
|
||||
{t.navGroups.find((g) => g.id === "together")?.items.find((i) => i.href === "/feedback")?.label || "Contact"}
|
||||
</Link>
|
||||
<a
|
||||
href={xProfileUrl(DEFAULT_X_HANDLE)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={() => trackFollow("click", { channel: "x", place: "social_footer" })}
|
||||
>
|
||||
{zh ? `关注 X ${formatXHandle()}` : `Follow ${formatXHandle()}`}
|
||||
</a>
|
||||
<Link href={socialPath("/join")}>{t.joinCommunity}</Link>
|
||||
<Link href={socialPath("/roster")}>
|
||||
{t.dock.find((d) => d.href === "/roster")?.label || "My intro"}
|
||||
</Link>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
|
||||
57
src/modules/social/components/blog/BlogAdSlot.tsx
Normal file
57
src/modules/social/components/blog/BlogAdSlot.tsx
Normal file
@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import Script from "next/script";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
/** AdSense — only mount when remote-config enabled + ids present */
|
||||
export function BlogAdSenseScript({ clientId }: { clientId: string }) {
|
||||
if (!clientId) return null;
|
||||
return (
|
||||
<Script
|
||||
async
|
||||
src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${clientId}`}
|
||||
crossOrigin="anonymous"
|
||||
strategy="afterInteractive"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function BlogAdSlot({
|
||||
clientId,
|
||||
slotId,
|
||||
label = "Sponsored",
|
||||
}: {
|
||||
clientId: string;
|
||||
slotId: string;
|
||||
label?: string;
|
||||
}) {
|
||||
const pushed = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!clientId || !slotId || pushed.current) return;
|
||||
try {
|
||||
const w = window as unknown as { adsbygoogle?: unknown[] };
|
||||
w.adsbygoogle = w.adsbygoogle || [];
|
||||
w.adsbygoogle.push({});
|
||||
pushed.current = true;
|
||||
} catch {
|
||||
/* blocked / not ready */
|
||||
}
|
||||
}, [clientId, slotId]);
|
||||
|
||||
if (!clientId || !slotId) return null;
|
||||
|
||||
return (
|
||||
<aside className="sblog-ad" aria-label={label}>
|
||||
<p className="sblog-ad-label">{label}</p>
|
||||
<ins
|
||||
className="adsbygoogle"
|
||||
style={{ display: "block", textAlign: "center" }}
|
||||
data-ad-client={clientId}
|
||||
data-ad-slot={slotId}
|
||||
data-ad-format="auto"
|
||||
data-full-width-responsive="true"
|
||||
/>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
196
src/modules/social/components/blog/BlogListClient.tsx
Normal file
196
src/modules/social/components/blog/BlogListClient.tsx
Normal file
@ -0,0 +1,196 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useDeferredValue, useMemo, useState } from "react";
|
||||
import SiteShell from "@social/components/SiteShell";
|
||||
import { SocialFooter } from "@social/components/SocialNavigation";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import type { BlogPostMeta } from "@social/lib/blog/types";
|
||||
|
||||
function formatDate(iso: string) {
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return iso;
|
||||
return d.toLocaleDateString("en-US", {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
}
|
||||
|
||||
const TOPIC_HINT: Record<string, string> = {
|
||||
nomad: "Getting started",
|
||||
coworking: "Where to work",
|
||||
community: "Meeting people",
|
||||
"remote-work": "Deep work",
|
||||
budget: "Money",
|
||||
privacy: "Trust & safety",
|
||||
};
|
||||
|
||||
export default function BlogListClient({
|
||||
posts,
|
||||
}: {
|
||||
posts: BlogPostMeta[];
|
||||
}) {
|
||||
const tags = useMemo(() => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const p of posts) {
|
||||
const primary = p.tags[0];
|
||||
if (!primary) continue;
|
||||
counts.set(primary, (counts.get(primary) || 0) + 1);
|
||||
}
|
||||
const ranked = Array.from(counts.entries())
|
||||
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
||||
.map(([t]) => t)
|
||||
.slice(0, 7);
|
||||
return ["all", ...ranked];
|
||||
}, [posts]);
|
||||
|
||||
const [tag, setTag] = useState("all");
|
||||
const [q, setQ] = useState("");
|
||||
const deferredQ = useDeferredValue(q.trim().toLowerCase());
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
return posts.filter((p) => {
|
||||
if (tag !== "all" && !p.tags.includes(tag)) return false;
|
||||
if (!deferredQ) return true;
|
||||
const hay = `${p.title} ${p.description} ${p.tags.join(" ")}`.toLowerCase();
|
||||
return hay.includes(deferredQ);
|
||||
});
|
||||
}, [posts, tag, deferredQ]);
|
||||
|
||||
const [featured, ...rest] = filtered;
|
||||
|
||||
return (
|
||||
<SiteShell title="Blog" editorial>
|
||||
<article className="sblog-page sblog-index">
|
||||
<header className="sblog-hero sblog-hero--index">
|
||||
<div className="sblog-hero-glow" aria-hidden />
|
||||
<p className="sblog-eyebrow">Nomadro · Field notes</p>
|
||||
<h1>Nomad Blog</h1>
|
||||
<p className="sblog-lead">
|
||||
Practical English guides for remote work, slow travel, and meeting
|
||||
people on the road.
|
||||
</p>
|
||||
<p className="sblog-count">
|
||||
<span>{posts.length} guides</span>
|
||||
<span className="sblog-dot" aria-hidden />
|
||||
<span>English · free to read</span>
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div className="sblog-toolbar">
|
||||
<label className="sblog-search">
|
||||
<span className="sr-only">Search guides</span>
|
||||
<input
|
||||
type="search"
|
||||
value={q}
|
||||
placeholder="Search guides…"
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{tags.length > 2 ? (
|
||||
<div className="sblog-tags" role="tablist" aria-label="Topics">
|
||||
{tags.map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tag === t}
|
||||
className={`sblog-tag${tag === t ? " is-on" : ""}`}
|
||||
onClick={() => setTag(t)}
|
||||
>
|
||||
{t === "all" ? "All" : TOPIC_HINT[t] || t}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!filtered.length ? (
|
||||
<div className="sblog-empty-box">
|
||||
<p>No guides match that filter.</p>
|
||||
<button
|
||||
type="button"
|
||||
className="sblog-text-btn"
|
||||
onClick={() => {
|
||||
setTag("all");
|
||||
setQ("");
|
||||
}}
|
||||
>
|
||||
Clear filters
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{featured ? (
|
||||
<Link
|
||||
href={socialPath(`/blog/${featured.slug}`)}
|
||||
className="sblog-featured reveal"
|
||||
>
|
||||
<div className="sblog-featured-top">
|
||||
<span className="sblog-featured-kicker">Latest</span>
|
||||
<time dateTime={featured.date}>{formatDate(featured.date)}</time>
|
||||
</div>
|
||||
<strong>{featured.title}</strong>
|
||||
<span className="sblog-featured-desc">{featured.description}</span>
|
||||
<span className="sblog-featured-foot">
|
||||
<em>
|
||||
{featured.readingMinutes} min read
|
||||
{featured.tags[0]
|
||||
? ` · ${TOPIC_HINT[featured.tags[0]] || featured.tags[0]}`
|
||||
: ""}
|
||||
</em>
|
||||
<span className="sblog-go">Read</span>
|
||||
</span>
|
||||
</Link>
|
||||
) : null}
|
||||
|
||||
{rest.length ? (
|
||||
<ul className="sblog-list">
|
||||
{rest.map((p, i) => (
|
||||
<li
|
||||
key={p.slug}
|
||||
className="reveal"
|
||||
style={{ animationDelay: `${Math.min(i, 6) * 40}ms` }}
|
||||
>
|
||||
<Link
|
||||
href={socialPath(`/blog/${p.slug}`)}
|
||||
className="sblog-card-link"
|
||||
>
|
||||
<div className="sblog-card-top">
|
||||
<time dateTime={p.date}>{formatDate(p.date)}</time>
|
||||
{p.tags[0] ? (
|
||||
<span className="sblog-pill">
|
||||
{TOPIC_HINT[p.tags[0]] || p.tags[0]}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<strong>{p.title}</strong>
|
||||
<span>{p.description}</span>
|
||||
<span className="sblog-card-foot">
|
||||
<em>{p.readingMinutes} min read</em>
|
||||
<span className="sblog-go" aria-hidden>
|
||||
→
|
||||
</span>
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
|
||||
<nav className="sblog-policy-row" aria-label="Publisher links">
|
||||
<Link href={socialPath("/blog/about")}>About</Link>
|
||||
<Link href={socialPath("/privacy")}>Privacy</Link>
|
||||
<Link href={socialPath("/feedback")}>Contact</Link>
|
||||
<a href="/social/blog/rss.xml">RSS</a>
|
||||
</nav>
|
||||
<SocialFooter />
|
||||
</article>
|
||||
</SiteShell>
|
||||
);
|
||||
}
|
||||
141
src/modules/social/components/blog/BlogMarkdown.tsx
Normal file
141
src/modules/social/components/blog/BlogMarkdown.tsx
Normal file
@ -0,0 +1,141 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, type ReactNode } from "react";
|
||||
|
||||
function parseTableRow(line: string): string[] {
|
||||
return line
|
||||
.split("|")
|
||||
.map((c) => c.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function inlineFormat(text: string): ReactNode[] {
|
||||
const parts: ReactNode[] = [];
|
||||
const re = /(\*\*[^*]+\*\*|`[^`]+`|\[[^\]]+\]\([^)]+\))/g;
|
||||
let last = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
let key = 0;
|
||||
while ((m = re.exec(text))) {
|
||||
if (m.index > last) parts.push(text.slice(last, m.index));
|
||||
const token = m[0];
|
||||
if (token.startsWith("**")) {
|
||||
parts.push(<strong key={key++}>{token.slice(2, -2)}</strong>);
|
||||
} else if (token.startsWith("`")) {
|
||||
parts.push(<code key={key++}>{token.slice(1, -1)}</code>);
|
||||
} else {
|
||||
const link = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
|
||||
if (link) {
|
||||
parts.push(
|
||||
<a key={key++} href={link[2]} rel="noopener noreferrer">
|
||||
{link[1]}
|
||||
</a>,
|
||||
);
|
||||
} else parts.push(token);
|
||||
}
|
||||
last = m.index + token.length;
|
||||
}
|
||||
if (last < text.length) parts.push(text.slice(last));
|
||||
return parts;
|
||||
}
|
||||
|
||||
/** Lightweight MD renderer — content-first for AdSense crawlability */
|
||||
export default function BlogMarkdown({ content }: { content: string }) {
|
||||
const elements = useMemo(() => {
|
||||
const lines = content.split("\n");
|
||||
const result: ReactNode[] = [];
|
||||
let listItems: string[] = [];
|
||||
let ordered = false;
|
||||
let tableRows: string[][] = [];
|
||||
let key = 0;
|
||||
|
||||
const flushList = () => {
|
||||
if (!listItems.length) return;
|
||||
const Tag = ordered ? "ol" : "ul";
|
||||
result.push(
|
||||
<Tag key={`list-${key++}`}>
|
||||
{listItems.map((item, i) => (
|
||||
<li key={i}>{inlineFormat(item)}</li>
|
||||
))}
|
||||
</Tag>,
|
||||
);
|
||||
listItems = [];
|
||||
ordered = false;
|
||||
};
|
||||
|
||||
const flushTable = () => {
|
||||
if (tableRows.length < 2) {
|
||||
tableRows = [];
|
||||
return;
|
||||
}
|
||||
const [header, , ...body] = tableRows;
|
||||
result.push(
|
||||
<div key={`table-${key++}`} className="sblog-table-wrap">
|
||||
<table className="sblog-table">
|
||||
<thead>
|
||||
<tr>
|
||||
{header.map((h, i) => (
|
||||
<th key={i}>{h}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{body.map((row, ri) => (
|
||||
<tr key={ri}>
|
||||
{row.map((cell, ci) => (
|
||||
<td key={ci}>{cell}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>,
|
||||
);
|
||||
tableRows = [];
|
||||
};
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("|")) {
|
||||
flushList();
|
||||
const cells = parseTableRow(line);
|
||||
if (cells.every((c) => /^[-:]+$/.test(c))) continue;
|
||||
tableRows.push(cells);
|
||||
continue;
|
||||
}
|
||||
flushTable();
|
||||
|
||||
if (line.startsWith("## ")) {
|
||||
flushList();
|
||||
const title = line.slice(3);
|
||||
const id = title
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\u4e00-\u9fff]+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.slice(0, 64);
|
||||
result.push(
|
||||
<h2 key={key++} id={id}>
|
||||
{title}
|
||||
</h2>,
|
||||
);
|
||||
} else if (line.startsWith("### ")) {
|
||||
flushList();
|
||||
result.push(<h3 key={key++}>{line.slice(4)}</h3>);
|
||||
} else if (line.startsWith("- ")) {
|
||||
ordered = false;
|
||||
listItems.push(line.slice(2));
|
||||
} else if (/^\d+\. /.test(line)) {
|
||||
ordered = true;
|
||||
listItems.push(line.replace(/^\d+\. /, ""));
|
||||
} else if (line.trim() === "") {
|
||||
flushList();
|
||||
} else {
|
||||
flushList();
|
||||
result.push(<p key={key++}>{inlineFormat(line)}</p>);
|
||||
}
|
||||
}
|
||||
flushList();
|
||||
flushTable();
|
||||
return result;
|
||||
}, [content]);
|
||||
|
||||
return <div className="sblog-prose">{elements}</div>;
|
||||
}
|
||||
187
src/modules/social/components/blog/BlogPostClient.tsx
Normal file
187
src/modules/social/components/blog/BlogPostClient.tsx
Normal file
@ -0,0 +1,187 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useMemo, useState } from "react";
|
||||
import SiteShell from "@social/components/SiteShell";
|
||||
import { SocialFooter } from "@social/components/SocialNavigation";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import type { BlogAdSenseConfig, BlogPost, BlogPostMeta } from "@social/lib/blog/types";
|
||||
import { ADSENSE_MIN_WORDS } from "@social/lib/blog/types";
|
||||
import BlogMarkdown from "./BlogMarkdown";
|
||||
import { BlogAdSenseScript, BlogAdSlot } from "./BlogAdSlot";
|
||||
import BlogReadingProgress from "./BlogReadingProgress";
|
||||
|
||||
function splitBodyForAd(body: string): [string, string] {
|
||||
const parts = body.split(/\n(?=## )/);
|
||||
if (parts.length < 3) return [body, ""];
|
||||
const mid = Math.max(2, Math.floor(parts.length / 2));
|
||||
return [parts.slice(0, mid).join("\n"), parts.slice(mid).join("\n")];
|
||||
}
|
||||
|
||||
function slugify(text: string) {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\u4e00-\u9fff]+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.slice(0, 64);
|
||||
}
|
||||
|
||||
export default function BlogPostClient({
|
||||
post,
|
||||
related,
|
||||
adsense,
|
||||
}: {
|
||||
post: BlogPost;
|
||||
related: BlogPostMeta[];
|
||||
adsense: BlogAdSenseConfig;
|
||||
}) {
|
||||
const showAds =
|
||||
adsense.enabled && post.wordCount >= ADSENSE_MIN_WORDS && post.locale === "en";
|
||||
const [before, after] = showAds && adsense.slotInArticle
|
||||
? splitBodyForAd(post.body)
|
||||
: [post.body, ""];
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const toc = useMemo(() => {
|
||||
const heads = post.body.match(/^## .+$/gm) || [];
|
||||
return heads.slice(0, 8).map((h) => {
|
||||
const title = h.replace(/^##\s+/, "");
|
||||
return { title, id: slugify(title) };
|
||||
});
|
||||
}, [post.body]);
|
||||
|
||||
const dateLabel = (() => {
|
||||
const d = new Date(post.date);
|
||||
if (Number.isNaN(d.getTime())) return post.date;
|
||||
return d.toLocaleDateString("en-US", {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
})();
|
||||
|
||||
async function copyLink() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(window.location.href);
|
||||
setCopied(true);
|
||||
window.setTimeout(() => setCopied(false), 1600);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<SiteShell title={post.title} editorial>
|
||||
<BlogReadingProgress />
|
||||
{showAds ? <BlogAdSenseScript clientId={adsense.clientId} /> : null}
|
||||
<article
|
||||
className="sblog-page sblog-article"
|
||||
itemScope
|
||||
itemType="https://schema.org/BlogPosting"
|
||||
>
|
||||
<header className="sblog-hero sblog-hero--article">
|
||||
<div className="sblog-hero-glow" aria-hidden />
|
||||
<p className="sblog-eyebrow">
|
||||
<Link href={socialPath("/blog")}>← All guides</Link>
|
||||
<span className="sblog-dot" aria-hidden />
|
||||
<time dateTime={post.date} itemProp="datePublished">
|
||||
{dateLabel}
|
||||
</time>
|
||||
</p>
|
||||
<h1 itemProp="headline">{post.title}</h1>
|
||||
<p className="sblog-lead" itemProp="description">
|
||||
{post.description}
|
||||
</p>
|
||||
<div className="sblog-meta-row">
|
||||
<p className="sblog-meta">
|
||||
<span itemProp="author">{post.author}</span>
|
||||
<span className="sblog-dot" aria-hidden />
|
||||
<span>{post.readingMinutes} min read</span>
|
||||
</p>
|
||||
<div className="sblog-actions">
|
||||
{post.tags.slice(0, 3).map((t) => (
|
||||
<span key={t} className="sblog-inline-tag">
|
||||
{t}
|
||||
</span>
|
||||
))}
|
||||
<button type="button" className="sblog-ghost-btn" onClick={() => void copyLink()}>
|
||||
{copied ? "Copied" : "Copy link"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{toc.length > 2 ? (
|
||||
<nav className="sblog-toc" aria-label="On this page">
|
||||
<p>On this page</p>
|
||||
<ol>
|
||||
{toc.map((item) => (
|
||||
<li key={item.id}>
|
||||
<a href={`#${item.id}`}>{item.title}</a>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</nav>
|
||||
) : null}
|
||||
|
||||
<div itemProp="articleBody" className="sblog-body">
|
||||
<BlogMarkdown content={before} />
|
||||
{showAds && adsense.slotInArticle ? (
|
||||
<BlogAdSlot
|
||||
clientId={adsense.clientId}
|
||||
slotId={adsense.slotInArticle}
|
||||
label="Sponsored"
|
||||
/>
|
||||
) : null}
|
||||
{after ? <BlogMarkdown content={after} /> : null}
|
||||
</div>
|
||||
|
||||
{showAds && adsense.slotEnd ? (
|
||||
<BlogAdSlot
|
||||
clientId={adsense.clientId}
|
||||
slotId={adsense.slotEnd}
|
||||
label="Sponsored"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<section className="sblog-cta">
|
||||
<h2>Meet people on the road</h2>
|
||||
<p>Reading helps. Saying hello helps more.</p>
|
||||
<div className="sblog-cta-row">
|
||||
<Link href={socialPath("/join")} className="sblog-cta-primary">
|
||||
Join community
|
||||
</Link>
|
||||
<Link href={socialPath("/people")} className="sblog-cta-secondary">
|
||||
Browse people
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{related.length ? (
|
||||
<section className="sblog-related">
|
||||
<h2>Keep reading</h2>
|
||||
<ul className="sblog-related-grid">
|
||||
{related.map((r) => (
|
||||
<li key={r.slug}>
|
||||
<Link href={socialPath(`/blog/${r.slug}`)}>
|
||||
<time dateTime={r.date}>{r.date}</time>
|
||||
<strong>{r.title}</strong>
|
||||
<em>{r.readingMinutes} min</em>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<nav className="sblog-policy-row" aria-label="Publisher links">
|
||||
<Link href={socialPath("/blog")}>All posts</Link>
|
||||
<Link href={socialPath("/blog/about")}>About</Link>
|
||||
<Link href={socialPath("/privacy")}>Privacy</Link>
|
||||
<Link href={socialPath("/feedback")}>Contact</Link>
|
||||
</nav>
|
||||
<SocialFooter />
|
||||
</article>
|
||||
</SiteShell>
|
||||
);
|
||||
}
|
||||
31
src/modules/social/components/blog/BlogReadingProgress.tsx
Normal file
31
src/modules/social/components/blog/BlogReadingProgress.tsx
Normal file
@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function BlogReadingProgress() {
|
||||
const [pct, setPct] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const onScroll = () => {
|
||||
const el = document.querySelector(".sblog-article");
|
||||
if (!el) return;
|
||||
const rect = el.getBoundingClientRect();
|
||||
const total = el.scrollHeight - window.innerHeight;
|
||||
const scrolled = Math.min(Math.max(-rect.top, 0), Math.max(total, 1));
|
||||
setPct(Math.round((scrolled / Math.max(total, 1)) * 100));
|
||||
};
|
||||
onScroll();
|
||||
window.addEventListener("scroll", onScroll, { passive: true });
|
||||
window.addEventListener("resize", onScroll);
|
||||
return () => {
|
||||
window.removeEventListener("scroll", onScroll);
|
||||
window.removeEventListener("resize", onScroll);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="sblog-progress" aria-hidden="true">
|
||||
<span style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -14,10 +14,19 @@ export function getGuestId(): string {
|
||||
return id;
|
||||
}
|
||||
|
||||
const _memTtl = new Map<string, { at: number; data: unknown }>();
|
||||
|
||||
async function req<T>(
|
||||
path: string,
|
||||
init?: RequestInit & { json?: unknown },
|
||||
init?: RequestInit & { json?: unknown; ttlMs?: number },
|
||||
): Promise<T> {
|
||||
const method = (init?.method || "GET").toUpperCase();
|
||||
const ttl = init?.ttlMs || 0;
|
||||
const cacheKey = ttl > 0 && method === "GET" ? `${method}:${path}` : "";
|
||||
if (cacheKey) {
|
||||
const hit = _memTtl.get(cacheKey);
|
||||
if (hit && Date.now() - hit.at < ttl) return hit.data as T;
|
||||
}
|
||||
const headers: Record<string, string> = {
|
||||
"X-Social-Guest-Id": getGuestId(),
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
@ -27,8 +36,9 @@ async function req<T>(
|
||||
headers["Content-Type"] = "application/json";
|
||||
body = JSON.stringify(init.json);
|
||||
}
|
||||
const { ttlMs: _ttlMs, json: _json, ...rest } = init || {};
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
...init,
|
||||
...rest,
|
||||
headers,
|
||||
body,
|
||||
cache: "no-store",
|
||||
@ -38,7 +48,9 @@ async function req<T>(
|
||||
const err = await res.text().catch(() => "");
|
||||
throw new Error(err || `HTTP ${res.status}`);
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
const data = (await res.json()) as T;
|
||||
if (cacheKey) _memTtl.set(cacheKey, { at: Date.now(), data });
|
||||
return data;
|
||||
}
|
||||
|
||||
export type SocialRealtimeToken = {
|
||||
@ -192,7 +204,7 @@ export const socialApi = {
|
||||
photoNote?: string;
|
||||
at: string;
|
||||
}>;
|
||||
}>(`/cafes/${encodeURIComponent(cafeId)}/reviews`),
|
||||
}>(`/cafes/${encodeURIComponent(cafeId)}/reviews`, { ttlMs: 30_000 }),
|
||||
|
||||
postReview: (
|
||||
cafeId: string,
|
||||
@ -213,6 +225,50 @@ export const socialApi = {
|
||||
saveRoster: (payload: Record<string, string>) =>
|
||||
req("/roster/me", { method: "PUT", json: payload }),
|
||||
|
||||
/** Two-frame live selfie challenge → verified front frame stored as avatar. */
|
||||
uploadAvatarChallenge: async (front: Blob, turn: Blob) => {
|
||||
const form = new FormData();
|
||||
// Explicit File+MIME — bare Blob parts often become application/octet-stream
|
||||
// and social_svc upload_bytes rejects non-image content types.
|
||||
const frontFile =
|
||||
front instanceof File && front.type.startsWith("image/")
|
||||
? front
|
||||
: new File([front], "front.jpg", { type: "image/jpeg" });
|
||||
const turnFile =
|
||||
turn instanceof File && turn.type.startsWith("image/")
|
||||
? turn
|
||||
: new File([turn], "turn.jpg", { type: "image/jpeg" });
|
||||
form.append("front", frontFile);
|
||||
form.append("turn", turnFile);
|
||||
const res = await fetch(`${BASE}/avatar/challenge`, {
|
||||
method: "POST",
|
||||
headers: { "X-Social-Guest-Id": getGuestId() },
|
||||
body: form,
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(90000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
let msg = "";
|
||||
try {
|
||||
const body = (await res.json()) as { detail?: unknown };
|
||||
if (typeof body?.detail === "string") msg = body.detail;
|
||||
} catch {
|
||||
msg = await res.text().catch(() => "");
|
||||
}
|
||||
throw new Error(msg || `核验失败 HTTP ${res.status}`);
|
||||
}
|
||||
return (await res.json()) as {
|
||||
ok: boolean;
|
||||
url: string;
|
||||
object_key: string;
|
||||
storage?: string;
|
||||
challenge?: {
|
||||
similarity?: number;
|
||||
yaw_delta?: number;
|
||||
};
|
||||
};
|
||||
},
|
||||
|
||||
/** Image → SeaweedFS S3 (s3.nomadro.com) via social_svc; local fallback. */
|
||||
uploadAvatar: async (file: File, purpose = "avatar") => {
|
||||
const form = new FormData();
|
||||
@ -226,14 +282,33 @@ export const socialApi = {
|
||||
signal: AbortSignal.timeout(60000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.text().catch(() => "");
|
||||
throw new Error(err || `上传失败 HTTP ${res.status}`);
|
||||
let msg = "";
|
||||
try {
|
||||
const body = (await res.json()) as { detail?: unknown };
|
||||
if (typeof body?.detail === "string") msg = body.detail;
|
||||
else if (Array.isArray(body?.detail)) {
|
||||
msg = body.detail
|
||||
.map((d) =>
|
||||
typeof d === "string"
|
||||
? d
|
||||
: d && typeof d === "object" && "msg" in d
|
||||
? String((d as { msg: unknown }).msg)
|
||||
: "",
|
||||
)
|
||||
.filter(Boolean)
|
||||
.join("; ");
|
||||
}
|
||||
} catch {
|
||||
msg = await res.text().catch(() => "");
|
||||
}
|
||||
throw new Error(msg || `上传失败 HTTP ${res.status}`);
|
||||
}
|
||||
return (await res.json()) as {
|
||||
ok: boolean;
|
||||
url: string;
|
||||
object_key: string;
|
||||
storage?: string;
|
||||
face?: { ok: boolean; faces: number; engine: string };
|
||||
};
|
||||
},
|
||||
|
||||
@ -265,6 +340,7 @@ export const socialApi = {
|
||||
const qs = q.toString();
|
||||
return req<{ items: import("./geoTypes").SocialMapCity[]; source?: string }>(
|
||||
`/map/cities${qs ? `?${qs}` : ""}`,
|
||||
{ ttlMs: 20_000 },
|
||||
);
|
||||
},
|
||||
|
||||
@ -292,7 +368,7 @@ export const socialApi = {
|
||||
departure_date: string;
|
||||
}>;
|
||||
};
|
||||
}>(`/cities/${encodeURIComponent(cityId)}`),
|
||||
}>(`/cities/${encodeURIComponent(cityId)}`, { ttlMs: 30_000 }),
|
||||
|
||||
peopleGeo: (opts?: {
|
||||
city?: string;
|
||||
|
||||
49
src/modules/social/lib/blog/adsense.ts
Normal file
49
src/modules/social/lib/blog/adsense.ts
Normal file
@ -0,0 +1,49 @@
|
||||
import "server-only";
|
||||
import { DEFAULT_REMOTE_CONFIG, type NomadroRemoteConfig } from "~/lib/remote-config";
|
||||
import type { BlogAdSenseConfig } from "./types";
|
||||
|
||||
/**
|
||||
* AdSense display rules for /social/blog:
|
||||
* - Default OFF until publisher approval (flags.adsenseEnabled)
|
||||
* - Need clientId + at least one slot
|
||||
* - Never show ads on thin posts (< ADSENSE_MIN_WORDS) — caller checks
|
||||
*/
|
||||
export function resolveBlogAdSense(
|
||||
config?: NomadroRemoteConfig | null,
|
||||
): BlogAdSenseConfig {
|
||||
const flags = config?.flags ?? DEFAULT_REMOTE_CONFIG.flags;
|
||||
const copy = config?.copy ?? DEFAULT_REMOTE_CONFIG.copy;
|
||||
const clientId = String(
|
||||
flags.adsenseClientId || copy.adsenseClientId || "",
|
||||
).trim();
|
||||
const slotInArticle = String(
|
||||
flags.adsenseSlotBlogMid || copy.adsenseSlotBlogMid || "",
|
||||
).trim();
|
||||
const slotEnd = String(
|
||||
flags.adsenseSlotBlogEnd || copy.adsenseSlotBlogEnd || "",
|
||||
).trim();
|
||||
const adsTxtPublisherId = String(
|
||||
flags.adsensePublisherId || copy.adsensePublisherId || "",
|
||||
).trim();
|
||||
|
||||
const enabled =
|
||||
flags.adsenseEnabled === true &&
|
||||
Boolean(clientId) &&
|
||||
(Boolean(slotInArticle) || Boolean(slotEnd));
|
||||
|
||||
return {
|
||||
enabled,
|
||||
clientId,
|
||||
slotInArticle,
|
||||
slotEnd,
|
||||
adsTxtPublisherId,
|
||||
};
|
||||
}
|
||||
|
||||
export function isSocialBlogModuleEnabled(
|
||||
config?: NomadroRemoteConfig | null,
|
||||
): boolean {
|
||||
const mod = config?.modules?.socialBlog;
|
||||
if (!mod) return true;
|
||||
return mod.enabled !== false;
|
||||
}
|
||||
108
src/modules/social/lib/blog/catalog.ts
Normal file
108
src/modules/social/lib/blog/catalog.ts
Normal file
@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Tina-like collection query: list / get documents from Git Markdown.
|
||||
* Offline-first: filesystem seeds; remote-config can hide slugs.
|
||||
*/
|
||||
import "server-only";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { countWords, estimateReadingMinutes, parseFrontmatter } from "./parse";
|
||||
import { ADSENSE_MIN_WORDS, type BlogPost, type BlogPostMeta } from "./types";
|
||||
|
||||
const CONTENT_DIR = path.join(
|
||||
process.cwd(),
|
||||
"src",
|
||||
"modules",
|
||||
"social-content",
|
||||
"blog",
|
||||
);
|
||||
|
||||
function slugFromFile(file: string) {
|
||||
return file.replace(/\.mdx?$/i, "");
|
||||
}
|
||||
|
||||
function readAllRaw(): Array<{ file: string; raw: string }> {
|
||||
try {
|
||||
if (!fs.existsSync(CONTENT_DIR)) return [];
|
||||
return fs
|
||||
.readdirSync(CONTENT_DIR)
|
||||
.filter((f) => /\.mdx?$/i.test(f))
|
||||
.map((file) => ({
|
||||
file,
|
||||
// strip UTF-8 BOM (Windows editors / PowerShell Set-Content)
|
||||
raw: fs
|
||||
.readFileSync(path.join(CONTENT_DIR, file), "utf8")
|
||||
.replace(/^\uFEFF/, ""),
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function toMeta(
|
||||
file: string,
|
||||
data: ReturnType<typeof parseFrontmatter>["data"],
|
||||
body: string,
|
||||
): BlogPostMeta | null {
|
||||
const title = (data.title || "").trim();
|
||||
if (!title) return null;
|
||||
const wordCount = countWords(body);
|
||||
const slug = slugFromFile(file);
|
||||
return {
|
||||
title,
|
||||
description: (data.description || title).trim(),
|
||||
date: data.date || "2026-01-01",
|
||||
updated: data.updated,
|
||||
tags: Array.isArray(data.tags) ? data.tags : [],
|
||||
cover: data.cover,
|
||||
locale: data.locale === "zh" ? "zh" : "en",
|
||||
draft: Boolean(data.draft),
|
||||
author: data.author || "Nomadro",
|
||||
readingMinutes: data.readingMinutes || estimateReadingMinutes(wordCount),
|
||||
slug,
|
||||
path: `blog/${file}`,
|
||||
wordCount,
|
||||
};
|
||||
}
|
||||
|
||||
export function listBlogPosts(opts?: {
|
||||
locale?: "en" | "zh" | "all";
|
||||
includeDrafts?: boolean;
|
||||
/** Prefer English long-form for AdSense lane */
|
||||
adsenseReadyOnly?: boolean;
|
||||
}): BlogPostMeta[] {
|
||||
const locale = opts?.locale ?? "en";
|
||||
const includeDrafts = opts?.includeDrafts ?? false;
|
||||
const adsenseReadyOnly = opts?.adsenseReadyOnly ?? false;
|
||||
|
||||
const items: BlogPostMeta[] = [];
|
||||
for (const { file, raw } of readAllRaw()) {
|
||||
const { data, body } = parseFrontmatter(raw);
|
||||
const meta = toMeta(file, data, body);
|
||||
if (!meta) continue;
|
||||
if (!includeDrafts && meta.draft) continue;
|
||||
if (locale !== "all" && meta.locale !== locale) continue;
|
||||
if (adsenseReadyOnly && meta.wordCount < ADSENSE_MIN_WORDS) continue;
|
||||
items.push(meta);
|
||||
}
|
||||
return items.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0));
|
||||
}
|
||||
|
||||
export function getBlogPost(slug: string): BlogPost | null {
|
||||
const safe = slug.replace(/[^a-zA-Z0-9._-]/g, "");
|
||||
if (!safe) return null;
|
||||
for (const ext of [".md", ".mdx"]) {
|
||||
const file = `${safe}${ext}`;
|
||||
const full = path.join(CONTENT_DIR, file);
|
||||
if (!fs.existsSync(full)) continue;
|
||||
const raw = fs.readFileSync(full, "utf8");
|
||||
const { data, body } = parseFrontmatter(raw);
|
||||
const meta = toMeta(file, data, body);
|
||||
if (!meta || meta.draft) return null;
|
||||
return { ...meta, body };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function listBlogSlugs(): string[] {
|
||||
return listBlogPosts({ locale: "all", includeDrafts: false }).map((p) => p.slug);
|
||||
}
|
||||
4
src/modules/social/lib/blog/index.ts
Normal file
4
src/modules/social/lib/blog/index.ts
Normal file
@ -0,0 +1,4 @@
|
||||
/** Client-safe barrel — do not re-export catalog/adsense (fs / server-only). */
|
||||
export * from "./types";
|
||||
export { parseFrontmatter, countWords, estimateReadingMinutes } from "./parse";
|
||||
export { blogPostingJsonLd, blogListJsonLd } from "./jsonld";
|
||||
53
src/modules/social/lib/blog/jsonld.ts
Normal file
53
src/modules/social/lib/blog/jsonld.ts
Normal file
@ -0,0 +1,53 @@
|
||||
import type { BlogPost } from "./types";
|
||||
|
||||
const SITE = "https://nomadro.com";
|
||||
|
||||
export function blogPostingJsonLd(post: BlogPost) {
|
||||
return {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "BlogPosting",
|
||||
headline: post.title,
|
||||
description: post.description,
|
||||
datePublished: post.date,
|
||||
dateModified: post.updated || post.date,
|
||||
inLanguage: post.locale === "zh" ? "zh-CN" : "en-US",
|
||||
wordCount: post.wordCount,
|
||||
author: {
|
||||
"@type": "Organization",
|
||||
name: post.author || "Nomadro",
|
||||
url: SITE,
|
||||
},
|
||||
publisher: {
|
||||
"@type": "Organization",
|
||||
name: "Nomadro",
|
||||
url: SITE,
|
||||
logo: {
|
||||
"@type": "ImageObject",
|
||||
url: `${SITE}/icon-512.png`,
|
||||
},
|
||||
},
|
||||
mainEntityOfPage: {
|
||||
"@type": "WebPage",
|
||||
"@id": `${SITE}/social/blog/${post.slug}`,
|
||||
},
|
||||
image: post.cover ? [post.cover.startsWith("http") ? post.cover : `${SITE}${post.cover}`] : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function blogListJsonLd(posts: Array<{ title: string; slug: string; date: string }>) {
|
||||
return {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Blog",
|
||||
name: "Nomadro Nomad Blog",
|
||||
description:
|
||||
"Field notes for digital nomads: cities, cafés, remote work, and meeting people on the road.",
|
||||
url: `${SITE}/social/blog`,
|
||||
publisher: { "@type": "Organization", name: "Nomadro", url: SITE },
|
||||
blogPost: posts.map((p) => ({
|
||||
"@type": "BlogPosting",
|
||||
headline: p.title,
|
||||
datePublished: p.date,
|
||||
url: `${SITE}/social/blog/${p.slug}`,
|
||||
})),
|
||||
};
|
||||
}
|
||||
73
src/modules/social/lib/blog/parse.ts
Normal file
73
src/modules/social/lib/blog/parse.ts
Normal file
@ -0,0 +1,73 @@
|
||||
import type { BlogFrontmatter, BlogLocale } from "./types";
|
||||
|
||||
function stripQuotes(v: string) {
|
||||
const s = v.trim();
|
||||
if (
|
||||
(s.startsWith('"') && s.endsWith('"')) ||
|
||||
(s.startsWith("'") && s.endsWith("'"))
|
||||
) {
|
||||
return s.slice(1, -1);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function parseTags(raw: string): string[] {
|
||||
const s = raw.trim();
|
||||
if (s.startsWith("[")) {
|
||||
return s
|
||||
.slice(1, -1)
|
||||
.split(",")
|
||||
.map((x) => stripQuotes(x))
|
||||
.filter(Boolean);
|
||||
}
|
||||
return s
|
||||
.split(",")
|
||||
.map((x) => stripQuotes(x))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
export function parseFrontmatter(raw: string): {
|
||||
data: Partial<BlogFrontmatter>;
|
||||
body: string;
|
||||
} {
|
||||
const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
|
||||
if (!m) return { data: {}, body: raw };
|
||||
const data: Partial<BlogFrontmatter> = {};
|
||||
for (const line of m[1].split(/\r?\n/)) {
|
||||
const i = line.indexOf(":");
|
||||
if (i < 0) continue;
|
||||
const key = line.slice(0, i).trim();
|
||||
const val = line.slice(i + 1).trim();
|
||||
if (!key) continue;
|
||||
if (key === "tags") data.tags = parseTags(val);
|
||||
else if (key === "draft") data.draft = /^(true|1|yes)$/i.test(val);
|
||||
else if (key === "readingMinutes") data.readingMinutes = Number(val) || undefined;
|
||||
else if (key === "locale") data.locale = (stripQuotes(val) as BlogLocale) || "en";
|
||||
else if (
|
||||
key === "title" ||
|
||||
key === "description" ||
|
||||
key === "date" ||
|
||||
key === "updated" ||
|
||||
key === "cover" ||
|
||||
key === "author"
|
||||
) {
|
||||
data[key] = stripQuotes(val);
|
||||
}
|
||||
}
|
||||
return { data, body: m[2] || "" };
|
||||
}
|
||||
|
||||
export function countWords(body: string): number {
|
||||
const text = body.replace(/[#>*`\[\]()_-]/g, " ").replace(/\s+/g, " ").trim();
|
||||
if (!text) return 0;
|
||||
const cjk = (text.match(/[\u4e00-\u9fff]/g) || []).length;
|
||||
const latin = text
|
||||
.replace(/[\u4e00-\u9fff]/g, " ")
|
||||
.split(/\s+/)
|
||||
.filter(Boolean).length;
|
||||
return cjk + latin;
|
||||
}
|
||||
|
||||
export function estimateReadingMinutes(wordCount: number): number {
|
||||
return Math.max(1, Math.round(wordCount / 220));
|
||||
}
|
||||
51
src/modules/social/lib/blog/types.ts
Normal file
51
src/modules/social/lib/blog/types.ts
Normal file
@ -0,0 +1,51 @@
|
||||
/**
|
||||
* TinaCMS-inspired content model (collection / document / frontmatter).
|
||||
* SoT: Git Markdown under social-content/blog — no Tina Cloud runtime.
|
||||
*/
|
||||
|
||||
/** Soft floor before in-article ads may render. */
|
||||
export const ADSENSE_MIN_WORDS = 280;
|
||||
|
||||
export type BlogLocale = "en" | "zh";
|
||||
|
||||
/** Tina "collection" = posts */
|
||||
export type BlogCollectionName = "posts";
|
||||
|
||||
/** Document frontmatter (Tina fields) */
|
||||
export type BlogFrontmatter = {
|
||||
title: string;
|
||||
description: string;
|
||||
date: string;
|
||||
/** ISO date preferred */
|
||||
updated?: string;
|
||||
tags: string[];
|
||||
cover?: string;
|
||||
locale: BlogLocale;
|
||||
/** Tina draft: false = published */
|
||||
draft?: boolean;
|
||||
/** Author display name */
|
||||
author?: string;
|
||||
/** Minutes; computed if missing */
|
||||
readingMinutes?: number;
|
||||
};
|
||||
|
||||
export type BlogPostMeta = BlogFrontmatter & {
|
||||
slug: string;
|
||||
/** Relative path from content root */
|
||||
path: string;
|
||||
wordCount: number;
|
||||
};
|
||||
|
||||
export type BlogPost = BlogPostMeta & {
|
||||
body: string;
|
||||
};
|
||||
|
||||
export type BlogAdSenseConfig = {
|
||||
/** Master switch — keep false until AdSense approved */
|
||||
enabled: boolean;
|
||||
clientId: string;
|
||||
slotInArticle: string;
|
||||
slotEnd: string;
|
||||
/** Publisher id for ads.txt (pub-xxx without ca-) */
|
||||
adsTxtPublisherId: string;
|
||||
};
|
||||
@ -19,6 +19,7 @@ const EMPTY: SocialRosterProfile = {
|
||||
linktree: "",
|
||||
skills: "",
|
||||
bio: "",
|
||||
avatar: "",
|
||||
};
|
||||
|
||||
const STORAGE_CHANGE = "nomadro-social-storage";
|
||||
@ -51,8 +52,14 @@ export function profileToMember(
|
||||
.map((t) => t.trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, 6);
|
||||
const avatar =
|
||||
avatarPack === "cn"
|
||||
const own = (profile.avatar || "").trim();
|
||||
const ownOk =
|
||||
own.startsWith("https://") ||
|
||||
own.startsWith("http://") ||
|
||||
own.startsWith("/api/social/");
|
||||
const avatar = ownOk
|
||||
? own
|
||||
: avatarPack === "cn"
|
||||
? cnAvatarForSeed(name, "f")
|
||||
: `https://api.dicebear.com/7.x/initials/svg?seed=${encodeURIComponent(name)}`;
|
||||
return {
|
||||
@ -88,9 +95,12 @@ export function useDiscoveryRoster(): SocialRosterMember[] {
|
||||
);
|
||||
const profile = useMemo(() => {
|
||||
const raw = JSON.parse(profileSnapshot) as Partial<SocialRosterProfile> | null;
|
||||
return Object.fromEntries(Object.entries(EMPTY).map(([key, fallback]) => [
|
||||
key, typeof raw?.[key as keyof SocialRosterProfile] === "string" ? raw[key as keyof SocialRosterProfile] : fallback,
|
||||
])) as SocialRosterProfile;
|
||||
const next = { ...EMPTY };
|
||||
(Object.keys(EMPTY) as (keyof SocialRosterProfile)[]).forEach((key) => {
|
||||
const val = raw?.[key];
|
||||
if (typeof val === "string") next[key] = val;
|
||||
});
|
||||
return next;
|
||||
}, [profileSnapshot]);
|
||||
const seed = useMemo(
|
||||
() => mapRosterAvatarPack(MOCK_ROSTER, pack),
|
||||
|
||||
@ -238,6 +238,7 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
|
||||
"动效 · 轻量": "Motion · light",
|
||||
"旅居社群": "Travel community",
|
||||
"数字游民小册": "Nomad guidebook",
|
||||
"博客": "Blog",
|
||||
"看看 TA": "View profile",
|
||||
"附近可能同城的人": "Maybe nearby",
|
||||
"关注保存在当前设备": "Follows are saved on this device",
|
||||
@ -335,11 +336,60 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
|
||||
"上传头像": "Upload avatar",
|
||||
"头像": "Avatar",
|
||||
"上传中…": "Uploading…",
|
||||
"检测人脸并上传中…": "Checking face & uploading…",
|
||||
"点选上传,存到 s3.nomadro.com": "Tap to upload → s3.nomadro.com",
|
||||
"点选上传,需含清晰正脸": "Tap to upload — clear front face required",
|
||||
"建议前置摄像头自拍,系统会做人脸与真人检测":
|
||||
"Prefer a front-camera selfie — we check face presence & liveness",
|
||||
"建议现场自拍核验:正脸 + 微转头":
|
||||
"Live selfie check: front face + slight head turn",
|
||||
"检测设备中…": "Detecting device…",
|
||||
"电脑已检测到摄像头:建议现场预览自拍(正脸 + 微转头)":
|
||||
"Webcam found — live preview selfie recommended (front + slight turn)",
|
||||
"手机可调用前置摄像头拍照核验;也可从相册选":
|
||||
"Phone can use the front camera, or pick from album",
|
||||
"当前无可用摄像头,请从相册上传清晰正脸":
|
||||
"No camera available — upload a clear front-face photo from album",
|
||||
"电脑摄像头自拍": "Webcam selfie",
|
||||
"打开前置摄像头": "Open front camera",
|
||||
"从相册上传正脸": "Upload front face from album",
|
||||
"正在打开摄像头…": "Opening camera…",
|
||||
"现场自拍": "Take selfie",
|
||||
"从相册选": "From album",
|
||||
"现场自拍核验": "Live selfie verification",
|
||||
"正对镜头,脸放进圈内": "Face the camera — keep your face in the oval",
|
||||
"请稍微转头(左右任一方向)再拍": "Turn your head slightly (either side), then shoot",
|
||||
"核验中…": "Verifying…",
|
||||
"正脸": "Front",
|
||||
"转头": "Turn",
|
||||
"拍正脸": "Capture front",
|
||||
"拍转头": "Capture turn",
|
||||
"无法打开摄像头,请允许权限或改用相册":
|
||||
"Camera unavailable — allow permission or use album",
|
||||
"拍照失败,请重试": "Capture failed — try again",
|
||||
"真人核验失败,请重试": "Liveness check failed — try again",
|
||||
"两张照片不是同一个人,请本人连续自拍完成核验":
|
||||
"The two shots are not the same person — retake as yourself",
|
||||
"转头幅度不够,请稍微左右转头后再拍第二张":
|
||||
"Head turn too small — turn a bit more for the second shot",
|
||||
"移除头像": "Remove avatar",
|
||||
"请选择图片文件": "Please choose an image",
|
||||
"头像不能超过 8MB": "Avatar must be under 8MB",
|
||||
"头像上传失败": "Avatar upload failed",
|
||||
"未检测到人脸,请上传含清晰正脸的照片":
|
||||
"No face detected — please upload a clear front-facing photo",
|
||||
"未检测到人脸,请上传本人清晰正脸照片":
|
||||
"No face detected — please upload your clear front-facing photo",
|
||||
"请只上传一张本人正脸(不要合影)":
|
||||
"Upload only your own face (no group photos)",
|
||||
"未通过真人检测,请用前置摄像头现场自拍(勿用网图/截图)":
|
||||
"Liveness failed — take a live front-camera selfie (no screenshots/stock photos)",
|
||||
"人脸区域不足,请靠近镜头、露出完整正脸再拍":
|
||||
"Face crop too small — move closer and show a full front face",
|
||||
"真人检测未完成,请重新自拍一张正脸":
|
||||
"Liveness incomplete — please retake a front-face selfie",
|
||||
"请用摄像头现场自拍以完成真人验证":
|
||||
"Please take a live camera selfie to finish verification",
|
||||
"支付已完成。先写这几项,之后还能改。": "Payment done. Fill these in — you can edit later.",
|
||||
"基本信息": "Basics",
|
||||
"工作与背景": "Work & background",
|
||||
|
||||
87
src/modules/social/lib/useCaptureCapability.ts
Normal file
87
src/modules/social/lib/useCaptureCapability.ts
Normal file
@ -0,0 +1,87 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export type CaptureCapability = {
|
||||
ready: boolean;
|
||||
/** phone / tablet-ish UA or narrow touch viewport */
|
||||
isMobile: boolean;
|
||||
/** MediaDevices API present */
|
||||
canMedia: boolean;
|
||||
/** at least one videoinput after permission/enumerate */
|
||||
hasCamera: boolean;
|
||||
/** PC + camera → live preview modal; mobile + camera → capture input; else album */
|
||||
mode: "live-modal" | "native-capture" | "album-only";
|
||||
};
|
||||
|
||||
function detectMobile(): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
const ua = navigator.userAgent || "";
|
||||
const uaMobile = /Android|iPhone|iPad|iPod|Mobile|webOS|BlackBerry|IEMobile|Opera Mini/i.test(
|
||||
ua,
|
||||
);
|
||||
const coarse =
|
||||
typeof window.matchMedia === "function" &&
|
||||
window.matchMedia("(pointer: coarse)").matches;
|
||||
const narrow = window.innerWidth > 0 && window.innerWidth < 820;
|
||||
return uaMobile || (coarse && narrow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Soft probe only — never call getUserMedia here (avoids permission prompt on join page).
|
||||
* - enumerated videoinput → true
|
||||
* - MediaDevices present but list empty/hidden → optimistic true (real open happens on click)
|
||||
* - no MediaDevices → false
|
||||
*/
|
||||
async function probeCamera(): Promise<boolean> {
|
||||
if (typeof navigator === "undefined") return false;
|
||||
const md = navigator.mediaDevices;
|
||||
if (!md?.getUserMedia) return false;
|
||||
|
||||
try {
|
||||
if (md.enumerateDevices) {
|
||||
const list = await md.enumerateDevices();
|
||||
if (list.some((d) => d.kind === "videoinput")) return true;
|
||||
}
|
||||
} catch {
|
||||
/* fall through — still optimistic if API exists */
|
||||
}
|
||||
|
||||
// Browsers often hide cams until permission; still offer camera UX.
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* PC/手机 + 是否有摄像头 → 头像采集 UX 分流。
|
||||
* 不在 SSR 假设有摄像头;挂载后再探测。
|
||||
*/
|
||||
export function useCaptureCapability(): CaptureCapability {
|
||||
const [state, setState] = useState<CaptureCapability>({
|
||||
ready: false,
|
||||
isMobile: false,
|
||||
canMedia: false,
|
||||
hasCamera: false,
|
||||
mode: "album-only",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const isMobile = detectMobile();
|
||||
const canMedia = Boolean(navigator.mediaDevices?.getUserMedia);
|
||||
|
||||
void (async () => {
|
||||
const hasCamera = canMedia ? await probeCamera() : false;
|
||||
if (cancelled) return;
|
||||
let mode: CaptureCapability["mode"] = "album-only";
|
||||
if (hasCamera && isMobile) mode = "native-capture";
|
||||
else if (hasCamera && !isMobile) mode = "live-modal";
|
||||
setState({ ready: true, isMobile, canMedia, hasCamera, mode });
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return state;
|
||||
}
|
||||
@ -5,6 +5,7 @@ import { useEffect } from "react";
|
||||
/** Observe `.reveal` inside a root selector and mark `.visible` once. */
|
||||
export function useRevealMotion(rootSelector: string, deps: unknown[] = []) {
|
||||
useEffect(() => {
|
||||
if (!rootSelector) return;
|
||||
const root = document.querySelector(rootSelector);
|
||||
if (!root) return;
|
||||
const media = matchMedia("(prefers-reduced-motion: reduce)");
|
||||
|
||||
@ -45,12 +45,18 @@ export function useSocialChat(channelId: string) {
|
||||
),
|
||||
[channelId],
|
||||
);
|
||||
const [messages, setMessages] = useLocalState<SocialChatMessage[]>(
|
||||
`chat:${channelId}`,
|
||||
seeds,
|
||||
);
|
||||
// Keep transcript in memory — localStorage only for a short offline seed (avoids JSON thrash each poll).
|
||||
const [messages, setMessages] = useState<SocialChatMessage[]>(() => {
|
||||
const cached = loadJson<SocialChatMessage[]>(`chat:${channelId}`, seeds);
|
||||
return (cached?.length ? cached : seeds).slice(-200);
|
||||
});
|
||||
const [draft, setDraft] = useLocalState(`chat-draft:${channelId}`, "");
|
||||
const [nick, setNick] = useLocalState("nick", "游民");
|
||||
const persistTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
useEffect(() => {
|
||||
const cached = loadJson<SocialChatMessage[]>(`chat:${channelId}`, seeds);
|
||||
setMessages((cached?.length ? cached : seeds).slice(-200));
|
||||
}, [channelId, seeds]);
|
||||
const [status, setStatus] = useState<
|
||||
"connecting" | "online" | "offline" | "preview"
|
||||
>("connecting");
|
||||
@ -130,13 +136,14 @@ export function useSocialChat(channelId: string) {
|
||||
if (typeof response.seq === "number" && response.seq > lastSeq.current) {
|
||||
lastSeq.current = response.seq;
|
||||
}
|
||||
if (lastSeq.current > 0) {
|
||||
// Only ack read when we actually received new rows (avoid empty-poll spam)
|
||||
if (items.length && lastSeq.current > 0) {
|
||||
void socialApi
|
||||
.postNote(channelId, "read", lastSeq.current)
|
||||
.catch(() => undefined);
|
||||
}
|
||||
setStatus(items.length || lastSeq.current ? "online" : "preview");
|
||||
void beatPresence();
|
||||
if (mode === "full") void beatPresence();
|
||||
} catch {
|
||||
if (!cancelled) setStatus("offline");
|
||||
} finally {
|
||||
@ -144,16 +151,16 @@ export function useSocialChat(channelId: string) {
|
||||
}
|
||||
};
|
||||
|
||||
// bootstrap: full pull then realtime
|
||||
lastSeq.current = maxSeq(
|
||||
loadJson<SocialChatMessage[]>(`chat:${channelId}`, seeds),
|
||||
);
|
||||
oldestSeq.current = minSeq(
|
||||
loadJson<SocialChatMessage[]>(`chat:${channelId}`, seeds),
|
||||
);
|
||||
// bootstrap: full pull then realtime; poll only as WS fallback
|
||||
const cached = loadJson<SocialChatMessage[]>(`chat:${channelId}`, seeds);
|
||||
lastSeq.current = maxSeq(cached);
|
||||
oldestSeq.current = minSeq(cached);
|
||||
void refresh("full");
|
||||
const timer = setInterval(() => void refresh("since"), 12000);
|
||||
const presenceTimer = setInterval(() => void beatPresence(), 20000);
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = setInterval(
|
||||
() => void refresh("since"),
|
||||
18000,
|
||||
);
|
||||
const presenceTimer = setInterval(() => void beatPresence(), 30000);
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) {
|
||||
void refresh("since");
|
||||
@ -192,21 +199,44 @@ export function useSocialChat(channelId: string) {
|
||||
}
|
||||
},
|
||||
);
|
||||
if (cancelled) connection?.disconnect();
|
||||
else stop = connection?.disconnect || null;
|
||||
if (cancelled) {
|
||||
connection?.disconnect();
|
||||
return;
|
||||
}
|
||||
stop = connection?.disconnect || null;
|
||||
// WS healthy → stop dual polling; keep presence + visibility refresh
|
||||
if (connection && pollTimer) {
|
||||
clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
mounted.current = false;
|
||||
clearInterval(timer);
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
clearInterval(presenceTimer);
|
||||
stop?.();
|
||||
if (typingTimer.current) clearTimeout(typingTimer.current);
|
||||
if (persistTimer.current) clearTimeout(persistTimer.current);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
}, [channelId, seeds, setMessages]);
|
||||
}, [channelId, seeds]);
|
||||
|
||||
// Debounced offline seed (last 80) — not every merge
|
||||
useEffect(() => {
|
||||
if (persistTimer.current) clearTimeout(persistTimer.current);
|
||||
persistTimer.current = setTimeout(() => {
|
||||
const keep = messages
|
||||
.filter((m) => m.delivery !== "demo")
|
||||
.slice(-80);
|
||||
if (keep.length) saveJson(`chat:${channelId}`, keep);
|
||||
}, 1500);
|
||||
return () => {
|
||||
if (persistTimer.current) clearTimeout(persistTimer.current);
|
||||
};
|
||||
}, [channelId, messages]);
|
||||
|
||||
const mergeOne = useCallback(
|
||||
(saved: SocialChatMessage) => {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user