Harden social UX and APIs: idempotent chat/join, config cache, weapp polish.

Improve hall chat retries, meetup-live lifecycle, home/mine remote-config UX, and add isolated social/API regression tests without deploying.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-02 14:00:11 +08:00
parent 92bbee3c6c
commit f20406397a
58 changed files with 2597 additions and 778 deletions

View File

@ -1,5 +1,27 @@
# Nomadro 统一 API
## 2026-11-02:社区消息与报名兼容修复(未部署)
仅修改 `social_svc/store.py` 与 `social_svc/routers/api.py`:聊天改为读取最近一批、按时间正序返回,同秒消息以 rowid 保持稳定顺序;消息可带 `clientId`、报名可带 `requestId`,由设备身份和频道/岗位限定作用域,重复请求复用同一记录与时间,不同载荷返回 409。旧客户端不传标识继续兼容。纯 SQLite 接口移入线程池,消息发布失败不影响已提交记录。
没有 schema 迁移、删除、历史重写或业务库同步;使用已有主键实现幂等。社区 SQLite 与会员/订单库隔离。`test_social_store.py` 7 项与 `test_social_api.py` 4 项均使用临时数据库并 mock 实时发布,验证最近 100 条消息、同秒排序、重试与冲突、旧请求兼容、资料隐私字段和设备隔离、旧表和记录保留。连同配置测试,18 项全部通过。
线上只读检查显示 `nomadro-social` 监听 8020、单进程运行且不支持热重载;`live.py` 的视频房间状态保存在进程内。为满足不影响现有业务的约束,本轮未执行直接重启、数据库同步或线上测试写入。发布须先处理活动视频房间的状态连续性,并保留旧版本与回滚路径;客户端可先构建验收,后端可选字段兼容现有请求。
## 2026-11-02:公开配置读取优化(未部署)
`public_config_snapshot.py` 按文件修改时间、大小及 inode 复用 JSON 解析结果;文件变化立即重新读取。文件短暂缺失、写入未完成或 JSON 损坏时,保留同一路径最近一次有效快照;首次读取失败仍返回原有默认配置。路径变化不会复用旧路径数据。返回深拷贝防止调用方污染缓存,meta 遇到非法 version 返回 0,避免 500。
保持 `/api/config`、`/api/ebook/config` 及对应 `/meta` 的路由、响应结构、CORS 和 no-store 头兼容。此次改动只有文件读取和进程内缓存,没有数据库访问、迁移、配置写回或支付/订单/会员修改,尚未更新线上服务。
隔离验证(仅临时 JSON 文件,不启动业务应用、不连接生产):
```bash
apps/api/.venv/Scripts/python.exe -m unittest discover -s apps/api/tests -v
```
七项回归覆盖缓存复用、文件替换即时生效、损坏/缺失兜底、路径隔离、读取过程中文件变化、接口兼容性与非法版本。
合并原三套后端为一个入口(路径兼容):
| 模块 | 来源 | 路径前缀 |

View File

@ -6,40 +6,20 @@
"""
from __future__ import annotations
import json
from typing import Any
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from ebook_svc.services.tt_platform_config import resolve_config_file
from ebook_svc.services.public_config_snapshot import PublicConfigSnapshot
router = APIRouter(tags=["public-config"])
_snapshot = PublicConfigSnapshot()
def _read_full_config() -> dict[str, Any]:
path = resolve_config_file()
if not path.is_file():
return {
"version": 1,
"updatedAt": "",
"modules": {},
"flags": {},
"copy": {},
"platforms": {},
}
try:
raw = json.loads(path.read_text(encoding="utf-8"))
return raw if isinstance(raw, dict) else {}
except Exception:
return {
"version": 1,
"updatedAt": "",
"modules": {},
"flags": {},
"copy": {},
"platforms": {},
}
return _snapshot.read(resolve_config_file())
@router.get("/api/config")
@ -60,10 +40,14 @@ async def public_remote_config() -> JSONResponse:
@router.get("/api/ebook/config/meta")
async def public_remote_config_meta() -> JSONResponse:
config = _read_full_config()
try:
version = int(config.get("version") or 0)
except (TypeError, ValueError, OverflowError):
version = 0
return JSONResponse(
content={
"ok": True,
"version": int(config.get("version") or 0),
"version": version,
"updatedAt": str(config.get("updatedAt") or ""),
},
headers={

View File

@ -0,0 +1,53 @@
"""Read-only configuration snapshots. Never writes configuration or business data."""
from __future__ import annotations
import json
from copy import deepcopy
from pathlib import Path
from threading import RLock
from typing import Any
class PublicConfigSnapshot:
"""Reuse parsed JSON until the file changes; retain a valid snapshot during writes."""
def __init__(self) -> None:
self._lock = RLock()
self._path: Path | None = None
self._signature: tuple[int, int, int] | None = None
self._config: dict[str, Any] | None = None
@staticmethod
def _stat(path: Path) -> tuple[int, int, int]:
stat = path.stat()
return stat.st_mtime_ns, stat.st_size, stat.st_ino
def read(self, path: Path) -> dict[str, Any]:
with self._lock:
if path != self._path:
self._path = path
self._signature = None
self._config = None
try:
signature = self._stat(path)
if signature != self._signature:
raw = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(raw, dict):
raise ValueError("Configuration must be an object")
# Do not cache an intermediate read while the file is changing.
if self._stat(path) != signature:
raise ValueError("Configuration changed during read")
self._config = raw
self._signature = signature
except (OSError, ValueError, UnicodeError):
pass
if self._config is not None:
return deepcopy(self._config)
return {
"version": 1,
"updatedAt": "",
"modules": {},
"flags": {},
"copy": {},
"platforms": {},
}

View File

@ -3,6 +3,7 @@ from __future__ import annotations
from fastapi import APIRouter, Header, HTTPException, Query
from pydantic import BaseModel, Field
from starlette.concurrency import run_in_threadpool
from social_svc import live, store
from social_svc.config import SOCIAL_ENABLED
@ -28,6 +29,7 @@ def _guest(
class MessageIn(BaseModel):
author: str = Field(default="游民", max_length=48)
text: str = Field(min_length=1, max_length=2000)
clientId: str | None = Field(default=None, min_length=1, max_length=80)
class ReviewIn(BaseModel):
@ -57,6 +59,7 @@ class GigAppIn(BaseModel):
name: str = Field(min_length=1, max_length=64)
contact: str = Field(min_length=1, max_length=120)
note: str = Field(default="", max_length=2000)
requestId: str | None = Field(default=None, min_length=1, max_length=80)
@router.get("/health")
@ -81,7 +84,7 @@ async def realtime_token(
@router.get("/channels/{channel_id}/messages")
async def get_messages(channel_id: str, limit: int = 100):
def get_messages(channel_id: str, limit: int = 100):
store.init_db()
return {"items": store.list_messages(channel_id, limit)}
@ -94,10 +97,15 @@ async def post_message(
guest: str | None = Query(default=None),
):
peer = _guest(x_social_guest_id, guest)
store.init_db()
if not body.text.strip():
raise HTTPException(status_code=400, detail="empty text")
saved = store.add_message(channel_id, body.author, body.text, peer)
def persist():
store.init_db()
return store.add_message(channel_id, body.author, body.text, peer, body.clientId)
try:
saved = await run_in_threadpool(persist)
except ValueError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
# 实时推送失败不影响落库成功
try:
await publish_chat_message(channel_id, saved)
@ -107,13 +115,13 @@ async def post_message(
@router.get("/cafes/{cafe_id}/reviews")
async def get_reviews(cafe_id: str, limit: int = 50):
def get_reviews(cafe_id: str, limit: int = 50):
store.init_db()
return {"items": store.list_reviews(cafe_id, limit)}
@router.post("/cafes/{cafe_id}/reviews")
async def post_review(
def post_review(
cafe_id: str,
body: ReviewIn,
x_social_guest_id: str | None = Header(default=None),
@ -131,14 +139,14 @@ async def post_review(
@router.get("/roster/me")
async def get_my_roster(x_social_guest_id: str | None = Header(default=None)):
def get_my_roster(x_social_guest_id: str | None = Header(default=None)):
guest = _guest(x_social_guest_id)
store.init_db()
return {"item": store.get_roster(guest)}
@router.put("/roster/me")
async def put_my_roster(
def put_my_roster(
body: RosterIn,
x_social_guest_id: str | None = Header(default=None),
):
@ -148,7 +156,7 @@ async def put_my_roster(
@router.post("/feedback")
async def post_feedback(
def post_feedback(
body: FeedbackIn,
x_social_guest_id: str | None = Header(default=None),
):
@ -158,14 +166,19 @@ async def post_feedback(
@router.post("/gigs/{gig_id}/apply")
async def post_gig_apply(
def post_gig_apply(
gig_id: str,
body: GigAppIn,
x_social_guest_id: str | None = Header(default=None),
):
guest = _guest(x_social_guest_id)
if not body.name.strip() or not body.contact.strip():
raise HTTPException(status_code=400, detail="请填写称呼和联系方式")
store.init_db()
return store.add_gig_app(gig_id, body.name, body.contact, body.note, guest)
try:
return store.add_gig_app(gig_id, body.name, body.contact, body.note, guest, body.requestId)
except ValueError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
class LiveJoinIn(BaseModel):

View File

@ -2,6 +2,7 @@
from __future__ import annotations
import json
import hashlib
import sqlite3
import time
import uuid
@ -112,7 +113,7 @@ def list_messages(channel_id: str, limit: int = 100) -> list[dict[str, Any]]:
SELECT id, channel_id, author, text, guest_id, created_at
FROM messages
WHERE channel_id = ?
ORDER BY created_at ASC
ORDER BY created_at DESC, rowid DESC
LIMIT ?
""",
(channel_id, max(1, min(limit, 500))),
@ -126,13 +127,13 @@ def list_messages(channel_id: str, limit: int = 100) -> list[dict[str, Any]]:
"guestId": r["guest_id"],
"at": r["created_at"],
}
for r in rows
for r in reversed(rows)
]
def add_message(channel_id: str, author: str, text: str, guest_id: str) -> dict[str, Any]:
def add_message(channel_id: str, author: str, text: str, guest_id: str, client_id: str | None = None) -> dict[str, Any]:
item = {
"id": _uid("msg"),
"id": ("msg_" + hashlib.sha256(json.dumps([guest_id, channel_id, client_id]).encode()).hexdigest()[:32]) if client_id else _uid("msg"),
"channelId": channel_id,
"author": (author or "游民").strip()[:48] or "游民",
"text": text.strip()[:2000],
@ -142,11 +143,17 @@ def add_message(channel_id: str, author: str, text: str, guest_id: str) -> dict[
with db() as conn:
conn.execute(
"""
INSERT INTO messages(id, channel_id, author, text, guest_id, created_at)
INSERT OR IGNORE INTO messages(id, channel_id, author, text, guest_id, created_at)
VALUES (?, ?, ?, ?, ?, ?)
""",
(item["id"], item["channelId"], item["author"], item["text"], guest_id, item["at"]),
)
row = conn.execute("SELECT * FROM messages WHERE id = ?", (item["id"],)).fetchone()
if row["text"] != item["text"] or row["author"] != item["author"]:
raise ValueError("同一请求标识不能用于不同消息")
item["at"] = row["created_at"]
if client_id:
item["clientId"] = client_id
return item
@ -296,9 +303,9 @@ def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str,
return item
def add_gig_app(gig_id: str, name: str, contact: str, note: str, guest_id: str) -> dict[str, Any]:
def add_gig_app(gig_id: str, name: str, contact: str, note: str, guest_id: str, request_id: str | None = None) -> dict[str, Any]:
item = {
"id": _uid("app"),
"id": ("app_" + hashlib.sha256(json.dumps([guest_id, gig_id, request_id]).encode()).hexdigest()[:32]) if request_id else _uid("app"),
"gigId": gig_id,
"name": name.strip()[:64],
"contact": contact.strip()[:120],
@ -309,11 +316,15 @@ def add_gig_app(gig_id: str, name: str, contact: str, note: str, guest_id: str)
with db() as conn:
conn.execute(
"""
INSERT INTO gig_apps(id, gig_id, name, contact, note, guest_id, created_at)
INSERT OR IGNORE INTO gig_apps(id, gig_id, name, contact, note, guest_id, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(item["id"], item["gigId"], item["name"], item["contact"], item["note"], guest_id, item["at"]),
)
row = conn.execute("SELECT * FROM gig_apps WHERE id = ?", (item["id"],)).fetchone()
if (row["name"], row["contact"], row["note"]) != (item["name"], item["contact"], item["note"]):
raise ValueError("同一请求标识不能用于不同申请")
item["at"] = row["created_at"]
return item

View File

@ -0,0 +1,99 @@
"""Isolated tests: temporary JSON only, no app startup or database connections."""
import json
import asyncio
import importlib.util
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "services"))
from ebook_svc.services.public_config_snapshot import PublicConfigSnapshot
class PublicConfigSnapshotTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.path = Path(self.directory.name) / "config.json"
self.reader = PublicConfigSnapshot()
def write(self, value):
self.path.write_text(json.dumps(value), encoding="utf-8")
def test_unchanged_file_is_not_parsed_again(self):
self.write({"version": 10, "flags": {"payEnabled": False}})
first = self.reader.read(self.path)
first["flags"]["payEnabled"] = True
with patch.object(Path, "read_text", side_effect=AssertionError("read again")):
self.assertFalse(self.reader.read(self.path)["flags"]["payEnabled"])
def test_update_visible_immediately(self):
self.write({"version": 1})
self.assertEqual(self.reader.read(self.path)["version"], 1)
replacement = self.path.with_suffix(".new")
replacement.write_text('{"version": 222}', encoding="utf-8")
replacement.replace(self.path)
self.assertEqual(self.reader.read(self.path)["version"], 222)
def test_partial_write_and_missing_file_keep_last_good_config(self):
self.write({"version": 9, "modules": {"vip": {"enabled": False}}})
expected = self.reader.read(self.path)
for text in ('{"version":', '[]', '\ufffd'):
self.path.write_text(text, encoding="utf-8")
self.assertEqual(self.reader.read(self.path), expected)
self.path.unlink()
self.assertEqual(self.reader.read(self.path), expected)
self.write({"version": 123})
self.assertEqual(self.reader.read(self.path)["version"], 123)
def test_new_path_does_not_reuse_old_config(self):
self.write({"version": 99})
self.reader.read(self.path)
empty = self.reader.read(self.path.with_name("missing.json"))
self.assertEqual(empty["version"], 1)
self.assertEqual(empty["modules"], {})
def test_changing_file_during_read_does_not_replace_snapshot(self):
self.write({"version": 9})
self.reader.read(self.path)
self.write({"version": 100})
with patch.object(self.reader, "_stat", side_effect=[(1, 2, 3), (4, 5, 6)]):
self.assertEqual(self.reader.read(self.path)["version"], 9)
def load_router(self):
# Avoid importing settings/app startup: neither real databases nor live APIs.
target = Path(__file__).resolve().parents[1] / "services/ebook_svc/routers/public_config.py"
spec = importlib.util.spec_from_file_location("public_config_under_test", target)
module = importlib.util.module_from_spec(spec)
with patch.dict(sys.modules, {
"ebook_svc.services.tt_platform_config": SimpleNamespace(resolve_config_file=lambda: self.path),
}):
spec.loader.exec_module(module)
return module
def test_public_response_preserves_envelope_headers_and_aliases(self):
config = {"version": 7, "updatedAt": "now", "flags": {"payEnabled": False}}
self.write(config)
router = self.load_router()
response = asyncio.run(router.public_remote_config())
self.assertEqual(json.loads(response.body), {"ok": True, "source": "file", "config": config})
self.assertIn("no-store", response.headers["cache-control"])
self.assertEqual(response.headers["access-control-allow-origin"], "*")
self.assertEqual({route.path for route in router.router.routes}, {
"/api/config", "/api/ebook/config", "/api/config/meta", "/api/ebook/config/meta",
})
def test_meta_handles_malformed_version_without_server_error(self):
self.write({"version": {"unexpected": True}})
router = self.load_router()
response = asyncio.run(router.public_remote_config_meta())
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.body)["version"], 0)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,64 @@
"""HTTP compatibility tests against a temporary database and mocked realtime."""
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import AsyncMock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'services'))
from fastapi import FastAPI
from fastapi.testclient import TestClient
from social_svc import store
from social_svc.routers.api import router
class SocialApiTests(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
override = patch.object(store, 'SOCIAL_DB_PATH', Path(directory.name) / 'social.db')
override.start()
self.addCleanup(override.stop)
publish = patch('social_svc.routers.api.publish_chat_message', new_callable=AsyncMock)
publish.start()
self.addCleanup(publish.stop)
app = FastAPI()
app.include_router(router, prefix='/api/social/v1')
self.client = TestClient(app)
self.addCleanup(self.client.close)
self.headers = {'X-Social-Guest-Id': 'isolated-test'}
def test_message_retry_conflict_and_legacy_payload(self):
url = '/api/social/v1/channels/general/messages'
body = {'author': 'Name', 'text': 'Hello', 'clientId': 'same'}
first = self.client.post(url, json=body, headers=self.headers)
self.assertEqual(first.status_code, 200)
self.assertEqual(self.client.post(url, json=body, headers=self.headers).json(), first.json())
self.assertEqual(self.client.post(url, json={**body, 'text': 'Changed'}, headers=self.headers).status_code, 409)
self.assertEqual(self.client.post(url, json={'text': 'Legacy'}, headers=self.headers).status_code, 200)
self.assertEqual(len(self.client.get(url).json()['items']), 2)
def test_whitespace_and_missing_identity_do_not_write_messages(self):
url = '/api/social/v1/channels/general/messages'
self.assertEqual(self.client.post(url, json={'text': ' '}, headers=self.headers).status_code, 400)
self.assertEqual(self.client.post(url, json={'text': 'Hello'}).status_code, 400)
def test_application_retry_and_whitespace_validation(self):
url = '/api/social/v1/gigs/project/apply'
body = {'name': 'Name', 'contact': 'Contact', 'requestId': 'same'}
first = self.client.post(url, json=body, headers=self.headers)
self.assertEqual(first.status_code, 200)
self.assertEqual(self.client.post(url, json=body, headers=self.headers).json(), first.json())
self.assertEqual(self.client.post(url, json={**body, 'contact': 'Changed'}, headers=self.headers).status_code, 409)
self.assertEqual(self.client.post(url, json={**body, 'name': ' '}, headers=self.headers).status_code, 400)
def test_roster_round_trip_keeps_private_fields_and_guest_isolation(self):
url = '/api/social/v1/roster/me'
body = {'name': 'Name', 'phone': 'private-contact', 'linktree': 'https://example.invalid'}
self.assertEqual(self.client.put(url, json=body, headers=self.headers).status_code, 200)
self.assertEqual(self.client.get(url, headers=self.headers).json()['item']['phone'], 'private-contact')
self.assertIsNone(self.client.get(url, headers={'X-Social-Guest-Id': 'another-test'}).json()['item'])
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,82 @@
"""Social regressions use a temporary SQLite database; no production app startup."""
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'services'))
from social_svc import store
class SocialStoreTests(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
override = patch.object(store, 'SOCIAL_DB_PATH', Path(directory.name) / 'social.db')
override.start()
self.addCleanup(override.stop)
store.init_db()
def test_recent_history_is_chronological_even_with_equal_timestamps(self):
with patch.object(store, '_now', return_value='2026-11-02T00:00:00.000Z'):
for i in range(125):
store.add_message('lobby', 'Guest', str(i), 'guest')
self.assertEqual([m['text'] for m in store.list_messages('lobby')], [str(i) for i in range(25, 125)])
self.assertEqual(store.list_messages('other'), [])
def test_message_replay_is_idempotent_and_preserves_time(self):
with patch.object(store, '_now', return_value='first'):
first = store.add_message('lobby', 'Guest', 'hello', 'guest', 'request1')
self.assertEqual(store.add_message('lobby', 'Guest', 'hello', 'guest', 'request1'), first)
self.assertEqual(len(store.list_messages('lobby')), 1)
with self.assertRaises(ValueError):
store.add_message('lobby', 'Guest', 'different', 'guest', 'request1')
self.assertEqual(store.list_messages('lobby')[0]['text'], 'hello')
def test_message_keys_are_scoped_to_guest_and_channel(self):
items = [store.add_message(channel, 'Guest', 'hello', guest, 'same')
for channel, guest in [('a', 'one'), ('a', 'two'), ('b', 'one')]]
self.assertEqual(len({item['id'] for item in items}), 3)
def test_old_clients_without_keys_keep_working(self):
one = store.add_message('lobby', 'Guest', 'hello', 'guest')
two = store.add_message('lobby', 'Guest', 'hello', 'guest')
self.assertNotEqual(one['id'], two['id'])
self.assertNotIn('clientId', one)
def test_gig_replay_and_payload_conflict(self):
first = store.add_gig_app('gig', 'Name', 'Contact', 'Note', 'guest', 'key')
self.assertEqual(store.add_gig_app('gig', 'Name', 'Contact', 'Note', 'guest', 'key'), first)
with self.assertRaises(ValueError):
store.add_gig_app('gig', 'Name', 'Changed', 'Note', 'guest', 'key')
second = store.add_gig_app('other', 'Name', 'Contact', 'Note', 'guest', 'key')
self.assertNotEqual(first['id'], second['id'])
with store.db() as conn:
self.assertEqual(conn.execute('SELECT COUNT(*) FROM gig_apps').fetchone()[0], 2)
def test_roster_round_trip_isolated_by_guest(self):
profile = dict(name='Name', title='Designer', city='Dali', phone='private',
linktree='https://example.invalid', skills='Design', bio='Hello')
saved = store.upsert_roster('one', profile)
self.assertEqual(store.get_roster('one'), saved)
self.assertIsNone(store.get_roster('two'))
store.init_db()
self.assertEqual(store.get_roster('one'), saved)
def test_existing_tables_and_rows_survive_reinitialization(self):
message = store.add_message('lobby', 'Guest', 'existing', 'guest')
review = store.add_review('cafe', 'Guest', 4, 'Good', '', 'guest')
with store.db() as conn:
before = list(conn.execute("SELECT name, sql FROM sqlite_master WHERE type='table' ORDER BY name"))
store.init_db()
store.add_message('lobby', 'Guest', 'new', 'guest', 'key')
with store.db() as conn:
after = list(conn.execute("SELECT name, sql FROM sqlite_master WHERE type='table' ORDER BY name"))
self.assertEqual([tuple(row) for row in before], [tuple(row) for row in after])
self.assertEqual(store.list_messages('lobby')[0]['id'], message['id'])
self.assertEqual(store.list_reviews('cafe')[0]['id'], review['id'])
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,97 @@
"""Check built shared pages using mocked APIs only; no production network access.
Serve h5/dist on localhost:10086 first. Requires Python Playwright + Chromium.
"""
from pathlib import Path
import json
from playwright.sync_api import sync_playwright
BASE = "http://127.0.0.1:10086"
OUT = Path(__file__).resolve().parents[1] / "tmp" / "account-ux"
OUT.mkdir(parents=True, exist_ok=True)
def run():
results = []
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
for width in (320, 390, 430):
context = browser.new_context(viewport={"width": width, "height": 844}, is_mobile=True)
errors = []
state = {"offline": False, "favorites_error": True}
def route_request(route):
url = route.request.url
if not url.startswith(BASE + "/"):
return route.abort()
if not any(prefix in url for prefix in ("/api/", "/ebook-api", "/community-api")):
return route.continue_()
payload = {}
status = 200
if url.endswith("/api/config"):
payload = {"config": {"version": 99, "flags": {"offlineBadge": True}}}
elif url.endswith("/api/config/meta"):
payload = {"version": 99}
elif url.endswith("/auth/presence"):
payload = {"openid": "ux-test", "isVip": True}
status = 503 if state["offline"] else 200
elif url.endswith("/auth/profile/stats"):
payload = {"favorites_count": 0, "destinations_explored": 3, "member_since": "2026-01", "nomad_level": "探索者"}
elif url.endswith("/auth/favorites/detail"):
payload = []
status = 503 if state["favorites_error"] else 200
elif "/config/stream" in url:
status = 503
route.fulfill(status=status, content_type="application/json", body=json.dumps(payload))
context.route("**/*", route_request)
page = context.new_page()
page.on("pageerror", lambda error: errors.append(str(error)))
page.goto(BASE + "/#/pages/home/index")
toggle = page.locator(".hub-theme-toggle")
toggle.wait_for()
assert toggle.bounding_box()["height"] >= 44
assert page.locator(".hub-portal-card").count() > 0
toggle.click()
assert page.locator(".hub-root").get_attribute("data-theme") == "light"
page.wait_for_function("getComputedStyle(document.querySelector('.hub-root')).backgroundColor === 'rgb(248, 250, 252)'")
page.screenshot(path=str(OUT / f"home-light-{width}.png"), full_page=True)
page.goto(BASE + "/#/pages/mine/index")
page.get_by_text("未登录", exact=True).wait_for()
assert page.locator(".profile-header .btn").bounding_box()["height"] >= 44
page.evaluate("""() => {
localStorage.setItem('nomadro_token', JSON.stringify({data:'mock-token'}));
localStorage.setItem('nomadro_openid', JSON.stringify({data:'ux-test'}));
}""")
page.reload()
page.get_by_text("收藏暂未同步,请刷新重试", exact=True).wait_for()
assert page.get_by_text("探索目的地", exact=True).count() == 0
page.screenshot(path=str(OUT / f"account-partial-{width}.png"), full_page=True)
state["offline"] = True
page.get_by_text("刷新", exact=True).click()
page.get_by_text("同步失败,请检查网络后重试", exact=True).wait_for()
assert page.get_by_text("退出登录", exact=True).count() == 1
assert page.evaluate("localStorage.getItem('nomadro_token')") is not None
state["offline"] = False
state["favorites_error"] = False
page.get_by_text("重试同步", exact=True).click()
page.get_by_text("探索目的地", exact=True).wait_for()
assert page.locator(".profile-stats").evaluate("el => el.scrollWidth <= el.clientWidth")
assert page.evaluate("document.documentElement.scrollWidth <= innerWidth")
page.screenshot(path=str(OUT / f"account-restored-{width}.png"), full_page=True)
page.get_by_text("退出登录", exact=True).click()
page.get_by_text("未登录", exact=True).wait_for()
assert page.evaluate("localStorage.getItem('nomadro_token')") is None
assert not errors, errors
results.append({"width": width, "ok": True})
context.close()
browser.close()
print(json.dumps(results))
if __name__ == "__main__":
run()

View File

@ -0,0 +1,157 @@
"""Community browser regressions; external requests are mocked or blocked."""
import json
from pathlib import Path
from playwright.sync_api import sync_playwright
BASE = 'http://127.0.0.1:10086'
OUT = Path(__file__).resolve().parents[1] / 'tmp' / 'social-ux'
OUT.mkdir(parents=True, exist_ok=True)
def run():
results = []
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
for width in (320, 390, 430):
context = browser.new_context(viewport={'width': width, 'height': 844}, is_mobile=True)
errors, writes = [], []
state = {'roster': None, 'fail_save': False, 'fail_send': True, 'messages': [], 'fail_apply': True, 'reviews': []}
def route_request(route):
request = route.request
url = request.url
if '/api/social/v1/' in url:
payload, status = {}, 200
if '/realtime/token' in url:
payload = {'ok': True, 'enabled': False}
elif '/roster/me' in url:
if request.method == 'PUT':
writes.append(('roster', request.post_data_json))
if state['fail_save']: status = 503
else: state['roster'] = request.post_data_json
payload = state['roster'] or {}
else: payload = {'item': state['roster']}
elif '/messages' in url:
if request.method == 'POST':
body = request.post_data_json
writes.append(('message', body))
if state['fail_send']: status = 503
payload = {**body, 'id': 'msg_saved', 'channelId': 'general', 'guestId': request.headers.get('x-social-guest-id'), 'at': '2026-11-02T00:00:00.000Z'}
if status == 200: state['messages'] = [payload]
else: payload = {'items': state['messages']}
elif '/reviews' in url:
if request.method == 'POST':
payload = {**request.post_data_json, 'id': 'review_saved', 'at': '2026-11-02T00:00:00.000Z'}
state['reviews'] = [payload]
else: payload = {'items': state['reviews']}
elif '/apply' in url:
writes.append(('apply', request.post_data_json))
payload = {'id': 'application_saved'}
if state['fail_apply']: status = 503
return route.fulfill(status=status, content_type='application/json', body=json.dumps(payload))
if not url.startswith(BASE + '/'):
return route.abort()
if '/api/' in url or '/ebook-api' in url:
payload = {}
if '/api/config' in url:
payload = {'config': {'version': 99, 'modules': {'social': {'enabled': True}}, 'flags': {'socialFollow': False}}}
elif '/social-join-status' in url:
payload = {'ok': True, 'isMember': False, 'enabled': False, 'priceFen': 4900}
return route.fulfill(status=200, content_type='application/json', body=json.dumps(payload))
return route.continue_()
context.route('**/*', route_request)
page = context.new_page()
page.on('pageerror', lambda error: errors.append(str(error)))
routes = ['index', 'people/index', 'people/index?mode=cafe', 'people/profile/index?id=m01', 'date/index', 'team/index', 'roster/index', 'chat/index', 'meetup/index', 'meetup-live/index']
for index, route in enumerate(routes):
page.goto(BASE + '/#/pages/social/' + route)
page.locator('.soc-taro-root').wait_for()
page.wait_for_timeout(250)
assert page.locator('.soc-taro-root').inner_text().strip(), route
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), (width, route, 'overflow')
page.screenshot(path=str(OUT / f'{width}-{index}.png'), full_page=True)
if page.locator('.social-theme-control').count():
page.locator('.social-theme-control').click()
page.wait_for_function("document.querySelector('.soc-taro-root').dataset.theme === 'light'")
page.wait_for_timeout(500)
if index == 1:
assert page.locator('.social-people-chip').first.evaluate("el => getComputedStyle(el).backgroundColor === 'rgb(255, 255, 255)'")
page.screenshot(path=str(OUT / f'{width}-{index}-light.png'), full_page=True)
page.locator('.social-theme-control').click()
page.goto(BASE + '/#/pages/social/people/index')
page.get_by_role('button', name='关注', exact=True).first.click()
page.reload()
page.get_by_role('button', name='取消关注', exact=True).first.wait_for()
page.locator('.social-search-row input').fill('no-such-person')
assert page.locator('.social-people-chip').count() == 0
page.get_by_role('button', name='清空筛选', exact=True).click()
assert page.locator('.social-people-chip').count() > 0
page.goto(BASE + '/#/pages/social/date/index')
page.locator('.social-date-act.like').click()
page.wait_for_timeout(350)
page.locator('.social-date-act.undo').click()
page.goto(BASE + '/#/pages/social/team/index')
page.get_by_role('button', name='我想参与 ↗', exact=True).first.click()
page.locator('.social-apply-sheet input').nth(0).fill('Applicant')
page.locator('.social-apply-sheet input').nth(1).fill('contact@example.invalid')
page.get_by_role('button', name='发送参与申请', exact=True).click()
page.get_by_role('button', name='重试提交', exact=True).wait_for()
state['fail_apply'] = False
page.get_by_role('button', name='重试提交', exact=True).click()
page.get_by_text('已表达兴趣', exact=True).wait_for()
apply_writes = [body for kind, body in writes if kind == 'apply']
assert apply_writes[0]['requestId'] == apply_writes[1]['requestId']
page.goto(BASE + '/#/pages/social/people/index?mode=cafe')
page.get_by_role('button', name='查看与分享评价', exact=True).first.click()
page.locator('.social-sheet-panel textarea').fill('Useful workspace')
page.get_by_role('button', name='发表评价', exact=True).click()
page.get_by_text('Useful workspace', exact=True).wait_for()
page.get_by_role('button', name='关闭评价', exact=True).click()
page.goto(BASE + '/#/pages/social/index')
page.get_by_role('tab', name='共创', exact=True).click()
page.locator('.social-ugc-card').first.click()
page.get_by_role('dialog').wait_for()
page.get_by_role('button', name='关闭介绍', exact=True).click()
page.get_by_role('button', name='社区故事', exact=False).click()
page.get_by_role('dialog', name='社区故事').wait_for()
page.locator('.connection-video-content header').click()
assert page.get_by_role('dialog', name='社区故事').is_visible()
page.get_by_role('dialog', name='社区故事').get_by_role('button', name='关闭', exact=True).click()
page.locator('.social-join-btn').count() # Joining must never send a mock payment order.
page.get_by_role('button', name='加入社区', exact=True).first.click()
page.get_by_role('dialog', name='加入社区').wait_for()
page.locator('.social-join-sheet-submit').wait_for()
assert page.locator('.social-join-sheet-submit').is_disabled()
page.get_by_role('dialog', name='加入社区').get_by_role('button', name='关闭', exact=True).click()
page.goto(BASE + '/#/pages/social/roster/index')
page.locator('#profile_name input').wait_for()
page.locator('#profile_name input').fill('Test Nomad')
page.locator('#profile_city input').fill('Dali')
state['fail_save'] = True
page.get_by_role('button', name='保存到社区', exact=True).click()
page.get_by_text('同步未完成,草稿已保留,可以稍后重试', exact=True).wait_for()
page.reload()
page.wait_for_timeout(400)
assert page.locator('#profile_name input').input_value() == 'Test Nomad'
state['fail_save'] = False
page.get_by_role('button', name='保存到社区', exact=True).click()
page.get_by_text('已同步到社区', exact=True).wait_for()
assert state['roster']['city'] == 'Dali'
page.goto(BASE + '/#/pages/social/chat/index')
page.locator('.im-composer input').fill('Hello from test')
page.get_by_role('button', name='发送消息', exact=True).click()
page.get_by_text('未送达 · 点重试', exact=True).wait_for()
state['fail_send'] = False
page.get_by_text('未送达 · 点重试', exact=True).click()
page.get_by_text('已送达', exact=True).wait_for()
message_writes = [body for kind, body in writes if kind == 'message']
assert len(message_writes) == 2
assert message_writes[0]['clientId'] == message_writes[1]['clientId']
assert not errors, errors
results.append({'width': width, 'routes': len(routes), 'writes': len(writes), 'ok': True})
context.close()
browser.close()
print(json.dumps(results))
if __name__ == '__main__':
run()

View File

@ -20,8 +20,6 @@ function App({ children }: PropsWithChildren) {
useLaunch(() => {
trackAppLaunch()
void loadRemoteConfig(true)
startRemoteConfigLiveSync()
startVipAccessLiveSync()
if (process.env.TARO_ENV === 'h5') {
applyH5Theme(getStoredH5Theme())
}

View File

@ -86,9 +86,26 @@ export type NomadroRemoteConfig = {
joinGroupDouyinQr?: string
/** 知识社群解锁文案 */
memoUnlockCta?: string
socialPages?: Record<string, { eyebrow?: string; title?: string; accent?: string; description?: string }>
socialVideoSources?: Record<string, string>
socialCatalogs?: Partial<Record<'roster' | 'gigs' | 'meetups' | 'cafes' | 'videos' | 'ebooks', unknown[]>>
socialHiddenSections?: string[]
[key: `social${string}`]: unknown
}
/** 导航分类/链接(后台 CRUD);离线用 links.json */
navContent?: NavContent
/** 社区运营内容;缺省使用包内目录。空数组可用于下架某类内容。 */
socialContent?: {
copy?: Record<string, string>
promoUrl?: string
hiddenSections?: string[]
roster?: unknown[]
gigs?: unknown[]
meetups?: unknown[]
cafes?: unknown[]
videos?: unknown[]
ebooks?: unknown[]
}
/** 分端配置:weapp.vipContent 仅微信 VIP 落地页;tt 由抖音端读,此处透传不解析 */
platforms?: {
weapp?: {

View File

@ -34,7 +34,7 @@ export const SOCIAL_COPY = {
socialWayTeam: '找搭子 · 共创',
} as const
export type SocialLandingCopy = typeof SOCIAL_COPY
export type SocialLandingCopy = { -readonly [K in keyof typeof SOCIAL_COPY]: string }
export const SOCIAL_DOCK = [
{ path: '/pages/social/index', label: '首页', short: '首页', emoji: '🏠', match: 'exact' as const },

View File

@ -51,6 +51,7 @@ export type SocialMeetup = {
};
export type SocialVideo = {
url?: string;
id: string;
title: string;
city: string;

View File

@ -1,209 +1,154 @@
/**
* 群组聊天:HTTP 拉历史/发消息 + Centrifugo WebSocket 实时。
* 无假消息;离线时本地队列可重试,UI 标明状态。
*/
/** Community chat: persistent outbox, explicit retries, HTTP + WebSocket. */
import { useCallback, useEffect, useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import {
getSocialGuestId,
socialApi,
type SocialChatMessage,
} from '@/services/socialApi'
import Taro, { useDidHide, useDidShow } from '@tarojs/taro'
import { createSocialRequestId, getSocialGuestId, socialApi, type SocialChatMessage } from '@/services/socialApi'
import { connectChatRealtime } from '@/services/socialRealtime'
import { mergeChatMessages } from '@/services/socialChatState'
import { readSocialLocal, writeSocialLocal } from '@/services/socialLocal'
export type ChatLinkStatus = 'connecting' | 'live' | 'polling' | 'offline'
const NICK_KEY = 'nick'
export function useSocialChat(channelId: string) {
const guest = getSocialGuestId()
const outboxKey = `outbox_${guest}_${channelId}`
const draftKey = `chat_draft_${channelId}`
const [messages, setMessages] = useState<SocialChatMessage[]>([])
const [draft, setDraft] = useState('')
const [draft, setDraft] = useState(() => readSocialLocal(draftKey, ''))
const [nick, setNick] = useState(() => {
try {
return String(Taro.getStorageSync(NICK_KEY) || '游民')
} catch {
return '游民'
}
try { return String(Taro.getStorageSync('nick') || '游民') } catch { return '游民' }
})
const [status, setStatus] = useState<ChatLinkStatus>('connecting')
const [sending, setSending] = useState(false)
const lock = useRef(false)
const mounted = useRef(true)
const guest = getSocialGuestId()
const active = useRef(channelId)
const mounted = useRef(false)
const initializedKey = useRef('')
const visible = useRef(true)
const refreshRef = useRef<() => Promise<void>>(async () => {})
active.current = channelId
const mergeRemote = useCallback((items: SocialChatMessage[]) => {
setMessages((current) => {
const pendingMine = current.filter(
(m) => m.mine && (m.delivery === 'local' || m.delivery === 'pending'),
)
const remote = items.map((item) => ({
...item,
mine: item.guestId === guest,
delivery: 'sent' as const,
}))
const ids = new Set(remote.map((m) => m.id))
return [
...remote,
...pendingMine.filter((m) => !ids.has(m.id)),
].slice(-300)
})
}, [guest])
useDidHide(() => { visible.current = false })
useDidShow(() => { visible.current = true; void refreshRef.current() })
useEffect(() => {
const timer = setTimeout(() => writeSocialLocal(draftKey, draft), 250)
return () => clearTimeout(timer)
}, [draft, draftKey])
useEffect(() => {
if (!mounted.current || initializedKey.current !== outboxKey) return
const pending = messages.filter((m) => m.mine && m.delivery !== 'sent').slice(-50)
.map((m) => ({ ...m, delivery: 'local' as const }))
writeSocialLocal(outboxKey, pending)
}, [messages, outboxKey])
useEffect(() => {
mounted.current = true
let cancelled = false
let stopWs: (() => void) | null = null
let stopWs: (() => void) | undefined
let refreshing = false
let realtime = false
let failures = 0
let nextRefresh = 0
const refresh = async () => {
if (cancelled || refreshing) return
if (cancelled || refreshing || !visible.current) return
refreshing = true
try {
const res = await socialApi.listMessages(channelId)
const response = await socialApi.listMessages(channelId)
if (cancelled) return
mergeRemote(res.items || [])
setStatus((s) => (s === 'live' ? 'live' : 'polling'))
if (!Array.isArray(response.items)) throw new Error('消息格式异常')
setMessages((current) => mergeChatMessages(current, response.items, guest))
failures = 0
nextRefresh = 0
setStatus(realtime ? 'live' : 'polling')
} catch {
if (!cancelled) setStatus((s) => (s === 'live' ? 'live' : 'offline'))
} finally {
refreshing = false
}
failures++
nextRefresh = Date.now() + Math.min(60000, 8000 * 2 ** Math.min(failures, 3))
if (!cancelled) setStatus(realtime ? 'live' : 'offline')
} finally { refreshing = false }
}
setMessages([])
refreshRef.current = refresh
const local = readSocialLocal<SocialChatMessage[]>(outboxKey, [])
initializedKey.current = outboxKey
setMessages(Array.isArray(local) ? local.filter((m) => m.channelId === channelId && m.guestId === guest).map((m) => ({ ...m, delivery: 'local' as const })) : [])
setDraft(readSocialLocal(draftKey, ''))
setSending(false)
lock.current = false
setStatus('connecting')
void refresh()
const poll = setInterval(() => void refresh(), 8000)
const timer = setInterval(() => {
if (Date.now() >= nextRefresh) void refresh()
}, 8000)
void connectChatRealtime(channelId, (item) => {
if (cancelled) return
setMessages((current) => {
if (current.some((m) => m.id === item.id)) return current
return [
...current,
{
...item,
mine: item.guestId === guest,
delivery: 'sent',
},
].slice(-300)
})
setStatus('live')
}).then((conn) => {
if (cancelled) {
conn?.disconnect()
return
}
if (conn) {
stopWs = conn.disconnect
setStatus('live')
} else {
setStatus((s) => (s === 'offline' ? 'offline' : 'polling'))
}
})
setMessages((current) => mergeChatMessages(current, [item], guest))
}, (connected) => {
realtime = connected
if (!cancelled) setStatus(connected ? 'live' : 'polling')
}).then((connection) => {
if (cancelled) connection?.disconnect()
else stopWs = connection?.disconnect
}).catch(() => { if (!cancelled) setStatus('polling') })
return () => {
cancelled = true
mounted.current = false
clearInterval(poll)
clearInterval(timer)
stopWs?.()
}
}, [channelId, guest, mergeRemote])
}, [channelId, guest, outboxKey, draftKey])
const deliver = useCallback(async (item: SocialChatMessage) => {
if (lock.current) return false
lock.current = true
setSending(true)
setMessages((current) => current.map((m) => m.id === item.id ? { ...m, delivery: 'pending' as const } : m))
try {
const saved = await socialApi.sendMessage(channelId, item.author, item.text, item.clientId)
if (!saved?.id) throw new Error('发送结果异常')
const pending = readSocialLocal<SocialChatMessage[]>(outboxKey, [])
if (Array.isArray(pending)) writeSocialLocal(outboxKey, pending.filter((message) => message.id !== item.id && (!item.clientId || message.clientId !== item.clientId)))
if (!mounted.current || active.current !== channelId) return true
setMessages((current) => mergeChatMessages(current.filter((m) => m.id !== item.id), [{ ...saved, guestId: guest, clientId: item.clientId }], guest))
return true
} catch {
if (!mounted.current || active.current !== channelId) return false
setMessages((current) => current.map((m) => m.id === item.id ? { ...m, delivery: 'local' as const } : m))
setStatus('offline')
void Taro.showToast({ title: '消息已保留,点击重试发送', icon: 'none' })
return false
} finally {
if (active.current === channelId) {
lock.current = false
if (mounted.current) setSending(false)
}
}
}, [channelId, guest, outboxKey])
const send = useCallback(async () => {
const text = draft.trim()
if (!text || text.length > 2000 || lock.current) return false
lock.current = true
setSending(true)
const author = nick.trim() || '游民'
const tempId = `local_${Date.now()}`
setMessages((current) =>
[
...current,
{
id: tempId,
channelId,
author,
text,
at: new Date().toISOString(),
guestId: guest,
mine: true,
delivery: 'pending',
},
].slice(-300),
)
setDraft('')
try {
Taro.setStorageSync(NICK_KEY, author)
const saved = await socialApi.sendMessage(channelId, author, text)
if (!mounted.current) return true
setMessages((current) =>
[
...current.filter((m) => m.id !== tempId && m.id !== saved.id),
{
...saved,
mine: true,
guestId: guest,
delivery: 'sent',
},
].slice(-300),
)
return true
} catch {
if (!mounted.current) return false
setMessages((current) =>
current.map((m) =>
m.id === tempId ? { ...m, delivery: 'local' as const } : m,
),
)
setStatus('offline')
Taro.showToast({ title: '发送失败,已留在本地', icon: 'none' })
return false
} finally {
lock.current = false
if (mounted.current) setSending(false)
const clientId = createSocialRequestId()
const item: SocialChatMessage = {
id: `local_${clientId}`, clientId, channelId, author: nick.trim().slice(0, 24) || '游民',
text, at: new Date().toISOString(), guestId: guest, mine: true, delivery: 'pending',
}
}, [channelId, draft, guest, nick])
// Save before clearing the input so navigating away cannot lose unsent text.
const existing = readSocialLocal<SocialChatMessage[]>(outboxKey, [])
if (!writeSocialLocal(outboxKey, [...(Array.isArray(existing) ? existing : []), { ...item, delivery: 'local' }].slice(-50))) {
void Taro.showToast({ title: '本地保存失败,请保留输入后重试', icon: 'none' })
return false
}
setMessages((current) => [...current, item].slice(-300))
setDraft('')
writeSocialLocal(draftKey, '')
try { Taro.setStorageSync('nick', item.author) } catch { /* optional */ }
return deliver(item)
}, [channelId, draft, draftKey, deliver, guest, nick, outboxKey])
const retryLocal = useCallback(
async (id: string) => {
const item = messages.find((m) => m.id === id && m.delivery === 'local')
if (!item || lock.current) return
lock.current = true
setSending(true)
try {
const saved = await socialApi.sendMessage(
channelId,
item.author,
item.text,
)
setMessages((current) =>
[
...current.filter((m) => m.id !== id && m.id !== saved.id),
{ ...saved, mine: true, guestId: guest, delivery: 'sent' },
].slice(-300),
)
setStatus((s) => (s === 'offline' ? 'polling' : s))
} catch {
Taro.showToast({ title: '仍失败,稍后重试', icon: 'none' })
} finally {
lock.current = false
setSending(false)
}
},
[channelId, guest, messages],
)
const retryLocal = useCallback(async (id: string) => {
const item = messages.find((m) => m.id === id && m.delivery === 'local')
if (item) await deliver(item)
}, [deliver, messages])
return {
messages,
draft,
setDraft,
nick,
setNick,
status,
sending,
send,
retryLocal,
}
return { messages, draft, setDraft, nick, setNick, status, sending, send, retryLocal, refresh: () => refreshRef.current() }
}

View File

@ -0,0 +1,41 @@
import { useEffect, useMemo, useState } from 'react'
import { getCachedRemoteConfig, subscribeRemoteConfig } from '@/services/remoteConfig'
import { DEFAULT_PROMO, MOCK_ROSTER, SEED_CAFES, SEED_EBOOKS, SEED_GIGS, SEED_MEETUPS, SEED_VIDEOS, SOCIAL_COPY, type SocialLandingCopy } from '@/data/socialSeed'
function catalog<T>(value: unknown, fallback: T[], valid: (row: any) => boolean): T[] {
if (!Array.isArray(value)) return fallback
const seen = new Set<string>()
const rows = value.filter((row) => {
if (!row || typeof row.id !== 'string' || !row.id || seen.has(row.id) || !valid(row)) return false
seen.add(row.id)
return true
})
return value.length && !rows.length ? fallback : rows as T[]
}
const text = (row: any, keys: string[]) => keys.every((key) => typeof row[key] === 'string')
const tags = (row: any) => Array.isArray(row.tags) && row.tags.every((tag: unknown) => typeof tag === 'string')
export function useSocialContent() {
const [config, setConfig] = useState(getCachedRemoteConfig)
useEffect(() => subscribeRemoteConfig((result) => setConfig(result.config)), [])
return useMemo(() => {
const source = { ...config.socialContent, ...config.copy.socialCatalogs }
const copy = { ...SOCIAL_COPY } as SocialLandingCopy
for (const key of Object.keys(copy) as (keyof SocialLandingCopy)[]) {
const value = config.copy[key] ?? source.copy?.[key]
if (typeof value === 'string') copy[key] = value
}
return {
copy,
pages: config.copy.socialPages || {},
promoUrl: typeof config.copy.socialPromoUrl === 'string' ? config.copy.socialPromoUrl : typeof source.promoUrl === 'string' ? source.promoUrl : DEFAULT_PROMO,
hiddenSections: Array.isArray(config.copy.socialHiddenSections) ? config.copy.socialHiddenSections.filter((key) => typeof key === 'string') : (Array.isArray(source.hiddenSections) ? source.hiddenSections : []),
roster: catalog(source.roster, MOCK_ROSTER, (r) => text(r, ['name', 'title', 'city', 'bio', 'lookingFor', 'avatar']) && tags(r) && (!r.gallery || (Array.isArray(r.gallery) && r.gallery.every((url: unknown) => typeof url === 'string'))) && (!r.languages || (Array.isArray(r.languages) && r.languages.every((value: unknown) => typeof value === 'string')))),
gigs: catalog(source.gigs, SEED_GIGS, (r) => text(r, ['title', 'role', 'pay']) && tags(r)),
meetups: catalog(source.meetups, SEED_MEETUPS, (r) => text(r, ['title', 'city', 'date', 'time', 'mirotalkRoom', 'channelId'])),
cafes: catalog(source.cafes, SEED_CAFES, (r) => text(r, ['name', 'city', 'vibe']) && Number.isFinite(r.wifiMbps)),
videos: catalog(source.videos, SEED_VIDEOS, (r) => text(r, ['title', 'city', 'summary', 'coverEmoji']) && Number.isFinite(r.minutes)).map((video) => ({ ...video, url: config.copy.socialVideoSources?.[video.id] || video.url })),
ebooks: catalog(source.ebooks, SEED_EBOOKS, (r) => text(r, ['title', 'blurb']) && Number.isFinite(r.chapters)),
}
}, [config])
}

View File

@ -0,0 +1,16 @@
import { useMemo, type CSSProperties } from 'react'
import { useNomadroTheme } from '@/utils/h5Theme'
import { safePx, useSafeAreaMetrics } from '@/utils/safeArea'
import '@/styles/social-next/ux.scss'
export function useSocialPage() {
const theme = useNomadroTheme()
const safe = useSafeAreaMetrics()
const pageStyle = useMemo(() => ({
'--safe-status-bar': safePx(safe.statusBarHeight),
'--safe-nav-bar': safePx(safe.navBarHeight),
'--safe-menu-pad': safePx(safe.menuRightPad),
'--safe-header': safePx(safe.headerHeight),
}) as CSSProperties, [safe.statusBarHeight, safe.navBarHeight, safe.menuRightPad, safe.headerHeight])
return { theme, pageStyle }
}

View File

@ -1,2 +1,64 @@
@use '../../styles/hub.scss';
@import '../../styles/weapp-parity.scss';
.hub-root .hub-theme-toggle,
.hub-root .hub-status-retry {
display: flex;
align-items: center;
justify-content: center;
min-width: 2.75rem;
min-height: 2.75rem;
margin: 0;
padding: 0 0.75rem;
border: var(--hub-border);
border-radius: 0.875rem;
background: var(--hub-bg-glass);
color: var(--hub-text);
font-size: 0.8125rem;
line-height: 1.4;
&::after { border: 0; }
&:active { opacity: 0.7; }
}
.hub-root .hub-theme-toggle { font-size: 1.375rem; }
.hub-home-lead,
.hub-offline-status,
.hub-empty-status {
order: 3;
width: 100%;
box-sizing: border-box;
color: var(--hub-muted);
font-size: 0.875rem;
text-align: center;
margin-top: 1rem;
}
.hub-offline-status,
.hub-empty-status {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 0.75rem;
}
.hub-root .hub-portal-card:active { opacity: 0.75; }
.hub-root[data-theme='light'] .hub-gradient-text {
color: #b45309 !important;
-webkit-text-fill-color: #b45309 !important;
}
.hub-root[data-theme='light'] .hub-portal-card--main .hub-portal-name {
color: #0f766e;
background: none;
-webkit-text-fill-color: #0f766e;
}
@media (prefers-reduced-motion: reduce) {
.hub-root .hub-shape,
.hub-root .hub-float-card,
.hub-root .hub-globe-css-dot,
.hub-root .hub-globe-css-path { animation: none !important; }
}

View File

@ -3,7 +3,7 @@
* H5 真布局用原生 div(Taro View 自定义元素会弄塌 grid/绝对定位)。
*/
import { useEffect, useState, type CSSProperties, type ReactNode } from 'react'
import { View, Text } from '@tarojs/components'
import { View, Text, Button } from '@tarojs/components'
import Taro, { useDidShow, usePageScroll } from '@tarojs/taro'
import {
getCachedRemoteConfig,
@ -12,7 +12,7 @@ import {
subscribeRemoteConfig,
} from '@/services/remoteConfig'
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
import { applyH5Theme, useNomadroTheme } from '@/utils/h5Theme'
import { applyH5Theme, toggleH5Theme, useNomadroTheme } from '@/utils/h5Theme'
import { goPage } from '@/utils/nav'
import { usePageShare, markPageShare } from '@/utils/pageShare'
import { safePx, useSafeAreaMetrics } from '@/utils/safeArea'
@ -167,10 +167,26 @@ function IndexPage() {
const [config, setConfig] = useState<NomadroRemoteConfig>(() => getCachedRemoteConfig())
const theme = useNomadroTheme()
const [navScrolled, setNavScrolled] = useState(false)
const [offline, setOffline] = useState(false)
const [refreshing, setRefreshing] = useState(false)
async function refreshConfig() {
if (refreshing) return
setRefreshing(true)
try {
const result = await loadRemoteConfig(true)
setConfig(result.config)
setOffline(result.fromOffline)
} finally {
setRefreshing(false)
}
}
useEffect(() => {
const unsub = subscribeRemoteConfig((r) => setConfig(r.config))
void loadRemoteConfig(true).then((r) => setConfig(r.config))
const unsub = subscribeRemoteConfig((r) => {
setConfig(r.config)
setOffline(r.fromOffline)
})
applyH5Theme(theme)
return unsub
}, [])
@ -342,6 +358,13 @@ function IndexPage() {
<Txt className="hub-logo-text">{brand}</Txt>
</Box>
<Box className="hub-nav-actions">
<Button
className="hub-theme-toggle"
aria-label={theme === 'dark' ? '切换日间模式' : '切换夜间模式'}
onClick={() => toggleH5Theme(theme)}
>
{theme === 'dark' ? '☀' : '☾'}
</Button>
{showQuickNav && isH5 && isDev ? (
<Box className="hub-dev-nav">
<Box className="hub-dev-link" onClick={() => openDevLink('admin')}>
@ -408,6 +431,17 @@ function IndexPage() {
<Txt className="hub-gradient-text">自由生活</Txt>
</Box>
{cfg.copy.homeLead ? <Box className="hub-home-lead"><Txt>{cfg.copy.homeLead}</Txt></Box> : null}
{offline && cfg.flags.offlineBadge ? (
<Box className="hub-offline-status">
<Txt>当前显示本地内容</Txt>
<Button className="hub-status-retry" loading={refreshing} disabled={refreshing} onClick={refreshConfig}>
重新连接
</Button>
</Box>
) : null}
<Box className="hub-portal-grid hub-reveal visible">
{portals.map((portal) => (
<Box
@ -424,6 +458,14 @@ function IndexPage() {
</Box>
))}
</Box>
{!portals.length ? (
<Box className="hub-empty-status">
<Txt>内容正在准备中</Txt>
<Button className="hub-status-retry" loading={refreshing} disabled={refreshing} onClick={refreshConfig}>
刷新内容
</Button>
</Box>
) : null}
</Box>
</Box>
</Box>

View File

@ -1 +1,69 @@
/* mine — shared theme */
.mine-page {
--mine-bg: #0a0e17;
--mine-card: #111827;
--mine-text: #f1f5f9;
--mine-muted: #94a3b8;
--mine-border: rgba(148, 163, 184, 0.18);
min-height: 100vh;
background: var(--mine-bg);
color: var(--mine-text);
}
.mine-page[data-theme='light'] {
--mine-bg: #f8fafc;
--mine-card: #fff;
--mine-text: #0f172a;
--mine-muted: #64748b;
--mine-border: rgba(15, 23, 42, 0.12);
}
.mine-page .mine-container {
padding: 1.25rem 1rem calc(2rem + env(safe-area-inset-bottom));
box-sizing: border-box;
}
.mine-page .profile-header,
.mine-page .profile-stats,
.mine-page .mine-empty {
padding: 1.5rem;
margin-bottom: 1.25rem;
background: var(--mine-card);
border: 1rpx solid var(--mine-border);
border-radius: 1.25rem;
color: var(--mine-text);
}
.mine-page .profile-header { align-items: center; gap: 0.5rem; text-align: center; }
.mine-page .profile-avatar { width: 4.5rem; height: 4.5rem; font-size: 2rem; margin-bottom: 0.75rem; }
.mine-page .profile-name { display: block; font-size: 1.25rem; font-weight: 600; }
.mine-page .profile-email,
.mine-page .profile-level { display: block; margin-top: 0.5rem; color: var(--mine-muted); font-size: 0.875rem; }
.mine-page .profile-stats { display: flex; flex-wrap: nowrap; justify-content: space-around; gap: 0.75rem; padding: 1.25rem 0.75rem; }
.mine-page .profile-stat { display: flex; flex: 1; min-width: 0; padding: 0; border: 0; background: transparent; flex-direction: column; align-items: center; gap: 0.375rem; font-size: 0.875rem; overflow-wrap: anywhere; }
.mine-page .profile-stat-n { font-size: 1.125rem; font-weight: 600; }
.mine-page .profile-stat-l { color: var(--mine-muted); }
.mine-page .btn {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
min-height: 2.75rem;
padding: 0.625rem 1rem;
margin-top: 1rem;
border-radius: 0.875rem;
box-sizing: border-box;
font-size: 0.9375rem;
line-height: 1.5;
&::after { border: 0; }
&:active { opacity: 0.75; }
&[disabled] { opacity: 0.65; }
}
.mine-page .btn-primary { background: #4ecdc4; color: #0a0e17; font-weight: 600; }
.mine-page .btn-ghost { background: transparent; border: 1rpx solid var(--mine-border); color: var(--mine-text); }
.mine-page .mine-sync-row { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; color: var(--mine-muted); font-size: 0.8125rem; margin: 1.25rem 0; }
.mine-page .mine-sync-row .btn { width: auto; margin: 0; flex-shrink: 0; }
.mine-page .mine-favorites-title { display: block; font-size: 1.125rem; margin-bottom: 1rem; color: var(--mine-text); }
.mine-page .mine-empty { text-align: center; color: var(--mine-muted); font-size: 0.875rem; line-height: 1.75; }
.mine-page .mine-inline-error { display: block; margin: 0.75rem 0; color: var(--mine-muted); font-size: 0.875rem; }

View File

@ -1,6 +1,6 @@
import { View, Text, Button, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useEffect, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { useEffect, useRef, useState } from 'react'
import { BrandNav, SiteFooter } from '../../components/Chrome'
import { DestCard } from '../../components/DestCard'
import { STORAGE_OPENID, STORAGE_TOKEN } from '../../utils/config'
@ -12,6 +12,10 @@ import {
type ProfileStats,
} from '../../services/api'
import { usePageShare, markPageShare } from '@/utils/pageShare'
import { useNomadroTheme } from '@/utils/h5Theme'
import { goPage } from '@/utils/nav'
import { isAccountBlockedError } from '@/utils/accountBlocked'
import { safePx, useSafeAreaMetrics } from '@/utils/safeArea'
import './index.scss'
type MineUser = {
@ -28,8 +32,17 @@ function MinePage() {
const [stats, setStats] = useState<ProfileStats | null>(null)
const [favs, setFavs] = useState<Destination[]>([])
const [loading, setLoading] = useState(false)
const [refreshing, setRefreshing] = useState(false)
const [refreshError, setRefreshError] = useState('')
const [favoritesError, setFavoritesError] = useState(false)
const refreshId = useRef(0)
const refreshInFlight = useRef(false)
const theme = useNomadroTheme()
const safe = useSafeAreaMetrics()
async function refresh() {
if (refreshInFlight.current) return
const id = ++refreshId.current
const token = Taro.getStorageSync(STORAGE_TOKEN)
const openid = Taro.getStorageSync(STORAGE_OPENID)
if (!token || !openid) {
@ -38,6 +51,12 @@ function MinePage() {
setFavs([])
return
}
// 已有会话先显示账户壳;弱网不把用户退回登录页。
setUser((current) => current || { id: String(openid), name: 'Nomadro 用户', email: '', avatar: '🟢' })
refreshInFlight.current = true
setRefreshing(true)
setRefreshError('')
setFavoritesError(false)
try {
// 主会话:ebook Bearer(与支付 / VIP 一致)
const presence = await requestEbook<{
@ -45,6 +64,7 @@ function MinePage() {
openid?: string
isVip?: boolean
}>({ url: '/api/ebook/auth/presence', method: 'POST' })
if (id !== refreshId.current) return
setUser({
id: String(presence.openid || openid),
name: 'Nomadro 用户',
@ -53,22 +73,34 @@ function MinePage() {
isVip: Boolean(presence.isVip),
})
// 社群收藏为增强项,失败不踢主登录
const [s, f] = await Promise.all([
fetchProfileStats().catch(() => null),
fetchFavoriteDetails().catch(() => [] as Destination[]),
const [s, f] = await Promise.allSettled([
fetchProfileStats(),
fetchFavoriteDetails(),
])
setStats(s)
setFavs(f)
} catch {
clearLogin()
setUser(null)
setStats(null)
setFavs([])
if (id !== refreshId.current) return
if (s.status === 'fulfilled') setStats(s.value)
if (f.status === 'fulfilled') setFavs(f.value)
else setFavoritesError(true)
} catch (error) {
if (id !== refreshId.current) return
if (isAccountBlockedError(error) || !Taro.getStorageSync(STORAGE_TOKEN)) {
setUser(null)
setStats(null)
setFavs([])
}
setRefreshError(isAccountBlockedError(error) ? '账号不可用' : '同步失败,请检查网络后重试')
} finally {
if (id === refreshId.current) {
refreshInFlight.current = false
setRefreshing(false)
}
}
}
useDidShow(() => { void refresh() })
useEffect(() => {
void refresh()
return () => { refreshId.current += 1 }
}, [])
async function onWechatLogin() {
@ -97,6 +129,11 @@ function MinePage() {
}
function onLogout() {
refreshId.current += 1
refreshInFlight.current = false
setRefreshing(false)
setRefreshError('')
setFavoritesError(false)
clearLogin()
setUser(null)
setStats(null)
@ -104,9 +141,10 @@ function MinePage() {
}
return (
<ScrollView scrollY className="page-shell" showScrollbar={false}>
<ScrollView scrollY className="page-shell mine-page" data-theme={theme} showScrollbar={false}
style={{ paddingTop: safePx(safe.statusBarHeight), boxSizing: 'border-box' }}>
<BrandNav chip="我的" />
<View className="container" style={{ paddingBottom: '48px' }}>
<View className="container mine-container">
<Text className="section-tag">👤 MINE</Text>
<Text className="section-h2">我的</Text>
@ -117,8 +155,8 @@ function MinePage() {
</View>
<Text className="profile-name">未登录</Text>
<Text className="profile-email">微信一键登录,同步会员与收藏</Text>
<Button className="btn btn-primary" loading={loading} onClick={onWechatLogin}>
微信登录
<Button className="btn btn-primary" loading={loading} disabled={loading} onClick={onWechatLogin}>
{loading ? '正在登录' : '微信登录'}
</Button>
</View>
) : (
@ -129,7 +167,7 @@ function MinePage() {
</View>
<Text className="profile-name">{user.name}</Text>
<Text className="profile-email">
{user.isVip ? '👑 VIP 会员' : '普通用户 · 可开通 VIP'}
{user.isVip === undefined ? '会员信息待同步' : user.isVip ? '👑 VIP 会员' : '普通用户 · 可开通 VIP'}
</Text>
{stats ? <Text className="profile-level">{stats.nomad_level}</Text> : null}
<Button className="btn btn-ghost" onClick={onLogout}>
@ -157,27 +195,39 @@ function MinePage() {
</View>
) : null}
<Text className="section-h2" style={{ fontSize: '32px', marginBottom: '16px' }}>
<View className="mine-sync-row">
<Text>{refreshing ? '正在同步账户' : refreshError || '账户与收藏'}</Text>
<Button className="btn btn-ghost" loading={refreshing} disabled={refreshing} onClick={refresh}>
{refreshError ? '重试同步' : '刷新'}
</Button>
</View>
<Text className="section-h2 mine-favorites-title">
❤️ 收藏的城市
</Text>
{favoritesError ? <Text className="mine-inline-error">收藏暂未同步,请刷新重试</Text> : null}
{favs.length ? (
favs.map((d) => <DestCard key={d.slug} d={d} favorited />)
) : (
<Text className="dest-empty">还没有收藏 · 去目的地逛逛</Text>
<View className="mine-empty">
<Text>{refreshing ? '正在加载收藏…' : favoritesError || refreshError ? '连接恢复后即可查看收藏' : '收藏喜欢的城市,留给下一次出发'}</Text>
{!refreshing && !favoritesError && !refreshError ? (
<Button className="btn btn-ghost" onClick={() => goPage('/pages/destinations/index')}>探索目的地</Button>
) : null}
</View>
)}
</>
)}
{!user && refreshError ? <Text className="mine-inline-error">{refreshError}</Text> : null}
<Button
className="btn btn-primary"
style={{ marginTop: '16px', width: '100%' }}
onClick={() => Taro.navigateTo({ url: '/pages/vip/index' })}
onClick={() => goPage('/pages/vip/index')}
>
👑 开通 VIP
</Button>
<Button
className="btn btn-ghost"
style={{ marginTop: '24px', width: '100%' }}
onClick={() => Taro.setClipboardData({ data: 'https://nomadro.cn' })}
>
复制官网 nomadro.cn

View File

@ -1,6 +1,8 @@
import { useSocialLikes } from '@/services/socialLocal'
import { useSocialContent } from '@/hooks/useSocialContent'
import { useMemo, useState } from 'react'
import { MOCK_ROSTER } from '@/data/socialSeed'
import { goPage } from '@/utils/nav'
import { goSocialPage as goPage } from '@/utils/socialNavigation'
import { SocialAvatar } from './SocialAvatar'
import { PeopleChip } from './PeopleChip'
import { H5El } from './H5El'
@ -13,18 +15,19 @@ const FILTERS = [
]
export function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
const { roster } = useSocialContent()
const [filter, setFilter] = useState<'all' | 'online' | 'f' | 'm'>('all')
const [likes, setLikes] = useState<Record<string, boolean>>({})
const [likes, setLikes] = useSocialLikes()
const list = useMemo(() => {
return MOCK_ROSTER.filter((m) => {
return roster.filter((m) => {
if (filter === 'online') return m.online
if (filter === 'f' || filter === 'm') return m.gender === filter
return true
})
}, [filter])
}, [filter, roster])
const online = useMemo(() => MOCK_ROSTER.filter((m) => m.online), [])
const online = useMemo(() => roster.filter((m) => m.online), [roster])
return (
<H5El as='section' className='section section-compact' id='people' aria-label='在线游民'>

View File

@ -0,0 +1,70 @@
import { useEffect, useRef, useState } from 'react'
import { Textarea } from '@tarojs/components'
import Taro from '@tarojs/taro'
import type { SocialCafe, SocialCafeReview } from '@/data/socialTypes'
import { socialApi } from '@/services/socialApi'
import { readSocialLocal, writeSocialLocal } from '@/services/socialLocal'
import { H5El } from './H5El'
export function CafeReviews({ cafe, onClose }: { cafe: SocialCafe; onClose: () => void }) {
const [items, setItems] = useState<SocialCafeReview[]>([])
const [text, setText] = useState(() => readSocialLocal(`cafe_draft_${cafe.id}`, ''))
const [score, setScore] = useState(5)
const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const lock = useRef(false)
const alive = useRef(true)
const load = async () => {
setLoading(true)
try {
const response = await socialApi.listCafeReviews(cafe.id)
if (alive.current) { setItems(response.items || []); setError('') }
} catch { if (alive.current) setError('评价暂时无法加载,可稍后重试') }
finally { if (alive.current) setLoading(false) }
}
useEffect(() => {
alive.current = true
void load()
return () => { alive.current = false }
}, [cafe.id])
const submit = async () => {
if (lock.current || !text.trim()) return
lock.current = true
setBusy(true)
writeSocialLocal(`cafe_draft_${cafe.id}`, text)
try {
const saved = await socialApi.addCafeReview(cafe.id, String(Taro.getStorageSync('nick') || '游民'), score, text.trim())
if (!alive.current) return
setItems((current) => [saved, ...current.filter((item) => item.id !== saved.id)])
setText('')
writeSocialLocal(`cafe_draft_${cafe.id}`, '')
setError('')
} catch { if (alive.current) setError('未确认提交结果,草稿已保留;请刷新评价后再决定是否重试') }
finally { lock.current = false; if (alive.current) setBusy(false) }
}
return <H5El className='social-sheet-mask' onClick={() => !busy && onClose()}>
<H5El className='social-sheet-panel social-panel' role='dialog' aria-modal='true' aria-label={`${cafe.name}评价`} onClick={(event) => event?.stopPropagation?.()}>
<H5El className='social-sheet-head'><H5El as='strong'>☕ {cafe.name}</H5El>
<H5El as='button' disabled={busy} aria-label='关闭评价' onClick={onClose}>✕</H5El></H5El>
<H5El as='p' className='social-muted'>{cafe.city} · {cafe.power} · WiFi {cafe.wifiMbps} Mbps(目录参考值)</H5El>
<H5El className='social-rating-row' aria-label='评分'>
{[1, 2, 3, 4, 5].map((rating) => <H5El as='button' key={rating} className={score === rating ? 'is-on' : ''}
aria-label={`${rating}星`} aria-pressed={score === rating} disabled={busy} onClick={() => setScore(rating)}>{rating}★</H5El>)}
</H5El>
<Textarea className='social-field-input' value={text} maxlength={2000} autoHeight disabled={busy}
placeholder='分享真实到访体验:网络、插座、环境…' onInput={(event) => {
setText(event.detail.value); writeSocialLocal(`cafe_draft_${cafe.id}`, event.detail.value)
}} />
<H5El as='button' className='btn btn-primary' disabled={busy || !text.trim()} loading={busy} onClick={() => void submit()}>发表评价</H5El>
{error ? <H5El className='social-inline-status' role='alert'>{error}</H5El> : null}
<H5El className='social-search-summary'><H5El as='strong'>大家的评价</H5El>
<H5El as='button' disabled={loading || busy} onClick={() => void load()}>{loading ? '加载中…' : '刷新评价'}</H5El></H5El>
{!loading && !items.length ? <H5El as='p' className='social-muted'>{error ? '暂未取得评价' : '还没有评价,欢迎分享你的体验'}</H5El> : null}
{items.map((item) => <H5El key={item.id} className='social-review-item'>
<H5El as='strong'>{item.author} · {item.score}★</H5El><H5El as='p'>{item.text}</H5El>
<H5El as='small' className='social-muted'>{item.at.slice(0, 10)}</H5El>
</H5El>)}
</H5El>
</H5El>
}

View File

@ -1,8 +1,9 @@
import { useState, type CSSProperties } from 'react'
import { Video } from '@tarojs/components'
import { useSocialContent } from '@/hooks/useSocialContent'
import Taro from '@tarojs/taro'
import { MOCK_ROSTER, SOCIAL_COPY, type SocialLandingCopy } from '@/data/socialSeed'
import { goPage } from '@/utils/nav'
import { SOCIAL_COPY, type SocialLandingCopy } from '@/data/socialSeed'
import { goSocialPage as goPage } from '@/utils/socialNavigation'
import { SocialAvatar } from './SocialAvatar'
import { FloatingEmojiField } from './SocialExperience'
import { H5El } from './H5El'
@ -48,8 +49,10 @@ export function ConnectionHero({
copy?: SocialLandingCopy
}) {
const [videoOpen, setVideoOpen] = useState(false)
const { roster } = useSocialContent()
return (
<>
<H5El as='section' className='connection-hero' id='hero' aria-labelledby='connection-title'>
<H5El className='connection-hero-grid' aria-hidden />
<FloatingEmojiField />
@ -118,7 +121,7 @@ export function ConnectionHero({
</H5El>
<H5El className='connection-proof'>
<H5El className='connection-avatar-stack' aria-hidden>
{MOCK_ROSTER.slice(0, 5).map((m) => (
{roster.slice(0, 5).map((m) => (
<SocialAvatar key={m.id} src={m.avatar} size={36} />
))}
</H5El>
@ -155,8 +158,8 @@ export function ConnectionHero({
<H5El as='strong'>同频,自有引力</H5El>
<H5El as='span'>想见的人</H5El>
</H5El>
{NODES.map(({ member, x, y, rotate }, i) => {
const m = MOCK_ROSTER[member]!
{NODES.slice(0, roster.length).map(({ member, x, y, rotate }, i) => {
const m = roster[member % roster.length]!
const style = {
['--node-x' as string]: `${x}%`,
['--node-y' as string]: `${y}%`,
@ -166,7 +169,7 @@ export function ConnectionHero({
return (
<H5El
as='a'
key={m.id}
key={`${i}:${m.id}`}
href='#people'
className={`connection-person connection-person-${i}`}
style={style}
@ -237,6 +240,7 @@ export function ConnectionHero({
<H5El as='span'>认识人 · 开视频 · 见一面</H5El>
</H5El>
</H5El>
{videoOpen ? (
<H5El
className='connection-video-dialog is-open'
@ -247,23 +251,31 @@ export function ConnectionHero({
inset: 0,
zIndex: 2000,
display: 'flex',
alignItems: 'center',
alignItems: 'flex-end',
justifyContent: 'center',
background: 'rgba(0,0,0,0.72)',
padding: 16,
padding: '0',
width: '100%',
height: '100%',
maxHeight: 'none',
margin: 0,
border: 0,
borderRadius: 0,
}}
onClick={() => setVideoOpen(false)}
>
<H5El
className='connection-video-content'
style={{
width: 'min(920px, 100%)',
background: '#0c0c0f',
borderRadius: 16,
width: '100%',
maxWidth: '57.5rem',
background: 'var(--social-surface, #0c0c0f)',
borderRadius: '1rem 1rem 0 0',
paddingBottom: 'env(safe-area-inset-bottom)',
overflow: 'hidden',
border: '1px solid rgba(255,255,255,0.1)',
}}
onClick={() => undefined}
onClick={(event) => event.stopPropagation()}
>
<H5El
as='header'
@ -271,11 +283,11 @@ export function ConnectionHero({
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: '12px 16px',
padding: '0.75rem 1rem',
}}
>
<H5El as='h2'>游民社区 · 社区故事</H5El>
<H5El as='button' onClick={() => setVideoOpen(false)} aria-label='关闭'>
<H5El as='button' style={{ minWidth: '2.75rem', minHeight: '2.75rem' }} onClick={() => setVideoOpen(false)} aria-label='关闭'>
✕
</H5El>
</H5El>
@ -283,12 +295,12 @@ export function ConnectionHero({
src={promoUrl}
controls
autoplay
style={{ width: '100%', height: 360, display: 'block' }}
style={{ width: '100%', height: '15rem', display: 'block' }}
/>
</H5El>
</H5El>
) : null}
</H5El>
</>
)
}

View File

@ -0,0 +1,22 @@
import { Video } from '@tarojs/components'
import type { SocialEbook, SocialVideo } from '@/data/socialTypes'
import { goSocialPage } from '@/utils/socialNavigation'
import { H5El } from './H5El'
export function CreationSheet({ item, kind, onClose }: { item: SocialEbook | SocialVideo; kind: 'ebook' | 'video'; onClose: () => void }) {
const video = kind === 'video' ? item as SocialVideo : null
const book = kind === 'ebook' ? item as SocialEbook : null
return <H5El className='social-sheet-mask' onClick={onClose}>
<H5El className='social-sheet-panel social-panel' role='dialog' aria-modal='true' aria-label={item.title} onClick={(event) => event?.stopPropagation?.()}>
<H5El className='social-sheet-head'><H5El as='strong'>{video ? '🎬' : '📖'} {item.title}</H5El>
<H5El as='button' aria-label='关闭介绍' onClick={onClose}>✕</H5El></H5El>
<H5El as='p' className='social-muted'>{video ? `${video.city} · ${video.minutes} 分钟` : `${book?.chapters} 章 · 约 ${book?.minutes} 分钟`}</H5El>
<H5El as='p'>{video?.summary || book?.blurb}</H5El>
{video?.url && /^https:\/\//.test(video.url) ? <Video src={video.url} controls style={{ width: '100%', height: '14rem' }} /> : null}
<H5El className='social-section-actions'>
{book ? <H5El as='button' className='btn btn-primary' onClick={() => goSocialPage('/pages/book/index')}>浏览数字游民小册</H5El> : null}
<H5El as='button' className='btn' onClick={() => goSocialPage('/pages/social/team/index?kind=volunteer')}>参与社区共创</H5El>
</H5El>
</H5El>
</H5El>
}

View File

@ -4,7 +4,7 @@ import type {
ReactNode,
ElementType,
} from 'react'
import { Text, View } from '@tarojs/components'
import { Button, Text, View } from '@tarojs/components'
import { trackClick } from '@/utils/track'
const isH5 = process.env.TARO_ENV === 'h5'
@ -20,6 +20,8 @@ type Props = {
href?: string
htmlFor?: string
type?: string
disabled?: boolean
loading?: boolean
role?: string
'aria-label'?: string
'aria-hidden'?: boolean | 'true' | 'false'
@ -54,6 +56,8 @@ export function H5El({
trackLabel,
href,
type,
disabled,
loading,
role,
'aria-label': ariaLabel,
'aria-hidden': ariaHidden,
@ -66,6 +70,7 @@ export function H5El({
}: Props) {
const handleClick = onClick
? (e?: any) => {
if (disabled || loading) return
if (trackLabel) trackClick(trackLabel)
onClick(e)
}
@ -87,7 +92,7 @@ export function H5El({
},
}
: Tag === 'button'
? { type: type || 'button', onClick: handleClick }
? { type: type || 'button', onClick: handleClick, disabled: disabled || loading, 'aria-busy': loading }
: handleClick
? { onClick: handleClick }
: {}
@ -97,7 +102,7 @@ export function H5El({
id={id}
className={className}
style={style}
role={role}
role={role || (handleClick && Tag !== 'a' && Tag !== 'button' ? 'button' : undefined)}
aria-label={ariaLabel}
aria-hidden={ariaHidden}
aria-current={ariaCurrent}
@ -106,6 +111,14 @@ export function H5El({
data-theme={dataTheme}
dangerouslySetInnerHTML={dangerouslySetInnerHTML}
{...clickProps}
{...(handleClick && Tag !== 'a' && Tag !== 'button' ? {
tabIndex: 0,
onKeyDown: (event: any) => {
if (event.target === event.currentTarget && (event.key === 'Enter' || event.key === ' ')) {
event.preventDefault(); handleClick(event)
}
},
} : {})}
{...rest}
>
{dangerouslySetInnerHTML ? undefined : children}
@ -124,8 +137,14 @@ export function H5El({
: View
// weapp 无语义标签:补 as-* class,方便 CSS 用 .as-i / .as-h1 对齐 Next 选择器
const miniClass = [className, `as-${tag}`].filter(Boolean).join(' ')
if (tag === 'button') {
return <Button id={id} className={miniClass} style={style} disabled={disabled || loading}
loading={loading} onClick={handleClick} hoverClass='social-pressed' aria-label={ariaLabel}>
{children}
</Button>
}
return (
<Mini id={id} className={miniClass} style={style} onClick={handleClick}>
<Mini id={id} className={miniClass} style={style} onClick={handleClick} data-theme={dataTheme}>
{children}
</Mini>
)

View File

@ -1,10 +1,9 @@
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { H5El } from './H5El'
import {
fetchSocialJoinStatus,
isSocialJoinLocal,
paySocialJoin,
} from '@/utils/socialJoinPay'
import './JoinPaySheet.scss'
@ -28,6 +27,9 @@ export function JoinPaySheet({ open, onClose, onPaid }: Props) {
const [err, setErr] = useState('')
const [priceLabel, setPriceLabel] = useState('¥49')
const [already, setAlready] = useState(false)
const [checking, setChecking] = useState(true)
const [enabled, setEnabled] = useState(false)
const submitLock = useRef(false)
useEffect(() => {
if (!open) return
@ -37,19 +39,27 @@ export function JoinPaySheet({ open, onClose, onPaid }: Props) {
setEmail('')
}
setErr('')
let cancelled = false
setChecking(true)
setEnabled(false)
setBusy(false)
setAlready(isSocialJoinLocal())
setAlready(false)
void fetchSocialJoinStatus().then((s) => {
if (!s) return
if (s.isMember) setAlready(true)
if (s.priceFen > 0) setPriceLabel(`¥${(s.priceFen / 100).toFixed(0)}`)
if (cancelled) return
setChecking(false)
if (!s?.ok) { setErr('暂时无法确认价格与资格,请重新打开后重试'); return }
setAlready(s.isMember)
setEnabled(s.enabled)
if (!s.enabled && !s.isMember) setErr('暂未开放加群支付')
setPriceLabel(`¥${(s.priceFen / 100).toFixed(2).replace(/\.00$/, '')}`)
})
return () => { cancelled = true }
}, [open])
if (!open) return null
const submit = async () => {
if (busy) return
if (submitLock.current || checking || !enabled) return
if (already) {
onClose()
return
@ -60,6 +70,7 @@ export function JoinPaySheet({ open, onClose, onPaid }: Props) {
return
}
setErr('')
submitLock.current = true
setBusy(true)
try {
Taro.setStorageSync(EMAIL_KEY, value)
@ -77,6 +88,7 @@ export function JoinPaySheet({ open, onClose, onPaid }: Props) {
setErr(msg || '支付唤起失败,请稍后重试')
}
} finally {
submitLock.current = false
setBusy(false)
}
}
@ -85,6 +97,7 @@ export function JoinPaySheet({ open, onClose, onPaid }: Props) {
<H5El className='social-join-sheet-mask' onClick={() => !busy && onClose()}>
<H5El
className='social-join-sheet-panel'
role='dialog' aria-modal='true' aria-label='加入社区'
onClick={(e) => {
e?.stopPropagation?.()
}}
@ -99,6 +112,7 @@ export function JoinPaySheet({ open, onClose, onPaid }: Props) {
type='button'
className='social-join-sheet-close'
aria-label='关闭'
disabled={busy}
onClick={() => !busy && onClose()}
>
✕
@ -140,9 +154,10 @@ export function JoinPaySheet({ open, onClose, onPaid }: Props) {
as='button'
type='button'
className='btn btn-primary social-join-sheet-submit'
disabled={busy || checking || !enabled} loading={busy || checking}
onClick={() => void submit()}
>
{busy ? '正在唤起支付…' : `确认并支付 ${priceLabel}`}
{checking ? '正在确认…' : busy ? '正在唤起支付…' : `确认并支付 ${priceLabel}`}
</H5El>
<H5El as='p' className='social-join-privacy'>
🔒 邮箱用于账号识别 · 微信小程序虚拟支付

View File

@ -1,5 +1,5 @@
import type { SocialRosterMember } from '@/data/socialSeed'
import { goPage } from '@/utils/nav'
import { goSocialPage as goPage } from '@/utils/socialNavigation'
import { SocialAvatar } from './SocialAvatar'
import { H5El } from './H5El'

View File

@ -1,5 +1,5 @@
import type { CSSProperties } from 'react'
import { Image } from '@tarojs/components'
import { useState, type CSSProperties } from 'react'
import { Image, Text } from '@tarojs/components'
const isH5 = process.env.TARO_ENV === 'h5'
@ -12,15 +12,22 @@ export function SocialAvatar({
size?: number
className?: string
}) {
const [failedSrc, setFailedSrc] = useState('')
const fallback = !src || failedSrc === src
const style: CSSProperties = {
width: size,
height: size,
width: `${size / 16}rem`,
height: `${size / 16}rem`,
borderRadius: '999px',
display: 'block',
objectFit: 'cover',
flexShrink: 0,
background: '#1a1d24',
}
if (fallback) {
const fallbackStyle: CSSProperties = { ...style, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: `${size / 32}rem`, color: '#68ddd0', background: '#1b3541' }
return isH5 ? <span className={`social-avatar ${className}`} style={fallbackStyle} aria-hidden='true'>☺</span> :
<Text className={`social-avatar ${className}`} style={fallbackStyle}>☺</Text>
}
if (isH5) {
return (
@ -28,6 +35,7 @@ export function SocialAvatar({
<img
className={`social-avatar ${className}`.trim()}
src={src}
onError={() => setFailedSrc(src)}
width={size}
height={size}
style={style}
@ -41,6 +49,7 @@ export function SocialAvatar({
<Image
className={`social-avatar ${className}`.trim()}
src={src}
onError={() => setFailedSrc(src)}
mode='aspectFill'
style={style}
lazyLoad

View File

@ -1,7 +1,7 @@
import { useMemo } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { SOCIAL_DOCK } from '@/data/socialSeed'
import { goPage } from '@/utils/nav'
import { goSocialPage as goPage } from '@/utils/socialNavigation'
import { H5El } from './H5El'
function normalize(path: string) {

View File

@ -6,6 +6,7 @@ import {
type ReactNode,
} from 'react'
import { H5El } from './H5El'
import { toggleH5Theme, useNomadroTheme } from '@/utils/h5Theme'
const isH5 = process.env.TARO_ENV === 'h5'
@ -188,6 +189,7 @@ export function SocialExperience({
children: ReactNode
showEmojiField?: boolean
}) {
const theme = useNomadroTheme()
const [immersive, setImmersive] = useState(true)
const rootRef = useRef<HTMLDivElement | null>(null)
@ -227,8 +229,10 @@ export function SocialExperience({
// 微信禁止裸 <div>/<canvas>,否则整页黑屏;H5 才挂 pointer ref
if (!isH5) {
return (
<H5El className='social-experience' data-theme='dark'>
<H5El className='social-experience' data-theme={theme}>
{children}
<H5El as='button' className='social-theme-control' aria-label={theme === 'dark' ? '切换日间模式' : '切换夜间模式'}
onClick={() => toggleH5Theme(theme)}>{theme === 'dark' ? '☀' : '☾'}</H5El>
</H5El>
)
}
@ -238,6 +242,7 @@ export function SocialExperience({
ref={rootRef}
className='social-experience'
data-immersive={immersive ? 'true' : 'false'}
data-theme={theme}
>
<H5El className='social-ambient' aria-hidden>
<H5El as='i' />
@ -248,6 +253,8 @@ export function SocialExperience({
<H5El className='social-pointer-glow' aria-hidden />
{showEmojiField ? <FloatingEmojiField /> : null}
{children}
<H5El as='button' className='social-theme-control' aria-label={theme === 'dark' ? '切换日间模式' : '切换夜间模式'}
onClick={() => toggleH5Theme(theme)}>{theme === 'dark' ? '☀' : '☾'}</H5El>
<H5El
as='button'
type='button'

View File

@ -2,6 +2,7 @@
/* 全屏单大厅 IM:无频道条、无侧栏、无底栏 Dock */
.im-root {
padding-top: var(--safe-status-bar, 0PX);
display: flex;
flex-direction: column;
width: 100%;
@ -13,6 +14,15 @@
color: #f1f5f9;
}
.im-header { display: flex; align-items: center; gap: 0.625rem; min-height: var(--safe-nav-bar, 2.75rem); padding: 0.5rem var(--safe-menu-pad, 1rem) 0.5rem 0.75rem; background: var(--social-surface); }
.im-header-title { flex: 1; min-width: 0; font-size: 1rem; font-weight: 700; }
.im-header .im-back, .im-header .im-reconnect { padding: 0.5rem !important; font-size: 0.8125rem !important; }
.im-new-messages { position: absolute; bottom: calc(5rem + env(safe-area-inset-bottom)); left: 25%; z-index: 20; color: var(--social-text); background: var(--social-raised); }
.im-root[data-theme] .im-composer, .im-root[data-theme] .im-bubble { background: var(--social-surface); color: var(--social-text); border-color: var(--social-line); }
.im-root[data-theme] .im-input, .im-root[data-theme] .im-nick { background: var(--social-raised); color: var(--social-text); min-height: 2.75rem; }
.im-root[data-theme] .im-meta, .im-root[data-theme] .im-author, .im-root[data-theme] .im-empty-desc { color: var(--social-muted); }
.im-root[data-theme] .im-send.is-on { background: #52d3c4; color: #082f2b; }
.im-status-row {
flex: 0 0 auto;
display: flex;
@ -197,3 +207,15 @@
.im-send.is-busy {
opacity: 0.7;
}
.soc-taro-root.im-root[data-theme] .im-back,
.soc-taro-root.im-root[data-theme] .im-reconnect {
min-height: 2.75rem; min-width: 2.75rem; margin: 0;
padding: 0.5rem 0.75rem !important; border: 0; border-radius: 0.75rem;
background: var(--social-raised); color: var(--social-text); font-size: 0.875rem !important;
&::after { border: 0; }
}
.soc-taro-root.im-root[data-theme] .im-send { border: 0; margin: 0; }
.soc-taro-root.im-root[data-theme] .im-input { min-width: 0; }
.soc-taro-root.im-root[data-theme] .im-bubble.is-mine { background: var(--social-raised); border-color: var(--social-accent); }
.soc-taro-root.im-root[data-theme='light'] .im-fail { color: #926000; }

View File

@ -1,4 +1,6 @@
import { useEffect, useState } from 'react'
import { useSocialPage } from '@/hooks/useSocialPage'
import { useSocialContent } from '@/hooks/useSocialContent'
import { useEffect, useRef, useState } from 'react'
import { Input, ScrollView, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { MiniModuleGate } from '@/components/MiniModuleGate'
@ -7,6 +9,8 @@ import { useSocialChat } from '@/hooks/useSocialChat'
import { usePageShare } from '@/utils/pageShare'
import { usePageTrack } from '@/hooks/usePageTrack'
import type { SocialChatMessage } from '@/services/socialApi'
import { H5El } from '../_components/H5El'
import { goSocialPage } from '@/utils/socialNavigation'
import '@/styles/social-next/entry'
import '../_components/social-subpage.scss'
import './index.scss'
@ -61,6 +65,8 @@ function Bubble({
}
function SocialChatLobby() {
const { theme, pageStyle } = useSocialPage()
const { pages } = useSocialContent()
usePageShare({ title: 'nomadro · 游民大厅', path: '/pages/social/chat/index' })
usePageTrack('social_chat')
const {
@ -73,9 +79,13 @@ function SocialChatLobby() {
sending,
send,
retryLocal,
refresh,
} = useSocialChat(LOBBY)
const [scrollInto, setScrollInto] = useState('')
const nearBottom = useRef(true)
const [unread, setUnread] = useState(false)
const [refreshing, setRefreshing] = useState(false)
const lastId = messages[messages.length - 1]?.id
useEffect(() => {
@ -83,7 +93,7 @@ function SocialChatLobby() {
const q = Taro.getCurrentInstance().router?.params || {}
const raw = String(q.intro || '').trim()
if (!raw) return
setDraft((d) => d || decodeURIComponent(raw))
setDraft((d) => d || raw)
} catch {
/* ignore */
}
@ -91,6 +101,7 @@ function SocialChatLobby() {
useEffect(() => {
if (!lastId) return
if (!nearBottom.current && !messages[messages.length - 1]?.mine) { setUnread(true); return }
const t = setTimeout(() => setScrollInto(`msg_${lastId}`), 48)
return () => clearTimeout(t)
}, [lastId, messages.length])
@ -109,7 +120,14 @@ function SocialChatLobby() {
}
return (
<H5Box className='soc-taro-root im-root social-weapp' data-theme='dark'>
<H5Box className='soc-taro-root social-root im-root social-weapp' data-theme={theme} style={pageStyle}>
<H5Box className='im-header'>
<H5El as='button' className='im-back' onClick={() => goSocialPage('/pages/social/index')}>← 社区</H5El>
<Text className='im-header-title'>{pages.chat?.title || '游民大厅'}</Text>
<H5El as='button' className='im-reconnect' disabled={refreshing} onClick={async () => {
setRefreshing(true); try { await refresh() } finally { setRefreshing(false) }
}}>{refreshing ? '连接中…' : '刷新'}</H5El>
</H5Box>
<H5Box className='im-status-row'>
<H5Box className={`im-pill is-${status}`}>
<Text>{statusLabel(status)}</Text>
@ -139,6 +157,14 @@ function SocialChatLobby() {
scrollIntoView={scrollInto}
enhanced
showScrollbar={false}
onScroll={(event) => {
const detail = event.detail as { scrollHeight: number; scrollTop: number }
// Obtain the actual viewport so incoming messages do not pull users away from history.
Taro.createSelectorQuery().select('.im-thread').boundingClientRect((rect: any) => {
if (rect?.height) nearBottom.current = detail.scrollHeight - detail.scrollTop - rect.height < 100
}).exec()
}}
onScrollToLower={() => { nearBottom.current = true; setUnread(false) }}
>
{messages.length === 0 ? (
<H5Box className='im-empty'>
@ -162,6 +188,9 @@ function SocialChatLobby() {
</H5Box>
)}
</ScrollView>
{unread ? <H5El as='button' className='im-new-messages' onClick={() => {
nearBottom.current = true; setUnread(false); setScrollInto('chat_bottom')
}}>有新消息 · 回到最新 ↓</H5El> : null}
<H5Box className='im-composer'>
<Input
@ -178,14 +207,14 @@ function SocialChatLobby() {
onInput={(e) => setDraft(e.detail.value)}
onConfirm={() => void onSend()}
/>
<H5Box
<H5El as='button' disabled={!canSend} aria-label='发送消息'
className={`im-send${canSend ? ' is-on' : ''}${
sending ? ' is-busy' : ''
}`}
onClick={() => void onSend()}
>
<Text>{sending ? '…' : '发送'}</Text>
</H5Box>
</H5El>
</H5Box>
</H5Box>
)

View File

@ -1,10 +1,14 @@
import { useSocialLikes } from '@/services/socialLocal'
import { useSocialLocal } from '@/services/socialLocal'
import { useSocialContent } from '@/hooks/useSocialContent'
import { useSocialPage } from '@/hooks/useSocialPage'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { MiniModuleGate } from '@/components/MiniModuleGate'
import { H5Box } from '@/components/H5Box'
import { MOCK_ROSTER, type SocialRosterMember } from '@/data/socialSeed'
import { goPage } from '@/utils/nav'
import { goSocialPage as goPage } from '@/utils/socialNavigation'
import { usePageShare } from '@/utils/pageShare'
import { usePageTrack } from '@/hooks/usePageTrack'
import { SocialDock } from '../_components/SocialDock'
@ -36,11 +40,11 @@ function DateCardFace({ member }: { member: SocialRosterMember }) {
backgroundImage: `linear-gradient(180deg, transparent 40%, #0a0a0ef5 90%), url(${member.avatar})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
minHeight: 280,
minHeight: '17.5rem',
}}
/>
<H5Box className='social-date-card-body'>
<Text style={{ fontWeight: 750, fontSize: 22 }}>
<Text style={{ fontWeight: 750, fontSize: '1.375rem' }}>
{member.name}
{member.online ? ' · 在线' : ''}
</Text>
@ -64,24 +68,25 @@ function DateCardFace({ member }: { member: SocialRosterMember }) {
}
function SocialDate() {
const { theme, pageStyle } = useSocialPage()
usePageShare({ title: 'nomadro · 认识一下', path: '/pages/social/date/index' })
usePageTrack('social_date')
const roster = MOCK_ROSTER
const { roster, pages } = useSocialContent()
const [filter, setFilter] = useState<Filter>('all')
const [swipes, setSwipes] = useState<Record<string, Decision>>({})
const [history, setHistory] = useState<{ id: string; decision: Decision }[]>(
[],
)
const [swipes, setSwipes] = useSocialLocal<Record<string, Decision>>('swipes_v1', {})
const [history, setHistory] = useSocialLocal<{ id: string; decision: Decision; previousLiked?: boolean }[]>('swipe_history_v1', [])
const [order, setOrder] = useState<string[]>(() =>
shuffle(roster.map((m) => m.id)),
)
const [drag, setDrag] = useState({ x: 0, y: 0, active: false })
const [fly, setFly] = useState<null | { id: string; dir: Decision }>(null)
const [likes, setLikes] = useState<Record<string, boolean>>({})
const [likes, setLikes] = useSocialLikes()
const start = useRef({ x: 0, y: 0 })
const dragging = useRef(false)
const dragRef = useRef({ x: 0, y: 0 })
const busy = useRef(false)
const commitTimer = useRef<ReturnType<typeof setTimeout>>()
useEffect(() => () => { if (commitTimer.current) clearTimeout(commitTimer.current) }, [])
const deck = useMemo(() => {
const ids = [
@ -106,9 +111,9 @@ function SocialDate() {
if (busy.current || fly) return
busy.current = true
setFly({ id: member.id, dir: decision })
setTimeout(() => {
commitTimer.current = setTimeout(() => {
setSwipes((prev) => ({ ...prev, [member.id]: decision }))
setHistory((prev) => [...prev, { id: member.id, decision }])
setHistory((prev) => [...prev, { id: member.id, decision, previousLiked: !!likes[member.id] }].slice(-300))
if (decision === 'like') {
setLikes((prev) => ({ ...prev, [member.id]: true }))
Taro.showToast({ title: `想认识 ${member.name}`, icon: 'none' })
@ -121,7 +126,7 @@ function SocialDate() {
busy.current = false
}, 280)
},
[fly],
[fly, likes, setSwipes, setHistory, setLikes],
)
const undo = useCallback(() => {
@ -133,7 +138,7 @@ function SocialDate() {
delete nextStore[last.id]
return nextStore
})
if (last.decision === 'like') {
if (last.decision === 'like' && !last.previousLiked) {
setLikes((prev) => {
const n = { ...prev }
delete n[last.id]
@ -149,6 +154,8 @@ function SocialDate() {
const clientY = event.clientY ?? event.touches?.[0]?.clientY
if (clientX == null) return
dragging.current = true
event.currentTarget?.setPointerCapture?.(event.pointerId)
dragRef.current = { x: 0, y: 0 }
start.current = { x: clientX, y: clientY || 0 }
setDrag({ x: 0, y: 0, active: true })
}
@ -185,20 +192,22 @@ function SocialDate() {
}
const resetDeck = () => {
if (busy.current) return
setSwipes({})
setHistory([])
setOrder(shuffle(roster.map((m) => m.id)))
setDrag({ x: 0, y: 0, active: false })
dragRef.current = { x: 0, y: 0 }
setFly(null)
setLikes({})
busy.current = false
Taro.showToast({ title: '已重新洗牌', icon: 'none' })
Taro.showToast({ title: '已重新开始,关注已保留', icon: 'none' })
}
useEffect(() => {
if (typeof window === 'undefined') return
const onKey = (event: KeyboardEvent) => {
const target = event.target as HTMLElement | null
if (target?.isContentEditable || /INPUT|TEXTAREA|SELECT/.test(target?.tagName || '')) return
if (event.key === 'ArrowRight' && current) {
event.preventDefault()
commit(current, 'like')
@ -223,13 +232,13 @@ function SocialDate() {
: THRESHOLD_DESKTOP
const likeOpacity = Math.min(1, Math.max(0, drag.x / stampThreshold))
const passOpacity = Math.min(1, Math.max(0, -drag.x / stampThreshold))
const likedCount = Object.keys(likes).length
const likedCount = Object.values(likes).filter(Boolean).length
return (
<SocialExperience>
<H5Box
className='soc-taro-root social-root social-live-root social-skin social-date-root social-weapp'
data-theme='dark'
data-theme={theme} style={pageStyle}
>
<H5Box className='social-live-bar social-date-bar'>
<H5Box className='social-live-bar-main'>
@ -237,7 +246,7 @@ function SocialDate() {
<Text>← 首页</Text>
</H5Box>
<H5Box>
<Text style={{ fontWeight: 700 }}>认识一下</Text>
<Text style={{ fontWeight: 700 }}>{pages.date?.title || '认识一下'}</Text>
<Text className='social-muted'>
左滑划走 · 右滑想认识
{totalForFilter ? ` · 还剩 ${remaining}/${totalForFilter}` : ''}
@ -285,7 +294,7 @@ function SocialDate() {
</H5Box>
) : null}
<H5Box className='social-date-deck' style={{ touchAction: 'none' }}>
<H5Box className='social-date-deck' style={{ touchAction: 'pan-y' }}>
{!current ? (
<H5Box className='social-date-empty'>
<Text style={{ fontSize: 36 }}>✨</Text>

View File

@ -1,3 +1,5 @@
import { useSocialContent } from '@/hooks/useSocialContent'
import { useSocialPage } from '@/hooks/useSocialPage'
import { useEffect, useMemo, useState, type CSSProperties } from 'react'
import Taro, { usePageScroll } from '@tarojs/taro'
import { MiniModuleGate } from '@/components/MiniModuleGate'
@ -14,7 +16,7 @@ import {
SOCIAL_COPY,
TEAM_KIND_LABEL,
} from '@/data/socialSeed'
import { goPage } from '@/utils/nav'
import { goSocialPage as goPage } from '@/utils/socialNavigation'
import { usePageShare } from '@/utils/pageShare'
import { usePageTrack } from '@/hooks/usePageTrack'
import { getSafeAreaMetrics, safePx } from '@/utils/safeArea'
@ -28,6 +30,8 @@ import { SocialAvatar } from './_components/SocialAvatar'
import { FxBelt, SocialExperience } from './_components/SocialExperience'
import { H5El } from './_components/H5El'
import { JoinPaySheet } from './_components/JoinPaySheet'
import { CreationSheet } from './_components/CreationSheet'
import type { SocialEbook, SocialVideo } from '@/data/socialTypes'
import '@/styles/social-next/entry'
import './index.scss'
@ -62,18 +66,19 @@ function scrollToId(id: string) {
}
function SocialHome() {
const { theme, pageStyle } = useSocialPage()
usePageShare({ title: 'nomadro · 游民社区', path: '/pages/social/index' })
usePageTrack('social_home')
const [scrolled, setScrolled] = useState(false)
const [activeSection, setActiveSection] = useState('people')
const [joinOpen, setJoinOpen] = useState(false)
const copy = SOCIAL_COPY
const [teamTab, setTeamTab] = useState<'gigs' | 'creation'>('gigs')
const [creation, setCreation] = useState<{ item: SocialEbook | SocialVideo; kind: 'ebook' | 'video' } | null>(null)
const { copy, roster, meetups, gigs, ebooks, videos, promoUrl, hiddenSections } = useSocialContent()
const datePreview = useMemo(
() => MOCK_ROSTER.filter((m) => m.online).slice(0, 3),
[],
() => roster.filter((m) => m.online).slice(0, 3),
[roster],
)
const meetups = SEED_MEETUPS
const gigs = SEED_GIGS
const cities = SOCIAL_CITIES.filter((c) => c.hot).slice(0, 8)
const safe = useMemo(() => getSafeAreaMetrics(), [])
const rootStyle = useMemo(
@ -104,9 +109,7 @@ function SocialHome() {
useEffect(() => {
if (!isH5 || typeof document === 'undefined') return
const html = document.documentElement
html.setAttribute('data-theme', 'dark')
html.setAttribute('data-social-skin', '1')
html.classList.add('dark')
document.body.classList.add('social-body')
return () => {
document.body.classList.remove('social-body')
@ -166,8 +169,8 @@ function SocialHome() {
<SocialExperience>
<H5El
className={`soc-taro-root community-root social-skin home-flow social-flow social-fx social-home social-root${isH5 ? '' : ' social-weapp'}`}
data-theme='dark'
style={rootStyle}
data-theme={theme}
style={pageStyle}
>
<H5El className='social-fx-orbs' aria-hidden>
<H5El as='i' className='social-fx-orb o1' />
@ -202,13 +205,13 @@ function SocialHome() {
</H5El>
<H5El as='main' id='social-main' className='social-main'>
<ConnectionHero onJoin={onJoin} promoUrl={DEFAULT_PROMO} copy={copy} />
<ConnectionHero onJoin={onJoin} promoUrl={promoUrl} copy={copy} />
<ConnectionWays copy={copy} />
<H5El as='nav' className='social-path' aria-label='本页导航'>
<H5El className='container'>
<H5El className='social-path-track reveal visible'>
{PATH_CHIPS.map((p) => (
{PATH_CHIPS.filter((p) => !hiddenSections.includes(p.href.slice(1))).map((p) => (
<H5El
as='a'
key={p.href}
@ -232,7 +235,7 @@ function SocialHome() {
</H5El>
</H5El>
<AttractiveRoster onJoin={onJoin} />
{!hiddenSections.includes('people') ? <AttractiveRoster onJoin={onJoin} /> : null}
<FxBelt />
@ -240,6 +243,7 @@ function SocialHome() {
as='section'
className='section section-compact social-section-alt'
id='date'
style={hiddenSections.includes('date') ? { display: 'none' } : undefined}
aria-label='认识一下'
>
<H5El className='container'>
@ -340,6 +344,7 @@ function SocialHome() {
as='section'
className='section section-compact social-section-alt'
id='meetup'
style={hiddenSections.includes('meetup') ? { display: 'none' } : undefined}
aria-label='开视频聊聊'
>
<H5El className='container'>
@ -383,7 +388,7 @@ function SocialHome() {
))}
</H5El>
<H5El className='social-video-grid'>
{MOCK_ROSTER.slice(i, i + 4).map((p) => (
{roster.slice(i, i + 4).map((p) => (
<H5El as='span' key={p.id} className='social-video-tile'>
<SocialAvatar src={p.avatar} size={36} />
</H5El>
@ -400,10 +405,10 @@ function SocialHome() {
</H5El>
</H5El>
<H5El className='social-meetup-faces' aria-hidden>
{MOCK_ROSTER.slice(i + 1, i + 5).map((p) => (
{roster.slice(i + 1, i + 5).map((p) => (
<SocialAvatar key={p.id} src={p.avatar} size={24} />
))}
<H5El as='em'>+{6 + i} 想参加</H5El>
<H5El as='em'>示例场次 · 点击查看</H5El>
</H5El>
<H5El as='h3'>{m.title}</H5El>
<H5El as='p'>群里打个招呼 → 开麦 / 开视频 → 认识新朋友</H5El>
@ -440,7 +445,8 @@ function SocialHome() {
<FxBelt />
<H5El as='section' className='section section-compact' id='cities' aria-label='同城见一面'>
<H5El as='section' className='section section-compact' id='cities' aria-label='同城见一面'
style={hiddenSections.includes('cities') ? { display: 'none' } : undefined}>
<H5El className='container'>
<H5El className='section-header reveal visible'>
<H5El as='span' className='section-tag'>
@ -465,7 +471,7 @@ function SocialHome() {
href='#cities'
className='social-panel social-panel-fx reveal visible is-clickable'
style={{ ['--stagger' as string]: `${i * 50}ms` }}
onClick={() => goPage('/pages/social/people/index?mode=cafe')}
onClick={() => goPage(`/pages/social/people/index?mode=cafe&city=${encodeURIComponent(c.name)}`)}
>
<H5El as='span' style={{ fontSize: 28 }}>
{c.emoji}
@ -505,6 +511,7 @@ function SocialHome() {
as='section'
className='section section-compact social-section-alt'
id='team'
style={hiddenSections.includes('team') ? { display: 'none' } : undefined}
aria-label='一起做点事'
>
<H5El className='container'>
@ -525,15 +532,17 @@ function SocialHome() {
</H5El>
<H5El className='social-together-tabs reveal visible' role='tablist'>
<H5El as='a' href='#team' className='is-on' role='tab' aria-selected='true'>
<H5El as='button' className={teamTab === 'gigs' ? 'is-on' : ''} role='tab' aria-selected={teamTab === 'gigs'}
onClick={() => setTeamTab('gigs')}>
找搭子
</H5El>
<H5El as='a' href='#team' role='tab' aria-selected='false'>
<H5El as='button' className={teamTab === 'creation' ? 'is-on' : ''} role='tab' aria-selected={teamTab === 'creation'}
onClick={() => setTeamTab('creation')}>
共创
</H5El>
</H5El>
<H5El className='social-panel-grid social-panel-grid-3'>
{teamTab === 'gigs' ? <H5El className='social-panel-grid social-panel-grid-3'>
{gigs.slice(0, 3).map((g, i) => (
<H5El
as='a'
@ -563,16 +572,16 @@ function SocialHome() {
</H5El>
</H5El>
))}
</H5El>
</H5El> : null}
<H5El className='social-ugc-row reveal visible'>
{SEED_EBOOKS.slice(0, 2).map((book) => (
{teamTab === 'creation' ? <H5El className='social-ugc-row reveal visible'>
{ebooks.slice(0, 2).map((book) => (
<H5El
as='a'
key={book.id}
href='#ebook'
className='social-ugc-card'
onClick={() => goPage('/pages/book/index')}
onClick={() => setCreation({ item: book, kind: 'ebook' })}
>
<H5El as='span' className='social-ugc-ico' aria-hidden>
📖
@ -585,8 +594,9 @@ function SocialHome() {
<H5El as='span'>↗</H5El>
</H5El>
))}
{SEED_VIDEOS.slice(0, 2).map((vid) => (
<H5El as='a' key={vid.id} href='#videos' className='social-ugc-card is-video'>
{videos.slice(0, 2).map((vid) => (
<H5El as='a' key={vid.id} href='#videos' className='social-ugc-card is-video'
onClick={() => setCreation({ item: vid, kind: 'video' })}>
<H5El as='span' className='social-ugc-ico' aria-hidden>
{vid.coverEmoji}
</H5El>
@ -600,7 +610,7 @@ function SocialHome() {
<H5El as='span'>↗</H5El>
</H5El>
))}
</H5El>
</H5El> : null}
<H5El className='social-section-actions reveal visible'>
<H5El
@ -686,6 +696,7 @@ function SocialHome() {
</H5El>
<JoinPaySheet open={joinOpen} onClose={() => setJoinOpen(false)} />
{creation ? <CreationSheet {...creation} onClose={() => setCreation(null)} /> : null}
<SocialDock />
</H5El>
</SocialExperience>

View File

@ -1,3 +1,5 @@
import { useSocialContent } from '@/hooks/useSocialContent'
import { useSocialPage } from '@/hooks/useSocialPage'
import {
useCallback,
useEffect,
@ -13,11 +15,11 @@ import {
LivePusher,
View,
} from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import Taro, { useDidHide, useRouter } from '@tarojs/taro'
import { MiniModuleGate } from '@/components/MiniModuleGate'
import { MIROTALK_URL, MOCK_ROSTER, SEED_MEETUPS } from '@/data/socialSeed'
import { socialApi, type LivePeer } from '@/services/socialApi'
import { goPage } from '@/utils/nav'
import { goSocialPage as goPage } from '@/utils/socialNavigation'
import { usePageShare } from '@/utils/pageShare'
import { usePageTrack } from '@/hooks/usePageTrack'
import { getSafeAreaMetrics, safePx } from '@/utils/safeArea'
@ -33,17 +35,19 @@ const ENV = Taro.getEnv()
const isH5 = ENV === Taro.ENV_TYPE.WEB
const isWeapp = ENV === Taro.ENV_TYPE.WEAPP
const PUSHER_ID = 'socialLivePusher'
const htmlAttribute = (value: string) => value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
function joinMiro(room: string, name: string) {
const q = new URLSearchParams({
const params = {
room,
name,
notify: '0',
chat: '0',
audio: '0',
video: '0',
})
return `${MIROTALK_URL.replace(/\/$/, '')}/join?${q.toString()}`
}
const query = Object.entries(params).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join('&')
return `${MIROTALK_URL.replace(/\/$/, '')}/join?${query}`
}
/** 微信 LivePusher 真机:RTMP 地址去掉 query,避免连不上导致黑屏 */
@ -108,7 +112,7 @@ async function ensureMediaAuth(): Promise<boolean> {
})
}
} catch {
/* continue */
return false
}
try {
await Taro.authorize({ scope: 'scope.camera' })
@ -126,10 +130,12 @@ async function ensureMediaAuth(): Promise<boolean> {
}
function SocialMeetupLive() {
const { theme, pageStyle } = useSocialPage()
const router = useRouter()
const meetupId = String(router.params?.id || SEED_MEETUPS[0]?.id || 'office')
const { meetups } = useSocialContent()
const meetupId = String(router.params?.id || meetups[0]?.id || 'office')
const meetup =
SEED_MEETUPS.find((m) => m.id === meetupId) || {
meetups.find((m) => m.id === meetupId) || {
id: meetupId,
title: '开视频见面',
city: 'Online',
@ -168,6 +174,11 @@ function SocialMeetupLive() {
const [roomId, setRoomId] = useState(meetup.id)
const [previewOk, setPreviewOk] = useState(false)
const hbRef = useRef<ReturnType<typeof setInterval> | null>(null)
const activeRoom = useRef('')
const joinLock = useRef(false)
const joinGeneration = useRef(0)
const [joining, setJoining] = useState(false)
const heartbeatBusy = useRef(false)
const miroSrc = useMemo(
() => joinMiro(meetup.mirotalkRoom, nick.trim() || '游民'),
@ -182,7 +193,18 @@ function SocialMeetupLive() {
}
const leaveNative = useCallback(async () => {
joinGeneration.current += 1
stopHeartbeat()
const leavingRoom = activeRoom.current
activeRoom.current = ''
joinLock.current = false
setJoining(false)
setLiveOn(false)
setPusherUrl('')
pendingPush.current = ''
setPeers([])
setPreviewOk(false)
setStatus('已离开')
try {
const ctx = getPusherCtx()
ctx.stop({ complete: () => undefined })
@ -191,27 +213,30 @@ function SocialMeetupLive() {
/* ignore */
}
try {
await socialApi.liveLeave(roomId)
if (leavingRoom) await socialApi.liveLeave(leavingRoom)
} catch {
/* ignore */
}
setLiveOn(false)
setPusherUrl('')
pendingPush.current = ''
setPeers([])
setPreviewOk(false)
setStatus('已离开')
}, [roomId])
}, [])
useDidHide(() => {
if (isWeapp && (activeRoom.current || joinLock.current)) void leaveNative()
else if (isH5) setLiveOn(false)
})
useEffect(() => {
return () => {
stopHeartbeat()
if (isWeapp && liveOn) {
joinGeneration.current += 1
if (isWeapp && activeRoom.current) {
try {
socialApi.liveLeave(roomId)
getPusherCtx().stop({})
getPusherCtx().stopPreview({})
} catch {
/* ignore */
}
void socialApi.liveLeave(activeRoom.current).catch(() => undefined)
activeRoom.current = ''
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
@ -286,8 +311,12 @@ function SocialMeetupLive() {
}, [liveOn, pusherUrl, previewOk])
const startWeappLive = async () => {
if (joinLock.current || activeRoom.current) return
joinLock.current = true
setJoining(true)
const generation = ++joinGeneration.current
const ok = await ensureMediaAuth()
if (!ok) return
if (!ok || generation !== joinGeneration.current) { joinLock.current = false; setJoining(false); return }
const name = nick.trim() || '游民'
Taro.setStorageSync('nick', name)
setStatus('正在进厅…')
@ -295,6 +324,12 @@ function SocialMeetupLive() {
setPusherUrl('')
try {
const joined = await socialApi.liveJoin(meetup.id, name)
if (generation !== joinGeneration.current) {
void socialApi.liveLeave(joined.roomId).catch(() => undefined)
return
}
if (!joined.ok || !joined.pushUrl) throw new Error('暂时无法进入此场次')
activeRoom.current = joined.roomId
const rtmp = cleanRtmpUrl(joined.pushUrl)
pendingPush.current = rtmp
setRoomId(joined.roomId)
@ -304,15 +339,21 @@ function SocialMeetupLive() {
setStatus('正在打开摄像头…')
stopHeartbeat()
hbRef.current = setInterval(() => {
if (heartbeatBusy.current || activeRoom.current !== joined.roomId) return
heartbeatBusy.current = true
socialApi
.liveHeartbeat(joined.roomId)
.then((r) => setPeers(r.peers || []))
.catch(() => undefined)
.then((r) => { if (activeRoom.current === joined.roomId) setPeers(r.peers || []) })
.catch(() => { if (activeRoom.current === joined.roomId) setStatus('连接不稳定,正在重连…') })
.finally(() => { heartbeatBusy.current = false })
}, 4000)
} catch (e) {
const msg = String((e as Error)?.message || '进厅失败')
setStatus(msg)
Taro.showToast({ title: msg, icon: 'none', duration: 3200 })
} finally {
joinLock.current = false
if (generation === joinGeneration.current) setJoining(false)
}
}
@ -334,15 +375,8 @@ function SocialMeetupLive() {
<SocialExperience>
<H5El
className='soc-taro-root social-root social-workspace social-live-root social-weapp social-meetup-live'
data-theme='dark'
style={
{
['--safe-status-bar' as string]: safePx(safe.statusBarHeight),
['--safe-nav-bar' as string]: safePx(safe.navBarHeight),
['--safe-menu-pad' as string]: safePx(safe.menuRightPad),
['--safe-header' as string]: safePx(safe.headerHeight),
} as CSSProperties
}
data-theme={theme}
style={pageStyle}
>
<H5El className='social-live-bar'>
<H5El className='social-live-bar-main'>
@ -372,8 +406,8 @@ function SocialMeetupLive() {
<H5El as='h2'>语音视频厅</H5El>
<H5El as='p' className='social-muted'>
{isWeapp
? '先进厅打开本地摄像头,再推流到厅内。请允许相机与麦克风。'
: 'H5 使用 MiroTalk WebRTC;微信端为自研原生厅。'}
? '确认昵称后进入,届时会请求相机和麦克风权限。离开页面会停止音视频。'
: '确认昵称后进入语音视频;首次进入请允许使用相机与麦克风。'}
</H5El>
<H5El className='social-meetup-faces' aria-hidden>
{MOCK_ROSTER.filter((m) => m.online)
@ -390,6 +424,7 @@ function SocialMeetupLive() {
className='social-field-input'
value={nick}
maxlength={24}
disabled={joining}
onInput={(e) => setNick(e.detail.value)}
/>
</H5El>
@ -397,9 +432,10 @@ function SocialMeetupLive() {
as='button'
type='button'
className='btn btn-primary'
disabled={joining} loading={joining}
onClick={() => void (isWeapp ? startWeappLive() : startH5())}
>
进入语音视频厅
{joining ? '正在进入…' : '进入语音视频厅'}
</H5El>
</H5El>
) : isWeapp ? (
@ -468,7 +504,7 @@ function SocialMeetupLive() {
src={p.playUrl}
mode='live'
autoplay
mute={false}
muted={false}
objectFit='contain'
/>
<CoverView className='social-live-tile-label'>
@ -527,7 +563,7 @@ function SocialMeetupLive() {
<H5El
className='social-live-iframe-host'
dangerouslySetInnerHTML={{
__html: `<iframe title="${meetup.title}" src="${miroSrc}" class="social-live-iframe" allow="camera; microphone; display-capture; autoplay; fullscreen; clipboard-write" referrerpolicy="no-referrer-when-downgrade" style="width:100%;height:70vh;border:0;border-radius:12px;background:#000"></iframe>`,
__html: `<iframe title="${htmlAttribute(meetup.title)}" src="${htmlAttribute(miroSrc)}" class="social-live-iframe" allow="camera; microphone; display-capture; autoplay; fullscreen; clipboard-write" referrerpolicy="no-referrer-when-downgrade" style="width:100%;height:70vh;border:0;border-radius:0.75rem;background:#000"></iframe>`,
}}
/>
<H5El className='social-live-tools'>

View File

@ -1,7 +1,9 @@
import { useSocialContent } from '@/hooks/useSocialContent'
import { useSocialPage } from '@/hooks/useSocialPage'
import { useMemo, type CSSProperties } from 'react'
import { MiniModuleGate } from '@/components/MiniModuleGate'
import { MOCK_ROSTER, SEED_MEETUPS } from '@/data/socialSeed'
import { goPage } from '@/utils/nav'
import { goSocialPage as goPage } from '@/utils/socialNavigation'
import { usePageShare } from '@/utils/pageShare'
import { usePageTrack } from '@/hooks/usePageTrack'
import { getSafeAreaMetrics, safePx } from '@/utils/safeArea'
@ -14,23 +16,18 @@ import '../_components/social-subpage.scss'
import './index.scss'
function SocialMeetupList() {
const { theme, pageStyle } = useSocialPage()
usePageShare({ title: 'nomadro · 开视频', path: '/pages/social/meetup/index' })
usePageTrack('social_meetup')
const { meetups, roster, pages } = useSocialContent()
const safe = useMemo(() => getSafeAreaMetrics(), [])
return (
<SocialExperience>
<H5El
className='soc-taro-root social-root social-workspace social-weapp'
data-theme='dark'
style={
{
['--safe-status-bar' as string]: safePx(safe.statusBarHeight),
['--safe-nav-bar' as string]: safePx(safe.navBarHeight),
['--safe-menu-pad' as string]: safePx(safe.menuRightPad),
['--safe-header' as string]: safePx(safe.headerHeight),
} as CSSProperties
}
data-theme={theme}
style={pageStyle}
>
<H5El className='social-live-bar'>
<H5El className='social-live-bar-main'>
@ -43,9 +40,9 @@ function SocialMeetupList() {
← 首页
</H5El>
<H5El>
<H5El as='strong'>开视频场次</H5El>
<H5El as='strong'>{pages.meetup?.title || '开视频场次'}</H5El>
<H5El as='span' className='social-muted'>
WebRTC · 与门户同款 MiroTalk
选择话题 · 和同频的人聊聊
</H5El>
</H5El>
</H5El>
@ -53,10 +50,10 @@ function SocialMeetupList() {
<H5El className='container social-sub-body'>
<H5El as='p' className='social-muted social-sub-block'>
先进场次热热身,再开语音或视频。小程序内会引导用系统浏览器进入真正的 WebRTC 房间(禁止 web-view)。
{pages.meetup?.description || '选一个感兴趣的话题,确认昵称后进入。微信内使用原生语音视频,进入前会请求相机和麦克风权限。'}
</H5El>
<H5El className='social-panel-grid social-panel-grid-2'>
{SEED_MEETUPS.map((m, i) => (
{meetups.map((m, i) => (
<H5El
as='article'
key={m.id}
@ -71,14 +68,14 @@ function SocialMeetupList() {
</H5El>
</H5El>
<H5El className='social-meetup-faces' aria-hidden>
{MOCK_ROSTER.slice(i + 1, i + 5).map((p) => (
{roster.slice(i + 1, i + 5).map((p) => (
<SocialAvatar key={p.id} src={p.avatar} size={24} />
))}
<H5El as='em'>+{6 + i} 想参加</H5El>
<H5El as='em'>示例场次 · 进入后查看在线成员</H5El>
</H5El>
<H5El as='h3'>{m.title}</H5El>
<H5El as='p' className='social-muted'>
房间 {m.mirotalkRoom}
{m.timeZone ? `时间以 ${m.timeZone} 为准` : '进入前可确认设备与权限'}
</H5El>
<H5El
as='button'
@ -93,6 +90,8 @@ function SocialMeetupList() {
</H5El>
))}
</H5El>
{!meetups.length ? <H5El className='social-panel social-empty-state'><H5El as='strong'>暂时没有开放的场次</H5El>
<H5El as='button' className='btn' onClick={() => goPage('/pages/social/chat/index')}>先去大厅聊聊</H5El></H5El> : null}
</H5El>
<SocialDock />
</H5El>

View File

@ -1,5 +1,11 @@
import { useSocialLikes } from '@/services/socialLocal'
import { useSocialContent } from '@/hooks/useSocialContent'
import { useSocialPage } from '@/hooks/useSocialPage'
import { useEffect, useMemo, useState, type CSSProperties } from 'react'
import { useRouter } from '@tarojs/taro'
import { Input } from '@tarojs/components'
import type { SocialCafe } from '@/data/socialTypes'
import { CafeReviews } from '../_components/CafeReviews'
import { MiniModuleGate } from '@/components/MiniModuleGate'
import {
MOCK_ROSTER,
@ -9,7 +15,7 @@ import {
TEAM_KIND_LABEL,
ROLE_EMOJI,
} from '@/data/socialSeed'
import { goPage } from '@/utils/nav'
import { goSocialPage as goPage } from '@/utils/socialNavigation'
import { usePageShare } from '@/utils/pageShare'
import { usePageTrack } from '@/hooks/usePageTrack'
import { getSafeAreaMetrics, safePx } from '@/utils/safeArea'
@ -21,12 +27,20 @@ import '@/styles/social-next/entry'
import './index.scss'
function SocialPeople() {
const { theme, pageStyle } = useSocialPage()
usePageShare({ title: 'nomadro · 想见的人', path: '/pages/social/people/index' })
usePageTrack('social_people')
const router = useRouter()
const mode = (router.params?.mode as string) || 'all'
const [filter, setFilter] = useState<'all' | 'online' | 'f' | 'm'>('all')
const [likes, setLikes] = useState<Record<string, boolean>>({})
const mode = ['all', 'cafe', 'team'].includes(String(router.params?.mode)) ? String(router.params?.mode) : 'all'
const { roster, cafes, pages } = useSocialContent()
const [filter, setFilter] = useState<'all' | 'online' | 'f' | 'm' | 'liked'>('all')
const [query, setQuery] = useState('')
const [city, setCity] = useState(() => {
const value = String(router.params?.city || '')
return SOCIAL_CITIES.find((item) => item.id === value || item.name === value)?.name || value
})
const [activeCafe, setActiveCafe] = useState<SocialCafe | null>(null)
const [likes, setLikes] = useSocialLikes()
const safe = useMemo(() => getSafeAreaMetrics(), [])
useEffect(() => {
@ -37,26 +51,26 @@ function SocialPeople() {
mode === 'cafe' ? '同城,见一面' : mode === 'team' ? '一起,做点事' : '想见的人'
const list = useMemo(() => {
return MOCK_ROSTER.filter((m) => {
return roster.filter((m) => {
if (city && !m.city.includes(city)) return false
const q = query.trim().toLowerCase()
if (q && !`${m.name} ${m.title} ${m.city} ${m.tags.join(' ')} ${m.lookingFor}`.toLowerCase().includes(q)) return false
if (filter === 'liked') return !!likes[m.id]
if (filter === 'online') return m.online
if (filter === 'f' || filter === 'm') return m.gender === filter
return true
})
}, [filter])
}, [filter, roster, query, city, likes])
const visibleCafes = cafes.filter((cafe) => (!city || cafe.city.includes(city)) &&
(!query.trim() || `${cafe.name} ${cafe.city} ${cafe.vibe}`.toLowerCase().includes(query.trim().toLowerCase())))
const clearFilters = () => { setCity(''); setQuery(''); setFilter('all') }
return (
<SocialExperience>
<H5El
className='soc-taro-root social-root social-workspace social-home social-weapp'
data-theme='dark'
style={
{
['--safe-status-bar' as string]: safePx(safe.statusBarHeight),
['--safe-nav-bar' as string]: safePx(safe.navBarHeight),
['--safe-menu-pad' as string]: safePx(safe.menuRightPad),
['--safe-header' as string]: safePx(safe.headerHeight),
} as CSSProperties
}
data-theme={theme}
style={pageStyle}
>
<H5El className='social-live-bar'>
<H5El className='social-live-bar-main'>
@ -69,9 +83,9 @@ function SocialPeople() {
← 首页
</H5El>
<H5El>
<H5El as='strong'>{title}</H5El>
<H5El as='strong'>{pages[mode === 'cafe' ? 'coffeechat' : 'people']?.title || title}</H5El>
<H5El as='span' className='social-muted'>
示例介绍 · 离线可逛
{pages[mode === 'cafe' ? 'coffeechat' : 'people']?.description || '示例介绍 · 离线可逛'}
</H5El>
</H5El>
<H5El
@ -86,13 +100,24 @@ function SocialPeople() {
</H5El>
<H5El className='container social-sub-body'>
<H5El className='social-search-row'><Input className='social-field-input' value={query} maxlength={80}
placeholder={mode === 'cafe' ? '搜索城市、咖啡馆或想认识的人' : '搜索昵称、城市、职业或兴趣'}
confirmType='search' onInput={(event) => setQuery(event.detail.value)} /></H5El>
<H5El className='social-search-summary'>
<H5El as='span'>{city ? `${city} · ` : ''}{list.length} 份介绍{mode === 'cafe' ? ` · ${visibleCafes.length} 家咖啡馆` : ''}</H5El>
<H5El as='button' className='btn btn-ghost' onClick={clearFilters}>清空筛选</H5El>
</H5El>
<H5El className='social-section-actions'>
<H5El as='button' className='btn' onClick={() => goPage('/pages/social/roster/index')}>编辑我的介绍</H5El>
</H5El>
{mode === 'cafe' ? (
<>
<H5El className='social-panel-grid social-panel-grid-2 social-sub-block'>
{SOCIAL_CITIES.filter((c) => c.hot)
.slice(0, 6)
.map((c) => (
<H5El key={c.id} className='social-panel'>
<H5El key={c.id} className='social-panel' role='button' aria-pressed={city === c.name}
onClick={() => setCity(city === c.name ? '' : c.name)}>
<H5El as='span' style={{ fontSize: 26 }}>
{c.emoji}
</H5El>
@ -104,16 +129,20 @@ function SocialPeople() {
))}
</H5El>
<H5El className='social-panel-grid social-panel-grid-2 social-sub-block'>
{SEED_CAFES.map((cafe) => (
{visibleCafes.map((cafe) => (
<H5El key={cafe.id} className='social-panel'>
<H5El as='strong'>☕ {cafe.name}</H5El>
<H5El as='p' className='social-muted'>
{cafe.city} · WiFi {cafe.wifiMbps}Mbps
</H5El>
<H5El as='p'>{cafe.vibe}</H5El>
<H5El as='button' className='btn' onClick={() => setActiveCafe(cafe)}>查看与分享评价</H5El>
</H5El>
))}
</H5El>
{!visibleCafes.length ? <H5El className='social-panel social-empty-state'>
<H5El as='strong'>这个筛选下暂未收录咖啡馆</H5El><H5El as='button' className='btn' onClick={clearFilters}>看看全部咖啡馆</H5El>
</H5El> : null}
</>
) : null}
@ -141,6 +170,7 @@ function SocialPeople() {
['online', '在线', '🟢'],
['f', '女生', '👩'],
['m', '男生', '👨'],
['liked', '已关注', '♥'],
] as const
).map(([id, label, emoji]) => (
<H5El
@ -148,12 +178,18 @@ function SocialPeople() {
as='button'
type='button'
className={`social-people-filter${filter === id ? ' is-on active' : ''}`}
aria-pressed={filter === id}
onClick={() => setFilter(id)}
>
{emoji} {label}
</H5El>
))}
</H5El>
{!list.length ? <H5El className='social-panel social-empty-state'>
<H5El as='strong'>{filter === 'liked' ? '还没有符合筛选的关注' : '暂时没有匹配的介绍'}</H5El>
<H5El as='p' className='social-muted'>换个关键词,或看看其他城市的人。</H5El>
<H5El as='button' className='btn' onClick={clearFilters}>查看全部介绍</H5El>
</H5El> : null}
<H5El className='social-people-grid'>
{list.map((m, i) => (
<PeopleChip
@ -170,6 +206,7 @@ function SocialPeople() {
</>
) : null}
</H5El>
{activeCafe ? <CafeReviews key={activeCafe.id} cafe={activeCafe} onClose={() => setActiveCafe(null)} /> : null}
<SocialDock />
</H5El>
</SocialExperience>

View File

@ -1,9 +1,12 @@
import { useSocialLikes } from '@/services/socialLocal'
import { useSocialContent } from '@/hooks/useSocialContent'
import { useSocialPage } from '@/hooks/useSocialPage'
import { useMemo, useState, type CSSProperties } from 'react'
import { Image } from '@tarojs/components'
import { useRouter } from '@tarojs/taro'
import Taro, { useRouter } from '@tarojs/taro'
import { MiniModuleGate } from '@/components/MiniModuleGate'
import { findRosterMember, MOCK_ROSTER } from '@/data/socialSeed'
import { goPage } from '@/utils/nav'
import { goSocialPage as goPage } from '@/utils/socialNavigation'
import { usePageShare } from '@/utils/pageShare'
import { usePageTrack } from '@/hooks/usePageTrack'
import { getSafeAreaMetrics, safePx } from '@/utils/safeArea'
@ -16,10 +19,13 @@ import '@/styles/social-next/entry'
import './index.scss'
function SocialPeopleProfile() {
const { theme, pageStyle } = useSocialPage()
const router = useRouter()
const { roster } = useSocialContent()
const id = String(router.params?.id || '').trim()
const member = useMemo(() => findRosterMember(id), [id])
const [liked, setLiked] = useState(false)
const member = useMemo(() => roster.find((m) => m.id === id), [id, roster])
const [likes, setLikes] = useSocialLikes()
const liked = !!likes[id]
const safe = useMemo(() => getSafeAreaMetrics(), [])
usePageShare({
@ -35,13 +41,13 @@ function SocialPeopleProfile() {
const similar = useMemo(() => {
if (!member) return []
const cityKey = member.city.split(/[·/]/)[0]?.trim() || ''
return MOCK_ROSTER.filter(
return roster.filter(
(m) =>
m.id !== member.id &&
cityKey.length >= 2 &&
m.city.includes(cityKey.slice(0, 2)),
).slice(0, 4)
}, [member])
}, [member, roster])
const intro = member
? encodeURIComponent(
@ -53,15 +59,8 @@ function SocialPeopleProfile() {
<SocialExperience>
<H5El
className='soc-taro-root social-root social-workspace social-home social-weapp social-profile-page'
data-theme='dark'
style={
{
['--safe-status-bar' as string]: safePx(safe.statusBarHeight),
['--safe-nav-bar' as string]: safePx(safe.navBarHeight),
['--safe-menu-pad' as string]: safePx(safe.menuRightPad),
['--safe-header' as string]: safePx(safe.headerHeight),
} as CSSProperties
}
data-theme={theme}
style={pageStyle}
>
<H5El className='social-live-bar'>
<H5El className='social-live-bar-main'>
@ -141,7 +140,7 @@ function SocialPeopleProfile() {
as='button'
type='button'
className={`btn${liked ? ' btn-primary' : ''}`}
onClick={() => setLiked((v) => !v)}
onClick={() => setLikes((values) => ({ ...values, [id]: !values[id] }))}
>
{liked ? '♥ 已关注' : '♡ 关注一下'}
</H5El>
@ -217,7 +216,8 @@ function SocialPeopleProfile() {
<H5El as='h2'>生活瞬间</H5El>
<H5El className='social-profile-gallery-grid'>
{member.gallery.map((src) => (
<Image key={src} src={src} mode='aspectFill' lazyLoad />
<Image key={src} src={src} mode='aspectFill' lazyLoad
onClick={() => void Taro.previewImage({ current: src, urls: member.gallery || [] })} />
))}
</H5El>
</H5El>
@ -228,7 +228,8 @@ function SocialPeopleProfile() {
<H5El as='h2'>附近可能同城的人</H5El>
<H5El className='social-people-grid social-profile-similar-grid'>
{similar.map((m) => (
<PeopleChip key={m.id} member={m} />
<PeopleChip key={m.id} member={m} liked={!!likes[m.id]}
onToggleLike={() => setLikes((values) => ({ ...values, [m.id]: !values[m.id] }))} />
))}
</H5El>
</H5El>

View File

@ -1,121 +1,169 @@
import { useState } from 'react'
import { Text, Input, Textarea } from '@tarojs/components'
import { useEffect, useRef, useState } from 'react'
import { Input, Textarea } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { MiniModuleGate } from '@/components/MiniModuleGate'
import { H5Box } from '@/components/H5Box'
import { MOCK_ROSTER } from '@/data/socialSeed'
import { goPage } from '@/utils/nav'
import { useSocialPage } from '@/hooks/useSocialPage'
import { usePageShare } from '@/utils/pageShare'
import { usePageTrack } from '@/hooks/usePageTrack'
import { SocialAvatar } from '../_components/SocialAvatar'
import { socialApi } from '@/services/socialApi'
import { readSocialLocal, writeSocialLocal } from '@/services/socialLocal'
import type { SocialRosterProfile } from '@/data/socialTypes'
import { SocialDock } from '../_components/SocialDock'
import { SocialExperience } from '../_components/SocialExperience'
import { H5El } from '../_components/H5El'
import '@/styles/social-next/entry'
import './index.scss'
const SEED = MOCK_ROSTER[0]!
const EMPTY: SocialRosterProfile = { name: '', title: '', city: '', phone: '', linktree: '', skills: '', bio: '' }
const FIELDS = [
['name', '昵称', '大家怎么称呼你?', 64],
['title', '职业', '例如:独立设计师 / 开发者', 80],
['city', '所在城市', '例如:大理 / 清迈', 64],
['skills', '擅长的事情', '用逗号分隔,方便同伴了解你', 200],
['phone', '联系方式(选填)', '仅用于社区联系,不公开展示', 32],
['linktree', '个人主页(选填)', 'https://你的主页', 240],
] as const
function SocialRoster() {
const { theme, pageStyle } = useSocialPage()
usePageShare({ title: 'nomadro · 我的介绍', path: '/pages/social/roster/index' })
usePageTrack('social_roster')
const [name, setName] = useState(SEED.name)
const [title, setTitle] = useState(SEED.title)
const [city, setCity] = useState(SEED.city)
const [bio, setBio] = useState(SEED.bio)
const [lookingFor, setLookingFor] = useState(SEED.lookingFor)
const [profile, setProfile] = useState<SocialRosterProfile>(() => ({ ...EMPTY, ...readSocialLocal('profile_draft_v1', EMPTY) }))
const [status, setStatus] = useState('正在读取你的介绍…')
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const dirty = useRef(false)
const lock = useRef(false)
const alive = useRef(true)
const hydrated = useRef(false)
const latest = useRef(profile)
latest.current = profile
const dirtyFields = useRef<string[]>(readSocialLocal('profile_dirty_fields_v1', []))
return (
<SocialExperience>
<H5Box className='soc-taro-root social-root social-workspace social-weapp' data-theme='dark'>
<H5Box className='social-live-bar'>
<H5Box className='social-live-bar-main'>
<H5Box
className='social-nav-back'
onClick={() => goPage('/pages/social/index')}
>
<Text>← 首页</Text>
</H5Box>
<H5Box>
<Text style={{ fontWeight: 700 }}>我的介绍</Text>
<Text className='social-muted'>让别人更快认识你</Text>
</H5Box>
</H5Box>
</H5Box>
const load = async () => {
if (lock.current) return
lock.current = true
setLoading(true)
try {
const result = await socialApi.getRoster()
if (!alive.current) return
if (result.item) {
const next = { ...EMPTY, ...result.item }
for (const field of dirtyFields.current) {
if (field in EMPTY) (next as Record<string, unknown>)[field] = (latest.current as Record<string, unknown>)[field]
}
setProfile(next)
latest.current = next
writeSocialLocal('profile_draft_v1', next)
}
hydrated.current = true
setStatus(readSocialLocal('profile_unsynced_v1', false) ? '有本地修改,保存后同步到社区' : result.item ? '已读取保存的介绍' : '写下介绍,让同频的人认识你')
} catch {
if (alive.current) setStatus('暂时无法连接,草稿保留在此设备')
} finally {
lock.current = false
if (alive.current) setLoading(false)
}
}
useEffect(() => {
alive.current = true
void load()
return () => {
alive.current = false
if (dirty.current) {
writeSocialLocal('profile_draft_v1', latest.current)
writeSocialLocal('profile_unsynced_v1', true)
}
}
}, [])
<H5Box className='container social-sub-body'>
<H5Box className='social-panel social-profile-studio'>
<H5Box style={{ display: 'flex', gap: 14, alignItems: 'center', marginBottom: 16 }}>
<SocialAvatar src={SEED.avatar} size={64} />
<H5Box>
<Text style={{ fontWeight: 750, fontSize: 18 }}>{name || '未命名'}</Text>
<Text className='social-muted'>
{title || '身份'} · {city || '城市'}
</Text>
</H5Box>
</H5Box>
const update = (key: keyof SocialRosterProfile, value: string) => {
dirty.current = true
if (!dirtyFields.current.includes(key)) dirtyFields.current.push(key)
writeSocialLocal('profile_dirty_fields_v1', dirtyFields.current)
setProfile((previous) => ({ ...previous, [key]: value }))
setStatus('正在保存本地草稿…')
}
useEffect(() => {
if (!dirty.current) return
const timer = setTimeout(() => {
if (writeSocialLocal('profile_draft_v1', profile)) {
writeSocialLocal('profile_unsynced_v1', true)
setStatus('草稿已保留,尚未同步')
} else setStatus('本地空间不足,请及时保存到社区')
}, 350)
return () => clearTimeout(timer)
}, [profile])
<H5Box className='social-form' style={{ display: 'grid', gap: 12 }}>
<H5Box>
<Text className='social-muted'>昵称</Text>
<Input
className='social-field-input'
value={name}
onInput={(e) => setName(e.detail.value)}
/>
</H5Box>
<H5Box>
<Text className='social-muted'>身份</Text>
<Input
className='social-field-input'
value={title}
onInput={(e) => setTitle(e.detail.value)}
/>
</H5Box>
<H5Box>
<Text className='social-muted'>城市</Text>
<Input
className='social-field-input'
value={city}
onInput={(e) => setCity(e.detail.value)}
/>
</H5Box>
<H5Box>
<Text className='social-muted'>简介</Text>
<Textarea
className='social-field-input'
value={bio}
maxlength={160}
autoHeight
onInput={(e) => setBio(e.detail.value)}
/>
</H5Box>
<H5Box>
<Text className='social-muted'>想认识</Text>
<Input
className='social-field-input'
value={lookingFor}
onInput={(e) => setLookingFor(e.detail.value)}
/>
</H5Box>
<H5Box
className='btn btn-primary'
onClick={() => Taro.showToast({ title: '已保存到本机(离线)', icon: 'none' })}
>
<Text>保存介绍</Text>
</H5Box>
</H5Box>
</H5Box>
</H5Box>
<SocialDock />
</H5Box>
</SocialExperience>
)
const save = async () => {
if (lock.current) return
const name = profile.name.trim()
if (!name) { setStatus('请先填写昵称'); return }
if (profile.linktree.trim() && !/^https?:\/\//i.test(profile.linktree.trim())) {
setStatus('个人主页请填写以 https:// 或 http:// 开头的完整地址'); return
}
const snapshot = { ...profile, name }
writeSocialLocal('profile_draft_v1', snapshot)
writeSocialLocal('profile_unsynced_v1', true)
if (!hydrated.current) {
// Loading failed: fetch first so hidden existing fields cannot be overwritten by defaults.
setStatus('需要先读取已有介绍,请连接成功后再次保存')
void load()
return
}
lock.current = true
setSaving(true)
try {
const saved = await socialApi.saveRoster(snapshot)
writeSocialLocal('profile_draft_v1', saved)
writeSocialLocal('profile_unsynced_v1', false)
dirtyFields.current = []
writeSocialLocal('profile_dirty_fields_v1', [])
if (!alive.current) return
dirty.current = false
setProfile({ ...EMPTY, ...saved })
setStatus('已同步到社区')
void Taro.showToast({ title: '介绍已保存', icon: 'success' })
} catch {
if (alive.current) setStatus('同步未完成,草稿已保留,可以稍后重试')
} finally {
lock.current = false
if (alive.current) setSaving(false)
}
}
return <SocialExperience>
<H5El className='soc-taro-root social-root social-workspace social-weapp' data-theme={theme} style={pageStyle}>
<H5El className='social-live-bar'><H5El className='social-live-bar-main'>
<H5El as='strong'>我的介绍</H5El><H5El as='span' className='social-muted'>从一句自我介绍开始</H5El>
</H5El></H5El>
<H5El className='container social-sub-body'>
<H5El className='social-panel social-profile-studio'>
<H5El as='h2'>{profile.name || '让同频的人认识你'}</H5El>
<H5El as='p' className='social-muted'>修改会自动保留在此设备;点击保存后同步到社区。联系方式不会出现在公开成员目录中。</H5El>
<H5El className='social-inline-status' role='status'>{status}</H5El>
{FIELDS.map(([key, label, placeholder, limit]) => <H5El key={key} className='social-profile-field'>
<H5El as='label' htmlFor={`profile_${key}`}>{label}</H5El>
<Input id={`profile_${key}`} className='social-field-input' value={profile[key] || ''} maxlength={limit}
placeholder={placeholder} disabled={saving} onInput={(e) => update(key, e.detail.value)} />
</H5El>)}
<H5El className='social-profile-field'>
<H5El as='label' htmlFor='profile_bio'>自我介绍 · {profile.bio.length}/2000</H5El>
<Textarea id='profile_bio' className='social-field-input' value={profile.bio} maxlength={2000}
placeholder='最近在做什么?想认识怎样的朋友或搭档?' autoHeight disabled={saving} onInput={(e) => update('bio', e.detail.value)} />
</H5El>
<H5El className='social-profile-save-row'>
<H5El as='button' className='btn btn-primary' disabled={loading || saving} loading={saving} onClick={() => void save()}>
{saving ? '正在同步…' : '保存到社区'}
</H5El>
<H5El as='button' className='btn btn-ghost' disabled={loading || saving} onClick={() => void load()}>重新连接</H5El>
</H5El>
</H5El>
</H5El><SocialDock />
</H5El>
</SocialExperience>
}
export default function SocialRosterPage() {
return (
<MiniModuleGate moduleKey='social'>
<SocialRoster />
</MiniModuleGate>
)
return <MiniModuleGate moduleKey='social'><SocialRoster /></MiniModuleGate>
}

View File

@ -1,11 +1,13 @@
import { useEffect, useMemo, useState, type CSSProperties } from 'react'
import { useSocialContent } from '@/hooks/useSocialContent'
import { useSocialPage } from '@/hooks/useSocialPage'
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'
import { Input, Textarea } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import { MiniModuleGate } from '@/components/MiniModuleGate'
import { ROLE_EMOJI, SEED_GIGS, TEAM_KIND_LABEL } from '@/data/socialSeed'
import type { SocialGig, SocialTeamKind } from '@/data/socialTypes'
import { socialApi, getLocalApply, markLocalApplySent } from '@/services/socialApi'
import { goPage } from '@/utils/nav'
import { goSocialPage as goPage } from '@/utils/socialNavigation'
import { usePageShare } from '@/utils/pageShare'
import { usePageTrack } from '@/hooks/usePageTrack'
import { getSafeAreaMetrics, safePx } from '@/utils/safeArea'
@ -47,9 +49,10 @@ function ApplySheet({
const local = getLocalApply(gig.id)
const [draft, setDraft] = useState<Draft>(() => loadDraft(gig.id))
const [busy, setBusy] = useState(false)
const [status, setStatus] = useState('')
const [status, setStatus] = useState(local?.delivery === 'sent' ? '申请已提交,可查看或继续浏览其他机会。' : local?.delivery === 'local' ? '本机有未确认送达的申请,可重试。' : '')
const submitLock = useRef(false)
const [delivery, setDelivery] = useState<'draft' | 'local' | 'sent'>(
local?.delivery === 'sent' ? 'sent' : 'draft',
local?.delivery === 'sent' ? 'sent' : local?.delivery === 'local' ? 'local' : 'draft',
)
const filled =
@ -72,11 +75,12 @@ function ApplySheet({
}
const submit = async () => {
if (busy || delivery === 'sent') return
if (submitLock.current || delivery === 'sent') return
if (!draft.name.trim() || !draft.contact.trim()) {
setStatus('请填写称呼和联系方式')
return
}
submitLock.current = true
setBusy(true)
try {
await socialApi.applyGig(gig.id, {
@ -93,14 +97,16 @@ function ApplySheet({
setStatus('申请已先留在本机。有网后再点一次即可重试。')
Taro.showToast({ title: '已存本机', icon: 'none' })
} finally {
submitLock.current = false
setBusy(false)
}
}
return (
<H5El className='social-apply-mask' onClick={onClose}>
<H5El className='social-apply-mask' onClick={() => !submitLock.current && onClose()}>
<H5El
className='social-apply-sheet'
role='dialog' aria-modal='true' aria-label='参与申请'
onClick={(e) => {
e?.stopPropagation?.()
}}
@ -108,7 +114,7 @@ function ApplySheet({
<H5El className='social-apply-handle' aria-hidden />
<H5El className='social-apply-head'>
<H5El as='strong'>表达兴趣</H5El>
<H5El as='button' type='button' className='social-apply-close' onClick={onClose}>
<H5El as='button' type='button' className='social-apply-close' disabled={busy} aria-label='关闭申请' onClick={onClose}>
✕
</H5El>
</H5El>
@ -157,11 +163,7 @@ function ApplySheet({
<H5El as='i' style={{ width: `${(filled / 3) * 100}%` }} />
</H5El>
<H5El as='small' className='social-muted'>
{filled === 0
? '先简单介绍自己'
: filled < 3
? `还差 ${3 - filled} 项(简介可选)`
: '可以提交了'}
{draft.name.trim() && draft.contact.trim() ? '必填项已完成,简介可选' : '填写称呼与联系方式,简介可选'}
</H5El>
</H5El>
@ -172,6 +174,7 @@ function ApplySheet({
maxlength={64}
placeholder='昵称或真名都行'
value={draft.name}
disabled={busy}
onInput={(e) => update('name', e.detail.value)}
/>
</H5El>
@ -182,6 +185,7 @@ function ApplySheet({
maxlength={120}
placeholder='邮箱 / 微信 / Telegram…'
value={draft.contact}
disabled={busy}
onInput={(e) => update('contact', e.detail.value)}
/>
</H5El>
@ -193,6 +197,7 @@ function ApplySheet({
autoHeight
placeholder='相关经历、作品链接、每周能投入多久…'
value={draft.note}
disabled={busy}
onInput={(e) => update('note', e.detail.value)}
/>
<H5El className='social-apply-prompts'>
@ -202,6 +207,7 @@ function ApplySheet({
as='button'
type='button'
className='social-apply-chip'
disabled={busy}
onClick={() =>
update('note', draft.note.trim() ? `${draft.note.trim()}\n${tip}` : tip)
}
@ -222,6 +228,7 @@ function ApplySheet({
as='button'
type='button'
className='btn btn-primary social-apply-submit'
disabled={busy} loading={busy}
onClick={() => void submit()}
>
{busy ? '提交中…' : delivery === 'local' ? '重试提交' : '发送参与申请'}
@ -237,10 +244,12 @@ function ApplySheet({
}
function SocialTeam() {
const { theme, pageStyle } = useSocialPage()
usePageShare({ title: 'nomadro · 找搭子', path: '/pages/social/team/index' })
usePageTrack('social_team')
const router = useRouter()
const safe = useMemo(() => getSafeAreaMetrics(), [])
const { gigs, pages } = useSocialContent()
const initialKind = (router.params?.kind as string) || 'all'
const [kind, setKind] = useState<string>(initialKind)
const [query, setQuery] = useState(String(router.params?.q || ''))
@ -249,11 +258,11 @@ function SocialTeam() {
useEffect(() => {
const gigId = String(router.params?.gig || '')
if (!gigId) return
const gig = SEED_GIGS.find((g) => g.id === gigId)
const gig = gigs.find((g) => g.id === gigId)
if (gig) setActive(gig)
}, [router.params?.gig])
}, [router.params?.gig, gigs])
const roles = SEED_GIGS.filter((gig) => {
const roles = gigs.filter((gig) => {
if (kind !== 'all' && gig.kind !== kind) return false
const q = query.trim().toLowerCase()
if (!q) return true
@ -264,15 +273,8 @@ function SocialTeam() {
<SocialExperience>
<H5El
className='soc-taro-root social-root social-workspace social-weapp'
data-theme='dark'
style={
{
['--safe-status-bar' as string]: safePx(safe.statusBarHeight),
['--safe-nav-bar' as string]: safePx(safe.navBarHeight),
['--safe-menu-pad' as string]: safePx(safe.menuRightPad),
['--safe-header' as string]: safePx(safe.headerHeight),
} as CSSProperties
}
data-theme={theme}
style={pageStyle}
>
<H5El className='social-live-bar'>
<H5El className='social-live-bar-main'>
@ -285,7 +287,7 @@ function SocialTeam() {
← 首页
</H5El>
<H5El>
<H5El as='strong'>一起,做点事</H5El>
<H5El as='strong'>{pages.team?.title || '一起,做点事'}</H5El>
<H5El as='span' className='social-muted'>
找搭子 · 表单申请
</H5El>
@ -295,7 +297,7 @@ function SocialTeam() {
<H5El className='container social-sub-body'>
<H5El as='p' className='social-muted social-sub-block'>
远程也能一起推进:认领角色、写申请,草稿会先留在本机。
{pages.team?.description || '远程也能一起推进:认领角色、写申请,草稿会先留在本机。'}
</H5El>
<Input
@ -379,7 +381,7 @@ function SocialTeam() {
) : null}
</H5El>
{active ? <ApplySheet gig={active} onClose={() => setActive(null)} /> : null}
{active ? <ApplySheet key={active.id} gig={active} onClose={() => setActive(null)} /> : null}
<SocialDock />
</H5El>
</SocialExperience>

View File

@ -25,6 +25,11 @@ const listeners = new Set<Listener>()
let liveStarted = false
let metaTimer: ReturnType<typeof setInterval> | null = null
let knownVersion = 0
let configInFlight: Promise<LoadResult> | null = null
let metaInFlight: Promise<void> | null = null
let appVisible = true
let retryMetaAfter = 0
let metaFailures = 0
function emit(result: LoadResult) {
memory = result
@ -115,9 +120,19 @@ async function fetchMeta(): Promise<{ version: number; updatedAt: string } | nul
* 兜底顺序:内存 → 网络 → Storage → 包内 DEFAULT
* force=true:跳过内存,强制打 API(加群弹窗 / 前台唤醒)
*/
export async function loadRemoteConfig(force = false): Promise<LoadResult> {
if (!force && memory) return memory
export function loadRemoteConfig(force = false): Promise<LoadResult> {
if (configInFlight) return configInFlight
if (!force && memory) return Promise.resolve(memory)
const pending = fetchConfigWithFallback()
configInFlight = pending
const cleanup = () => {
if (configInFlight === pending) configInFlight = null
}
void pending.then(cleanup, cleanup)
return pending
}
async function fetchConfigWithFallback(): Promise<LoadResult> {
const cached = readStorage()
try {
@ -136,9 +151,10 @@ export async function loadRemoteConfig(force = false): Promise<LoadResult> {
/* fall through */
}
if (cached) {
// 断网仍保留最近一次成功配置,避免缓存过期后误恢复包内开关。
if (memory || cached) {
const result: LoadResult = {
config: cached,
config: memory?.config || cached!,
fromOffline: true,
source: 'storage',
}
@ -177,14 +193,27 @@ export function subscribeRemoteConfig(listener: Listener): () => void {
return () => listeners.delete(listener)
}
async function softCheckMeta() {
const meta = await fetchMeta()
if (!meta) {
function softCheckMeta(): Promise<void> {
if (metaInFlight) return metaInFlight
const pending = (async () => {
const meta = await fetchMeta()
if (!meta) {
// 弱网时避免每三秒堆积 meta + 全量配置请求。
metaFailures += 1
retryMetaAfter = Date.now() + Math.min(60000, META_POLL_MS * 2 ** Math.min(metaFailures, 5))
return
}
metaFailures = 0
retryMetaAfter = 0
if (memory?.source === 'network' && meta.version === knownVersion) return
await loadRemoteConfig(true)
return
})()
metaInFlight = pending
const cleanup = () => {
if (metaInFlight === pending) metaInFlight = null
}
if (knownVersion && meta.version === knownVersion) return
await loadRemoteConfig(true)
void pending.then(cleanup, cleanup)
return pending
}
/**
@ -199,6 +228,16 @@ export function startRemoteConfigLiveSync(): () => void {
let es: EventSource | null = null
let stopped = false
const onShow = () => {
appVisible = true
retryMetaAfter = 0
void softCheckMeta()
}
const onHide = () => { appVisible = false }
if (APP_TARGET !== 'h5') {
Taro.onAppShow(onShow)
Taro.onAppHide(onHide)
}
const stop = () => {
stopped = true
@ -209,6 +248,10 @@ export function startRemoteConfigLiveSync(): () => void {
}
es?.close()
es = null
if (APP_TARGET !== 'h5') {
Taro.offAppShow(onShow)
Taro.offAppHide(onHide)
}
}
if (APP_TARGET === 'h5' && typeof EventSource !== 'undefined') {
@ -234,7 +277,9 @@ export function startRemoteConfigLiveSync(): () => void {
}
metaTimer = setInterval(() => {
if (!stopped) void softCheckMeta()
const visible = APP_TARGET === 'h5' && typeof document !== 'undefined'
? document.visibilityState !== 'hidden' : appVisible
if (!stopped && visible && Date.now() >= retryMetaAfter) void softCheckMeta()
}, META_POLL_MS)
// 前台可见 / 小程序 onShow 由 app 层再调 softRefreshRemoteConfig

View File

@ -3,9 +3,19 @@
*/
import Taro from '@tarojs/taro'
import { API_BASE, WEB_BASE } from '@/utils/config'
import type { SocialRosterProfile, SocialCafeReview } from '@/data/socialTypes'
const GUEST_KEY = 'nomadro_social_guest'
const APPLY_LOCAL_KEY = 'nomadro_social_gig_apps'
let preferredBase = ''
export class SocialRequestError extends Error {
constructor(message: string, public status: number) { super(message) }
}
export function createSocialRequestId(): string {
return `c${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`
}
const SOCIAL_BASES = Array.from(
new Set(
@ -42,9 +52,9 @@ function errText(e: unknown, fallback: string) {
}
const raw = String(any.errMsg || any.message || any.detail || fallback)
if (/url not in domain|不在以下 request|合法域名/i.test(raw)) {
return '域名未配置:请加 api.nomadro.cn'
return '连接暂不可用,请稍后重试'
}
if (/timeout|超时/i.test(raw)) return '进厅超时,请重试'
if (/timeout|超时/i.test(raw)) return '连接超时,请稍后重试'
if (/fail|error/i.test(raw) && raw.length > 40) return raw.slice(0, 36)
return raw.slice(0, 40)
}
@ -56,8 +66,10 @@ async function req<T>(
const gid = guestId()
const qs = path.includes('?') ? `&guest=${encodeURIComponent(gid)}` : `?guest=${encodeURIComponent(gid)}`
let lastErr: Error | null = null
const readOnly = !init?.method || init.method === 'GET'
const bases = preferredBase ? [preferredBase, ...SOCIAL_BASES.filter((b) => b !== preferredBase)] : SOCIAL_BASES
for (const base of SOCIAL_BASES) {
for (const base of bases) {
const url = `${base}/api/social/v1${path}${qs}`
try {
const res = await Taro.request({
@ -78,13 +90,18 @@ async function req<T>(
: Array.isArray(detail)
? JSON.stringify(detail).slice(0, 80)
: `HTTP ${res.statusCode}`
lastErr = new Error(msg)
// 404 换下一个域名
const error = new SocialRequestError(msg, res.statusCode)
// 写请求结果不明时绝不换域重放;参数/权限错误也不能靠换域绕过。
if (!readOnly || ![404, 502, 503, 504].includes(res.statusCode)) throw error
lastErr = error
continue
}
preferredBase = base
return res.data as T
} catch (e) {
if (e instanceof SocialRequestError) throw e
lastErr = new Error(errText(e, '网络失败'))
if (!readOnly) throw lastErr
}
}
throw lastErr || new Error('进厅接口不可达')
@ -126,6 +143,7 @@ export type SocialChatMessage = {
guestId?: string
mine?: boolean
delivery?: 'sent' | 'local' | 'pending'
clientId?: string
}
export type SocialRealtimeToken = {
@ -136,7 +154,7 @@ export type SocialRealtimeToken = {
channel: string
}
function saveLocalApply(gigId: string, payload: GigApplyPayload) {
function saveLocalApply(gigId: string, payload: GigApplyPayload, requestId: string) {
try {
const raw = Taro.getStorageSync(APPLY_LOCAL_KEY)
const map = raw && typeof raw === 'object' ? { ...(raw as object) } : {}
@ -144,6 +162,7 @@ function saveLocalApply(gigId: string, payload: GigApplyPayload) {
...payload,
at: Date.now(),
delivery: 'local',
requestId,
}
Taro.setStorageSync(APPLY_LOCAL_KEY, map)
} catch {
@ -153,7 +172,7 @@ function saveLocalApply(gigId: string, payload: GigApplyPayload) {
export function getLocalApply(
gigId: string,
): (GigApplyPayload & { delivery?: string }) | null {
): (GigApplyPayload & { delivery?: string; requestId?: string }) | null {
try {
const raw = Taro.getStorageSync(APPLY_LOCAL_KEY)
if (!raw || typeof raw !== 'object') return null
@ -196,26 +215,39 @@ export const socialApi = {
`/channels/${encodeURIComponent(channelId)}/messages`,
),
sendMessage: (channelId: string, author: string, text: string) =>
sendMessage: (channelId: string, author: string, text: string, clientId?: string) =>
req<SocialChatMessage>(
`/channels/${encodeURIComponent(channelId)}/messages`,
{ method: 'POST', data: { author, text } },
{ method: 'POST', data: { author, text, ...(clientId ? { clientId } : {}) } },
),
applyGig: async (gigId: string, payload: GigApplyPayload) => {
const previous = getLocalApply(gigId)
const same = previous && previous.name === payload.name && previous.contact === payload.contact && (previous.note || '') === (payload.note || '')
const requestId = same && previous.requestId ? previous.requestId : createSocialRequestId()
try {
const res = await req<{ ok?: boolean }>(
`/gigs/${encodeURIComponent(gigId)}/apply`,
{ method: 'POST', data: payload },
{ method: 'POST', data: { ...payload, requestId } },
)
saveLocalApply(gigId, payload, requestId)
markLocalApplySent(gigId)
return res
} catch (e) {
saveLocalApply(gigId, payload)
saveLocalApply(gigId, payload, requestId)
throw e
}
},
getRoster: () => req<{ item: SocialRosterProfile | null }>('/roster/me'),
saveRoster: (profile: SocialRosterProfile) => req<SocialRosterProfile>('/roster/me', {
method: 'PUT', data: { ...profile },
}),
listCafeReviews: (id: string) => req<{ items: SocialCafeReview[] }>(`/cafes/${encodeURIComponent(id)}/reviews`),
addCafeReview: (id: string, author: string, score: number, text: string) => req<SocialCafeReview>(`/cafes/${encodeURIComponent(id)}/reviews`, {
method: 'POST', data: { author, score, text },
}),
liveJoin: (roomId: string, nick: string) =>
req<LiveJoinResult>(`/live/rooms/${encodeURIComponent(roomId)}/join`, {
method: 'POST',

View File

@ -0,0 +1,15 @@
import type { SocialChatMessage } from './socialApi'
export function mergeChatMessages(current: SocialChatMessage[], incoming: SocialChatMessage[], guest: string): SocialChatMessage[] {
const byId = new Map(current.map((item) => [item.id, item]))
for (const item of incoming) {
if (!item?.id || typeof item.text !== 'string') continue
if (item.clientId) {
for (const [id, existing] of byId) {
if (existing.clientId === item.clientId && existing.guestId === item.guestId) byId.delete(id)
}
}
byId.set(item.id, { ...item, mine: item.guestId === guest, delivery: 'sent' })
}
return Array.from(byId.values()).sort((a, b) => a.at.localeCompare(b.at)).slice(-300)
}

View File

@ -0,0 +1,44 @@
import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
const EVENT = 'nomadro:social:local'
export function readSocialLocal<T>(key: string, fallback: T): T {
try {
const value = Taro.getStorageSync(`nomadro_social_${key}`)
return value && typeof value === typeof fallback ? value as T : fallback
} catch { return fallback }
}
export function writeSocialLocal<T>(key: string, value: T): boolean {
try {
Taro.setStorageSync(`nomadro_social_${key}`, value)
Taro.eventCenter.trigger(EVENT, key)
return true
} catch { return false }
}
/** Share device preferences across home, directory, profile and swipe pages. */
export function useSocialLocal<T>(key: string, fallback: T) {
const [value, setValue] = useState<T>(() => readSocialLocal(key, fallback))
useEffect(() => {
const sync = (changed: string) => {
if (changed === key) setValue(readSocialLocal(key, fallback))
}
Taro.eventCenter.on(EVENT, sync)
return () => { Taro.eventCenter.off(EVENT, sync) }
}, [key])
const update = (next: T | ((previous: T) => T)) => {
const result = typeof next === 'function'
? (next as (previous: T) => T)(readSocialLocal(key, fallback)) : next
if (!writeSocialLocal(key, result)) {
setValue(result)
void Taro.showToast({ title: '本机存储空间不足,记录暂未保存', icon: 'none' })
}
}
return [value, update] as const
}
export function useSocialLikes() {
return useSocialLocal<Record<string, boolean>>('likes_v1', {})
}

View File

@ -1,192 +1,74 @@
/**
* Centrifugo WebSocket 客户端(微信小程序 Taro.connectSocket)
* 协议:Centrifugo JSON (command/push)
*/
/** Native Taro sockets; only report live after channel subscription succeeds. */
import Taro from '@tarojs/taro'
import { socialApi, type SocialChatMessage, type SocialRealtimeToken } from './socialApi'
import { socialApi, type SocialChatMessage } from './socialApi'
type PubHandler = (msg: SocialChatMessage) => void
type PubHandler = (message: SocialChatMessage) => void
function rewriteWsForWeapp(wsUrl: string): string[] {
const raw = String(wsUrl || '').trim()
const list: string[] = []
if (raw) list.push(raw)
// 真机 socket 合法域名常只有 api.nomadro.cn
if (raw.includes('nomadro.cn') && !raw.includes('api.nomadro.cn')) {
list.unshift(raw.replace('://nomadro.cn/', '://api.nomadro.cn/'))
}
if (!list.includes('wss://api.nomadro.cn/rt/connection/websocket')) {
list.push('wss://api.nomadro.cn/rt/connection/websocket')
}
if (!list.includes('wss://nomadro.cn/rt/connection/websocket')) {
list.push('wss://nomadro.cn/rt/connection/websocket')
}
return Array.from(new Set(list))
}
export async function connectChatRealtime(
channelId: string,
onMessage: PubHandler,
): Promise<{ disconnect: () => void } | null> {
let info: SocialRealtimeToken
try {
info = await socialApi.realtimeToken(channelId)
} catch {
return null
}
if (!info?.ok || !info.token) return null
const urls = rewriteWsForWeapp(info.wsUrl)
const channel = info.channel || `social:${channelId}`
let task: Taro.SocketTask | null = null
let closed = false
let cmdId = 1
const sendCmd = (payload: Record<string, unknown>) => {
if (!task || closed) return
const id = cmdId++
try {
task.send({ data: JSON.stringify({ id, ...payload }) })
} catch {
/* ignore */
}
}
const handleRaw = (raw: string) => {
let msg: any
try {
msg = JSON.parse(raw)
} catch {
return
}
// reply
if (msg.connect) {
sendCmd({ subscribe: { channel } })
return
}
// push publication
const push = msg.push
if (push?.pub?.data) {
const data = push.pub.data as {
type?: string
message?: SocialChatMessage
}
if (data?.type === 'chat.message' && data.message?.id) {
onMessage({
id: data.message.id,
channelId: data.message.channelId || channelId,
author: data.message.author || '游民',
text: data.message.text || '',
at: data.message.at || new Date().toISOString(),
guestId: data.message.guestId,
mine: false,
delivery: 'sent',
})
}
}
}
const bind = (
sock: Taro.SocketTask,
finish: (ok: boolean) => void,
markConnected: () => void,
) => {
const timer = setTimeout(() => {
try {
sock.close({})
} catch {
/* ignore */
}
finish(false)
}, 8000)
sock.onOpen(() => {
sendCmd({ connect: { token: info.token } })
})
sock.onMessage((ev) => {
const data = typeof ev.data === 'string' ? ev.data : ''
if (!data) return
let msg: any
try {
msg = JSON.parse(data)
} catch {
return
}
if (msg.connect) {
clearTimeout(timer)
markConnected()
sendCmd({ subscribe: { channel } })
finish(true)
return
}
handleRaw(data)
})
sock.onError(() => {
clearTimeout(timer)
finish(false)
})
sock.onClose(() => {
clearTimeout(timer)
finish(false)
})
}
const tryConnect = (index: number): Promise<boolean> =>
new Promise((resolve) => {
if (closed || index >= urls.length) {
resolve(false)
return
}
const url = urls[index]!
export async function connectChatRealtime(channelId: string, onMessage: PubHandler, onConnection?: (connected: boolean) => void): Promise<{ disconnect: () => void } | null> {
let info
try { info = await socialApi.realtimeToken(channelId) } catch { return null }
if (!info?.ok || !info.enabled || !info.token || !info.wsUrl) return null
const urls = Array.from(new Set([
info.wsUrl.replace('://nomadro.cn/', '://api.nomadro.cn/'), info.wsUrl,
])).filter((url) => /^wss?:\/\//.test(url))
for (const url of urls) {
const connection = await new Promise<{ disconnect: () => void } | null>((resolve) => {
let socket: Taro.SocketTask | undefined
let settled = false
const finish = (ok: boolean) => {
if (settled) return
settled = true
resolve(ok)
let disconnected = false
let commandId = 1
let timer: ReturnType<typeof setTimeout>
const stop = () => {
if (disconnected) return
disconnected = true
clearTimeout(timer)
onConnection?.(false)
try { socket?.close({}) } catch { /* closed */ }
}
const openSocket = (sock: Taro.SocketTask) => {
task = sock
bind(sock, finish, () => undefined)
const failed = () => {
stop()
if (!settled) { settled = true; resolve(null) }
}
try {
const maybe = Taro.connectSocket({
url,
fail: () => finish(false),
})
// Taro 3:可能同步返回 SocketTask,或返回 Promise
if (maybe && typeof (maybe as Taro.SocketTask).onOpen === 'function') {
openSocket(maybe as Taro.SocketTask)
} else {
Promise.resolve(maybe as unknown as Promise<Taro.SocketTask>)
.then(openSocket)
.catch(() => finish(false))
}
} catch {
finish(false)
timer = setTimeout(failed, 8000)
const send = (command: Record<string, unknown>) => {
try { socket?.send({ data: JSON.stringify({ id: commandId++, ...command }), fail: failed }) }
catch { failed() }
}
})
// 依次尝试多个 wss
for (let i = 0; i < urls.length; i += 1) {
if (closed) break
// eslint-disable-next-line no-await-in-loop
const ok = await tryConnect(i)
if (ok) {
return {
disconnect: () => {
closed = true
try {
task?.close({})
} catch {
/* ignore */
const bind = (task: Taro.SocketTask) => {
socket = task
if (disconnected) { try { task.close({}) } catch { /* closed */ }; return }
task.onOpen(() => send({ connect: { token: info.token } }))
task.onError(failed)
task.onClose(failed)
task.onMessage((event) => {
if (disconnected || typeof event.data !== 'string') return
for (const line of event.data.split('\n').filter(Boolean)) {
let message: any
try { message = JSON.parse(line) } catch { continue }
if (message.error) { failed(); return }
if (message.connect) send({ subscribe: { channel: info.channel || `social:${channelId}` } })
if (message.subscribe && !settled) {
clearTimeout(timer)
settled = true
onConnection?.(true)
resolve({ disconnect: stop })
}
const publication = message.push?.pub?.data
const item = publication?.type === 'chat.message' ? publication.message : publication
if (item?.id && item.channelId === channelId) onMessage(item)
if (!Object.keys(message).length) {
try { task.send({ data: '{}' }) } catch { failed() }
}
}
task = null
},
})
}
}
try {
const pending = Taro.connectSocket({ url, fail: failed }) as unknown as Taro.SocketTask | Promise<Taro.SocketTask>
if ('onOpen' in pending && typeof pending.onOpen === 'function') bind(pending as Taro.SocketTask)
else void Promise.resolve(pending).then(bind).catch(failed)
} catch { failed() }
})
if (connection) return connection
}
return null
}

View File

@ -0,0 +1,2 @@
// Vite must statically import styles; runtime require() breaks the browser entry.
import './bundle'

View File

@ -0,0 +1,217 @@
/* Shared native community surfaces. rem remains readable with a 750 design width. */
.soc-taro-root.social-root[data-theme] {
--social-bg: #0c111b;
--social-surface: #141d2b;
--social-raised: #1b2738;
--social-text: #eef3fb;
--social-muted: #a2b1c6;
--social-line: rgba(164, 184, 213, 0.16);
--social-accent: #68ddd0;
--bg-primary: var(--social-bg);
--bg-secondary: var(--social-surface);
--bg-card: var(--social-surface);
--text-primary: var(--social-text);
--text-secondary: var(--social-muted);
--text-muted: var(--social-muted);
--ink: var(--social-text);
--ink-muted: var(--social-muted);
--surface: var(--social-surface);
--surface-solid: var(--social-surface);
--bg: var(--social-bg);
background-color: var(--social-bg) !important;
color: var(--social-text) !important;
min-width: 0;
font-size: 1rem;
line-height: 1.6;
overflow-wrap: anywhere;
}
.soc-taro-root.social-root[data-theme='light'] {
--social-bg: #f4f7fb !important;
--social-surface: #fff !important;
--social-raised: #eaf0f7 !important;
--social-text: #15243a !important;
--social-muted: #52657e !important;
--social-line: rgba(37, 65, 99, 0.14) !important;
--social-accent: #087e72 !important;
}
.soc-taro-root.social-root.social-weapp[data-theme='light'] .social-people-chip,
.soc-taro-root.social-root.social-weapp[data-theme='light'] .social-panel {
background: #fff !important; color: #15243a !important; border-color: #dce5ef !important;
}
.soc-taro-root.social-root.social-weapp[data-theme='light'] .nav-logo,
.soc-taro-root.social-root.social-weapp[data-theme='light'] .connection-film,
.soc-taro-root.social-root.social-weapp[data-theme='light'] .social-people-chip strong { color: #15243a !important; }
.soc-taro-root.social-root.social-weapp[data-theme='light'] .btn:not(.btn-primary),
.soc-taro-root.social-root.social-weapp[data-theme='light'] .as-button:not(.btn-primary) { background: #eaf0f7 !important; color: #15243a !important; }
.soc-taro-root.social-root.social-weapp[data-theme] .social-people-chip > strong {
grid-column: 2 !important; grid-row: 1; font-size: 1rem !important; line-height: 1.5; color: var(--social-text) !important;
}
.soc-taro-root.social-root.social-weapp[data-theme] .social-people-chip > .connection-member-role { grid-row: 2; color: var(--social-muted) !important; }
.soc-taro-root.social-root.social-weapp[data-theme] .social-people-chip > em { grid-column: 1 / -1 !important; font-size: 0.8125rem; color: var(--social-muted) !important; font-style: normal; }
.soc-taro-root.social-root.social-weapp[data-theme] .social-people-chip-want { color: var(--social-muted) !important; }
.soc-taro-root.social-root[data-theme] .social-panel,
.soc-taro-root.social-root[data-theme] .social-profile-card,
.soc-taro-root.social-root[data-theme] .social-people-chip,
.soc-taro-root.social-root[data-theme] .social-date-card-body,
.soc-taro-root.social-root[data-theme] .social-apply-sheet,
.soc-taro-root.social-root[data-theme] .social-join-sheet-panel {
background: var(--social-surface) !important;
color: var(--social-text) !important;
border: 1rpx solid var(--social-line) !important;
border-radius: 1.25rem;
box-shadow: 0 0.5rem 1.75rem rgba(0, 0, 0, 0.08);
}
.soc-taro-root.social-root[data-theme] .social-muted,
.soc-taro-root.social-root[data-theme] .connection-member-role,
.soc-taro-root.social-root[data-theme] .social-people-chip-want,
.soc-taro-root.social-root[data-theme] .social-profile-title,
.soc-taro-root.social-root[data-theme] .social-profile-city {
color: var(--social-muted) !important;
font-size: 0.875rem !important;
line-height: 1.65;
}
.soc-taro-root.social-root[data-theme] .social-live-bar,
.soc-taro-root.social-root[data-theme] .social-mobile-dock {
background: var(--social-surface) !important;
color: var(--social-text) !important;
border-color: var(--social-line) !important;
}
.soc-taro-root.social-root[data-theme] .social-live-bar-main {
min-height: var(--safe-nav-bar, 2.75rem);
gap: 0.625rem;
}
.soc-taro-root.social-root[data-theme] .social-sub-body {
padding-bottom: calc(7rem + env(safe-area-inset-bottom)) !important;
}
.soc-taro-root.social-root[data-theme] .btn,
.soc-taro-root.social-root[data-theme] .as-button,
.soc-taro-root.social-root[data-theme] .social-nav-back,
.soc-taro-root.social-root[data-theme] .social-people-filter {
min-height: 2.75rem !important;
min-width: 2.75rem;
box-sizing: border-box;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.625rem 0.875rem;
margin: 0;
border-radius: 0.875rem;
border: 1rpx solid var(--social-line);
background: var(--social-raised);
color: var(--social-text);
font-size: 0.875rem !important;
line-height: 1.4;
font-weight: 600;
flex-shrink: 0;
&::after { border: 0; }
&:active { opacity: 0.7; }
&[disabled] { opacity: 0.5; }
&:focus-visible { outline: 2px solid var(--social-accent); outline-offset: 3px; }
}
.soc-taro-root.social-root[data-theme] .btn-primary {
background: #52d3c4 !important;
color: #082f2b !important;
box-shadow: none !important;
}
.soc-taro-root.social-root[data-theme] .social-people-chip-like {
min-width: 2.75rem;
min-height: 2.75rem;
padding: 0.375rem;
font-size: 1.375rem !important;
border-radius: 50%;
}
.soc-taro-root.social-root[data-theme] .social-live-bar-main > div { min-width: 0; }
.soc-taro-root.social-root[data-theme] .social-live-bar-main strong,
.soc-taro-root.social-root[data-theme] .social-live-bar-main .as-strong { display: block; }
.soc-taro-root.social-root[data-theme] .social-people-chip .connection-member-role {
display: block !important; visibility: visible !important; opacity: 1 !important;
}
.soc-taro-root.social-root[data-theme='light'] .social-people-chip strong,
.soc-taro-root.social-root[data-theme='light'] .social-panel strong,
.soc-taro-root.social-root[data-theme='light'] .social-panel h2,
.soc-taro-root.social-root[data-theme='light'] .social-panel h3 { color: var(--social-text) !important; }
.soc-taro-root.social-root[data-theme] .social-field-input,
.soc-taro-root.social-root[data-theme] .social-join-input {
display: block;
width: 100%;
min-height: 3rem;
box-sizing: border-box;
border: 1rpx solid var(--social-line) !important;
border-radius: 0.875rem;
background: var(--social-raised) !important;
color: var(--social-text) !important;
padding: 0.75rem 0.875rem;
font-size: 1rem !important;
line-height: 1.5;
}
.social-theme-control {
position: fixed;
right: 1rem;
bottom: calc(5.5rem + env(safe-area-inset-bottom));
z-index: 65;
display: flex;
align-items: center;
justify-content: center;
width: 2.75rem;
height: 2.75rem;
margin: 0;
padding: 0;
border: 1rpx solid rgba(148, 163, 184, 0.35);
border-radius: 50%;
background: #1b2738;
color: #eef3fb;
font-size: 1.25rem;
box-shadow: 0 0.25rem 1rem rgba(0,0,0,0.18);
&::after { border: 0; }
}
.social-experience .social-fx-control { bottom: calc(5.5rem + env(safe-area-inset-bottom)); left: 1rem; right: auto; min-height: 2.75rem; }
.social-pressed { opacity: 0.7; }
.social-inline-status { margin: 0.875rem 0; font-size: 0.875rem; line-height: 1.6; color: var(--social-muted); }
.social-search-row { margin-bottom: 1rem; }
.social-search-summary { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; margin: 0.75rem 0 1rem; font-size: 0.875rem; color: var(--social-muted); }
.social-empty-state { padding: 2rem 1.25rem; text-align: center; }
.social-empty-state .as-strong { display: block; margin-bottom: 0.5rem; font-size: 1.125rem; }
.social-empty-state .btn { margin-top: 1rem !important; }
.social-profile-field { display: flex; flex-direction: column; gap: 0.5rem; margin-bottom: 1rem; }
.social-profile-field .social-field-input { min-height: 3rem; }
.social-profile-field textarea { min-height: 7rem !important; }
.social-profile-save-row { display: flex; flex-direction: column; gap: 0.75rem; margin-top: 1rem; }
.social-profile-save-row .btn { width: 100%; }
.social-sheet-mask { position: fixed; inset: 0; z-index: 1000; display: flex; align-items: flex-end; background: rgba(3,8,18,0.72); }
.social-sheet-panel { width: 100%; max-height: 85vh; overflow-y: auto; box-sizing: border-box; padding: 1.25rem 1rem calc(1.5rem + env(safe-area-inset-bottom)); border-radius: 1.5rem 1.5rem 0 0 !important; }
.social-sheet-head { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: 1rem; }
.social-sheet-head .as-strong { font-size: 1.125rem; }
.social-review-item { border-top: 1rpx solid var(--social-line); padding: 1rem 0; }
.social-review-item .as-p { white-space: pre-wrap; }
.social-rating-row { display: flex; gap: 0.5rem; margin: 0.875rem 0; }
.social-rating-row .is-on { color: #9a6700 !important; background: #fef3c7 !important; }
.soc-taro-root.social-root[data-theme='light'] .social-profile-cover { opacity: 0.45; }
.soc-taro-root.social-root[data-theme='light'] .social-path,
.soc-taro-root.social-root[data-theme='light'] .navbar { background: #f4f7fb !important; color: #15243a !important; }
.soc-taro-root.social-root[data-theme='light'] .section-header h2,
.soc-taro-root.social-root[data-theme='light'] .section-header .as-h2,
.soc-taro-root.social-root[data-theme='light'] .social-profile .as-h1,
.soc-taro-root.social-root[data-theme='light'] .social-people-chip .as-strong { color: var(--social-text) !important; }
@media (prefers-reduced-motion: reduce) {
.social-experience .social-ambient,
.social-experience .social-fx-orbs,
.social-experience .social-emoji-field,
.social-experience .social-fx-belt { display: none !important; }
.social-root .reveal { animation: none !important; transform: none !important; opacity: 1 !important; }
}

View File

@ -2,6 +2,7 @@ import Taro from '@tarojs/taro'
import { trackClick } from './track'
const isH5 = process.env.TARO_ENV === 'h5'
let navigating = false
function normalizePath(url: string): string {
const raw = (url || '').split('?')[0]
@ -14,17 +15,22 @@ function normalizePath(url: string): string {
* (勿在此读 process.env.TARO_APP_* —— 未注入 Define 时小程序会 ReferenceError: process is not defined)
*/
export function goPage(url: string): void {
if (navigating) return
const path = normalizePath(url)
if (!path) return
const qs = url.includes('?') ? url.slice(url.indexOf('?')) : ''
const full = `${path}${qs}`
trackClick('页面跳转', { to: full })
if (isH5 && (path.includes('/pages/home') || path.includes('/pages/index'))) {
Taro.redirectTo({ url: full }).catch(() => Taro.navigateTo({ url: full }))
return
}
Taro.navigateTo({ url: full }).catch(() =>
Taro.redirectTo({ url: full }).catch(() => Taro.reLaunch({ url: full })),
)
navigating = true
const home = path === '/pages/home/index' || path === '/pages/index/index'
const navigate = home
? (isH5 ? Taro.redirectTo({ url: full }) : Taro.reLaunch({ url: full }))
: (Taro.getCurrentPages().length >= 10
? Taro.redirectTo({ url: full })
: Taro.navigateTo({ url: full }))
void navigate.catch(() => Taro.redirectTo({ url: full })).catch(() => {
void Taro.showToast({ title: '页面暂时无法打开,请重试', icon: 'none' })
}).finally(() => { navigating = false })
}
export function goHome(): void {

View File

@ -20,13 +20,19 @@ type RequestOptions = {
_retried?: boolean
}
let loginInFlight: Promise<{ openid: string; token: string }> | null = null
let sessionGeneration = 0
export function clearLogin() {
sessionGeneration += 1
loginInFlight = null
Taro.removeStorageSync(STORAGE_TOKEN)
Taro.removeStorageSync(STORAGE_OPENID)
}
/** 电子书 API(/api/ebook/auth|/api/ebook/pay|/api/ebook/books…)— 门户命名空间 */
export async function requestEbook<T = unknown>(options: RequestOptions): Promise<T> {
const generation = sessionGeneration
const token = Taro.getStorageSync(STORAGE_TOKEN)
const res = await Taro.request({
url: `${API_BASE}${options.url}`,
@ -43,12 +49,19 @@ export async function requestEbook<T = unknown>(options: RequestOptions): Promis
})
if (res.statusCode === 401 && !options._retried && !options.url.includes('/api/ebook/auth/login')) {
if (generation !== sessionGeneration && !Taro.getStorageSync(STORAGE_TOKEN) && !loginInFlight) {
throw new Error('需要登录')
}
// H5 无 wx.login:直接失败,交给上层 offline 兜底,避免卡在登录重试
if (process.env.TARO_ENV === 'h5' || APP_TARGET === 'h5') {
throw new Error('需要登录')
}
clearLogin()
await ensureLogin(true)
// 其他请求可能已经刷新了会话,避免迟到的 401 再次清除新 token。
if (Taro.getStorageSync(STORAGE_TOKEN) === token) {
await ensureLogin(true)
} else {
await ensureLogin()
}
return requestEbook<T>({ ...options, _retried: true })
}
@ -71,29 +84,46 @@ export async function requestEbook<T = unknown>(options: RequestOptions): Promis
/** ebook 兼容别名 */
export const request = requestEbook
export async function ensureLogin(force = false): Promise<{ openid: string; token: string }> {
export function ensureLogin(force = false): Promise<{ openid: string; token: string }> {
// 同一时间只允许一条 wx.login → 后端登录链路,force 也复用刷新中的会话。
if (loginInFlight) return loginInFlight
if (!force) {
const cachedOpenid = Taro.getStorageSync(STORAGE_OPENID)
const cachedToken = Taro.getStorageSync(STORAGE_TOKEN)
if (cachedOpenid && cachedToken) {
return { openid: cachedOpenid, token: cachedToken }
return Promise.resolve({ openid: cachedOpenid, token: cachedToken })
}
} else {
clearLogin()
}
const generation = sessionGeneration
const pending = performLogin(force, generation)
loginInFlight = pending
const cleanup = () => {
if (loginInFlight === pending) loginInFlight = null
}
void pending.then(cleanup, cleanup)
return pending
}
async function performLogin(force: boolean, generation: number): Promise<{ openid: string; token: string }> {
let lastErr: unknown
for (let i = 0; i < 3; i++) {
try {
const loginRes = await Taro.login()
if (generation !== sessionGeneration) throw new Error('登录已取消')
const loginRes = await Taro.login({ timeout: 8000 })
if (generation !== sessionGeneration) throw new Error('登录已取消')
const code = loginRes.code
if (!code) throw new Error('微信登录失败:未拿到 code')
const res = await Taro.request({
url: `${API_BASE}/api/ebook/auth/login`,
method: 'POST',
data: { code },
timeout: 8000,
header: { 'Content-Type': 'application/json' },
})
if (generation !== sessionGeneration) throw new Error('登录已取消')
if (res.statusCode >= 400) {
const msg =
(res.data as { detail?: string; message?: string })?.detail ||
@ -109,6 +139,12 @@ export async function ensureLogin(force = false): Promise<{ openid: string; toke
throw new Error(text)
}
const data = res.data as { openid: string; token: string; session_ready: boolean }
if (!data || typeof data.openid !== 'string' || !data.openid ||
typeof data.token !== 'string' || !data.token) {
throw new Error('登录响应异常,请稍后重试')
}
// 退出登录后,迟到的登录响应不可重新写入会话。
if (generation !== sessionGeneration) throw new Error('登录已取消')
Taro.setStorageSync(STORAGE_OPENID, data.openid)
Taro.setStorageSync(STORAGE_TOKEN, data.token)
track('login_ok', {
@ -119,7 +155,7 @@ export async function ensureLogin(force = false): Promise<{ openid: string; toke
} catch (e) {
lastErr = e
// 拉黑:不再重试登录,避免连弹
if (e instanceof Error && e.message === '账号不可用') {
if (generation !== sessionGeneration || (e instanceof Error && e.message === '账号不可用')) {
throw e
}
if (i >= 2) {
@ -128,7 +164,7 @@ export async function ensureLogin(force = false): Promise<{ openid: string; toke
props: { msg: String((e as Error)?.message || e).slice(0, 120) },
})
}
await new Promise((r) => setTimeout(r, 250 * (i + 1)))
if (i < 2) await new Promise((r) => setTimeout(r, 250 * (i + 1)))
}
}
throw lastErr || new Error('登录失败,请再试一次')
@ -202,6 +238,7 @@ export async function requestGateway<T = unknown>(
url: `${GATEWAY_API_BASE}${path.startsWith('/') ? path : `/${path}`}`,
method: opts.method || 'GET',
data: opts.data,
timeout: 8000,
header: {
'Content-Type': 'application/json',
...(opts.auth !== false && token ? { Authorization: `Bearer ${token}` } : {}),

View File

@ -73,7 +73,6 @@ function invokeVirtualPayment(payData: SocialJoinPayPayload): Promise<void> {
async function createSocialJoinOrder(): Promise<SocialJoinPayPayload> {
await ensureLogin(true)
const token = Taro.getStorageSync(STORAGE_TOKEN)
const urls = [
`${API_BASE}/api/ebook/pay/social-join-order`,
`${API_BASE}/api/pay/social-join-order`,
@ -83,10 +82,11 @@ async function createSocialJoinOrder(): Promise<SocialJoinPayPayload> {
const res = await Taro.request({
url,
method: 'POST',
timeout: 8000,
data: {},
header: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
Authorization: `Bearer ${Taro.getStorageSync(STORAGE_TOKEN)}`,
},
})
if (res.statusCode < 400) {
@ -94,9 +94,8 @@ async function createSocialJoinOrder(): Promise<SocialJoinPayPayload> {
}
const detail = (res.data as { detail?: string })?.detail
if (typeof detail === 'string' && detail) lastDetail = detail
if (res.statusCode === 401) {
await ensureLogin(true)
}
// Only a missing legacy route permits another endpoint. Never replay an uncertain order.
if (res.statusCode !== 404) throw new Error(lastDetail)
}
throw new Error(lastDetail)
}
@ -107,12 +106,12 @@ export async function fetchSocialJoinStatus(): Promise<SocialJoinStatus | null>
const token = Taro.getStorageSync(STORAGE_TOKEN)
if (!token) {
return {
ok: true,
ok: false,
isMember: Boolean(Taro.getStorageSync(LOCAL_MEMBER_KEY)),
bookId: '__social_join__',
title: '游民社区加群',
priceFen: 4900,
enabled: true,
enabled: false,
}
}
const urls = [
@ -123,11 +122,13 @@ export async function fetchSocialJoinStatus(): Promise<SocialJoinStatus | null>
const res = await Taro.request({
url,
method: 'GET',
timeout: 8000,
header: { Authorization: `Bearer ${token}` },
})
if (res.statusCode < 400) {
const data = res.data as SocialJoinStatus
if (data?.isMember) Taro.setStorageSync(LOCAL_MEMBER_KEY, '1')
else Taro.removeStorageSync(LOCAL_MEMBER_KEY)
return data
}
}
@ -135,12 +136,12 @@ export async function fetchSocialJoinStatus(): Promise<SocialJoinStatus | null>
/* offline */
}
return {
ok: true,
ok: false,
isMember: Boolean(Taro.getStorageSync(LOCAL_MEMBER_KEY)),
bookId: '__social_join__',
title: '游民社区加群',
priceFen: 4900,
enabled: true,
enabled: false,
}
}
@ -166,8 +167,7 @@ export async function paySocialJoin(): Promise<string> {
}
if (APP_TARGET === 'h5' || process.env.TARO_ENV === 'h5') {
markSocialJoinLocal()
return `h5_local_${Date.now()}`
throw new Error('请在微信小程序内完成加群支付')
}
let lastErr: unknown

View File

@ -0,0 +1,21 @@
import Taro from '@tarojs/taro'
import { goPage } from './nav'
/** Reuse pages already in the native stack, avoiding home/list/detail loops. */
export function goSocialPage(url: string): void {
const path = url.split('?')[0].replace(/^\//, '')
if (!url.includes('?') && path.startsWith('pages/social/')) {
const pages = Taro.getCurrentPages()
const current = pages.length - 1
let existing = -1
for (let index = current; index >= 0; index--) {
if ((pages[index] as { route?: string }).route?.replace(/^\//, '') === path) { existing = index; break }
}
if (existing === current) return
if (existing >= 0) {
void Taro.navigateBack({ delta: current - existing }).catch(() => goPage(url))
return
}
}
goPage(url)
}

View File

@ -1,5 +1,49 @@
# 微信 weapp
## 2026-11-02:社区全部页面优化(本地验收,尚未发布)
范围为 `pages/social/index` 及 8 个原生子页面:聊天、认识一下、成员列表、成员详情、我的介绍、视频场次、视频厅、团队;包含咖啡馆评价、共创介绍、社区故事和加群支付底栏。
- UI:共享日夜主题、表单与触控尺寸、安全区、加载/失败/空状态、头像失败占位;修复中文问号、故事遮罩被首页层级遮挡、成员卡片日间对比度和原生按钮样式。遵守 `.cursor/skills/multi-platform-ui-scale/SKILL.md`。
- 功能:成员搜索、城市筛选;首页/列表/详情/滑卡共享本机关注;滑卡记录与撤销;资料真实读取/保存、逐字段合并本地草稿,读取失败时阻止覆盖服务器已有字段;咖啡馆评价;报名草稿与显式重试;共创详情与原生 Video。关注与滑卡是设备本地记录,不是服务端关系或私信。
- 聊天:最近消息、订阅确认、持久化待发送消息、失败显式重试、后台暂停轮询与消息合并;页面卸载后的发送成功也会清除待发送记录。
- 视频/支付:进厅防连点、离开/切后台停止原生音视频,迟到进厅响应清理;价格与资格由服务端确认,H5 不再模拟支付成功。
- 配置:复用 `/admin/config` 的 `copy.social*`、`socialPages`、`socialVideoSources`、`socialCatalogs`;扩展 roster/videos/ebooks 目录 JSON 编辑与首页模块开关。非法目录回退包内种子,显式空数组下架该目录。
验证:`pnpm --dir apps/miniprogram/weapp test:social`(6 项)、`test:runtime`(8 项);API 隔离测试 18 项(其中社区 11 项);`pnpm build:weapp` / `pnpm build:h5` 通过。门户 `pnpm exec tsc --noEmit --incremental false` 通过;H5 全量 tsc 仍有 22 个非社区错误,社区文件无报错;未改冻结游戏。
```bash
python -m http.server 10086 --bind 127.0.0.1 --directory apps/miniprogram/h5/dist
python -X utf8 apps/miniprogram/h5/scripts/check-social-ux.py
```
浏览器用 mock API 并阻断外部流量,320/390/430 三种宽度各检查 10 个路由场景、日夜主题、关注持久化、搜索、滑卡/撤销、报名失败重试同一标识、评价、共创/故事弹窗、支付不可用时禁用、资料失败草稿恢复、聊天失败重试。截图在 `../h5/tmp/social-ux/`。这些检查不能替代微信真机音视频、支付及媒体域名验收。开发者工具服务端口关闭,未上传体验版或提交审核。
最终 weapp 包体:主包 477.6 KiB、social 分包 663.2 KiB,所有分包小于 2 MiB,生成 WXML 未发现 web-view。线上仅执行只读服务检查;`nomadro-social` 单进程且 `CanReload=no`,视频房间保存在进程内,直接重启会丢失房间状态,因此未部署/重启,未同步任何数据库。
## 2026-11-02:微信体验与稳定性优化(本地验证,尚未发布)
- 首页:日夜模式切换、日间文字对比度、44px 等价触控区;复用 `flags.offlineBadge` 控制离线状态提示,`copy.homeLead` 控制引导文案;入口全关闭时提供刷新。
- 我的:统一 rem 尺寸与安全区,区分同步中、失败、收藏为空;支持重试、回到页面重新同步;网络故障保留会话和已显示数据,退出后丢弃迟到响应。
- 登录与导航:并发请求共用一次登录;迟到 401 复用新 token;退出后迟到响应不能恢复登录;快速连点只跳一次,返回首页清理历史栈。
- 配置:合并启动/页面的重复请求;meta 不重叠轮询,后台暂停、失败退避到最多 60 秒,回到前台立即检查;断网保留最近有效配置。移除启动时重复开启的 VIP 同步。
- 同源 H5:增加 `styles/social-next/entry.h5.ts`,修复生产包运行时 `require is not defined` 白屏。
验证命令:
```bash
pnpm --dir apps/miniprogram/weapp test:runtime
pnpm build:weapp
pnpm build:h5
# 另开终端仅在本机提供静态产物
python -m http.server 10086 --bind 127.0.0.1 --directory apps/miniprogram/h5/dist
python -X utf8 apps/miniprogram/h5/scripts/check-account-ux.py
```
交互回归通过 320 / 390 / 430 宽度的首页日夜切换、账户部分接口失败、断网保留登录、重试恢复、退出登录,所有业务接口均 mock,外部请求被拦截。截图:`../h5/tmp/account-ux/`。
全量 H5 类型检查存在 29 个基线错误,本轮未新增;包含已冻结游戏模块,未修改。微信开发者工具服务端口关闭,尚未完成模拟器自动化/真机验收。产物在 `dist/`,未上传、未提交审核;上线前仍需真机验证登录、支付、阅读与分享。
源码与 Taro H5 **共用** `../h5/src`(`sourceRoot: ../h5/src`)。
```bash

View File

@ -4,6 +4,8 @@
"private": true,
"description": "Nomadro 微信小程序(独立目录,与 h5 / tt / xhs 互不影响)",
"scripts": {
"test:runtime": "node ./scripts/test-runtime.cjs",
"test:social": "node ./scripts/test-social.cjs",
"dev": "node ./scripts/copy-weapp-static.mjs && cross-env TARO_APP_TARGET=weapp node ./node_modules/@tarojs/cli/bin/taro build --type weapp --watch",
"build": "cross-env TARO_APP_TARGET=weapp node ./node_modules/@tarojs/cli/bin/taro build --type weapp && node ./scripts/copy-weapp-static.mjs && node ./scripts/run-sanitize-wxss.cjs",
"dev:weapp": "pnpm dev",

View File

@ -0,0 +1,196 @@
// Isolated request/config/navigation regressions; never connects to a live API.
const { test } = require('node:test')
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const vm = require('node:vm')
const ts = require('typescript')
const sourceRoot = path.resolve(__dirname, '../../h5/src')
const config = {
API_BASE: 'https://api.invalid', WEB_BASE: 'https://web.invalid',
APP_TARGET: 'weapp', STORAGE_OPENID: 'openid', STORAGE_TOKEN: 'token',
}
function deferred() {
let resolve
const promise = new Promise((done) => { resolve = done })
return { promise, resolve }
}
function harness(file, overrides = {}, imports = {}) {
const storage = new Map()
const intervals = []
const events = {}
const taro = {
getStorageSync: (key) => storage.get(key),
setStorageSync: (key, value) => storage.set(key, value),
removeStorageSync: (key) => storage.delete(key),
onAppShow: (fn) => { events.show = fn },
onAppHide: (fn) => { events.hide = fn },
offAppShow: () => {}, offAppHide: () => {},
...overrides,
}
const module = { exports: {} }
const stubs = {
'@tarojs/taro': taro,
'./config': config, '../utils/config': config,
'./accountBlocked': { isAccountBlockedHttp: () => false, notifyAccountBlocked: () => {} },
'./track': { track: () => {}, trackClick: () => {} },
...imports,
}
const code = ts.transpileModule(fs.readFileSync(path.join(sourceRoot, file), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2018, esModuleInterop: true },
}).outputText
vm.runInNewContext(code, {
module, exports: module.exports,
require: (id) => {
if (!(id in stubs)) throw new Error(`Unexpected dependency ${id}`)
return stubs[id]
},
process: { env: { TARO_ENV: 'weapp' } },
setTimeout, clearTimeout,
setInterval: (fn) => { intervals.push(fn); return intervals.length },
clearInterval: () => {},
}, { filename: file })
return { api: module.exports, storage, intervals, events }
}
test('concurrent login and forced refresh share one session exchange', async () => {
const gate = deferred()
let calls = 0
const { api, storage } = harness('utils/request.ts', {
login: async () => { calls++; await gate.promise; return { code: 'once' } },
request: async () => ({ statusCode: 200, data: { openid: 'user', token: 'new' } }),
})
const pending = [api.ensureLogin(), api.ensureLogin(true), api.ensureLogin()]
gate.resolve()
await Promise.all(pending)
assert.equal(calls, 1)
assert.equal(storage.get('token'), 'new')
})
test('logging out discards a late login response', async () => {
const gate = deferred()
const { api, storage } = harness('utils/request.ts', {
login: async () => ({ code: 'code' }),
request: () => gate.promise,
})
const pending = api.ensureLogin()
await Promise.resolve()
api.clearLogin()
gate.resolve({ statusCode: 200, data: { openid: 'user', token: 'late' } })
await assert.rejects(pending, /登录已取消/)
assert.equal(storage.get('token'), undefined)
})
test('late 401 reuses refreshed credentials without a second login', async () => {
const late = deferred()
let logins = 0
const headers = []
const { api, storage } = harness('utils/request.ts', {
login: async () => { logins++; return { code: 'code' } },
request: async (options) => {
if (options.url.endsWith('/auth/login')) return { statusCode: 200, data: { openid: 'user', token: 'fresh' } }
headers.push(options.header.Authorization)
if (options.header.Authorization === 'Bearer old') {
if (options.url.endsWith('/late')) return late.promise
return { statusCode: 401, data: {} }
}
return { statusCode: 200, data: { ok: true } }
},
})
storage.set('token', 'old'); storage.set('openid', 'user')
const second = api.requestEbook({ url: '/late' })
await api.requestEbook({ url: '/first' })
late.resolve({ statusCode: 401, data: {} })
await second
assert.equal(logins, 1)
assert.equal(headers.filter((header) => header === 'Bearer fresh').length, 2)
})
test('a late unauthorized request cannot log the user back in after logout', async () => {
const late = deferred()
let logins = 0
const { api } = harness('utils/request.ts', {
login: async () => { logins++; return { code: 'code' } },
request: () => late.promise,
})
const pending = api.requestEbook({ url: '/profile' })
api.clearLogin()
late.resolve({ statusCode: 401, data: {} })
await assert.rejects(pending, /需要登录/)
assert.equal(logins, 0)
})
test('failed order submission is never automatically replayed', async () => {
let requests = 0
const { api } = harness('utils/request.ts', {
request: async () => { requests++; throw new Error('timeout') },
})
await assert.rejects(api.requestEbook({ url: '/orders', method: 'POST' }), /timeout/)
assert.equal(requests, 1)
})
const seed = { version: 1, modules: {}, flags: {}, copy: {} }
const seedImport = {
'../data/remoteConfig.defaults': { DEFAULT_REMOTE_CONFIG: seed, mergeRemoteConfig: (raw) => ({ ...seed, ...raw }) },
}
test('startup configuration callers share one request and preserve last good data offline', async () => {
const gate = deferred()
let requests = 0
let offline = false
const { api } = harness('services/remoteConfig.ts', {
request: async () => {
requests++
if (offline) throw new Error('offline')
await gate.promise
return { statusCode: 200, data: { config: { ...seed, version: 9 } } }
},
}, seedImport)
const pending = [api.loadRemoteConfig(true), api.loadRemoteConfig(true), api.loadRemoteConfig()]
gate.resolve()
await Promise.all(pending)
assert.equal(requests, 1)
offline = true
const fallback = await api.loadRemoteConfig(true)
assert.equal(fallback.config.version, 9)
assert.equal(fallback.fromOffline, true)
})
test('configuration polling pauses in background and never overlaps slow meta requests', async () => {
const gate = deferred()
let requests = 0
const { api, events, intervals } = harness('services/remoteConfig.ts', {
request: async () => { requests++; return gate.promise },
}, seedImport)
const stop = api.startRemoteConfigLiveSync()
events.hide()
intervals[0]()
assert.equal(requests, 0)
events.show()
intervals[0](); intervals[0]()
assert.equal(requests, 1)
gate.resolve({ statusCode: 200, data: { version: 1 } })
await new Promise((resolve) => setImmediate(resolve))
stop()
})
test('rapid taps open one page; home resets the stack', async () => {
const gate = deferred()
let navigations = 0
let homes = 0
const { api } = harness('utils/nav.ts', {
getCurrentPages: () => [],
navigateTo: () => { navigations++; return gate.promise },
reLaunch: async () => { homes++ },
})
api.goPage('/pages/book/index'); api.goPage('/pages/book/index')
assert.equal(navigations, 1)
gate.resolve()
await new Promise((resolve) => setImmediate(resolve))
api.goHome()
await new Promise((resolve) => setImmediate(resolve))
assert.equal(homes, 1)
})

View File

@ -0,0 +1,75 @@
// All network/storage/socket behavior is mocked. Never calls a production service.
const { test } = require('node:test')
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const vm = require('node:vm')
const ts = require('typescript')
const root = path.resolve(__dirname, '../../h5/src/services')
function harness(file, overrides = {}, imports = {}) {
const storage = new Map()
const taro = { getStorageSync: key => storage.get(key), setStorageSync: (key, value) => storage.set(key, value), ...overrides }
const module = { exports: {} }
const code = ts.transpileModule(fs.readFileSync(path.join(root, file), 'utf8'), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2018, esModuleInterop: true } }).outputText
const stubs = { '@tarojs/taro': taro, '@/utils/config': { API_BASE: 'https://api.invalid', WEB_BASE: 'https://web.invalid' }, ...imports }
vm.runInNewContext(code, { module, exports: module.exports, require: id => { if (!(id in stubs)) throw Error(id); return stubs[id] }, setTimeout, clearTimeout })
return { api: module.exports, storage }
}
test('reads fail over and subsequent writes use the successful origin', async () => {
const urls = []
const { api } = harness('socialApi.ts', { request: async options => { urls.push(options.url); return { statusCode: urls.length === 1 ? 503 : 200, data: { items: [], id: 'saved' } } } })
await api.socialApi.listMessages('general')
await api.socialApi.sendMessage('general', 'Name', 'Hello', 'key')
assert.equal(urls.length, 3)
assert.ok(urls[2].startsWith('https://api.nomadro.cn/'))
})
test('uncertain message writes never replay across origins', async () => {
let count = 0
const { api } = harness('socialApi.ts', { request: async () => { count++; throw Error('timeout') } })
await assert.rejects(api.socialApi.sendMessage('general', 'Name', 'Hello', 'key'))
assert.equal(count, 1)
})
test('permission errors never fail over even on reads', async () => {
let count = 0
const { api } = harness('socialApi.ts', { request: async () => { count++; return { statusCode: 403, data: { detail: 'Denied' } } } })
await assert.rejects(api.socialApi.listMessages('general'), /Denied/)
assert.equal(count, 1)
})
test('failed applications retain one idempotency key across explicit retries', async () => {
const keys = []
const { api } = harness('socialApi.ts', { request: async options => { keys.push(options.data.requestId); return { statusCode: keys.length === 1 ? 503 : 200, data: { id: 'saved' } } } })
const payload = { name: 'Name', contact: 'Contact' }
await assert.rejects(api.socialApi.applyGig('gig', payload))
await api.socialApi.applyGig('gig', payload)
assert.equal(keys[0], keys[1])
assert.equal(api.getLocalApply('gig').delivery, 'sent')
})
test('chat snapshots retain newer messages and reconcile a realtime acknowledgement', () => {
const { api } = harness('socialChatState.ts')
const local = { id: 'local', clientId: 'key', text: 'Hello', at: '2026-11-02', channelId: 'general', guestId: 'me', delivery: 'pending' }
const ack = { ...local, id: 'saved' }
let result = api.mergeChatMessages([local], [ack], 'me')
assert.equal(result.length, 1)
assert.equal(result[0].delivery, 'sent')
result = api.mergeChatMessages(result, [], 'me')
assert.equal(result[0].id, 'saved')
})
test('socket reports live only after subscribe and unwraps backend publication envelopes', async () => {
const handlers = {}, commands = [], delivered = [], states = []
const task = { onOpen: fn => handlers.open = fn, onMessage: fn => handlers.message = fn, onError: fn => handlers.error = fn, onClose: fn => handlers.close = fn, send: ({data}) => commands.push(JSON.parse(data)), close: () => {} }
const { api } = harness('socialRealtime.ts', { connectSocket: () => task }, { './socialApi': { socialApi: { realtimeToken: async () => ({ ok: true, enabled: true, token: 'mock', wsUrl: 'wss://socket.invalid/ws', channel: 'social:general' }) } } })
const pending = api.connectChatRealtime('general', item => delivered.push(item), state => states.push(state))
await new Promise(resolve => setImmediate(resolve))
handlers.open()
assert.ok(commands[0].connect)
handlers.message({ data: JSON.stringify({ id: 1, connect: {} }) })
assert.ok(commands[1].subscribe)
assert.equal(states.length, 0)
handlers.message({ data: JSON.stringify({ id: 2, subscribe: {} }) })
const connection = await pending
assert.equal(states[0], true)
handlers.message({ data: JSON.stringify({ push: { pub: { data: { type: 'chat.message', message: { id: 'saved', channelId: 'general', text: 'Hello' } } } } }) })
assert.equal(delivered[0].id, 'saved')
connection.disconnect()
assert.equal(states[1], false)
})

View File

@ -13,7 +13,7 @@ function SocialJsonEditor({
}: {
label: string;
value: unknown;
type: "pages" | "sources";
type: "pages" | "sources" | "catalogs";
onValue: (value: Record<string, never>) => void;
onValidity: (valid: boolean) => void;
}) {
@ -42,6 +42,11 @@ function SocialJsonEditor({
(item && !/^https?:\/\//i.test(item) && !item.startsWith("/"))
)
throw new Error("片源需为 http(s) 地址或站内路径");
} else if (type === "catalogs") {
if (!Array.isArray(item) || item.some((row) => !row || typeof row !== "object" || Array.isArray(row) || typeof row.id !== "string" || !row.id))
throw new Error("目录需为数组,每条内容必须包含非空字符串 id");
if (new Set(item.map((row) => row.id)).size !== item.length)
throw new Error("同一目录中的 id 不能重复");
} else if (
!item ||
typeof item !== "object" ||
@ -397,6 +402,25 @@ export default function AdminConfigPage() {
setSocialJsonErrors((current) => ({ ...current, sources: !valid }))
}
/>
<SocialJsonEditor
key={`catalogs:${config.updatedAt}`}
label='社区目录 JSON:roster / cafes / meetups / gigs / videos / ebooks;省略目录使用内置内容,空数组下架该目录'
type="catalogs"
value={config.copy.socialCatalogs}
onValue={(value) => setConfig({ ...config, copy: { ...config.copy, socialCatalogs: value } })}
onValidity={(valid) => setSocialJsonErrors((current) => ({ ...current, catalogs: !valid }))}
/>
<p className={styles.muted}>首页模块开关(取消勾选后隐藏对应模块与页内导航)</p>
{Object.entries({ people: '成员目录', date: '认识一下', meetup: '语音视频', cities: '同城见面', team: '团队与共创' }).map(([id, label]) => (
<label key={id} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginRight: 18, marginBottom: 12 }}>
<input type="checkbox" checked={!config.copy.socialHiddenSections?.includes(id)}
onChange={(event) => {
const hidden = new Set(config.copy.socialHiddenSections || []);
if (event.target.checked) hidden.delete(id); else hidden.add(id);
setConfig({ ...config, copy: { ...config.copy, socialHiddenSections: [...hidden] } });
}} />{label}
</label>
))}
</div>
<button
type="button"

View File

@ -149,11 +149,15 @@ export type NomadroRemoteConfig = {
}
>;
socialVideoSources?: Record<string, string>;
socialHiddenSections?: string[];
/** 游民社区目录覆盖;空数组/非法字段回退包内 seed */
socialCatalogs?: {
cafes?: Array<Record<string, unknown>>;
meetups?: Array<Record<string, unknown>>;
gigs?: Array<Record<string, unknown>>;
roster?: Array<Record<string, unknown>>;
videos?: Array<Record<string, unknown>>;
ebooks?: Array<Record<string, unknown>>;
};
socialWayGroup?: string;
socialWayChat?: string;