Ship social live UX gates, hide no-face roster avatars, and slim join profile.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-05 12:48:49 +08:00
parent 613f639952
commit ae6dba026e
35 changed files with 1511 additions and 221 deletions

View File

@ -20,6 +20,28 @@ class ModuleIn(BaseModel):
note: str | None = Field(default=None, max_length=1000)
class SocialLiveIn(BaseModel):
"""游民社区实时 UX 超级兜底 — 不限于下列键,可继续扩展。"""
presenceEnabled: bool | None = None
presenceStrip: bool | None = None
presenceCityScope: bool | None = None
discoveryAutoRefresh: bool | None = None
discoveryRefreshSec: int | None = Field(default=None, ge=15, le=300)
configHotReloadToast: bool | None = None
offlineFallbackShell: bool | None = None
hideNoFaceAvatar: bool | None = None
livenessGate: bool | None = None
trackLiveEvents: bool | None = None
chatPresencePill: bool | None = None
mapLivePins: bool | None = None
joinPriceLive: bool | None = None
onlineCountBadge: bool | None = None
softStatusSync: bool | None = None
configVersionChip: bool | None = None
trialLive: bool | None = None
presenceHeartbeatSec: int | None = Field(default=None, ge=10, le=120)
class FlagsIn(BaseModel):
payEnabled: bool | None = None
socialFollow: bool | None = None
@ -29,6 +51,7 @@ class FlagsIn(BaseModel):
joinGroupWechat: bool | None = None
socialTrialEnabled: bool | None = None
socialAvatarFaceCheck: bool | None = None
socialLive: SocialLiveIn | None = None
adsenseEnabled: bool | None = None
adsenseClientId: str | None = Field(default=None, max_length=64, pattern=r"^(ca-pub-[0-9]+)?$")
adsensePublisherId: str | None = Field(default=None, max_length=64, pattern=r"^(pub-[0-9]+)?$")

View File

@ -95,6 +95,50 @@ def _social_trial(raw: Any) -> dict[str, Any]:
return base
DEFAULT_SOCIAL_LIVE: dict[str, Any] = {
"presenceEnabled": True,
"presenceStrip": True,
"presenceCityScope": True,
"discoveryAutoRefresh": True,
"discoveryRefreshSec": 45,
"configHotReloadToast": True,
"offlineFallbackShell": True,
"hideNoFaceAvatar": True,
"livenessGate": True,
"trackLiveEvents": True,
"chatPresencePill": True,
"mapLivePins": True,
"joinPriceLive": True,
"onlineCountBadge": True,
"softStatusSync": True,
"configVersionChip": False,
"trialLive": True,
"presenceHeartbeatSec": 25,
}
def _social_live(raw: Any) -> dict[str, Any]:
base = dict(DEFAULT_SOCIAL_LIVE)
if not isinstance(raw, dict):
return base
for k, default in DEFAULT_SOCIAL_LIVE.items():
if k not in raw or raw[k] is None:
continue
if isinstance(default, bool):
base[k] = bool(raw[k])
elif isinstance(default, int):
try:
n = int(raw[k])
except (TypeError, ValueError):
continue
if k.endswith("Sec"):
lo, hi = (15, 300) if k == "discoveryRefreshSec" else (10, 120)
base[k] = max(lo, min(hi, n))
else:
base[k] = max(0, n)
return base
def _vip_price_fen(raw: Any, fallback: int = 10) -> int:
try:
return max(0, int(raw))
@ -216,6 +260,7 @@ def read_weapp_switches() -> dict[str, Any]:
"adsenseSlotBlogEnd": str(flags_raw.get("adsenseSlotBlogEnd") or ""),
"socialAvatarFaceCheck": bool(flags_raw.get("socialAvatarFaceCheck")),
"socialTrialEnabled": flags_raw.get("socialTrialEnabled", True) is not False,
"socialLive": _social_live(flags_raw.get("socialLive")),
},
"copy": {
"homeBrand": str(copy_raw.get("homeBrand") or "nomadro"),
@ -291,6 +336,10 @@ def write_weapp_switches(patch: dict[str, Any]) -> dict[str, Any]:
flags["socialAvatarFaceCheck"] = bool(fp["socialAvatarFaceCheck"])
if "socialTrialEnabled" in fp:
flags["socialTrialEnabled"] = bool(fp["socialTrialEnabled"])
if "socialLive" in fp and fp["socialLive"] is not None:
prev = flags.get("socialLive") if isinstance(flags.get("socialLive"), dict) else {}
incoming = fp["socialLive"] if isinstance(fp["socialLive"], dict) else {}
flags["socialLive"] = _social_live({**prev, **incoming})
for ak in (
"adsenseClientId",
"adsensePublisherId",

View File

@ -160,11 +160,20 @@ def health() -> dict[str, Any]:
# —— roster ——
def _face_ok_raw(raw: Any) -> bool:
return raw is True or raw == 1 or str(raw).lower() in {"1", "true", "yes"}
def _roster_from_rec(r: dict[str, Any], *, public: bool = False) -> dict[str, Any]:
status = (r.get("status") or "online").strip() or "online"
skills = r.get("skills") or ""
intents = r.get("intents") or ""
tags = [t.strip() for t in skills.replace(",", ",").replace("、", ",").split(",") if t.strip()][:8]
face_ok = _face_ok_raw(r.get("face_ok"))
avatar = str(r.get("avatar") or "").strip()
# Public surfaces never leak no-face album photos — placeholder only.
if public and not face_ok:
avatar = ""
item: dict[str, Any] = {
"guestId": r.get("guest_id") or "",
"email": r.get("email") or "",
@ -173,7 +182,7 @@ def _roster_from_rec(r: dict[str, Any], *, public: bool = False) -> dict[str, An
"city": r.get("city") or "",
"skills": skills,
"bio": r.get("bio") or "",
"avatar": r.get("avatar") or "",
"avatar": avatar,
"gender": r.get("gender") or "",
"intents": intents,
"availability": r.get("availability") or "",
@ -182,7 +191,7 @@ def _roster_from_rec(r: dict[str, Any], *, public: bool = False) -> dict[str, An
"updatedAt": r.get("updated_at") or "",
"online": status in {"online", "here", "available"},
"tags": tags,
"faceOk": bool(r.get("face_ok")),
"faceOk": face_ok,
"livenessStatus": r.get("liveness_status") or "none",
"livenessAt": r.get("liveness_at") or "",
"livenessVideoUrl": r.get("liveness_video_url") or "",
@ -478,14 +487,9 @@ def list_discovery_roster(
continue
if not (r.get("name") or "").strip():
continue
# Dating / 约会: no face in avatar → never show
# Dating / 约会: no face in avatar → never show the person
if require_face:
face_raw = r.get("face_ok")
face_ok = face_raw is True or face_raw == 1 or str(face_raw).lower() in {
"1",
"true",
"yes",
}
face_ok = _face_ok_raw(r.get("face_ok"))
avatar = str(r.get("avatar") or "").strip()
if not face_ok:
continue
@ -585,7 +589,10 @@ def channel_seq(channel_id: str) -> int:
def _avatars_for_guests(guest_ids: list[str]) -> dict[str, str]:
"""Batch roster.avatar for chat bubbles (guest_id → url)."""
"""Batch roster.avatar for chat bubbles (guest_id → url).
No-face album photos are blanked — chat never paints them.
"""
ids = sorted({str(g or "").strip() for g in guest_ids if str(g or "").strip()})
if not ids:
return {}
@ -601,8 +608,10 @@ def _avatars_for_guests(guest_ids: list[str]) -> dict[str, str]:
rows = []
for r in rows:
gid = str(r.get("guest_id") or "").strip()
if not gid or not _face_ok_raw(r.get("face_ok")):
continue
av = str(r.get("avatar") or "").strip()[:500]
if gid and av:
if av:
out[gid] = av
return out

View File

@ -74,6 +74,17 @@ class ReportIn(BaseModel):
class PresenceIn(BaseModel):
nick: str = Field(default="游民", max_length=48)
city: str = Field(default="", max_length=64)
avatar: str = Field(default="", max_length=500)
softStatusSync: bool = False
class SocialPresenceIn(BaseModel):
"""Global / city who's-online heartbeat (not tied to a chat channel)."""
nick: str = Field(default="游民", max_length=48)
city: str = Field(default="", max_length=64)
avatar: str = Field(default="", max_length=500)
softStatusSync: bool = True
class NoteIn(BaseModel):
@ -363,7 +374,44 @@ async def post_presence(
guest: str | None = Query(default=None),
):
peer = _guest(x_social_guest_id, guest)
return store.touch_presence(channel_id, peer, body.nick)
return store.touch_presence(
channel_id,
peer,
body.nick,
city=body.city,
avatar=body.avatar,
soft_status_sync=bool(body.softStatusSync),
)
@router.post("/roster/presence")
async def post_roster_presence(
body: SocialPresenceIn,
x_social_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
"""Global social presence heartbeat — powers「谁在线」strip + city count."""
peer = _guest(x_social_guest_id, guest)
return store.touch_presence(
store.SOCIAL_GLOBAL_ROOM,
peer,
body.nick,
city=body.city,
avatar=body.avatar,
soft_status_sync=bool(body.softStatusSync),
)
@router.get("/roster/online")
def get_roster_online(
city: str = Query(default=""),
limit: int = Query(default=48, ge=1, le=64),
x_social_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
"""Who's online now (TTL presence). Offline clients get empty + UI fallback."""
_ = _guest(x_social_guest_id, guest)
return store.list_social_online(city=(city or "").strip(), limit=limit)
@router.post("/upload")

View File

@ -550,37 +550,112 @@ def get_file(file_id: str) -> dict[str, Any] | None:
# Element-like soft presence (TTL heartbeat; UI-agnostic)
# Rooms: chat channel ids + global "social:global" + optional "social:city:<slug>"
_PRESENCE: dict[str, dict[str, dict[str, Any]]] = {}
_PRESENCE_TTL_SEC = 45
SOCIAL_GLOBAL_ROOM = "social:global"
def _city_room(city: str) -> str:
slug = "".join((city or "").strip().lower().split())[:48]
return f"social:city:{slug}" if slug else SOCIAL_GLOBAL_ROOM
def touch_presence(
channel_id: str, guest_id: str, nick: str = ""
channel_id: str,
guest_id: str,
nick: str = "",
*,
city: str = "",
avatar: str = "",
soft_status_sync: bool = False,
) -> dict[str, Any]:
"""Soft presence: process-local TTL map (fast path). PB ch_meta.presence is best-effort mirror."""
now = time.time()
room = _PRESENCE.setdefault(channel_id, {})
room[guest_id] = {
"guestId": guest_id,
"nick": (nick or "游民").strip()[:48] or "游民",
"at": now,
}
# prune
dead = [gid for gid, meta in room.items() if now - float(meta["at"]) > _PRESENCE_TTL_SEC]
for gid in dead:
room.pop(gid, None)
peers = online_peers(channel_id)
rooms = [channel_id or SOCIAL_GLOBAL_ROOM]
if channel_id != SOCIAL_GLOBAL_ROOM:
rooms.append(SOCIAL_GLOBAL_ROOM)
city_slug = "".join((city or "").strip().lower().split())
if city_slug:
rooms.append(_city_room(city))
for room_id in rooms:
room = _PRESENCE.setdefault(room_id, {})
room[guest_id] = {
"guestId": guest_id,
"nick": (nick or "游民").strip()[:48] or "游民",
"city": (city or "").strip()[:64],
"avatar": (avatar or "").strip()[:500],
"at": now,
}
dead = [
gid
for gid, meta in room.items()
if now - float(meta["at"]) > _PRESENCE_TTL_SEC
]
for gid in dead:
room.pop(gid, None)
peers = online_peers(channel_id or SOCIAL_GLOBAL_ROOM)
city_peers = online_peers(_city_room(city)) if city_slug else peers
if soft_status_sync:
try:
from social_svc import pb_data
row = pb_data.get_roster(guest_id)
cur = str((row or {}).get("status") or "")
if row and cur in {"", "offline", "away"}:
# Full merge — upsert_roster replaces fields; never send a partial stub.
pb_data.upsert_roster(
guest_id,
{
**{
k: row.get(k)
for k in (
"name",
"title",
"city",
"phone",
"linktree",
"skills",
"bio",
"avatar",
"gender",
"intents",
"availability",
"lookingFor",
"relationship",
"education",
"graduation",
"wechat",
"email",
"discoverable",
)
if row.get(k) is not None
},
"status": "online",
"city": city or row.get("city") or "",
"avatar": avatar or row.get("avatar") or "",
"name": row.get("name") or nick or "游民",
},
)
except Exception:
pass
try:
from social_svc import pb_data
from nomadro_pb import get_pb, pb_quote
pb_data.init_pb()
meta = get_pb().first(
pb_data.C_CHMETA, filter=f"channel_id={pb_quote(channel_id)}"
pb_data.C_CHMETA, filter=f"channel_id={pb_quote(channel_id or SOCIAL_GLOBAL_ROOM)}"
)
presence = {
p["guestId"]: {"nick": p["nick"], "at": now} for p in peers
p["guestId"]: {"nick": p["nick"], "at": now, "city": p.get("city") or ""}
for p in peers
}
cid = channel_id or SOCIAL_GLOBAL_ROOM
if meta:
get_pb().update(
pb_data.C_CHMETA, meta["id"], {"presence": presence, "updated_at": _now()}
@ -589,7 +664,7 @@ def touch_presence(
get_pb().create(
pb_data.C_CHMETA,
{
"channel_id": channel_id,
"channel_id": cid,
"seq": 0,
"pins": [],
"presence": presence,
@ -598,7 +673,13 @@ def touch_presence(
)
except Exception:
pass
return {"channelId": channel_id, "online": len(peers), "peers": peers}
return {
"channelId": channel_id or SOCIAL_GLOBAL_ROOM,
"online": len(peers),
"peers": peers,
"cityOnline": len(city_peers),
"cityPeers": city_peers[:24],
}
def online_peers(channel_id: str) -> list[dict[str, Any]]:
@ -609,11 +690,34 @@ def online_peers(channel_id: str) -> list[dict[str, Any]]:
if now - float(meta["at"]) > _PRESENCE_TTL_SEC:
room.pop(gid, None)
continue
out.append({"guestId": gid, "nick": meta.get("nick") or "游民"})
out.append(
{
"guestId": gid,
"nick": meta.get("nick") or "游民",
"city": meta.get("city") or "",
"avatar": meta.get("avatar") or "",
}
)
out.sort(key=lambda p: p["nick"])
return out[:64]
def list_social_online(*, city: str = "", limit: int = 48) -> dict[str, Any]:
"""Public who's-online for social shell (global + optional city)."""
city_slug = "".join((city or "").strip().lower().split())
global_peers = online_peers(SOCIAL_GLOBAL_ROOM)
city_peers = online_peers(_city_room(city)) if city_slug else []
lim = max(1, min(int(limit or 48), 64))
return {
"ok": True,
"online": len(global_peers),
"peers": global_peers[:lim],
"city": (city or "").strip()[:64],
"cityOnline": len(city_peers),
"cityPeers": city_peers[:lim],
}
def report_message(
channel_id: str, msg_id: str, guest_id: str, reason: str = ""
) -> dict[str, Any]:
@ -667,6 +771,10 @@ def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]:
intents = (r["intents"] if "intents" in keys else "") or ""
skills = r["skills"] or ""
status = ((r["status"] if "status" in keys else "") or "online").strip() or "online"
face_ok = bool(int(r["face_ok"] if "face_ok" in keys and r["face_ok"] is not None else 0))
avatar = (r["avatar"] if "avatar" in keys else "") or ""
if public and not face_ok:
avatar = ""
item: dict[str, Any] = {
"guestId": r["guest_id"],
"name": r["name"],
@ -674,7 +782,7 @@ def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]:
"city": r["city"] or "",
"skills": skills,
"bio": r["bio"] or "",
"avatar": (r["avatar"] if "avatar" in keys else "") or "",
"avatar": avatar,
"gender": (r["gender"] if "gender" in keys else "") or "",
"intents": intents,
"availability": (r["availability"] if "availability" in keys else "") or "",
@ -695,7 +803,7 @@ def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]:
"wechat": (r["wechat"] if "wechat" in keys else "") or "",
"discoverable": int(r["discoverable"] if "discoverable" in keys and r["discoverable"] is not None else 1),
"onboardedAt": (r["onboarded_at"] if "onboarded_at" in keys else "") or "",
"faceOk": bool(int(r["face_ok"] if "face_ok" in keys and r["face_ok"] is not None else 0)),
"faceOk": face_ok,
"livenessStatus": (r["liveness_status"] if "liveness_status" in keys else "") or "none",
"livenessAt": (r["liveness_at"] if "liveness_at" in keys else "") or "",
"livenessVideoUrl": (r["liveness_video_url"] if "liveness_video_url" in keys else "") or "",
@ -703,7 +811,7 @@ def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]:
)
else:
item["linktree"] = r["linktree"] or ""
item["faceOk"] = bool(int(r["face_ok"] if "face_ok" in keys and r["face_ok"] is not None else 0))
item["faceOk"] = face_ok
item["livenessStatus"] = (r["liveness_status"] if "liveness_status" in keys else "") or "none"
return item

View File

@ -24,6 +24,8 @@ type SwitchesCfg = {
adsenseSlotBlogMid?: string
adsenseSlotBlogEnd?: string
socialTrialEnabled?: boolean
socialAvatarFaceCheck?: boolean
socialLive?: SocialLiveCfg
}
copy: {
homeBrand: string
@ -54,15 +56,60 @@ type SwitchesCfg = {
updatedAt?: string
}
type TabKey = 'pages' | 'flags' | 'vip' | 'copy'
type SocialLiveCfg = {
presenceEnabled?: boolean
presenceStrip?: boolean
presenceCityScope?: boolean
discoveryAutoRefresh?: boolean
discoveryRefreshSec?: number
configHotReloadToast?: boolean
offlineFallbackShell?: boolean
hideNoFaceAvatar?: boolean
livenessGate?: boolean
trackLiveEvents?: boolean
chatPresencePill?: boolean
mapLivePins?: boolean
joinPriceLive?: boolean
onlineCountBadge?: boolean
softStatusSync?: boolean
configVersionChip?: boolean
trialLive?: boolean
presenceHeartbeatSec?: number
}
type TabKey = 'pages' | 'flags' | 'live' | 'vip' | 'copy'
const TABS: Array<{ key: TabKey; label: string }> = [
{ key: 'pages', label: '页面' },
{ key: 'flags', label: '功能' },
{ key: 'live', label: '实时社区' },
{ key: 'vip', label: 'VIP 区块' },
{ key: 'copy', label: '文案' },
]
const SOCIAL_LIVE_FLAGS: Array<{
key: keyof SocialLiveCfg
label: string
desc: string
}> = [
{ key: 'presenceEnabled', label: '谁在线心跳', desc: '全局 presence 心跳;关则不报在线' },
{ key: 'presenceStrip', label: '在线条', desc: '壳层展示谁在线 / 人数' },
{ key: 'presenceCityScope', label: '同城在线', desc: '优先展示同城在线人数' },
{ key: 'discoveryAutoRefresh', label: '发现自动刷新', desc: '大厅 / 约会列表定时拉新' },
{ key: 'configHotReloadToast', label: '配置热更新 Toast', desc: '后台改开关后前端提示' },
{ key: 'offlineFallbackShell', label: '离线超级兜底壳', desc: '断网不白屏,展示本地兜底' },
{ key: 'hideNoFaceAvatar', label: '无人脸头像隐藏', desc: '无 faceOk 的头像不展示' },
{ key: 'livenessGate', label: '真人自拍闸', desc: '约会 / 畅聊要求自拍核验' },
{ key: 'trackLiveEvents', label: '实时埋点', desc: '在线心跳 / 配置热更 / 刷新上报' },
{ key: 'chatPresencePill', label: '聊天在线 pill', desc: '群聊顶栏显示在线人数' },
{ key: 'mapLivePins', label: '地图人钉实时', desc: '地图 pins 跟发现列表热刷新' },
{ key: 'joinPriceLive', label: '加入价实时', desc: '弹窗打开时强制拉最新价' },
{ key: 'onlineCountBadge', label: '在线人数角标', desc: '在线条显示数字' },
{ key: 'softStatusSync', label: '心跳同步在线状态', desc: '心跳把 roster 标为 online' },
{ key: 'configVersionChip', label: '配置版本 chip', desc: '弱提示当前 remote-config 版本' },
{ key: 'trialLive', label: '尝鲜限额实时', desc: '跟随后台 trial 配置;关则用离线种子' },
]
const PAGE_MODS = [
{ key: 'home', label: '首页', ico: '⌂', desc: '门户首页模块' },
{ key: 'nav', label: '出海导航', ico: '🧭', desc: '导航页入口' },
@ -285,6 +332,16 @@ export default function Switches() {
{ key: 'payEnabled', label: '支付总开关', desc: '关闭后隐藏付费 CTA' },
{ key: 'socialFollow', label: '关注引导', desc: '公众号 / X 关注弹窗' },
{ key: 'offlineBadge', label: '离线角标', desc: '展示「本地数据」提示' },
{
key: 'socialAvatarFaceCheck',
label: '头像人脸检测',
desc: '关=静默检测不提示;开=强制正面照文案',
},
{
key: 'socialTrialEnabled',
label: '尝鲜限额',
desc: '未完整加入时的聊天/约会配额',
},
{
key: 'adsenseEnabled',
label: 'AdSense 展示',
@ -358,6 +415,97 @@ export default function Switches() {
</section>
) : null}
{tab === 'live' ? (
<section className="com-panel">
<h2>实时社区 · UX 超级兜底</h2>
<p className="com-panel-desc">
谁在线、热更新、离线壳、埋点、发现刷新等。门户 SSE 热推;不限于下列开关,可持续扩展。
</p>
<div className="com-flag-list">
{SOCIAL_LIVE_FLAGS.map((f) => {
const defaults: Record<string, boolean> = {
presenceEnabled: true,
presenceStrip: true,
presenceCityScope: true,
discoveryAutoRefresh: true,
configHotReloadToast: true,
offlineFallbackShell: true,
hideNoFaceAvatar: true,
livenessGate: true,
trackLiveEvents: true,
chatPresencePill: true,
mapLivePins: true,
joinPriceLive: true,
onlineCountBadge: true,
softStatusSync: true,
configVersionChip: false,
trialLive: true,
}
const raw = cfg.flags.socialLive?.[f.key]
const on =
typeof raw === 'boolean' ? raw : Boolean(defaults[f.key as string])
return (
<div key={f.key} className="com-flag-row">
<div>
<strong>{f.label}</strong>
<p>{f.desc}</p>
</div>
<Switch
checked={on}
disabled={busy}
label={f.label}
onChange={(v) =>
void patch(
{ flags: { socialLive: { [f.key]: v } } },
`${f.label}已${v ? '开启' : '关闭'}`,
)
}
/>
</div>
)
})}
<div className="com-form-grid" style={{ marginTop: 12 }}>
<label className="com-field">
<span>发现刷新间隔(秒)</span>
<input
type="number"
min={15}
max={300}
disabled={busy}
defaultValue={Number(cfg.flags.socialLive?.discoveryRefreshSec) || 45}
onBlur={(e) => {
const n = Math.max(15, Math.min(300, Number(e.target.value) || 45))
if (n === Number(cfg.flags.socialLive?.discoveryRefreshSec)) return
void patch(
{ flags: { socialLive: { discoveryRefreshSec: n } } },
`发现刷新 → ${n}s`,
)
}}
/>
</label>
<label className="com-field">
<span>心跳周期(秒)</span>
<input
type="number"
min={10}
max={120}
disabled={busy}
defaultValue={Number(cfg.flags.socialLive?.presenceHeartbeatSec) || 25}
onBlur={(e) => {
const n = Math.max(10, Math.min(120, Number(e.target.value) || 25))
if (n === Number(cfg.flags.socialLive?.presenceHeartbeatSec)) return
void patch(
{ flags: { socialLive: { presenceHeartbeatSec: n } } },
`心跳周期 → ${n}s`,
)
}}
/>
</label>
</div>
</div>
</section>
) : null}
{tab === 'vip' ? (
<>
<section className="com-panel">

View File

@ -259,6 +259,11 @@ export default function AdminConfigPage() {
label: "头像人脸检测",
hint: "游民社区上传头像是否强制正脸检测;关=任意图可传。SSE/WS 热更新前端与 social 上传闸。默认关。",
},
{
key: "socialTrialEnabled" as const,
label: "尝鲜限额",
hint: "未完整加入时的聊天/约会配额。细项与实时 UX 见 admin.nomadro.com → 动态开关 → 实时社区。",
},
] as const
).map(({ key, label, hint }) => (
<label

View File

@ -14,6 +14,7 @@ import "@social/app/vivid.css";
import "@social/app/h5.css";
import "@social/app/blog.css";
import "@social/app/discovery.css";
import "@social/app/live.css";
import SocialExperience from "@social/components/SocialExperience";
export const metadata = {

View File

@ -99,6 +99,71 @@ export type TtPlatformConfig = {
bookContent: TtBookContent;
};
/**
* 游民社区「实时 UX 超级兜底」开关簇。
* 后台可动态改;门户 SSE/轮询热更新;客户端有离线默认值。
* 不限于下列键 — 新增实时能力继续往这里加。
*/
export type SocialLiveFlags = {
/** 1 全局谁在线心跳 */
presenceEnabled: boolean;
/** 2 壳层在线条 / 谁在线 */
presenceStrip: boolean;
/** 3 同城 scope 在线 */
presenceCityScope: boolean;
/** 4 发现列表自动刷新 */
discoveryAutoRefresh: boolean;
/** 5 发现刷新间隔(秒) */
discoveryRefreshSec: number;
/** 6 远程配置热更新 Toast */
configHotReloadToast: boolean;
/** 7 离线超级兜底壳(UI 永不白屏) */
offlineFallbackShell: boolean;
/** 8 无人脸头像不展示 */
hideNoFaceAvatar: boolean;
/** 9 约会真人自拍闸 */
livenessGate: boolean;
/** 10 实时埋点(在线/配置/刷新) */
trackLiveEvents: boolean;
/** 11 聊天在线人数 pill */
chatPresencePill: boolean;
/** 12 地图人钉实时刷新 */
mapLivePins: boolean;
/** 13 加入价跟随远程配置 */
joinPriceLive: boolean;
/** 14 在线人数角标 */
onlineCountBadge: boolean;
/** 15 心跳同步 roster.status=online */
softStatusSync: boolean;
/** 16 配置版本弱提示 chip */
configVersionChip: boolean;
/** 17 尝鲜限额实时跟随 */
trialLive: boolean;
/** 18 心跳周期(秒) */
presenceHeartbeatSec: number;
};
export const DEFAULT_SOCIAL_LIVE: SocialLiveFlags = {
presenceEnabled: true,
presenceStrip: true,
presenceCityScope: true,
discoveryAutoRefresh: true,
discoveryRefreshSec: 45,
configHotReloadToast: true,
offlineFallbackShell: true,
hideNoFaceAvatar: true,
livenessGate: true,
trackLiveEvents: true,
chatPresencePill: true,
mapLivePins: true,
joinPriceLive: true,
onlineCountBadge: true,
softStatusSync: true,
configVersionChip: false,
trialLive: true,
presenceHeartbeatSec: 25,
};
export type NomadroRemoteConfig = {
version: number;
updatedAt: string;
@ -154,6 +219,11 @@ export type NomadroRemoteConfig = {
* false 则关闭限额(仍建议保留加入漏斗)。
*/
socialTrialEnabled?: boolean;
/**
* 游民社区实时 UX 超级兜底(谁在线 / 热更新 / 离线壳 / 埋点…)。
* 不限于下列键;后台 Switches「实时社区」可改。
*/
socialLive?: SocialLiveFlags;
};
/**
* 受众分轨(.com 国际优先;中文用户特殊对待)。
@ -451,6 +521,7 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
adsenseEnabled: false,
socialAvatarFaceCheck: false,
socialTrialEnabled: true,
socialLive: { ...DEFAULT_SOCIAL_LIVE },
adsenseClientId: "",
adsensePublisherId: "",
adsenseSlotBlogMid: "",
@ -689,6 +760,72 @@ function asBool(v: unknown, fallback: boolean): boolean {
return typeof v === "boolean" ? v : fallback;
}
function asPosInt(v: unknown, fallback: number, min = 5, max = 600): number {
const n = Number(v);
if (!Number.isFinite(n)) return fallback;
return Math.min(max, Math.max(min, Math.round(n)));
}
export function mergeSocialLive(
base: SocialLiveFlags,
partial: Partial<SocialLiveFlags> | null | undefined,
): SocialLiveFlags {
const p = (partial || {}) as Partial<SocialLiveFlags>;
return {
presenceEnabled: asBool(p.presenceEnabled, base.presenceEnabled),
presenceStrip: asBool(p.presenceStrip, base.presenceStrip),
presenceCityScope: asBool(p.presenceCityScope, base.presenceCityScope),
discoveryAutoRefresh: asBool(
p.discoveryAutoRefresh,
base.discoveryAutoRefresh,
),
discoveryRefreshSec: asPosInt(
p.discoveryRefreshSec,
base.discoveryRefreshSec,
15,
300,
),
configHotReloadToast: asBool(
p.configHotReloadToast,
base.configHotReloadToast,
),
offlineFallbackShell: asBool(
p.offlineFallbackShell,
base.offlineFallbackShell,
),
hideNoFaceAvatar: asBool(p.hideNoFaceAvatar, base.hideNoFaceAvatar),
livenessGate: asBool(p.livenessGate, base.livenessGate),
trackLiveEvents: asBool(p.trackLiveEvents, base.trackLiveEvents),
chatPresencePill: asBool(p.chatPresencePill, base.chatPresencePill),
mapLivePins: asBool(p.mapLivePins, base.mapLivePins),
joinPriceLive: asBool(p.joinPriceLive, base.joinPriceLive),
onlineCountBadge: asBool(p.onlineCountBadge, base.onlineCountBadge),
softStatusSync: asBool(p.softStatusSync, base.softStatusSync),
configVersionChip: asBool(p.configVersionChip, base.configVersionChip),
trialLive: asBool(p.trialLive, base.trialLive),
presenceHeartbeatSec: asPosInt(
p.presenceHeartbeatSec,
base.presenceHeartbeatSec,
10,
120,
),
};
}
/** Resolve socialLive with offline seed — never throw / never undefined. */
export function resolveSocialLive(
config: NomadroRemoteConfig | null | undefined,
): SocialLiveFlags {
try {
return mergeSocialLive(
DEFAULT_SOCIAL_LIVE,
config?.flags?.socialLive || undefined,
);
} catch {
return { ...DEFAULT_SOCIAL_LIVE };
}
}
export function mergeRemoteConfig(
partial: Partial<NomadroRemoteConfig> | null | undefined,
): NomadroRemoteConfig {
@ -753,6 +890,10 @@ export function mergeRemoteConfig(
pf.socialTrialEnabled,
base.flags.socialTrialEnabled ?? true,
),
socialLive: mergeSocialLive(
base.flags.socialLive || DEFAULT_SOCIAL_LIVE,
(pf.socialLive || undefined) as Partial<SocialLiveFlags> | undefined,
),
},
audience: mergeAudienceConfig(base.audience, partial.audience),
copy: mergeCopy(base.copy, partial.copy),

View File

@ -0,0 +1,195 @@
/* Social Live — silent by default; float chip only when someone is online */
.social-live-shell {
z-index: 40;
display: flex;
flex-direction: column;
gap: 0;
pointer-events: none;
}
.social-live-shell > * {
pointer-events: auto;
}
/* Home: never steal sticky space under nav / hero brand */
.social-live-shell.is-home {
position: fixed;
left: 12px;
bottom: calc(76px + env(safe-area-inset-bottom, 0px));
right: auto;
top: auto;
width: auto;
max-width: min(72vw, 280px);
}
.social-live-shell:not(.is-home) {
position: sticky;
top: 0;
}
.social-live-offline {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
background: rgba(26, 18, 8, 0.92);
border: 1px solid rgba(245, 158, 11, 0.28);
border-radius: 12px;
color: #f8fafc;
margin: 8px 12px 0;
}
.social-live-shell.is-home .social-live-offline {
margin: 0 0 8px;
}
.social-live-offline strong {
display: block;
font-size: 0.8rem;
font-weight: 650;
}
.social-live-offline p {
margin: 1px 0 0;
font-size: 0.72rem;
color: #94a3b8;
line-height: 1.3;
}
.social-live-strip {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 5px 10px 5px 8px;
background: rgba(12, 12, 15, 0.72);
backdrop-filter: blur(12px);
border: 1px solid rgba(148, 163, 184, 0.14);
border-radius: 999px;
color: #e2e8f0;
font-size: 0.75rem;
width: fit-content;
margin: 8px 12px 0;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.28);
}
.social-live-strip.is-float,
.social-live-shell.is-home .social-live-strip {
margin: 0;
}
.social-live-strip strong {
font-weight: 600;
display: inline-flex;
align-items: center;
gap: 3px;
letter-spacing: 0.01em;
}
.social-live-count {
font-style: normal;
font-variant-numeric: tabular-nums;
color: #34d399;
font-weight: 700;
min-width: 0.9em;
}
.social-live-dot {
width: 7px;
height: 7px;
border-radius: 999px;
background: #64748b;
flex-shrink: 0;
}
.social-live-dot.is-ok {
background: #22c55e;
box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.2);
animation: social-live-pulse 2.2s ease-in-out infinite;
}
.social-live-dot.is-warn {
background: #f59e0b;
box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.18);
}
@keyframes social-live-pulse {
0%,
100% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(1.12);
opacity: 0.78;
}
}
.social-live-avs {
display: flex;
align-items: center;
margin-left: 2px;
}
.social-live-avs > * {
margin-left: -5px;
border-radius: 999px;
border: 1.5px solid #0c0c0f;
overflow: hidden;
}
.social-live-avs > *:first-child {
margin-left: 0;
}
.social-live-ver {
margin-left: 4px;
font-size: 0.65rem;
color: #64748b;
font-variant-numeric: tabular-nums;
}
.social-live-toast {
position: fixed;
left: 50%;
bottom: calc(72px + env(safe-area-inset-bottom, 0px));
transform: translateX(-50%);
z-index: 80;
max-width: min(92vw, 360px);
padding: 10px 16px;
border-radius: 12px;
background: #111827;
border: 1px solid rgba(52, 211, 153, 0.35);
color: #ecfdf5;
font-size: 0.85rem;
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
animation: social-live-toast-in 0.28s ease-out;
}
@keyframes social-live-toast-in {
from {
opacity: 0;
transform: translateX(-50%) translateY(8px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
@media (min-width: 901px) {
.social-live-shell.is-home {
bottom: 28px;
left: 24px;
}
.social-live-toast {
bottom: 28px;
}
}
@media (prefers-reduced-motion: reduce) {
.social-live-dot.is-ok,
.social-live-toast {
animation: none;
}
}

View File

@ -48,7 +48,8 @@ function cityKey(city: string) {
}
export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
const roster = useDiscoveryRoster();
// 想见的人:无人脸检测通过的头像一律不进列表(含无 faceOk / 空头像)
const roster = useDiscoveryRoster({ requireFace: true });
const likes = useRosterLikes();
const [filter, setFilter] = useState<FilterId>("all");
const [highlightId, setHighlightId] = useState<string | null>(null);
@ -155,7 +156,13 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
<div className="social-people-bar reveal">
<div className="social-people-bar-avs" aria-hidden>
{online.slice(0, 6).map((m) => (
<SocialAvatar key={m.id} src={m.avatar} size={30} lazy />
<SocialAvatar
key={m.id}
src={m.avatar}
size={30}
lazy
faceOk={m.faceOk}
/>
))}
</div>
<p>
@ -252,7 +259,12 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
onClick={() => setHighlightId(m.id)}
>
<span className="social-people-chip-ava">
<SocialAvatar src={m.avatar} size={52} lazy />
<SocialAvatar
src={m.avatar}
size={52}
lazy
faceOk={m.faceOk}
/>
{m.online ? <i aria-hidden /> : null}
{likes[m.id] ? (
<em className="social-chip-heart" aria-hidden>

View File

@ -48,6 +48,7 @@ import {
trialPaywallHint,
} from "@social/lib/socialTrial";
import { ensureGuestNick } from "@social/lib/guestNick";
import { getSocialLive } from "@social/lib/socialLive";
import { useSocialConfig } from "./SocialExperience";
import JoinPayModal from "./JoinPayModal";
@ -544,13 +545,15 @@ export function Conversation({
{muted ? "🔕" : "🔔"}
</button>
<ShareButton path={socialPath("/chat")} title={channel.topic} />
<span className="social-chat-presence-pill" suppressHydrationWarning>
{hydrated && chat.online > 0
? `${chat.online} ${socialTx("在线")}`
: chat.status === "online"
? socialTx("在线")
: STATUS[chat.status]}
</span>
{getSocialLive(config).chatPresencePill ? (
<span className="social-chat-presence-pill" suppressHydrationWarning>
{hydrated && chat.online > 0
? `${chat.online} ${socialTx("在线")}`
: chat.status === "online"
? socialTx("在线")
: STATUS[chat.status]}
</span>
) : null}
</div>
</div>

View File

@ -14,7 +14,6 @@ import {
Camera,
Check,
Globe2,
MapPin,
Send,
} from "lucide-react";
import SiteShell from "./SiteShell";
@ -25,6 +24,7 @@ import { PageIntro } from "./SocialUI";
import { useSocialConfig } from "./SocialExperience";
import { socialApi } from "@social/lib/api";
import { isSocialAvatarFaceCheckEnabled } from "@social/lib/avatarFaceCheck";
import { getSocialLive } from "@social/lib/socialLive";
import { useCaptureCapability } from "@social/lib/useCaptureCapability";
import {
getLivenessState,
@ -39,13 +39,11 @@ import {
} from "@social/lib/livenessGate";
import {
JOIN_AVAILABILITY_OPTIONS,
JOIN_EDUCATION_OPTIONS,
JOIN_GENDER_OPTIONS,
JOIN_INTENT_OPTIONS,
JOIN_LIVENESS_RETURN,
JOIN_PROFILE_RETURN,
JOIN_RELATIONSHIP_OPTIONS,
JOIN_STATUS_OPTIONS,
isJoinPaid,
clearJoinProfileDone,
isJoinProfileDone,
@ -299,6 +297,8 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
const { locale } = useSocialI18n();
const config = useSocialConfig();
const faceCheckOn = isSocialAvatarFaceCheckEnabled(config);
const liveUx = getSocialLive(config);
const livenessOn = liveUx.livenessGate;
const capture = useCaptureCapability();
const nameRef = useRef<HTMLInputElement>(null);
const avatarInputRef = useRef<HTMLInputElement>(null);
@ -326,20 +326,13 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
};
const avatarHint = (() => {
if (avatarBusy) {
return faceCheckOn
? socialTx("正在处理头像…")
: socialTx("上传中…");
}
if (!capture.ready) return socialTx("检测设备中…");
if (avatarBusy) return socialTx("上传中…");
if (!capture.ready) return socialTx("准备中…");
if (liveOk && (draft.avatar || "").trim()) {
return socialTx("头像和自拍都好了,可以去认识朋友");
}
if (liveOk) {
return faceCheckOn
? socialTx("自拍已通过。请再选一张照片当头像(自拍不算头像)")
: socialTx("自拍已通过。请上传一张头像");
}
if (liveOk) return socialTx("请上传一张头像");
// Face-copy only when admin switch is on — otherwise never mention 人脸/正面.
if (faceCheckOn && faceOk) {
return socialTx("照片看起来不错。再拍张自拍,确认是你本人");
}
@ -431,24 +424,23 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
saveJson("roster", { ...roster, avatar: url });
return next;
});
// faceOk is server-side only for display gates; never lecture the user unless switch on.
if (uploaded.faceOk) {
markFaceOk();
setFaceOk(true);
setAvatarErr("");
} else {
clearFaceOk();
setFaceOk(false);
setAvatarErr(
faceCheckOn
? socialTx("没看清脸,请上传一张清晰的正面照")
: socialTx(
"没看清脸:头像已保存,但约会里暂不展示。请换一张正面照。",
),
);
if (faceCheckOn) {
setAvatarErr(socialTx("没看清脸,请上传一张清晰的正面照"));
} else {
setAvatarErr("");
}
}
if (uploaded.faceOk) setAvatarErr("");
requestAnimationFrame(() => URL.revokeObjectURL(localUrl));
// After face photo OK → nudge live capture (do not auto-open camera)
if (
faceCheckOn &&
uploaded.faceOk &&
!isLivenessVerified() &&
capture.mode === "live-modal"
@ -460,11 +452,18 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
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("头像上传失败"));
// Soft-upload never throws face errors; hard gate (switch on) may.
const facey =
/脸|人脸|正面|face|liveness|selfie/i.test(raw);
if (facey && !faceCheckOn) {
setAvatarErr(socialTx("头像上传失败"));
} else {
const msg =
raw && !/^upload failed|^no url|^上传失败 HTTP/i.test(raw)
? socialTx(raw)
: socialTx("头像上传失败");
setAvatarErr(msg || socialTx("头像上传失败"));
}
} finally {
setAvatarBusy(false);
}
@ -526,26 +525,14 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
nameRef.current?.focus();
return;
}
if (!draft.city.trim()) {
setErr(socialTx("请填写当前城市,方便同城推荐"));
return;
}
if (!draft.intents.length) {
setErr(socialTx("请至少选一个「想认识 / 想做什么」"));
return;
}
if (!draft.skills.trim()) {
setErr(socialTx("请写几个技能或兴趣,用逗号分开"));
return;
}
const avatarUrl =
draft.avatar.startsWith("blob:") ? "" : draft.avatar.trim();
if (!avatarUrl) {
setErr(
faceCheckOn
? socialTx("请先上传一张头像")
: socialTx("请先上传头像"),
);
setErr(socialTx("请先上传头像"));
return;
}
if (faceCheckOn && !faceOk && !isFaceOk()) {
@ -639,7 +626,6 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
};
const summaryName = draft.name.trim() || socialTx("你的名字");
const summaryCity = draft.city.trim() || socialTx("城市待写");
const summaryTitle = draft.title.trim() || socialTx("职业待写");
const summaryBio =
draft.bio.trim() || socialTx("自我介绍会出现在这里");
@ -652,11 +638,6 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
JOIN_RELATIONSHIP_OPTIONS.find((opt) => opt.value === draft.relationship)?.[
locale === "en" ? "labelEn" : "labelZh"
] || "";
const summarySkills = draft.skills
.split(/[,,、]/)
.map((s) => s.trim())
.filter(Boolean)
.slice(0, 5);
const summaryIntents = draft.intents
.map(
(id) =>
@ -668,9 +649,9 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
const filled = [
draft.name,
draft.avatar && !draft.avatar.startsWith("blob:") ? draft.avatar : "",
draft.city,
draft.title,
draft.bio,
draft.intents.length ? "1" : "",
].filter((v) => v.trim()).length;
return (
@ -721,23 +702,12 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
<p className="social-join-live-kicker">{socialTx("实时预览")}</p>
<h2 className="social-join-live-name">{summaryName}</h2>
<p className="social-join-live-title">{summaryTitle}</p>
<p className="social-join-live-city">
<MapPin size={13} aria-hidden />
{summaryCity}
</p>
{(summaryGender && draft.gender) || (summaryRel && draft.relationship) ? (
<div className="social-join-live-meta">
{draft.gender ? <span>{summaryGender}</span> : null}
{draft.relationship ? <span>{summaryRel}</span> : null}
</div>
) : null}
{summarySkills.length ? (
<div className="social-join-live-tags">
{summarySkills.map((skill) => (
<span key={skill}>{skill}</span>
))}
</div>
) : null}
{summaryIntents.length ? (
<div className="social-join-live-tags is-intent">
{summaryIntents.map((item) => (
@ -822,7 +792,7 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
{avatarErr}
</p>
) : null}
{faceCheckOn && faceOk && !liveOk ? (
{livenessOn && faceOk && !liveOk ? (
<div className="social-join-liveness-banner" role="status">
<p>
{socialTx(
@ -865,7 +835,7 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
{socialTx("手机拍照上传")}
</button>
) : null}
{faceCheckOn &&
{livenessOn &&
faceOk &&
!liveOk &&
capture.mode === "live-modal" ? (
@ -919,35 +889,9 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
locale={locale}
onChange={(value) => update("relationship", value)}
/>
<label className="social-join-span-2">
{socialTx("此刻在哪座城市")}
<span className="social-join-req">*</span>
<input
required
maxLength={80}
autoComplete="address-level2"
placeholder={socialTx("清迈、里斯本,或者正在路上")}
value={draft.city}
onChange={(e) => update("city", e.target.value)}
/>
</label>
<JoinSelect
label={socialTx("当前状态")}
value={draft.status || "online"}
options={JOIN_STATUS_OPTIONS}
locale={locale}
onChange={(value) => update("status", value || "online")}
/>
<JoinSelect
label={socialTx("可约时段")}
value={draft.availability}
options={JOIN_AVAILABILITY_OPTIONS}
locale={locale}
onChange={(value) => update("availability", value)}
/>
<p className="social-join-section">{socialTx("工作与背景")}</p>
<label>
<label className="social-join-span-2">
{socialTx("你的职业或专业")}
<input
maxLength={80}
@ -956,33 +900,6 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
onChange={(e) => update("title", e.target.value)}
/>
</label>
<label>
{socialTx("擅长什么,喜欢什么")}
<span className="social-join-req">*</span>
<input
required
maxLength={200}
placeholder={socialTx("设计, 摄影, 冲浪, 开源项目…")}
value={draft.skills}
onChange={(e) => update("skills", e.target.value)}
/>
</label>
<JoinSelect
label={socialTx("学历(选填)")}
value={draft.education}
options={JOIN_EDUCATION_OPTIONS}
locale={locale}
onChange={(value) => update("education", value)}
/>
<label>
{socialTx("毕业时间(选填)")}
<input
maxLength={20}
placeholder={socialTx("如 2019 或 在读")}
value={draft.graduation}
onChange={(e) => update("graduation", e.target.value)}
/>
</label>
<p className="social-join-section">
{socialTx("你想在社区做什么")}

View File

@ -122,7 +122,12 @@ export default function ConnectionHero({
<div className="connection-proof">
<div className="connection-avatar-stack" aria-hidden="true">
{roster.slice(0, 5).map((m) => (
<SocialAvatar key={m.id} src={m.avatar} size={36} />
<SocialAvatar
key={m.id}
src={m.avatar}
size={36}
faceOk={m.faceOk}
/>
))}
</div>
<div>
@ -279,7 +284,11 @@ export default function ConnectionHero({
aria-label={`认识${m.name},${m.title}`}
>
<span className="connection-person-avatar">
<SocialAvatar src={m.avatar} size={44} />
<SocialAvatar
src={m.avatar}
size={44}
faceOk={m.faceOk}
/>
<i />
</span>
<span>

View File

@ -456,7 +456,13 @@ export default function DateClient() {
<span>想认识 · {liked.length}</span>
<div>
{liked.slice(0, 8).map((m) => (
<SocialAvatar key={m.id} src={m.avatar} size={34} lazy />
<SocialAvatar
key={m.id}
src={m.avatar}
size={34}
lazy
faceOk={m.faceOk}
/>
))}
</div>
<em>{socialTx("查看")}</em>
@ -476,7 +482,11 @@ export default function DateClient() {
onClose={() => setMatchId(null)}
>
<div className="social-member-profile">
<SocialAvatar src={matchMember.avatar} size={74} />
<SocialAvatar
src={matchMember.avatar}
size={74}
faceOk={matchMember.faceOk}
/>
<div>
<strong>{matchMember.name}</strong>
<p>{matchMember.title}</p>
@ -524,7 +534,7 @@ export default function DateClient() {
<div className="social-date-match-list">
{liked.map((m) => (
<article key={m.id} className="social-date-match-row">
<SocialAvatar src={m.avatar} size={48} lazy />
<SocialAvatar src={m.avatar} size={48} lazy faceOk={m.faceOk} />
<div>
<strong>{m.name}</strong>
<p>

View File

@ -107,7 +107,12 @@ export default function EventDirectory() {
<div className="social-video-grid social-video-grid-sm">
{roster.slice(index, index + 4).map((p) => (
<span key={p.id} className="social-video-tile">
<SocialAvatar src={p.avatar} size={32} lazy />
<SocialAvatar
src={p.avatar}
size={32}
lazy
faceOk={p.faceOk}
/>
</span>
))}
</div>
@ -121,7 +126,13 @@ export default function EventDirectory() {
</div>
<div className="social-meetup-faces" aria-hidden>
{roster.slice(index + 2, index + 6).map((p) => (
<SocialAvatar key={p.id} src={p.avatar} size={22} lazy />
<SocialAvatar
key={p.id}
src={p.avatar}
size={22}
lazy
faceOk={p.faceOk}
/>
))}
</div>
<h2>{event.title}</h2>

View File

@ -356,7 +356,12 @@ export default function HomeClient() {
<div className="social-video-grid">
{roster.slice(i, i + 4).map((p) => (
<span key={p.id} className="social-video-tile">
<SocialAvatar src={p.avatar} size={36} lazy />
<SocialAvatar
src={p.avatar}
size={36}
lazy
faceOk={p.faceOk}
/>
</span>
))}
</div>
@ -372,7 +377,13 @@ export default function HomeClient() {
</div>
<div className="social-meetup-faces" aria-hidden>
{roster.slice(i + 1, i + 5).map((p) => (
<SocialAvatar key={p.id} src={p.avatar} size={24} lazy />
<SocialAvatar
key={p.id}
src={p.avatar}
size={24}
lazy
faceOk={p.faceOk}
/>
))}
</div>
<h3>{m.title}</h3>

View File

@ -79,7 +79,7 @@ export default function HomeStatusStrip() {
let nextOpensJoin = true;
if (!faceOk) {
nextHint = socialTx("下一步:上传一张清晰的正面头像");
nextHint = socialTx("下一步:上传头像");
} else if (!liveOk) {
nextHint = livePending
? socialTx("自拍已提交,稍等一下")

View File

@ -10,6 +10,7 @@ import {
} from "@social/lib/joinFlow";
import { loginWithEmail } from "@social/lib/socialSession";
import { refreshRemoteConfig } from "~/lib/use-remote-config";
import { getSocialLive } from "@social/lib/socialLive";
import { useSocialConfig } from "./SocialExperience";
import { socialTx } from "@social/lib/socialTx";
@ -48,7 +49,7 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
const [busy, setBusy] = useState(false);
const [err, setErr] = useState("");
// 上下文被 SSE/轮询刷新时跟着变
// 上下文被 SSE/轮询刷新时跟着变(joinPriceLive 关则仍用上下文价作 UI 兜底)
useEffect(() => {
if (contextFen != null) setLiveFen(contextFen);
}, [contextFen]);
@ -63,8 +64,13 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
document.body.style.overflow = "hidden";
let cancelled = false;
setPriceSyncing(true);
const liveOn = getSocialLive(config).joinPriceLive;
setPriceSyncing(liveOn);
void (async () => {
if (!liveOn) {
if (!cancelled) setPriceSyncing(false);
return;
}
try {
const fresh = await refreshRemoteConfig(true);
if (cancelled) return;
@ -145,12 +151,12 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
};
const busyLabel = isFree
? socialTx("正在进入…")
? socialTx("确认中…")
: socialTx("正在前往支付…");
const ctaLabel = !priceKnown || priceSyncing
? socialTx("同步价格中…")
: isFree
? socialTx("免费加入,填资料")
? socialTx("确认")
: socialTx("确认并支付");
return (
@ -158,7 +164,7 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
ref={dialogRef}
className="social-join-overlay social-join-dialog"
aria-labelledby={titleId}
aria-describedby={descriptionId}
aria-describedby={isFree ? undefined : descriptionId}
onCancel={(event) => {
event.preventDefault();
if (!busy) onClose();
@ -183,15 +189,15 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
</button>
</header>
<h2 id={titleId} className="social-join-title">
{isFree ? socialTx("免费加入游民社区") : socialTx("加入游民社区")}
{socialTx("加入游民社区")}
</h2>
<p id={descriptionId} className="social-muted">
{priceSyncing
? socialTx("正在同步后台最新价格…")
: isFree
? socialTx("填写邮箱后直接完善资料,当前无需付款。")
{!isFree ? (
<p id={descriptionId} className="social-muted">
{priceSyncing
? socialTx("正在同步后台最新价格…")
: socialTx("填写邮箱后继续支付")}
</p>
</p>
) : null}
<label className="social-join-field">
{socialTx("邮箱")}
@ -223,11 +229,13 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
onClick={() => void submit()}
>
{busy ? busyLabel : ctaLabel}
<ArrowUpRight size={17} />
{!isFree ? <ArrowUpRight size={17} /> : null}
</button>
<p className="social-join-privacy">
<LockKeyhole size={11} /> {socialTx("请填写常用邮箱,方便找回账号")}
</p>
{!isFree ? (
<p className="social-join-privacy">
<LockKeyhole size={11} /> {socialTx("请填写常用邮箱,方便找回账号")}
</p>
) : null}
</div>
</dialog>
);

View File

@ -36,6 +36,8 @@ import {
resolveTrialLimits,
trialPaywallHint,
} from "@social/lib/socialTrial";
import { getSocialLive } from "@social/lib/socialLive";
import { useDiscoveryRoster } from "@social/lib/discoveryRoster";
import { useSocialConfig } from "./SocialExperience";
const SocialMapCanvas = dynamic(() => import("./SocialMapCanvas"), {
@ -122,7 +124,16 @@ function MapClientInner() {
const [selectedPersonId, setSelectedPersonId] = useState<string | null>(null);
const [offline, setOffline] = useState(false);
const [query, setQuery] = useState("");
const people = useMemo(() => buildMapPersonPins(), []);
const live = getSocialLive(config);
// mapLivePins on → discovery auto-refresh feeds live pins; off → seed only
const discovery = useDiscoveryRoster();
const people = useMemo(
() =>
buildMapPersonPins(
live.mapLivePins && discovery.length ? discovery : undefined,
),
[live.mapLivePins, discovery],
);
useEffect(() => {
if (cityParam) setSelectedId(cityParam);
@ -305,7 +316,11 @@ function MapClientInner() {
<X size={16} />
</button>
<div className="sm-rail-person-head">
<SocialAvatar src={selectedPerson.avatar} size={56} />
<SocialAvatar
src={selectedPerson.avatar}
size={56}
faceOk={selectedPerson.faceOk}
/>
<div>
<h2>{selectedPerson.name}</h2>
<p>{selectedPerson.title}</p>
@ -372,7 +387,11 @@ function MapClientInner() {
<X size={16} />
</button>
<div className="sm-rail-person-head">
<SocialAvatar src={selectedPerson.avatar} size={72} />
<SocialAvatar
src={selectedPerson.avatar}
size={72}
faceOk={selectedPerson.faceOk}
/>
<div>
<h2>
{selectedPerson.name}
@ -440,7 +459,11 @@ function MapClientInner() {
onClick={() => onSelectPerson(p)}
title={p.name}
>
<SocialAvatar src={p.avatar} size={40} />
<SocialAvatar
src={p.avatar}
size={40}
faceOk={p.faceOk}
/>
</button>
))}
{!cityPeople.length ? (

View File

@ -237,7 +237,12 @@ function PeopleDirectory({
style={{ ["--stagger" as string]: `${Math.min(index, 12) * 40}ms` }}
>
<span className="social-people-chip-ava">
<SocialAvatar src={person.avatar} size={52} lazy />
<SocialAvatar
src={person.avatar}
size={52}
lazy
faceOk={person.faceOk}
/>
{person.online ? <i aria-hidden /> : null}
</span>
<strong>

View File

@ -137,7 +137,13 @@ export default function PeopleProfileClient({ id }: { id: string }) {
aria-hidden
/>
<div className="social-profile-identity">
<SocialAvatar src={member.avatar} size={96} />
<SocialAvatar
src={member.avatar}
size={96}
faceOk={
member.id === SELF_MEMBER_ID ? undefined : member.faceOk
}
/>
<div>
<p className="social-profile-kicker">
{member.online ? (
@ -273,7 +279,13 @@ export default function PeopleProfileClient({ id }: { id: string }) {
<img key={src} src={src} alt="" loading="lazy" />
))}
<div className="social-profile-gallery-ava">
<SocialAvatar src={member.avatar} size={120} />
<SocialAvatar
src={member.avatar}
size={120}
faceOk={
member.id === SELF_MEMBER_ID ? undefined : member.faceOk
}
/>
</div>
</div>
</section>
@ -310,7 +322,7 @@ function PersonMini({ m }: { m: SocialRosterMember }) {
className={`social-people-chip social-chip-pop${m.online ? " is-online" : ""}`}
>
<span className="social-people-chip-ava">
<SocialAvatar src={m.avatar} size={52} lazy />
<SocialAvatar src={m.avatar} size={52} lazy faceOk={m.faceOk} />
{m.online ? <i aria-hidden /> : null}
</span>
<strong>{m.name}</strong>

View File

@ -386,7 +386,12 @@ export default function PlaceDetailClient({ cityId }: Props) {
href={socialPath(`/people/${p.id}`)}
className="spd-person"
>
<SocialAvatar src={p.avatar} size={48} lazy />
<SocialAvatar
src={p.avatar}
size={48}
lazy
faceOk={p.faceOk}
/>
<span>
<strong>{p.name}</strong>
<em>{p.title || p.city}</em>

View File

@ -28,6 +28,7 @@ import SocialBrandLogo from "./SocialBrandLogo";
import JoinPayModal from "./JoinPayModal";
import NavAccountMenu from "./NavAccountMenu";
import TrialNudgeBanner from "./TrialNudgeBanner";
import SocialLiveShell from "./SocialLiveShell";
import {
consumeOpenJoinModalFlag,
subscribeSocialJoinModal,
@ -309,6 +310,7 @@ export default function SiteShell({
{t.skipToMain}
</a>
{nav}
<SocialLiveShell home />
{children}
<SocialMobileDock />
{authModal}
@ -323,6 +325,7 @@ export default function SiteShell({
{t.skipToMain}
</a>
{nav}
<SocialLiveShell />
<main className="social-main social-main--immersive" id="social-main" data-page={title || t.brand}>
<TrialNudgeBanner />
{children}
@ -361,6 +364,7 @@ export default function SiteShell({
{t.skipToMain}
</a>
{nav}
<SocialLiveShell />
<div className="social-workspace-grid">
<main className="social-main" id="social-main" data-page={title || t.brand}>
<SocialQuickRail />

View File

@ -2,17 +2,23 @@
import Image from "next/image";
const PLACEHOLDER = "/icons/nomadro.webp";
/** Unoptimized keeps external/profile/API avatar URLs working offline & cross-host. */
export default function SocialAvatar({
src,
size,
lazy = false,
faceOk,
}: {
src: string;
size: number;
lazy?: boolean;
/** When false, never paint the raw album URL (no-face photos stay hidden). */
faceOk?: boolean;
}) {
const url = (src || "").trim();
const raw = (src || "").trim();
const url = faceOk === false ? "" : raw;
// Relative social API / blob: use plain <img> — next/image remotePatterns skip these.
if (
!url ||
@ -23,7 +29,7 @@ export default function SocialAvatar({
return (
// eslint-disable-next-line @next/next/no-img-element
<img
src={url || "/icons/nomadro.webp"}
src={url || PLACEHOLDER}
alt=""
width={size}
height={size}
@ -32,8 +38,7 @@ export default function SocialAvatar({
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";
if (!img.src.endsWith(PLACEHOLDER)) img.src = PLACEHOLDER;
}}
/>
);
@ -48,8 +53,7 @@ export default function SocialAvatar({
loading={lazy ? "lazy" : "eager"}
onError={(event) => {
const img = event.currentTarget;
if (!img.src.endsWith("/icons/nomadro.webp"))
img.src = "/icons/nomadro.webp";
if (!img.src.endsWith(PLACEHOLDER)) img.src = PLACEHOLDER;
}}
/>
);

View File

@ -0,0 +1,172 @@
"use client";
/**
* Social Live UX — heartbeat always; chrome only when it earns the pixel.
* Never paste landing copy into presence. Never sticky-bar the home hero.
*/
import { useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation";
import { useRemoteConfig } from "~/lib/use-remote-config";
import { socialPath } from "@social/lib/socialPath";
import { socialTx } from "@social/lib/socialTx";
import {
getSocialLive,
type SocialLiveFlags,
} from "@social/lib/socialLive";
import { socialTrack } from "@social/lib/socialTrack";
import { useSocialPresence } from "@social/lib/useSocialPresence";
import SocialAvatar from "./SocialAvatar";
function LiveToast({
text,
onDone,
}: {
text: string;
onDone: () => void;
}) {
useEffect(() => {
const t = setTimeout(onDone, 3200);
return () => clearTimeout(t);
}, [onDone, text]);
return (
<div className="social-live-toast" role="status" aria-live="polite">
{text}
</div>
);
}
export default function SocialLiveShell({
/** Home hero: never sticky-strip under nav */
home = false,
}: {
home?: boolean;
}) {
const pathname = usePathname();
const { config } = useRemoteConfig();
const live = getSocialLive(config);
const presence = useSocialPresence(config);
const [toast, setToast] = useState("");
const [navOffline, setNavOffline] = useState(false);
const lastVersion = useRef<number>(Number(config.version) || 0);
const booted = useRef(false);
const isHome =
home ||
pathname === socialPath("/") ||
pathname === socialPath("") ||
pathname === "/social" ||
pathname === "/social/";
useEffect(() => {
const sync = () =>
setNavOffline(typeof navigator !== "undefined" && !navigator.onLine);
sync();
window.addEventListener("online", sync);
window.addEventListener("offline", sync);
return () => {
window.removeEventListener("online", sync);
window.removeEventListener("offline", sync);
};
}, []);
useEffect(() => {
const v = Number(config.version) || 0;
if (!booted.current) {
booted.current = true;
lastVersion.current = v;
return;
}
if (v && v !== lastVersion.current) {
lastVersion.current = v;
socialTrack(live, "social_config_hot", { version: v });
if (live.configHotReloadToast) {
setToast(
socialTx("社区配置已更新") +
(live.configVersionChip ? ` · v${v}` : ""),
);
}
}
}, [config.version, live]);
// Only real browser offline — never flash on first-paint config seed.
const showOffline = live.offlineFallbackShell && navOffline;
const peers =
live.presenceCityScope && presence.cityPeers.length
? presence.cityPeers
: presence.peers;
const count =
live.presenceCityScope && presence.cityOnline > 0
? presence.cityOnline
: presence.online;
// Home: never float / never strip — heartbeat still runs, zero chrome.
const showStrip =
!isHome &&
live.presenceStrip &&
live.presenceEnabled &&
count > 0 &&
!presence.fromOffline;
if (!showStrip && !showOffline && !toast) {
return null;
}
return (
<div
className={`social-live-shell${isHome ? " is-home" : ""}`}
aria-live="polite"
>
{showOffline ? (
<div className="social-live-offline" role="status">
<span className="social-live-dot is-warn" aria-hidden />
<div>
<strong>{socialTx("网络已断开")}</strong>
<p>{socialTx("仍可浏览本地数据,连上后自动刷新。")}</p>
</div>
</div>
) : null}
{showStrip ? (
<div
className={`social-live-strip${isHome ? " is-float" : ""}`}
data-offline="0"
>
<span className="social-live-dot is-ok" aria-hidden />
<strong>
{live.onlineCountBadge ? (
<em className="social-live-count">{count}</em>
) : null}
{socialTx("人在线")}
</strong>
{peers.length ? (
<div className="social-live-avs" aria-hidden>
{peers.slice(0, 6).map((p) => (
<SocialAvatar
key={p.guestId}
src={p.avatar || ""}
size={20}
lazy
faceOk={
live.hideNoFaceAvatar ? Boolean(p.avatar) : undefined
}
/>
))}
</div>
) : null}
{live.configVersionChip ? (
<span className="social-live-ver">v{config.version || "—"}</span>
) : null}
</div>
) : null}
{toast ? <LiveToast text={toast} onDone={() => setToast("")} /> : null}
</div>
);
}
export function readLiveFlags(
config: { flags?: { socialLive?: Partial<SocialLiveFlags> } } | null,
): SocialLiveFlags {
return getSocialLive(config as never);
}

View File

@ -125,6 +125,64 @@ export const socialApi = {
json: { nick: nick || "游民" },
}),
/** Global who's-online heartbeat (social shell). */
rosterPresence: (opts?: {
nick?: string;
city?: string;
avatar?: string;
softStatusSync?: boolean;
}) =>
req<{
channelId: string;
online: number;
peers: Array<{
guestId: string;
nick: string;
city?: string;
avatar?: string;
}>;
cityOnline?: number;
cityPeers?: Array<{
guestId: string;
nick: string;
city?: string;
avatar?: string;
}>;
}>("/roster/presence", {
method: "POST",
json: {
nick: opts?.nick || "游民",
city: opts?.city || "",
avatar: opts?.avatar || "",
softStatusSync: opts?.softStatusSync !== false,
},
}),
rosterOnline: (opts?: { city?: string; limit?: number }) => {
const q = new URLSearchParams();
if (opts?.city) q.set("city", opts.city);
if (opts?.limit) q.set("limit", String(opts.limit));
const qs = q.toString();
return req<{
ok: boolean;
online: number;
peers: Array<{
guestId: string;
nick: string;
city?: string;
avatar?: string;
}>;
city?: string;
cityOnline?: number;
cityPeers?: Array<{
guestId: string;
nick: string;
city?: string;
avatar?: string;
}>;
}>(`/roster/online${qs ? `?${qs}` : ""}`, { ttlMs: 0 });
},
listMessages: (
channelId: string,
opts?: { limit?: number; since?: number; before?: number; q?: string },

View File

@ -2,6 +2,7 @@
import { useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { useAudienceModule } from "~/modules/audience";
import { useRemoteConfig } from "~/lib/use-remote-config";
import { socialApi } from "./api";
import { MOCK_ROSTER, type SocialRosterMember } from "./rosterMock";
import { cnAvatarForSeed, mapRosterAvatarPack } from "./rosterAvatars";
@ -11,6 +12,11 @@ import {
} from "./rankDiscovery";
import { isFaceOk } from "./livenessGate";
import { loadJson, saveJson } from "./storage";
import {
getSocialLive,
socialLiveDiscoveryMs,
} from "./socialLive";
import { socialTrack } from "./socialTrack";
import type { SocialRosterProfile } from "./types";
export const ROSTER_PUBLISH_KEY = "roster-publish";
@ -119,6 +125,8 @@ export function useDiscoveryRoster(opts?: {
}): SocialRosterMember[] {
const requireFace = Boolean(opts?.requireFace);
const { bundle } = useAudienceModule();
const { config } = useRemoteConfig();
const live = getSocialLive(config);
const pack = bundle.module.social.rosterAvatarPack;
const published = useSyncExternalStore(
subscribeSocialStorage,
@ -144,22 +152,52 @@ export function useDiscoveryRoster(opts?: {
useEffect(() => {
let cancelled = false;
void socialApi
.discoveryRoster({ limit: 48, requireFace })
.then((res) => {
if (cancelled || !res?.items?.length) {
if (!cancelled) setRemote([]);
return;
}
setRemote(res.items.map(discoveryItemToMember));
})
.catch(() => {
/* offline → keep mock */
});
let timer: ReturnType<typeof setInterval> | null = null;
const pull = () => {
void socialApi
.discoveryRoster({ limit: 48, requireFace })
.then((res) => {
if (cancelled) return;
if (!res?.items?.length) {
setRemote([]);
return;
}
setRemote(res.items.map(discoveryItemToMember));
socialTrack(live, "social_discovery_refresh", {
count: res.items.length,
requireFace: requireFace ? 1 : 0,
});
})
.catch(() => {
/* offline → keep mock / last good */
});
};
pull();
if (live.discoveryAutoRefresh) {
timer = setInterval(pull, socialLiveDiscoveryMs(live));
}
const onVis = () => {
if (!document.hidden) pull();
};
const onOnline = () => pull();
document.addEventListener("visibilitychange", onVis);
window.addEventListener("online", onOnline);
return () => {
cancelled = true;
if (timer) clearInterval(timer);
document.removeEventListener("visibilitychange", onVis);
window.removeEventListener("online", onOnline);
};
}, [profile.city, profile.skills, profile.intents, requireFace]);
}, [
profile.city,
profile.skills,
profile.intents,
requireFace,
live.discoveryAutoRefresh,
live.discoveryRefreshSec,
]);
const seed = useMemo(
() => mapRosterAvatarPack(MOCK_ROSTER, pack),

View File

@ -48,6 +48,7 @@ export type MapPersonPin = {
id: string;
name: string;
avatar: string;
faceOk?: boolean;
gender: "f" | "m";
title: string;
cityId: string;
@ -142,10 +143,12 @@ export function buildMapPersonPins(
? codeForCountry(loc.country)
: fromPool[index % fromPool.length];
const destCode = loc.nextName ? toCode : codeForCountry(loc.country);
const faceOk = m.faceOk !== false;
pins.push({
id: m.id,
name: m.name,
avatar: m.avatar,
avatar: faceOk ? m.avatar : "",
faceOk,
gender: m.gender,
title: m.title,
cityId: loc.cityId,

View File

@ -724,4 +724,17 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"关注": "Follow",
"👆 点卡片看看详情,也可以先点爱心关注":
"👆 Tap a card for details, or ♥ to follow",
"社区配置已更新": "Community settings updated",
"离线模式 · 本地兜底": "Offline · local fallback",
"网络已断开": "You’re offline",
"仍可浏览本地数据,连上后自动刷新。":
"Local data still works — refreshes when you’re back online.",
"网络不稳时仍可浏览本地数据;恢复后自动刷新谁在线与配置。":
"You can still browse local data offline; presence and config refresh when you’re back.",
"重试": "Retry",
"人在线": " online",
"等待同频游民上线": "Waiting for fellow nomads",
"下一步:上传头像": "Next: upload a photo",
"上传中…": "Uploading…",
"准备中…": "Getting ready…",
};

View File

@ -80,13 +80,15 @@ export function discoveryItemToMember(item: {
.map((t) => t.trim())
.filter(Boolean)
.slice(0, 8);
const faceOk = Boolean(item.faceOk);
return {
id: item.guestId,
name: item.name,
title: item.title || "游民",
city: item.city || "探索中",
tags: tags.length ? tags : ["新朋友"],
avatar: item.avatar || "",
// Never paint album photos without a detected face.
avatar: faceOk ? item.avatar || "" : "",
bio: item.bio || "",
vibe: item.status === "here" ? "同城想出来" : item.online ? "在线" : "刚出现",
online: Boolean(item.online),
@ -94,6 +96,6 @@ export function discoveryItemToMember(item: {
lookingFor: item.lookingFor || "想认识同频游民",
gender: (item.gender as SocialRosterMember["gender"]) || "f",
availability: item.availability || "",
faceOk: Boolean(item.faceOk),
faceOk,
};
}

View File

@ -0,0 +1,32 @@
/**
* Social live UX flags — offline-first resolve from remote-config.
* UI/UX is the super-fallback: never throw, always return seed defaults.
*/
import {
DEFAULT_SOCIAL_LIVE,
resolveSocialLive,
type NomadroRemoteConfig,
type SocialLiveFlags,
} from "~/lib/remote-config";
export type { SocialLiveFlags };
export function getSocialLive(
config: NomadroRemoteConfig | null | undefined,
): SocialLiveFlags {
try {
return resolveSocialLive(config);
} catch {
return { ...DEFAULT_SOCIAL_LIVE };
}
}
export function socialLiveHeartbeatMs(live: SocialLiveFlags): number {
const sec = Number(live.presenceHeartbeatSec) || 25;
return Math.min(120_000, Math.max(10_000, sec * 1000));
}
export function socialLiveDiscoveryMs(live: SocialLiveFlags): number {
const sec = Number(live.discoveryRefreshSec) || 45;
return Math.min(300_000, Math.max(15_000, sec * 1000));
}

View File

@ -0,0 +1,32 @@
/**
* Social live tracking — silent, never throws.
* Gated by flags.socialLive.trackLiveEvents (UI/UX still works when off).
*/
import { track } from "~/lib/analytics/track";
import type { SocialLiveFlags } from "./socialLive";
export function socialTrack(
live: SocialLiveFlags | null | undefined,
name: string,
props?: Record<string, string | number | boolean | undefined>,
): void {
try {
if (!live?.trackLiveEvents) return;
const clean: Record<string, string | number | boolean> = {
surface: "social_live",
};
if (props) {
for (const [k, v] of Object.entries(props)) {
if (v === undefined) continue;
clean[k] = v;
}
}
track(name, {
page: "social",
label: name,
props: clean,
});
} catch {
/* ignore */
}
}

View File

@ -43,13 +43,16 @@ export function resolveTrialLimits(
const raw = (config?.copy as { socialTrial?: Partial<SocialTrialLimits> } | undefined)
?.socialTrial;
const flagsOn = config?.flags?.socialTrialEnabled;
// trialLive=false → freeze to offline seed (UI still works; no remote trial thrash)
const liveOn = config?.flags?.socialLive?.trialLive !== false;
const enabledBase =
typeof flagsOn === "boolean"
? flagsOn
: typeof raw?.enabled === "boolean"
? raw.enabled
: DEFAULT_TRIAL_LIMITS.enabled;
return {
enabled:
typeof flagsOn === "boolean"
? flagsOn
: typeof raw?.enabled === "boolean"
? raw.enabled
: DEFAULT_TRIAL_LIMITS.enabled,
enabled: liveOn ? enabledBase : DEFAULT_TRIAL_LIMITS.enabled,
chatMessages: Math.max(
0,
Number(raw?.chatMessages ?? DEFAULT_TRIAL_LIMITS.chatMessages) || 0,

View File

@ -0,0 +1,176 @@
"use client";
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { socialApi } from "./api";
import { ensureGuestNick } from "./guestNick";
import { loadJson } from "./storage";
import {
getSocialLive,
socialLiveHeartbeatMs,
type SocialLiveFlags,
} from "./socialLive";
import { socialTrack } from "./socialTrack";
import type { NomadroRemoteConfig } from "~/lib/remote-config";
import type { SocialRosterProfile } from "./types";
export type SocialPresencePeer = {
guestId: string;
nick: string;
city?: string;
avatar?: string;
};
export type SocialPresenceState = {
online: number;
peers: SocialPresencePeer[];
cityOnline: number;
cityPeers: SocialPresencePeer[];
fromOffline: boolean;
lastBeatAt: number;
};
const EMPTY: SocialPresenceState = {
online: 0,
peers: [],
cityOnline: 0,
cityPeers: [],
fromOffline: true,
lastBeatAt: 0,
};
const STORAGE_CHANGE = "nomadro-social-storage";
function subscribeProfile(cb: () => void) {
window.addEventListener(STORAGE_CHANGE, cb);
window.addEventListener("storage", cb);
return () => {
window.removeEventListener(STORAGE_CHANGE, cb);
window.removeEventListener("storage", cb);
};
}
function readProfile(): Pick<SocialRosterProfile, "name" | "city" | "avatar"> {
const raw = loadJson<Partial<SocialRosterProfile>>("roster", {
name: "",
title: "",
city: "",
phone: "",
linktree: "",
skills: "",
bio: "",
avatar: "",
});
return {
name: typeof raw.name === "string" ? raw.name : "",
city: typeof raw.city === "string" ? raw.city : "",
avatar: typeof raw.avatar === "string" ? raw.avatar : "",
};
}
/**
* Global social presence heartbeat + who's-online snapshot.
* UI/UX fallback: never throws; offline → empty peers + fromOffline.
*/
export function useSocialPresence(
config: NomadroRemoteConfig | null | undefined,
): SocialPresenceState {
const live = getSocialLive(config);
const [state, setState] = useState<SocialPresenceState>(EMPTY);
const liveRef = useRef(live);
liveRef.current = live;
const profileSnap = useSyncExternalStore(
subscribeProfile,
() => JSON.stringify(readProfile()),
() => "{}",
);
useEffect(() => {
if (!live.presenceEnabled) {
setState(EMPTY);
return;
}
let cancelled = false;
let timer: ReturnType<typeof setInterval> | null = null;
const beat = async () => {
if (cancelled || document.hidden) return;
const profile = readProfile();
const nick =
(profile.name || "").trim() || ensureGuestNick() || "游民";
const city = liveRef.current.presenceCityScope
? (profile.city || "").trim()
: "";
try {
const res = await socialApi.rosterPresence({
nick,
city,
avatar: (profile.avatar || "").trim(),
softStatusSync: liveRef.current.softStatusSync,
});
if (cancelled) return;
const next: SocialPresenceState = {
online: Number(res.online) || 0,
peers: Array.isArray(res.peers) ? res.peers : [],
cityOnline: Number(res.cityOnline) || 0,
cityPeers: Array.isArray(res.cityPeers) ? res.cityPeers : [],
fromOffline: false,
lastBeatAt: Date.now(),
};
setState(next);
socialTrack(liveRef.current, "social_presence_beat", {
online: next.online,
cityOnline: next.cityOnline,
});
} catch {
if (cancelled) return;
// Soft fallback: keep last good peers; mark offline for UX shell
setState((prev) => ({
...prev,
fromOffline: true,
lastBeatAt: Date.now(),
}));
try {
const snap = await socialApi.rosterOnline({ city, limit: 32 });
if (cancelled) return;
setState({
online: Number(snap.online) || 0,
peers: Array.isArray(snap.peers) ? snap.peers : [],
cityOnline: Number(snap.cityOnline) || 0,
cityPeers: Array.isArray(snap.cityPeers) ? snap.cityPeers : [],
fromOffline: true,
lastBeatAt: Date.now(),
});
} catch {
/* keep previous */
}
}
};
void beat();
timer = setInterval(
() => void beat(),
socialLiveHeartbeatMs(liveRef.current),
);
const onVis = () => {
if (!document.hidden) void beat();
};
const onOnline = () => void beat();
document.addEventListener("visibilitychange", onVis);
window.addEventListener("online", onOnline);
return () => {
cancelled = true;
if (timer) clearInterval(timer);
document.removeEventListener("visibilitychange", onVis);
window.removeEventListener("online", onOnline);
};
}, [live.presenceEnabled, live.presenceCityScope, live.softStatusSync, profileSnap]);
return state;
}
export function useSocialLiveFlags(
config: NomadroRemoteConfig | null | undefined,
): SocialLiveFlags {
return getSocialLive(config);
}