Ship /social H5 deep polish on test7 and document release line.

Tighten mobile Ways/dock/chat/date sheets, add social loading/error boundaries, and mark test8 as the next branch.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-01 23:19:59 +08:00
parent da22814584
commit e65728601f
30 changed files with 707 additions and 268 deletions

View File

@ -118,7 +118,8 @@ pnpm dev:api
- **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准 - **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准
- 审核冻结分支:`pre4`(**微信审核包,勿在本分支继续功能迭代**) - 审核冻结分支:`pre4`(**微信审核包,勿在本分支继续功能迭代**)
- `pre5`:承接 pre4 之后的功能(含游民社区 `/social`) - `pre5`:承接 pre4 之后的功能(含游民社区 `/social`)
- **当前开发分支:`test5`**(从 `pre5` 拉出);发版前与 README / 远程对齐 - `test5` / `test6`:游民社区实时层与 H5 初版(已合入后续分支)
- **当前发版分支:`test7`**(游民社区 H5 深优);下一轮开发切 **`test8`**
### 游民社区(`/social`) ### 游民社区(`/social`)
@ -161,17 +162,27 @@ pnpm dev:api
- 隔离 API + SQLite;远程配置 `modules.social`;门户 hero 主入口切换为游民社区 - 隔离 API + SQLite;远程配置 `modules.social`;门户 hero 主入口切换为游民社区
- 社区 Settings `extra="ignore"`,避免统一 `.env` 拖垮 community 启动 - 社区 Settings `extra="ignore"`,避免统一 `.env` 拖垮 community 启动
## test5(当前开发) ## test5
从 `pre5` 切出。本轮已落地(细节以 `deploy/social/README.md` 为准): 从 `pre5` 切出。已落地(细节以 `deploy/social/README.md` 为准):
- **Social 实时**:Centrifugo + `/api/social/v1/realtime/token`;聊天页优先 WS,失败降级轮询 - **Social 实时**:Centrifugo + `/api/social/v1/realtime/token`;聊天页优先 WS,失败降级轮询
- **Social API 独立进程**:`nomadro-social` `:8020`,与 ebook/community/pay 隔离 - **Social API 独立进程**:`nomadro-social` `:8020`,与 ebook/community/pay 隔离
- **MiroTalk**:钉死 82 `.cn`、白标中文、极速进房 - **MiroTalk**:钉死 82 `.cn`、白标中文、极速进房
- **视觉**:T1 默认;T2 代码保留、切换器隐藏 - **视觉**:T1 默认;T2 代码保留、切换器隐藏
- **发版约定**:前端本地 `pnpm dev` 验收通过、**经允许后再部署**门户 `.next`
后续可做:课时资料后台可视化、桥接 UX、真机网络/域名排查。 ## test6 / test7(当前发版)
游民社区 `/social` 手机端深优(门户 `h5.css` 最后加载):
- **Ways**:`群组聊天 → 认识一下 → 开视频 → 见面 → 找搭子`;竖列表,勿再做成轮播
- **底栏**:首页 → 聊天 → 认识 → 看看谁 → 我;聊天/滑卡操作区避开 dock + safe-area
- **首屏**:群组聊天在左、认识一下在右;窄屏收掉宇宙轨道,Ways 进首视口
- **滑卡 / 群聊**:手机更低滑动阈值、震动反馈;composer / 加入 sheet 全宽底栏
- **Meetup**:活动卡保留参与者头像 + 声纹条
- **发版**:`python deploy/social/deploy_82.py`(仅 82);冒烟 `https://nomadro.cn/social`
下一轮:`test8`(从 `test7` 拉出)。后续还可做:课时资料后台可视化、桥接 UX、真机网络/域名排查。
## pre3 摘要(已合入) ## pre3 摘要(已合入)

View File

@ -54,10 +54,13 @@ python deploy/social/deploy_82.py
- `NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn`(`/etc/nomadro/portal.env`) - `NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn`(`/etc/nomadro/portal.env`)
- Centrifugo:`CENTRIFUGO_*`(见 `/etc/nomadro/centrifugo.env`,可并入 `portal.env`) - Centrifugo:`CENTRIFUGO_*`(见 `/etc/nomadro/centrifugo.env`,可并入 `portal.env`)
**前端发版**:先本地 `pnpm dev` 验收 `/social`;**未经负责人允许不上线**门户 `.next`。 **前端发版**:先本地 `pnpm dev` 验收 `/social`;**未经负责人允许不上线**门户 `.next`。当前发版线:`test7`(H5 深优见根 `README.md`);下一轮 `test8`。
**H5(≤900px)**:`src/modules/social/app/h5.css` 最后加载;Ways 竖列表(群组聊天优先)、底栏聊天在「认识」左侧、滑卡/composer 避开 dock。
冒烟: 冒烟:
- `https://nomadro.cn/social` → 200 - `https://nomadro.cn/social` → 200
- `https://nomadro.cn/social/chat` · `/social/date` → 200(手机视口)
- `https://mirotalk.nomadro.cn/join?...` → 200(勿再用 `.com`) - `https://mirotalk.nomadro.cn/join?...` → 200(勿再用 `.com`)
- `GET /api/social/v1/health` → `centrifugo: true` - `GET /api/social/v1/health` → `centrifugo: true`
- `GET /api/social/v1/realtime/token?channel_id=lobby`(头 `X-Social-Guest-Id`)→ `wsUrl` + JWT - `GET /api/social/v1/realtime/token?channel_id=lobby`(头 `X-Social-Guest-Id`)→ `wsUrl` + JWT

18
src/app/social/error.tsx Normal file
View File

@ -0,0 +1,18 @@
"use client";
import Link from "next/link";
import { RefreshCw } from "lucide-react";
export default function SocialError({ reset }: { reset: () => void }) {
return (
<main className="social-route-state">
<span className="social-route-state-mark" aria-hidden="true">🧭</span>
<h1>页面暂时没能打开</h1>
<p role="alert">请重试加载,当前设备中保存的草稿和收藏会继续保留。</p>
<div className="social-actions">
<button type="button" className="social-btn primary" onClick={reset}><RefreshCw size={16} />重新加载</button>
<Link className="social-btn" href="/social">返回社区首页</Link>
</div>
</main>
);
}

View File

@ -0,0 +1,10 @@
export default function SocialLoading() {
return (
<main className="social-route-state" aria-busy="true" aria-label="正在加载社区页面">
<p role="status">正在加载,请稍候…</p>
<div className="social-route-skeleton" aria-hidden="true">
<span /><span /><span />
</div>
</main>
);
}

View File

@ -1,8 +1,6 @@
import MeetupLiveClient from "@social/components/MeetupLiveClient"; import MeetupLiveClient from "@social/components/MeetupLiveClient";
import { SEED_MEETUPS } from "@social/lib/seed";
export default async function Page({ params }: { params: Promise<{ id: string }> }) { export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params; const { id } = await params;
const meetupId = SEED_MEETUPS.some((m) => m.id === id) ? id : SEED_MEETUPS[0].id; return <MeetupLiveClient meetupId={id} />;
return <MeetupLiveClient meetupId={meetupId} />;
} }

View File

@ -20,7 +20,8 @@
- **交互**:粘性区块导航与当前位置、方向键筛选成员、关注本地保存;原生 `dialog` 管理视频与加群弹窗的焦点、Escape、背景锁定。 - **交互**:粘性区块导航与当前位置、方向键筛选成员、关注本地保存;原生 `dialog` 管理视频与加群弹窗的焦点、Escape、背景锁定。
- **全站布局**:桌面为宽幅内容 + 顶部分组导航;移动端为顶部菜单 + 底部快捷入口。没有侧栏,聊天室频道也使用横向切换。 - **全站布局**:桌面为宽幅内容 + 顶部分组导航;移动端为顶部菜单 + 底部快捷入口。没有侧栏,聊天室频道也使用横向切换。
- **全站动效**:`SocialExperience` / `experience.css` 提供星点连线、鼠标柔光、漂移光晕、卡片聚光和页面入场;`interaction.css` / `studio.css` 提供声波、会前雷达、名片透视与书封动效。动效可切为轻量,系统减少动态效果设置优先;离开页面或标签页隐藏时清理/暂停动画。 - **全站动效**:`SocialExperience` / `experience.css` 提供星点连线、鼠标柔光、漂移光晕、卡片聚光和页面入场;`interaction.css` / `studio.css` 提供声波、会前雷达、名片透视与书封动效。动效可切为轻量,系统减少动态效果设置优先;离开页面或标签页隐藏时清理/暂停动画。
- **视觉终态层**:`depth.css` + `vivid.css`(最后加载)统一玻璃导航、快捷轨、约会进度、聊天跳转最新、咖啡馆主从、Meetup 雷达、触控 ≥44px;子页 `SocialQuickRail` 横向跳转。 - **视觉终态层**:`depth.css` + `vivid.css` 统一玻璃导航、快捷轨、约会进度、聊天跳转最新、咖啡馆主从、Meetup 雷达、触控 ≥44px;子页 `SocialQuickRail` 横向跳转。
- **H5(≤900px)**:`app/h5.css` **最后加载**;Ways 竖列表(群组聊天优先)、底栏「聊天」在「认识」左侧、滑卡/composer/加入 sheet 避开 dock + safe-area。
## 子页面与交互边界 ## 子页面与交互边界

View File

@ -491,7 +491,7 @@
/* —— Workspace pages —— */ /* —— Workspace pages —— */
.social-workspace { .social-workspace {
padding: 12px 12px calc(96px + env(safe-area-inset-bottom, 0px)); padding: 0;
} }
.social-toolbar { .social-toolbar {
display: flex; display: flex;
@ -564,13 +564,11 @@
justify-content: center; justify-content: center;
} }
.social-people-cta-bar { .social-people-cta-bar {
position: sticky; position: static;
bottom: calc(72px + env(safe-area-inset-bottom, 0px));
z-index: 25;
display: grid !important; display: grid !important;
grid-template-columns: 1fr 1fr; grid-template-columns: 1fr 1fr;
gap: 8px; gap: 8px;
margin: 12px 14px calc(12px + env(safe-area-inset-bottom, 0px)); margin: 20px 0 0;
padding: 10px; padding: 10px;
border-radius: 16px; border-radius: 16px;
background: color-mix(in srgb, var(--bg-card, #fff) 92%, transparent); background: color-mix(in srgb, var(--bg-card, #fff) 92%, transparent);
@ -610,6 +608,8 @@
.social-dialog[open] { .social-dialog[open] {
display: flex; display: flex;
align-items: flex-end; align-items: flex-end;
height: 100dvh;
max-height: 100dvh;
} }
.social-dialog-sheet { .social-dialog-sheet {
width: 100%; width: 100%;
@ -1058,7 +1058,7 @@
flex-shrink: 0; flex-shrink: 0;
} }
.social-profile-preview { .social-profile-preview {
order: -1; /* preview first on phone so users see result while editing */ order: 0;
} }
.social-member-grid { .social-member-grid {
grid-template-columns: 1fr; grid-template-columns: 1fr;
@ -1072,7 +1072,7 @@
min-height: 40px; min-height: 40px;
} }
.social-workspace { .social-workspace {
padding-bottom: calc(88px + env(safe-area-inset-bottom, 0px)); padding-bottom: 0;
} }
.social-page-intro { .social-page-intro {
padding: 12px 14px 8px; padding: 12px 14px 8px;
@ -1155,3 +1155,295 @@
margin-bottom: 4px; margin-bottom: 4px;
} }
} }
/* Shared page system: readable cards, resilient grids and keyboard access. */
.social-experience :is(a, button, input, textarea, select, summary):focus-visible {
outline: 2px solid var(--sx-mint, #4ecdc4);
outline-offset: 4px;
}
.social-workspace .social-main > :is(section, article, div),
.social-workspace :is(.social-card, .social-panel, .social-profile-grid > *, .social-cafe-layout > *) {
min-width: 0;
}
.social-workspace :is(.social-card, .social-panel, .social-profile-card) {
overflow-wrap: anywhere;
}
.social-workspace :is(.social-grid, .social-event-grid) > .social-empty,
.social-people-grid > .social-empty {
grid-column: 1 / -1;
width: 100%;
}
.social-result-summary {
min-height: 44px;
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin: 10px 0;
color: var(--text-secondary);
font-size: 13px;
}
.social-result-summary p { margin: 0; }
.social-result-summary button { min-height: 44px; }
.social-route-state {
display: grid;
justify-items: center;
align-content: center;
gap: 20px;
padding: 80px 24px;
min-height: 70dvh;
text-align: center;
color: var(--text-primary);
}
.social-route-state p { margin: 0; color: var(--text-secondary); }
.social-route-state h1 { font-size: clamp(24px, 4vw, 32px); margin: 0; }
.social-route-state-mark { font-size: 40px; }
.social-route-skeleton { width: min(100%, 600px); display: grid; gap: 16px; }
.social-route-skeleton span { min-height: 96px; border-radius: 20px; background: var(--bg-glass); border: 1px solid var(--sx-fog); }
html[data-theme="light"] .social-experience {
--text-muted: #596b80;
--sx-mint: #087f78;
}
html[data-theme="light"] .social-mobile-dock {
background: color-mix(in srgb, #ffffff 94%, transparent);
border-color: #24364b24;
box-shadow: 0 8px 32px #1428371a;
}
html[data-theme="light"] .social-mobile-dock a { color: #536477; }
html[data-theme="light"] .social-mobile-dock a[aria-current="page"] {
color: #08756f;
background: #0f8d8614;
}
.social-discovery-grid {
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 16px;
}
.social-discovery-grid .social-people-chip.is-rich {
grid-template-columns: 52px minmax(0, 1fr);
grid-template-rows: auto auto auto auto;
align-content: start;
justify-items: start;
align-items: center;
gap: 6px 14px;
padding: 20px;
min-height: 174px;
text-align: left;
}
.social-discovery-grid .social-people-chip-ava { grid-row: 1 / 3; }
.social-discovery-grid .social-people-chip strong {
grid-column: 2;
font-size: 16px;
white-space: normal;
overflow-wrap: anywhere;
}
.social-discovery-grid .connection-member-role {
grid-column: 2;
font-size: 12px;
line-height: 1.5;
}
.social-discovery-grid .social-people-chip > em {
grid-column: 1 / -1;
margin-top: 8px;
white-space: normal;
font-size: 12px;
color: var(--text-secondary);
}
.social-discovery-grid .social-people-chip-want {
grid-column: 1 / -1;
font-size: 13px;
line-height: 1.6;
-webkit-line-clamp: 2;
color: var(--text-secondary);
}
.social-dialog {
color: var(--text-primary);
width: min(560px, calc(100% - 40px));
max-width: 560px;
max-height: min(90dvh, 900px);
margin: auto;
overflow: hidden;
}
.social-dialog-sheet {
display: flex;
flex-direction: column;
max-height: min(90dvh, 900px);
background: var(--bg-secondary, #101925);
}
.social-dialog-sheet > header {
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
gap: 16px;
}
.social-dialog-sheet > header h2 { margin: 0; font-size: 20px; }
.social-dialog-sheet > header button {
display: grid;
place-items: center;
flex: 0 0 44px;
width: 44px;
height: 44px;
border: 1px solid var(--sx-fog);
border-radius: 12px;
background: var(--bg-glass);
color: inherit;
cursor: pointer;
}
.social-dialog-body {
overflow-y: auto;
overscroll-behavior: contain;
min-height: 0;
}
.social-experience :is(.social-form, .social-dialog-body) :is(input, textarea, select) {
max-width: 100%;
}
.social-workspace :is(.social-profile, .social-cafe-detail, .social-library-card, .social-role-card) {
scroll-margin-top: calc(var(--nav-height, 72px) + 24px);
}
.social-chat-live .social-thread-wrap {
display: flex;
flex-direction: column;
min-height: 0;
overflow: hidden;
padding: 0;
}
.social-chat-live .social-chat-thread {
min-height: 0;
max-height: none;
height: 100%;
overflow-y: auto;
}
.social-chat-live .social-composer-toolbar { flex-wrap: nowrap; }
.social-chat-live .social-chat-composer textarea {
display: block;
width: 100%;
box-sizing: border-box;
color: var(--text-primary);
font-family: inherit;
line-height: 1.6;
resize: vertical;
}
.social-experience .social-form label.social-publish-toggle {
display: flex;
align-items: center;
min-height: 44px;
cursor: pointer;
}
.social-experience .social-form .social-publish-toggle input[type="checkbox"] {
appearance: auto;
flex: 0 0 20px;
width: 20px;
height: 20px;
min-height: 20px;
padding: 0;
margin: 0;
accent-color: var(--sx-mint);
}
.social-chat-live .social-composer-emoji { order: 0; }
.social-chat-live .social-nick-label { order: 1; white-space: nowrap; }
.social-chat-live .social-nick-label input {
border: 1px solid var(--sx-fog);
border-radius: 10px;
background: var(--sx-glass);
color: var(--text-primary);
padding: 8px;
}
.social-chat-live .social-composer-toolbar button[type="submit"] { order: 2; margin-left: auto; }
.social-date-root {
height: auto;
max-height: none;
overflow-x: clip;
overflow-y: visible;
}
.social-meetup-live .social-live-video { overflow-y: auto; overscroll-behavior: contain; }
.social-meetup-live .social-live-gate { flex: 1 0 auto; min-height: min-content; }
.social-live-iframe-overlay button { pointer-events: auto; }
@media (min-width: 601px) and (max-width: 900px) {
.social-workspace :is(.social-role-grid, .social-library-grid, .social-event-grid) {
grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
gap: 16px;
}
}
@media (max-width: 900px) {
.social-workspace.social-workspace-dense .social-workspace-grid {
min-height: 100dvh;
padding: calc(80px + env(safe-area-inset-top, 0px)) 16px calc(100px + env(safe-area-inset-bottom, 0px));
}
.social-workspace .nav-container, .social-home .nav-container {
gap: 8px;
padding-inline: 10px;
min-width: 0;
}
.social-experience .social-brand-logo { min-width: 0; gap: 6px; }
.social-experience .nav-actions { flex-shrink: 0; gap: 4px; }
.social-experience :is(.nav-icon-btn, .mobile-menu-btn) { min-width: 44px; min-height: 44px; }
.social-workspace .nav-links.open, .social-home .nav-links.open {
top: calc(72px + env(safe-area-inset-top, 0px));
max-height: calc(100dvh - 170px - env(safe-area-inset-top, 0px));
overscroll-behavior: contain;
}
.social-experience .nav-group-panel a { min-height: 44px; }
.social-workspace .social-toolbar { align-items: stretch; }
.social-workspace .social-toolbar .social-search { width: 100%; max-width: none; }
.social-workspace .social-filters { max-width: 100%; padding: 4px 2px; }
.social-workspace .social-filters button { min-height: 44px; }
.social-workspace .social-grid .social-save { min-height: 44px; }
.social-composer-toolbar .social-nick-label { display: flex; flex: 0 1 130px; min-width: 0; }
.social-chat-live .social-chat-composer textarea { font-size: 16px; }
.social-composer-toolbar .social-nick-label input { min-width: 0; width: 100%; min-height: 44px; font-size: 16px; }
.social-mobile-dock[data-keyboard-open="true"] { display: none; }
.social-discovery-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
.social-discovery-grid .social-people-chip.is-rich {
grid-template-columns: minmax(0, 1fr);
justify-items: center;
text-align: center;
padding: 16px 12px;
gap: 7px;
min-height: 220px;
}
.social-discovery-grid .social-people-chip.is-rich > * { grid-column: 1; grid-row: auto; }
.social-discovery-grid .social-people-chip-ava { width: 52px; height: 52px; }
.social-discovery-grid .social-people-chip > em { margin-top: 2px; }
.social-discovery-grid .social-people-chip-want { font-size: 12px; }
.social-workspace .social-profile-studio { gap: 20px; }
.social-profile-preview { order: 0; }
.social-dialog { width: 100%; max-width: 100%; max-height: 100dvh; margin: 0; }
.social-dialog[open] { height: 100dvh; display: flex; align-items: flex-end; }
.social-dialog-sheet { max-height: 88dvh; border-bottom: 0; }
.social-workspace .social-people-cta-bar { position: static; }
}
@media (max-width: 380px) {
.social-experience .social-brand-section,
.social-experience .social-brand-sep { display: none; }
.social-experience .social-brand-name { font-size: 15px; }
.social-discovery-grid { grid-template-columns: minmax(0, 1fr); }
.social-discovery-grid .social-people-chip.is-rich {
grid-template-columns: 52px minmax(0, 1fr);
justify-items: start;
text-align: left;
min-height: 156px;
gap: 6px 12px;
}
.social-discovery-grid .social-people-chip-ava { grid-row: 1 / 3; }
.social-discovery-grid .social-people-chip :is(strong, .connection-member-role) { grid-column: 2; }
.social-discovery-grid .social-people-chip :is(em, .social-people-chip-want) { grid-column: 1 / -1; }
}
@media (max-height: 500px) {
.social-chat-live, .social-meetup-live {
height: auto;
max-height: none;
overflow: visible;
}
.social-chat-live .social-live-stage { flex: none; height: 420px; }
.social-meetup-live .social-live-stage { flex: none; height: 480px; }
}
@media (prefers-reduced-motion: reduce) {
.social-experience *, .social-experience *::before, .social-experience *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
.social-experience .reveal { opacity: 1 !important; transform: none !important; }
}

View File

@ -406,11 +406,11 @@ html[data-theme="light"] .social-workspace .nav-group-panel {
.social-people-chip.is-rich { .social-people-chip.is-rich {
position: relative; position: relative;
grid-template-columns: minmax(0, 1fr);
grid-template-rows: auto auto auto auto; grid-template-rows: auto auto auto auto;
padding-right: 36px;
} }
.social-people-chip-want { .social-people-chip-want {
grid-column: 2; grid-column: 1 / -1;
display: -webkit-box; display: -webkit-box;
-webkit-line-clamp: 1; -webkit-line-clamp: 1;
-webkit-box-orient: vertical; -webkit-box-orient: vertical;

View File

@ -6,7 +6,6 @@ import {
useMemo, useMemo,
useRef, useRef,
useState, useState,
useSyncExternalStore,
} from "react"; } from "react";
import Link from "next/link"; import Link from "next/link";
import type { SocialRosterMember } from "@social/lib/rosterMock"; import type { SocialRosterMember } from "@social/lib/rosterMock";
@ -14,34 +13,11 @@ import {
SELF_MEMBER_ID, SELF_MEMBER_ID,
useDiscoveryRoster, useDiscoveryRoster,
} from "@social/lib/discoveryRoster"; } from "@social/lib/discoveryRoster";
import { loadJson, saveJson } from "@social/lib/storage"; import { useRosterLikes, setRosterLike } from "@social/lib/useRosterLikes";
import { socialPath } from "@social/lib/socialPath"; import { socialPath } from "@social/lib/socialPath";
import SocialAvatar from "./SocialAvatar"; import SocialAvatar from "./SocialAvatar";
import SectionSpark from "./SectionSpark"; import SectionSpark from "./SectionSpark";
const LIKE_KEY = "social-roster-likes";
const LIKES_CHANGED = "social-roster-likes-changed";
function subscribeLikes(callback: () => void) {
window.addEventListener("storage", callback);
window.addEventListener(LIKES_CHANGED, callback);
return () => {
window.removeEventListener("storage", callback);
window.removeEventListener(LIKES_CHANGED, callback);
};
}
function getLikesSnapshot() {
const stored = loadJson<unknown>(LIKE_KEY, {});
return JSON.stringify(
stored && typeof stored === "object" && !Array.isArray(stored)
? stored
: {},
);
}
const getServerLikes = () => "{}";
const FILTERS = [ const FILTERS = [
{ id: "all" as const, label: "全部", emoji: "✨" }, { id: "all" as const, label: "全部", emoji: "✨" },
{ id: "online" as const, label: "在线", emoji: "🟢" }, { id: "online" as const, label: "在线", emoji: "🟢" },
@ -51,15 +27,7 @@ const FILTERS = [
export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) { export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
const roster = useDiscoveryRoster(); const roster = useDiscoveryRoster();
const likesSnapshot = useSyncExternalStore( const likes = useRosterLikes();
subscribeLikes,
getLikesSnapshot,
getServerLikes,
);
const likes = useMemo(
() => JSON.parse(likesSnapshot) as Record<string, boolean>,
[likesSnapshot],
);
const [filter, setFilter] = useState<"all" | "online" | "f" | "m">("all"); const [filter, setFilter] = useState<"all" | "online" | "f" | "m">("all");
const [highlightId, setHighlightId] = useState<string | null>(null); const [highlightId, setHighlightId] = useState<string | null>(null);
const [burst, setBurst] = useState(false); const [burst, setBurst] = useState(false);
@ -105,8 +73,7 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
) => { ) => {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
saveJson(LIKE_KEY, { ...likes, [m.id]: !likes[m.id] }); setRosterLike(m.id, !likes[m.id]);
window.dispatchEvent(new Event(LIKES_CHANGED));
setBurst(true); setBurst(true);
setHighlightId(m.id); setHighlightId(m.id);
if (burstTimer.current) clearTimeout(burstTimer.current); if (burstTimer.current) clearTimeout(burstTimer.current);

View File

@ -28,6 +28,7 @@ import {
EmptyState, EmptyState,
PageIntro, PageIntro,
SearchField, SearchField,
ResultSummary,
ShareButton, ShareButton,
} from "./SocialUI"; } from "./SocialUI";
import { socialApi } from "@social/lib/api"; import { socialApi } from "@social/lib/api";
@ -56,8 +57,8 @@ function CafeDetail({ cafe, id }: { cafe: SocialCafe; id: string }) {
); );
const [author, setAuthor] = useLocalState("nick", "游民"); const [author, setAuthor] = useLocalState("nick", "游民");
const [score, setScore] = useState(5); const [score, setScore] = useState(5);
const [text, setText] = useState(""); const [text, setText] = useLocalState(`cafe-review-draft:${cafe.id}`, "");
const [photoNote, setPhotoNote] = useState(""); const [photoNote, setPhotoNote] = useLocalState(`cafe-review-note:${cafe.id}`, "");
const [status, setStatus] = useState(""); const [status, setStatus] = useState("");
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const lock = useRef(false); const lock = useRef(false);
@ -227,6 +228,7 @@ function CafeDetail({ cafe, id }: { cafe: SocialCafe; id: string }) {
<label> <label>
体验 体验
<textarea <textarea
aria-label="体验"
required required
rows={4} rows={4}
maxLength={1000} maxLength={1000}
@ -323,13 +325,13 @@ export default function CafeDirectory() {
)?.city; )?.city;
return fuzzy || "all"; return fuzzy || "all";
}, [cityParam, seedCafes]); }, [cityParam, seedCafes]);
const [query, setQuery] = useState(cityParam && initialCity === "all" ? cityParam : ""); const [queryChoice, setQueryChoice] = useState<{ source: string; value: string } | null>(null);
const [city, setCity] = useState(initialCity); const [cityChoice, setCityChoice] = useState<{ source: string; value: string } | null>(null);
const query = queryChoice?.source === cityParam ? queryChoice.value : cityParam && initialCity === "all" ? cityParam : "";
const city = cityChoice?.source === cityParam ? cityChoice.value : initialCity;
const setQuery = (value: string) => setQueryChoice({ source: cityParam, value });
const setCity = (value: string) => setCityChoice({ source: cityParam, value });
const [sort, setSort] = useState("recommended"); const [sort, setSort] = useState("recommended");
useEffect(() => {
setCity(initialCity);
if (cityParam && initialCity === "all") setQuery(cityParam);
}, [initialCity, cityParam]);
const selected = const selected =
useSyncExternalStore( useSyncExternalStore(
subscribeHash, subscribeHash,
@ -347,7 +349,7 @@ export default function CafeDirectory() {
(sort !== "saved" || saved.includes(cafe.id)) && (sort !== "saved" || saved.includes(cafe.id)) &&
`${cafe.name} ${cafe.city} ${cafe.vibe}` `${cafe.name} ${cafe.city} ${cafe.vibe}`
.toLowerCase() .toLowerCase()
.includes(query.toLowerCase()), .includes(query.toLowerCase().trim()),
) )
.sort((a, b) => .sort((a, b) =>
sort === "wifi" sort === "wifi"
@ -418,6 +420,7 @@ export default function CafeDirectory() {
), ),
)} )}
</div> </div>
<ResultSummary count={cafes.length} unit="家咖啡馆" filtered={Boolean(query || city !== "all" || sort !== "recommended")} onReset={() => { setQuery(""); setCity("all"); setSort("recommended"); }} />
<div className="social-cafe-layout"> <div className="social-cafe-layout">
<div className="social-grid social-cafe-grid"> <div className="social-grid social-cafe-grid">
{cafes.map((cafe, index) => ( {cafes.map((cafe, index) => (
@ -452,7 +455,7 @@ export default function CafeDirectory() {
aria-pressed={active?.id === cafe.id} aria-pressed={active?.id === cafe.id}
aria-controls={id} aria-controls={id}
onClick={() => { onClick={() => {
history.replaceState(null, "", `#${cafe.id}`); history.replaceState(history.state, "", `#${cafe.id}`);
window.dispatchEvent(new Event("hashchange")); window.dispatchEvent(new Event("hashchange"));
document.getElementById(id)?.scrollIntoView({ document.getElementById(id)?.scrollIntoView({
behavior: matchMedia("(prefers-reduced-motion: reduce)") behavior: matchMedia("(prefers-reduced-motion: reduce)")

View File

@ -137,7 +137,7 @@ export function Conversation({
if (thread) if (thread)
thread.scrollTo({ thread.scrollTo({
top: thread.scrollHeight, top: thread.scrollHeight,
behavior: "smooth", behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "instant" : "smooth",
}); });
}); });
composerRef.current?.focus(); composerRef.current?.focus();
@ -438,7 +438,7 @@ export default function ChatWorkspace() {
<ShareButton path={socialPath("/chat")} title="游民社区群组聊天" /> <ShareButton path={socialPath("/chat")} title="游民社区群组聊天" />
</div> </div>
</header> </header>
<div className="social-chat-presence reveal"> <div className="social-chat-presence">
<div className="social-chat-presence-avs" aria-hidden> <div className="social-chat-presence-avs" aria-hidden>
{online.map((m) => ( {online.map((m) => (
<SocialAvatar key={m.id} src={m.avatar} size={28} lazy /> <SocialAvatar key={m.id} src={m.avatar} size={28} lazy />
@ -446,7 +446,7 @@ export default function ChatWorkspace() {
</div> </div>
<p> <p>
<Users size={13} /> <Users size={13} />
<strong>{online.length}+</strong> 位在线气味 · 进群打个招呼就好 <strong>{online.length}</strong> 位示例成员 · 进群打个招呼就好
</p> </p>
<Link href={socialPath("/people")} className="social-chat-presence-link"> <Link href={socialPath("/people")} className="social-chat-presence-link">
看看是谁 看看是谁

View File

@ -30,15 +30,14 @@ export default function CityDirectory({
<div className={`social-city-dir${compact ? " is-compact" : ""}`}> <div className={`social-city-dir${compact ? " is-compact" : ""}`}>
<div <div
className="social-city-filters" className="social-city-filters"
role="tablist" role="group"
aria-label="城市筛选" aria-label="城市筛选"
> >
{CITY_FILTER_TAGS.map((t) => ( {CITY_FILTER_TAGS.map((t) => (
<button <button
key={t} key={t}
type="button" type="button"
role="tab" aria-pressed={tag === t}
aria-selected={tag === t}
className={`social-city-filter${tag === t ? " is-active" : ""}`} className={`social-city-filter${tag === t ? " is-active" : ""}`}
onClick={() => setTag(t)} onClick={() => setTag(t)}
> >

View File

@ -22,9 +22,9 @@ import SocialAvatar from "./SocialAvatar";
import { DemoBadge, ShareButton, SocialDialog } from "./SocialUI"; import { DemoBadge, ShareButton, SocialDialog } from "./SocialUI";
import { SocialMobileDock } from "./SocialNavigation"; import { SocialMobileDock } from "./SocialNavigation";
import type { SocialRosterMember } from "@social/lib/rosterMock"; import type { SocialRosterMember } from "@social/lib/rosterMock";
import { useDiscoveryRoster } from "@social/lib/discoveryRoster"; import { useDiscoveryRoster, SELF_MEMBER_ID } from "@social/lib/discoveryRoster";
import { socialPath } from "@social/lib/socialPath"; import { socialPath } from "@social/lib/socialPath";
import { loadJson, saveJson } from "@social/lib/storage"; import { setRosterLike, useRosterLikes } from "@social/lib/useRosterLikes";
import { useLocalState } from "@social/lib/useLocalState"; import { useLocalState } from "@social/lib/useLocalState";
type Filter = "all" | "f" | "m"; type Filter = "all" | "f" | "m";
@ -32,13 +32,11 @@ type Decision = "like" | "pass";
const SWIPE_KEY = "social-date-swipes"; const SWIPE_KEY = "social-date-swipes";
const HISTORY_KEY = "social-date-history"; const HISTORY_KEY = "social-date-history";
const LIKE_KEY = "social-roster-likes";
const LIKES_CHANGED = "social-roster-likes-changed";
const THRESHOLD_DESKTOP = 110; const THRESHOLD_DESKTOP = 110;
const THRESHOLD_MOBILE = 78; const THRESHOLD_MOBILE = 78;
type SwipeStore = Record<string, Decision>; type SwipeStore = Record<string, Decision>;
type HistoryEntry = { id: string; decision: Decision }; type HistoryEntry = { id: string; decision: Decision; previouslyLiked?: boolean };
function shuffle<T>(list: T[]) { function shuffle<T>(list: T[]) {
const next = [...list]; const next = [...list];
@ -49,20 +47,14 @@ function shuffle<T>(list: T[]) {
return next; return next;
} }
function syncRosterLike(id: string, liked: boolean) {
const current = loadJson<Record<string, boolean>>(LIKE_KEY, {});
const next = { ...current };
if (liked) next[id] = true;
else delete next[id];
saveJson(LIKE_KEY, next);
window.dispatchEvent(new Event(LIKES_CHANGED));
}
export default function DateClient() { export default function DateClient() {
const roster = useDiscoveryRoster(); const discovery = useDiscoveryRoster();
const roster = useMemo(() => discovery.filter((member) => member.id !== SELF_MEMBER_ID), [discovery]);
const likes = useRosterLikes();
const [filter, setFilter] = useState<Filter>("all"); const [filter, setFilter] = useState<Filter>("all");
const [swipes, setSwipes] = useLocalState<SwipeStore>(SWIPE_KEY, {}); const [swipes, setSwipes] = useLocalState<SwipeStore>(SWIPE_KEY, {});
const [history, setHistory] = useLocalState<HistoryEntry[]>(HISTORY_KEY, []); const [storedHistory, setHistory] = useLocalState<HistoryEntry[]>(HISTORY_KEY, []);
const history = useMemo<HistoryEntry[]>(() => storedHistory.length ? storedHistory : Object.entries(swipes).map(([id, decision]) => ({ id, decision })), [storedHistory, swipes]);
const [order, setOrder] = useState<string[]>([]); const [order, setOrder] = useState<string[]>([]);
const [drag, setDrag] = useState({ x: 0, y: 0, active: false }); const [drag, setDrag] = useState({ x: 0, y: 0, active: false });
const [fly, setFly] = useState<null | { id: string; dir: Decision }>(null); const [fly, setFly] = useState<null | { id: string; dir: Decision }>(null);
@ -74,32 +66,19 @@ export default function DateClient() {
const dragRef = useRef({ x: 0, y: 0 }); const dragRef = useRef({ x: 0, y: 0 });
const busy = useRef(false); const busy = useRef(false);
const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null); const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const swipeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
setOrder((prev) => {
const ids = roster.map((m) => m.id);
const keep = prev.filter((id) => ids.includes(id));
const missing = ids.filter((id) => !keep.includes(id));
return keep.length ? [...keep, ...missing] : shuffle(ids);
});
}, [roster]);
useEffect(() => {
if (history.length) return;
const entries = Object.entries(swipes) as [string, Decision][];
if (!entries.length) return;
setHistory(entries.map(([id, decision]) => ({ id, decision })));
}, [swipes, history.length, setHistory]);
useEffect( useEffect(
() => () => { () => () => {
if (toastTimer.current) clearTimeout(toastTimer.current); if (toastTimer.current) clearTimeout(toastTimer.current);
if (swipeTimer.current) clearTimeout(swipeTimer.current);
}, },
[], [],
); );
const deck = useMemo(() => { const deck = useMemo(() => {
return order const ids = [...order, ...roster.map((member) => member.id).filter((id) => !order.includes(id))];
return ids
.map((id) => roster.find((m) => m.id === id)!) .map((id) => roster.find((m) => m.id === id)!)
.filter((m) => m && !swipes[m.id]) .filter((m) => m && !swipes[m.id])
.filter((m) => filter === "all" || m.gender === filter); .filter((m) => filter === "all" || m.gender === filter);
@ -114,10 +93,10 @@ export default function DateClient() {
const liked = useMemo( const liked = useMemo(
() => () =>
roster roster
.filter((m) => swipes[m.id] === "like") .filter((m) => likes[m.id])
.slice() .slice()
.reverse(), .reverse(),
[swipes, roster], [likes, roster],
); );
const matchMember = matchId const matchMember = matchId
? roster.find((m) => m.id === matchId) || null ? roster.find((m) => m.id === matchId) || null
@ -139,11 +118,11 @@ export default function DateClient() {
} catch { } catch {
/* ignore */ /* ignore */
} }
window.setTimeout(() => { swipeTimer.current = setTimeout(() => {
setSwipes((prev) => ({ ...prev, [member.id]: decision })); setSwipes((prev) => ({ ...prev, [member.id]: decision }));
setHistory((prev) => [...prev, { id: member.id, decision }]); setHistory((prev) => [...prev, { id: member.id, decision, previouslyLiked: Boolean(likes[member.id]) }]);
if (decision === "like") { if (decision === "like") {
syncRosterLike(member.id, true); setRosterLike(member.id, true);
setMatchId(member.id); setMatchId(member.id);
flash(`想认识 ${member.name}`); flash(`想认识 ${member.name}`);
} else { } else {
@ -155,25 +134,26 @@ export default function DateClient() {
busy.current = false; busy.current = false;
}, 280); }, 280);
}, },
[fly, setSwipes, flash], [fly, setSwipes, setHistory, flash, likes],
); );
const undo = useCallback(() => { const undo = useCallback(() => {
if (busy.current || fly || !history.length) return; if (busy.current || fly || !history.length) return;
const last = history[history.length - 1]; const last = history[history.length - 1];
setHistory((prev) => prev.slice(0, -1)); setHistory(history.slice(0, -1));
setSwipes((prev) => { setSwipes((prev) => {
const nextStore = { ...prev }; const nextStore = { ...prev };
delete nextStore[last.id]; delete nextStore[last.id];
return nextStore; return nextStore;
}); });
if (last.decision === "like") syncRosterLike(last.id, false); if (last.decision === "like") setRosterLike(last.id, Boolean(last.previouslyLiked));
setMatchId(null); setMatchId(null);
setDrag({ x: 0, y: 0, active: false }); setDrag({ x: 0, y: 0, active: false });
flash("已撤销"); flash("已撤销");
}, [history, fly, setSwipes, flash]); }, [history, fly, setSwipes, setHistory, flash]);
const onPointerDown = (event: ReactPointerEvent<HTMLElement>) => { const onPointerDown = (event: ReactPointerEvent<HTMLElement>) => {
if ((event.target as HTMLElement).closest("button, a, input") || event.button !== 0) return;
if (!current || fly || busy.current) return; if (!current || fly || busy.current) return;
dragging.current = true; dragging.current = true;
start.current = { x: event.clientX, y: event.clientY }; start.current = { x: event.clientX, y: event.clientY };
@ -208,6 +188,7 @@ export default function DateClient() {
}; };
const resetDeck = () => { const resetDeck = () => {
if (swipeTimer.current) clearTimeout(swipeTimer.current);
setSwipes({}); setSwipes({});
setHistory([]); setHistory([]);
setOrder(shuffle(roster.map((m) => m.id))); setOrder(shuffle(roster.map((m) => m.id)));
@ -222,6 +203,8 @@ export default function DateClient() {
useEffect(() => { useEffect(() => {
const onKey = (event: KeyboardEvent) => { const onKey = (event: KeyboardEvent) => {
if (likesOpen || matchId || document.querySelector("dialog[open]")) return;
if ((event.target as HTMLElement | null)?.isContentEditable) return;
const tag = (event.target as HTMLElement | null)?.tagName; const tag = (event.target as HTMLElement | null)?.tagName;
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return; if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
if (event.key === "ArrowRight") { if (event.key === "ArrowRight") {
@ -243,7 +226,7 @@ export default function DateClient() {
}; };
window.addEventListener("keydown", onKey); window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey);
}, [current, commit, undo]); }, [current, commit, undo, likesOpen, matchId]);
const rotate = drag.x / 18; const rotate = drag.x / 18;
const stampThreshold = const stampThreshold =
@ -360,7 +343,7 @@ export default function DateClient() {
)} )}
{next && ( {next && (
<article className="social-date-card is-next" aria-hidden> <article className="social-date-card is-next" aria-hidden inert>
<DateCardFace member={next} /> <DateCardFace member={next} />
</article> </article>
)} )}
@ -378,7 +361,11 @@ export default function DateClient() {
onPointerDown={onPointerDown} onPointerDown={onPointerDown}
onPointerMove={onPointerMove} onPointerMove={onPointerMove}
onPointerUp={onPointerUp} onPointerUp={onPointerUp}
onPointerCancel={onPointerUp} onPointerCancel={() => {
dragging.current = false;
dragRef.current = { x: 0, y: 0 };
setDrag({ x: 0, y: 0, active: false });
}}
> >
<span <span
className="social-date-stamp like" className="social-date-stamp like"

View File

@ -18,6 +18,7 @@ import {
EmptyState, EmptyState,
PageIntro, PageIntro,
SearchField, SearchField,
ResultSummary,
ShareButton, ShareButton,
} from "./SocialUI"; } from "./SocialUI";
import { eventDate, saveEventCalendar } from "@social/lib/calendar"; import { eventDate, saveEventCalendar } from "@social/lib/calendar";
@ -40,7 +41,7 @@ export default function EventDirectory() {
(item) => (item) =>
`${item.title} ${item.city}` `${item.title} ${item.city}`
.toLowerCase() .toLowerCase()
.includes(query.toLowerCase()) && .includes(query.toLowerCase().trim()) &&
(filter !== "saved" || saved.includes(item.id)), (filter !== "saved" || saved.includes(item.id)),
); );
return ( return (
@ -80,11 +81,16 @@ export default function EventDirectory() {
<div className="social-status social-event-banner reveal"> <div className="social-status social-event-banner reveal">
<Globe2 size={15} /> <Globe2 size={15} />
<span> <span>
时间按北京时间显示 · 「想参加」先记在你这边,还不等于已经约好 每场标注活动时区,并换算你的本地时间 · 「想参加」先记在你这边,还不等于已经约好
</span> </span>
</div> </div>
<ResultSummary count={events.length} unit="个场次" filtered={Boolean(query || filter !== "all")} onReset={() => { setQuery(""); setFilter("all"); }} />
<div className="social-event-grid"> <div className="social-event-grid">
{events.map((event, index) => ( {events.map((event, index) => {
const start = eventDate(event);
const scheduled = Number.isFinite(start.getTime());
const zone = event.timeZone || "Asia/Shanghai";
return (
<article <article
className={`social-card social-event-card social-panel-fx reveal event-${index % 3}`} className={`social-card social-event-card social-panel-fx reveal event-${index % 3}`}
key={event.id} key={event.id}
@ -125,22 +131,21 @@ export default function EventDirectory() {
{MOCK_ROSTER.slice(index + 2, index + 6).map((p) => ( {MOCK_ROSTER.slice(index + 2, index + 6).map((p) => (
<SocialAvatar key={p.id} src={p.avatar} size={22} lazy /> <SocialAvatar key={p.id} src={p.avatar} size={22} lazy />
))} ))}
<em>+{5 + index} 想参加</em> <em>示例成员</em>
</div> </div>
<h2>{event.title}</h2> <h2>{event.title}</h2>
<p className="social-event-time"> <p className="social-event-time">
<Clock3 size={14} /> <Clock3 size={14} />
{event.date} · {event.time} 北京时间 {scheduled ? `${event.date} · ${event.time} ${zone === "Asia/Shanghai" ? "北京时间" : zone}` : "时间待确认"}
</p> </p>
<p className="social-muted" suppressHydrationWarning> <p className="social-muted" suppressHydrationWarning>
你那边大约是: {scheduled ? `你那边大约是:${start.toLocaleString([], {
{eventDate(event).toLocaleString([], {
month: "short", month: "short",
day: "numeric", day: "numeric",
hour: "2-digit", hour: "2-digit",
minute: "2-digit", minute: "2-digit",
timeZoneName: "short", timeZoneName: "short",
})} })}` : "排期待更新,请在活动频道确认。"}
</p> </p>
<div className="social-event-cta"> <div className="social-event-cta">
<Link <Link
@ -159,6 +164,7 @@ export default function EventDirectory() {
<button <button
type="button" type="button"
className="social-save" className="social-save"
disabled={!scheduled}
onClick={() => saveEventCalendar(event)} onClick={() => saveEventCalendar(event)}
> >
<CalendarPlus size={14} /> <CalendarPlus size={14} />
@ -175,7 +181,8 @@ export default function EventDirectory() {
</div> </div>
</div> </div>
</article> </article>
))} );
})}
{!events.length && ( {!events.length && (
<EmptyState <EmptyState
emoji="📡" emoji="📡"

View File

@ -146,7 +146,7 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
disabled={busy} disabled={busy}
onChange={(e) => setEmail(e.target.value)} onChange={(e) => setEmail(e.target.value)}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === "Enter") void submit(); if (e.key === "Enter" && !e.nativeEvent.isComposing) void submit();
}} }}
/> />
</label> </label>

View File

@ -11,6 +11,7 @@ import { useSocialConfig } from "./SocialExperience";
import { SocialMobileDock } from "./SocialNavigation"; import { SocialMobileDock } from "./SocialNavigation";
import SocialAvatar from "./SocialAvatar"; import SocialAvatar from "./SocialAvatar";
import { MOCK_ROSTER } from "@social/lib/rosterMock"; import { MOCK_ROSTER } from "@social/lib/rosterMock";
import { EmptyState } from "./SocialUI";
type Layout = "split" | "video" | "chat"; type Layout = "split" | "video" | "chat";
@ -32,8 +33,8 @@ function joinUrl(room: string, name: string) {
name, name,
notify: "0", notify: "0",
chat: "0", chat: "0",
audio: "1", audio: "0",
video: "1", video: "0",
}); });
return `${MIROTALK_URL.replace(/\/$/, "")}/join?${q.toString()}`; return `${MIROTALK_URL.replace(/\/$/, "")}/join?${q.toString()}`;
} }
@ -83,7 +84,7 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
); );
const meetup = const meetup =
meetups.find((m) => m.id === meetupId) || meetups.find((m) => m.id === meetupId) ||
meetups[0] || { {
id: meetupId, id: meetupId,
title: "开视频见面", title: "开视频见面",
city: "Online", city: "Online",
@ -102,6 +103,8 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
const [videoReady, setVideoReady] = useState(false); const [videoReady, setVideoReady] = useState(false);
const [embedBlocked, setEmbedBlocked] = useState(false); const [embedBlocked, setEmbedBlocked] = useState(false);
const [iframeLoading, setIframeLoading] = useState(true); const [iframeLoading, setIframeLoading] = useState(true);
const [frameKey, setFrameKey] = useState(0);
const [loadSlow, setLoadSlow] = useState(false);
const bottomRef = useRef<HTMLDivElement>(null); const bottomRef = useRef<HTMLDivElement>(null);
const videoSrc = useMemo( const videoSrc = useMemo(
@ -115,34 +118,37 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
}, []); }, []);
useEffect(() => { useEffect(() => {
warmMirotalkOrigin();
const name = (loadJson("nick", "游民") || "游民").trim() || "游民"; const name = (loadJson("nick", "游民") || "游民").trim() || "游民";
chat.setNick(name); chat.setNick(name);
setJoinName(name); setJoinName(name);
if (canEmbedHere()) {
setIframeLoading(true);
setVideoReady(true);
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount once // eslint-disable-next-line react-hooks/exhaustive-deps -- mount once
}, []); }, []);
useEffect(() => { useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: "smooth" }); if (!videoReady || !iframeLoading) return;
const timer = setTimeout(() => setLoadSlow(true), 15000);
return () => clearTimeout(timer);
}, [videoReady, iframeLoading, frameKey]);
useEffect(() => {
const thread = bottomRef.current?.parentElement;
if (thread) thread.scrollTop = thread.scrollHeight;
}, [chat.messages]); }, [chat.messages]);
const startVideo = useCallback( const startVideo = useCallback(
(forceReload = false) => { (forceReload = false) => {
const name = chat.nick.trim() || "游民"; const name = chat.nick.trim() || "游民";
saveJson("nick", name); saveJson("nick", name);
warmMirotalkOrigin();
setJoinName(name); setJoinName(name);
if (!preferEmbed) { if (!preferEmbed) {
window.location.assign(joinUrl(meetup.mirotalkRoom, name)); window.location.assign(joinUrl(meetup.mirotalkRoom, name));
return; return;
} }
setIframeLoading(true); setIframeLoading(true);
setLoadSlow(false);
if (forceReload && videoReady) { if (forceReload && videoReady) {
setVideoReady(false); setFrameKey((key) => key + 1);
window.requestAnimationFrame(() => setVideoReady(true));
} else { } else {
setVideoReady(true); setVideoReady(true);
} }
@ -155,6 +161,10 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
await chat.send(chat.draft); await chat.send(chat.draft);
}; };
if (!meetups.some((item) => item.id === meetupId)) {
return <div className="social-root social-live-root social-meetup-live"><EmptyState title="没有找到这个场次" description="场次可能已下线,请返回选择其他活动。"><Link className="social-btn primary" href={socialPath("/meetup")}>查看全部场次</Link></EmptyState><SocialMobileDock /></div>;
}
return ( return (
<div className="social-root social-live-root social-skin social-meetup-live"> <div className="social-root social-live-root social-skin social-meetup-live">
<header className="social-live-bar"> <header className="social-live-bar">
@ -182,6 +192,11 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
</span> </span>
</div> </div>
<div className="social-live-bar-tools"> <div className="social-live-bar-tools">
{videoReady && <div className="social-actions">
<button type="button" className="social-btn" onClick={() => { setVideoReady(false); setLoadSlow(false); }}>离开视频</button>
<button type="button" className="social-btn" onClick={() => startVideo(true)}>重新连接</button>
<a className="social-btn" href={videoSrc} target="_blank" rel="noopener noreferrer">新窗口打开</a>
</div>}
<label className="social-live-nick"> <label className="social-live-nick">
<span className="social-muted">昵称</span> <span className="social-muted">昵称</span>
<input <input
@ -212,6 +227,16 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
type="button" type="button"
role="tab" role="tab"
aria-selected={layout === m} aria-selected={layout === m}
tabIndex={layout === m ? 0 : -1}
onKeyDown={(event) => {
const modes = ["split", "video", "chat"] as const;
const index = modes.indexOf(m);
const next = event.key === "ArrowRight" ? (index + 1) % 3 : event.key === "ArrowLeft" ? (index + 2) % 3 : event.key === "Home" ? 0 : event.key === "End" ? 2 : -1;
if (next < 0) return;
event.preventDefault();
setLayout(modes[next]);
event.currentTarget.parentElement?.querySelectorAll<HTMLButtonElement>("button")[next]?.focus();
}}
className={`social-live-tab${layout === m ? " active" : ""}`} className={`social-live-tab${layout === m ? " active" : ""}`}
onClick={() => setLayout(m)} onClick={() => setLayout(m)}
> >
@ -245,7 +270,7 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
.map((m) => ( .map((m) => (
<SocialAvatar key={m.id} src={m.avatar} size={28} lazy /> <SocialAvatar key={m.id} src={m.avatar} size={28} lazy />
))} ))}
<em>有人想参加 · 随时可进</em> <em>示例成员 · 可先进入了解</em>
</div> </div>
<button <button
type="button" type="button"
@ -268,17 +293,19 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
<div className="social-live-iframe-mark" aria-hidden> <div className="social-live-iframe-mark" aria-hidden>
N N
</div> </div>
<p>接通中…</p> <p>{loadSlow ? "连接较慢,可以重试或在新窗口打开" : "接通中…"}</p>
{loadSlow && <button type="button" className="social-btn" onClick={() => startVideo(true)}>重试连接</button>}
</div> </div>
)} )}
<iframe <iframe
key={frameKey}
title={`${meetup.title} video`} title={`${meetup.title} video`}
src={videoSrc} src={videoSrc}
className="social-live-iframe" className="social-live-iframe"
allow="camera; microphone; display-capture; autoplay; fullscreen; clipboard-write" allow="camera; microphone; display-capture; autoplay; fullscreen; clipboard-write"
referrerPolicy="no-referrer-when-downgrade" referrerPolicy="no-referrer-when-downgrade"
loading="eager" loading="eager"
onLoad={() => setIframeLoading(false)} onLoad={() => { setIframeLoading(false); setLoadSlow(false); }}
onError={() => { onError={() => {
setEmbedBlocked(true); setEmbedBlocked(true);
setIframeLoading(false); setIframeLoading(false);
@ -340,7 +367,7 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
value={chat.draft} value={chat.draft}
onChange={(e) => chat.setDraft(e.target.value)} onChange={(e) => chat.setDraft(e.target.value)}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) { if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing && e.keyCode !== 229) {
e.preventDefault(); e.preventDefault();
void send(); void send();
} }

View File

@ -11,17 +11,23 @@ import {
EmptyState, EmptyState,
PageIntro, PageIntro,
SearchField, SearchField,
ResultSummary,
} from "./SocialUI"; } from "./SocialUI";
import { SELF_MEMBER_ID, useDiscoveryRoster } from "@social/lib/discoveryRoster"; import { SELF_MEMBER_ID, useDiscoveryRoster } from "@social/lib/discoveryRoster";
import { socialPath } from "@social/lib/socialPath"; import { socialPath } from "@social/lib/socialPath";
import { useLocalState } from "@social/lib/useLocalState"; import { useRosterLikes } from "@social/lib/useRosterLikes";
export default function PeopleClient() { export default function PeopleClient() {
const params = useSearchParams(); const params = useSearchParams();
const initialQuery = params.get("city") || "";
return <PeopleDirectory key={initialQuery} initialQuery={initialQuery} />;
}
function PeopleDirectory({ initialQuery }: { initialQuery: string }) {
const roster = useDiscoveryRoster(); const roster = useDiscoveryRoster();
const [query, setQuery] = useState(params.get("city") || ""); const [query, setQuery] = useState(initialQuery);
const [filter, setFilter] = useState("all"); const [filter, setFilter] = useState("all");
const [saved] = useLocalState<string[]>("saved-people", []); const likes = useRosterLikes();
const list = useMemo( const list = useMemo(
() => () =>
roster.filter((person) => { roster.filter((person) => {
@ -29,11 +35,11 @@ export default function PeopleClient() {
`${person.name} ${person.city} ${person.title} ${person.tags.join(" ")} ${person.lookingFor}`.toLowerCase(); `${person.name} ${person.city} ${person.title} ${person.tags.join(" ")} ${person.lookingFor}`.toLowerCase();
return ( return (
haystack.includes(query.toLowerCase().trim()) && haystack.includes(query.toLowerCase().trim()) &&
(filter !== "saved" || saved.includes(person.id)) && (filter !== "saved" || likes[person.id]) &&
(filter !== "online" || person.online) (filter !== "online" || person.online)
); );
}), }),
[query, filter, saved, roster], [query, filter, likes, roster],
); );
return ( return (
<SiteShell title="想见的人"> <SiteShell title="想见的人">
@ -54,7 +60,7 @@ export default function PeopleClient() {
<div className="social-filters" aria-label="筛选"> <div className="social-filters" aria-label="筛选">
{[ {[
{ id: "all", title: "全部" }, { id: "all", title: "全部" },
{ id: "online", title: "现在在线" }, { id: "online", title: "示例在线" },
{ id: "saved", title: "我关注的" }, { id: "saved", title: "我关注的" },
].map((f) => ( ].map((f) => (
<button <button
@ -68,7 +74,8 @@ export default function PeopleClient() {
))} ))}
</div> </div>
</div> </div>
<div className="social-people-grid"> <ResultSummary count={list.length} unit="位朋友" filtered={Boolean(query || filter !== "all")} onReset={() => { setQuery(""); setFilter("all"); }} />
<div className="social-people-grid social-discovery-grid">
{list.map((person, index) => ( {list.map((person, index) => (
<Link <Link
key={person.id} key={person.id}

View File

@ -1,6 +1,5 @@
"use client"; "use client";
import { useMemo, useSyncExternalStore } from "react";
import Link from "next/link"; import Link from "next/link";
import { import {
ArrowLeft, ArrowLeft,
@ -26,44 +25,15 @@ import {
SELF_MEMBER_ID, SELF_MEMBER_ID,
useDiscoveryRoster, useDiscoveryRoster,
} from "@social/lib/discoveryRoster"; } from "@social/lib/discoveryRoster";
import { loadJson, saveJson } from "@social/lib/storage"; import { useRosterLikes, setRosterLike } from "@social/lib/useRosterLikes";
import { socialPath } from "@social/lib/socialPath"; import { socialPath } from "@social/lib/socialPath";
const LIKE_KEY = "social-roster-likes";
const LIKES_CHANGED = "social-roster-likes-changed";
function subscribeLikes(cb: () => void) {
window.addEventListener("storage", cb);
window.addEventListener(LIKES_CHANGED, cb);
return () => {
window.removeEventListener("storage", cb);
window.removeEventListener(LIKES_CHANGED, cb);
};
}
function getLikesSnapshot() {
const stored = loadJson<unknown>(LIKE_KEY, {});
return JSON.stringify(
stored && typeof stored === "object" && !Array.isArray(stored)
? stored
: {},
);
}
export default function PeopleProfileClient({ id }: { id: string }) { export default function PeopleProfileClient({ id }: { id: string }) {
const roster = useDiscoveryRoster(); const roster = useDiscoveryRoster();
const member = const member =
roster.find((m) => m.id === id) || findRosterMember(id); roster.find((m) => m.id === id) || findRosterMember(id);
const likesSnapshot = useSyncExternalStore( const likes = useRosterLikes();
subscribeLikes,
getLikesSnapshot,
() => "{}",
);
const likes = useMemo(
() => JSON.parse(likesSnapshot) as Record<string, boolean>,
[likesSnapshot],
);
if (!member) { if (!member) {
return ( return (
@ -91,8 +61,7 @@ export default function PeopleProfileClient({ id }: { id: string }) {
.slice(0, 4); .slice(0, 4);
const toggleLike = () => { const toggleLike = () => {
saveJson(LIKE_KEY, { ...likes, [member.id]: !liked }); setRosterLike(member.id, !liked);
window.dispatchEvent(new Event(LIKES_CHANGED));
}; };
const intro = encodeURIComponent( const intro = encodeURIComponent(
@ -149,6 +118,8 @@ export default function PeopleProfileClient({ id }: { id: string }) {
type="button" type="button"
className={`social-btn${liked ? " coral" : ""}`} className={`social-btn${liked ? " coral" : ""}`}
onClick={toggleLike} onClick={toggleLike}
aria-pressed={liked}
title="关注保存在当前设备"
> >
<Heart size={15} fill={liked ? "currentColor" : "none"} /> <Heart size={15} fill={liked ? "currentColor" : "none"} />
{liked ? "已关注" : "关注一下"} {liked ? "已关注" : "关注一下"}

View File

@ -212,12 +212,12 @@ export default function ProfileStudio() {
setRosterPublished(next); setRosterPublished(next);
setStatus( setStatus(
next next
? "好的,别人在「想见的人」里能看到你(仅当前这台设备的示例列表)。" ? "已加入当前设备的发现列表,方便预览。不会向其他用户公开发布。"
: "已先藏起来,别人暂时看不到你。", : "已从当前设备的发现列表隐藏。",
); );
}} }}
/> />
<span>出现在「想见的人 / 认识一下」里,让别人看到我</span> <span>在当前设备的「想见的人」中预览我的介绍</span>
</label> </label>
{published && complete < 5 ? ( {published && complete < 5 ? (
<p className="social-status warn" role="status"> <p className="social-status warn" role="status">

View File

@ -1,7 +1,7 @@
"use client"; "use client";
import Link from "next/link"; import Link from "next/link";
import { useRef, useState, type FormEvent } from "react"; import { useRef, useState, useSyncExternalStore, type FormEvent } from "react";
import { import {
ArrowUpRight, ArrowUpRight,
BookOpen, BookOpen,
@ -19,6 +19,7 @@ import {
EmptyState, EmptyState,
PageIntro, PageIntro,
SearchField, SearchField,
ResultSummary,
ShareButton, ShareButton,
SocialDialog, SocialDialog,
} from "./SocialUI"; } from "./SocialUI";
@ -26,6 +27,7 @@ import { useSocialConfig } from "./SocialExperience";
import { SEED_EBOOKS, SEED_VIDEOS } from "@social/lib/seed"; import { SEED_EBOOKS, SEED_VIDEOS } from "@social/lib/seed";
import { useLocalState } from "@social/lib/useLocalState"; import { useLocalState } from "@social/lib/useLocalState";
import { socialPath } from "@social/lib/socialPath"; import { socialPath } from "@social/lib/socialPath";
import { socialApi } from "@social/lib/api";
type Kind = "videos" | "date" | "ebook"; type Kind = "videos" | "date" | "ebook";
const COPY = { const COPY = {
@ -34,6 +36,23 @@ const COPY = {
ebook: { title: "共创 · 小册", accent: "大家写的" }, ebook: { title: "共创 · 小册", accent: "大家写的" },
}; };
function subscribeSelection(callback: () => void) {
window.addEventListener("hashchange", callback);
window.addEventListener("popstate", callback);
return () => {
window.removeEventListener("hashchange", callback);
window.removeEventListener("popstate", callback);
};
}
const readSelection = () => location.hash.slice(1);
const emptySelection = () => "";
function setSelection(id: string | null) {
const url = new URL(location.href);
url.hash = id || "";
history.replaceState(history.state, "", url);
window.dispatchEvent(new Event("hashchange"));
}
function safeSource(value?: string) { function safeSource(value?: string) {
if (!value) return undefined; if (!value) return undefined;
try { try {
@ -82,23 +101,34 @@ function ContributeForm({
title: "", title: "",
note: "", note: "",
}); });
const [sent, setSent] = useLocalState(`cocreate-sent:${kind}`, false); // v2 only records real API acknowledgements; v1 was a local-only timer.
const [sent, setSent] = useLocalState(`cocreate-delivered-v2:${kind}`, false);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [status, setStatus] = useState("");
const lock = useRef(false); const lock = useRef(false);
const update = (key: keyof typeof draft, value: string) => { const update = (key: keyof typeof draft, value: string) => {
setDraft((c) => ({ ...c, [key]: value })); setDraft((c) => ({ ...c, [key]: value }));
setSent(false); setSent(false);
setStatus("");
}; };
const submit = (event: FormEvent) => { const submit = async (event: FormEvent) => {
event.preventDefault(); event.preventDefault();
if (lock.current || !draft.name.trim() || !draft.contact.trim()) return; if (lock.current || !draft.name.trim() || !draft.contact.trim()) return;
lock.current = true; lock.current = true;
setBusy(true); setBusy(true);
window.setTimeout(() => { try {
await socialApi.postFeedback({
kind: "建议",
text: `【共创${books ? "小册" : "视频 / 访谈"}投稿】\n称呼:${draft.name.trim()}\n主题:${draft.title.trim() || "待讨论"}\n${draft.note.trim()}`,
contact: draft.contact.trim(),
});
setSent(true); setSent(true);
} catch {
setStatus("暂时未发送,草稿已保留在当前设备。请重试提交。");
} finally {
setBusy(false); setBusy(false);
lock.current = false; lock.current = false;
}, 420); }
}; };
if (sent) { if (sent) {
@ -107,9 +137,9 @@ function ContributeForm({
<span className="social-apply-done-mark" aria-hidden> <span className="social-apply-done-mark" aria-hidden>
<PenLine size={20} /> <PenLine size={20} />
</span> </span>
<strong>意向已记下</strong> <strong>共创意向已提交</strong>
<p> <p>
先留在你这边。有网或运营看到后,会再联系你聊聊怎么一起做。 已发送给社区运营。请保留联系方式,方便后续沟通。
</p> </p>
<div className="social-actions"> <div className="social-actions">
<Link className="social-btn primary" href={socialPath("/team")}> <Link className="social-btn primary" href={socialPath("/team")}>
@ -119,6 +149,7 @@ function ContributeForm({
<button type="button" className="social-btn" onClick={onClose}> <button type="button" className="social-btn" onClick={onClose}>
关闭 关闭
</button> </button>
<button type="button" className="social-btn" onClick={() => { setSent(false); setDraft({ name: "", contact: "", title: "", note: "" }); }}>再写一个主题</button>
</div> </div>
</div> </div>
); );
@ -135,7 +166,7 @@ function ContributeForm({
</div> </div>
<form <form
className="social-form social-apply-form" className="social-form social-apply-form"
onSubmit={submit} onSubmit={(event) => void submit(event)}
> >
<fieldset disabled={busy} className="social-fieldset"> <fieldset disabled={busy} className="social-fieldset">
<label> <label>
@ -185,12 +216,13 @@ function ContributeForm({
disabled={busy || !draft.name.trim() || !draft.contact.trim()} disabled={busy || !draft.name.trim() || !draft.contact.trim()}
> >
<Send size={14} /> <Send size={14} />
{busy ? "保存中…" : "提交意向"} {busy ? "提交中…" : status ? "重试提交" : "提交意向"}
</button> </button>
<button type="button" className="social-btn" onClick={onClose}> <button type="button" className="social-btn" onClick={onClose}>
取消 取消
</button> </button>
</div> </div>
{status && <p role="status" className="social-status warn">{status}</p>}
<small className="social-muted"> <small className="social-muted">
草稿离线也能写。提交不等于立刻上线,只是先把想法放进来。 草稿离线也能写。提交不等于立刻上线,只是先把想法放进来。
</small> </small>
@ -202,7 +234,7 @@ function ContributeForm({
export default function ResourceLibrary({ kind }: { kind: Kind }) { export default function ResourceLibrary({ kind }: { kind: Kind }) {
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const [savedOnly, setSavedOnly] = useState(false); const [savedOnly, setSavedOnly] = useState(false);
const [selected, setSelected] = useState<string | null>(null); const selected = useSyncExternalStore(subscribeSelection, readSelection, emptySelection);
const [contributeOpen, setContributeOpen] = useState(false); const [contributeOpen, setContributeOpen] = useState(false);
const config = useSocialConfig(); const config = useSocialConfig();
const [saved] = useLocalState<string[]>(`saved-${kind}`, []); const [saved] = useLocalState<string[]>(`saved-${kind}`, []);
@ -224,7 +256,7 @@ export default function ResourceLibrary({ kind }: { kind: Kind }) {
(!savedOnly || saved.includes(item.id)) && (!savedOnly || saved.includes(item.id)) &&
`${item.title} ${item.summary} ${item.city}` `${item.title} ${item.summary} ${item.city}`
.toLowerCase() .toLowerCase()
.includes(query.toLowerCase()), .includes(query.toLowerCase().trim()),
); );
const active = items.find((item) => item.id === selected); const active = items.find((item) => item.id === selected);
const source = const source =
@ -295,6 +327,7 @@ export default function ResourceLibrary({ kind }: { kind: Kind }) {
</button> </button>
</div> </div>
</div> </div>
<ResultSummary count={shown.length} unit={books ? "本小册" : "个视频"} filtered={Boolean(query || savedOnly)} onReset={() => { setQuery(""); setSavedOnly(false); }} />
<div <div
className={`social-grid social-library-grid ${books ? "is-books" : ""}`} className={`social-grid social-library-grid ${books ? "is-books" : ""}`}
> >
@ -308,7 +341,7 @@ export default function ResourceLibrary({ kind }: { kind: Kind }) {
<button <button
type="button" type="button"
className={`social-library-art library-tone-${index % 3}`} className={`social-library-art library-tone-${index % 3}`}
onClick={() => setSelected(item.id)} onClick={() => setSelection(item.id)}
aria-label={`查看${item.title}`} aria-label={`查看${item.title}`}
> >
<span className="social-film-grain" /> <span className="social-film-grain" />
@ -351,7 +384,7 @@ export default function ResourceLibrary({ kind }: { kind: Kind }) {
<button <button
type="button" type="button"
className="social-btn" className="social-btn"
onClick={() => setSelected(item.id)} onClick={() => setSelection(item.id)}
> >
打开 打开
<ArrowUpRight size={14} /> <ArrowUpRight size={14} />
@ -387,7 +420,7 @@ export default function ResourceLibrary({ kind }: { kind: Kind }) {
)} )}
</div> </div>
{active && ( {active && (
<SocialDialog title={active.title} onClose={() => setSelected(null)}> <SocialDialog title={active.title} onClose={() => setSelection(null)}>
<div className="social-tags"> <div className="social-tags">
<span>{active.detail}</span> <span>{active.detail}</span>
<span>{books ? "共创小册" : source ? "可播放" : "先看封面"}</span> <span>{books ? "共创小册" : source ? "可播放" : "先看封面"}</span>

View File

@ -19,6 +19,7 @@ import {
EmptyState, EmptyState,
PageIntro, PageIntro,
SearchField, SearchField,
ResultSummary,
SocialDialog, SocialDialog,
} from "./SocialUI"; } from "./SocialUI";
import { TEAM_KIND_LABEL } from "@social/lib/seed"; import { TEAM_KIND_LABEL } from "@social/lib/seed";
@ -264,7 +265,7 @@ export default function RoleBoard({
(!savedOnly || saved.includes(gig.id)) && (!savedOnly || saved.includes(gig.id)) &&
`${gig.title} ${gig.role} ${gig.tags.join(" ")}` `${gig.title} ${gig.role} ${gig.tags.join(" ")}`
.toLowerCase() .toLowerCase()
.includes(query.toLowerCase()), .includes(query.toLowerCase().trim()),
); );
return ( return (
<SiteShell title="一起做事"> <SiteShell title="一起做事">
@ -316,6 +317,7 @@ export default function RoleBoard({
), ),
)} )}
</div> </div>
<ResultSummary count={roles.length} unit="个机会" filtered={Boolean(query || kind !== "all" || savedOnly)} onReset={() => { setQuery(""); setKind("all"); setSavedOnly(false); }} />
<div className="social-grid social-role-grid"> <div className="social-grid social-role-grid">
{roles.map((gig, index) => ( {roles.map((gig, index) => (
<article <article

View File

@ -8,7 +8,6 @@ import {
useId, useId,
useRef, useRef,
useState, useState,
useSyncExternalStore,
type ReactNode, type ReactNode,
} from "react"; } from "react";
import { socialPath } from "@social/lib/socialPath"; import { socialPath } from "@social/lib/socialPath";
@ -17,28 +16,7 @@ import { useRevealMotion } from "@social/lib/useRevealMotion";
import { SocialMobileDock } from "./SocialNavigation"; import { SocialMobileDock } from "./SocialNavigation";
import SocialQuickRail from "./SocialQuickRail"; import SocialQuickRail from "./SocialQuickRail";
import SocialBrandLogo from "./SocialBrandLogo"; import SocialBrandLogo from "./SocialBrandLogo";
import { useTheme } from "~/components/theme-provider";
function readTheme(): "light" | "dark" {
try {
return (localStorage.getItem("nomadro-theme") ||
localStorage.getItem("nomad-theme")) === "light"
? "light"
: "dark";
} catch {
return "dark";
}
}
function subscribeTheme(callback: () => void) {
window.addEventListener("storage", callback);
window.addEventListener("nomadro-theme-changed", callback);
return () => {
window.removeEventListener("storage", callback);
window.removeEventListener("nomadro-theme-changed", callback);
};
}
const serverTheme = () => "dark" as const;
const GROUPS = [ const GROUPS = [
{ {
@ -81,7 +59,7 @@ export default function SiteShell({
home?: boolean; home?: boolean;
onJoin?: () => void; onJoin?: () => void;
}) { }) {
const theme = useSyncExternalStore(subscribeTheme, readTheme, serverTheme); const { resolvedTheme: theme, setTheme } = useTheme();
const [openGroup, setOpenGroup] = useState<string | null>(null); const [openGroup, setOpenGroup] = useState<string | null>(null);
const [menuOpen, setMenuOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false);
const [scrolled, setScrolled] = useState(false); const [scrolled, setScrolled] = useState(false);
@ -89,6 +67,7 @@ export default function SiteShell({
const menuId = useId(); const menuId = useId();
const menuButtonRef = useRef<HTMLButtonElement>(null); const menuButtonRef = useRef<HTMLButtonElement>(null);
const navRef = useRef<HTMLElement>(null); const navRef = useRef<HTMLElement>(null);
const menuPanelRef = useRef<HTMLDivElement>(null);
useEffect(() => { useEffect(() => {
applySocialSkin(SOCIAL_SKIN_DEFAULT); applySocialSkin(SOCIAL_SKIN_DEFAULT);
@ -99,12 +78,6 @@ export default function SiteShell({
pathname, pathname,
]); ]);
useEffect(() => {
document.documentElement.setAttribute("data-theme", theme);
document.documentElement.classList.toggle("light", theme === "light");
document.documentElement.classList.toggle("dark", theme === "dark");
}, [theme]);
useEffect(() => { useEffect(() => {
const onScroll = () => setScrolled(window.scrollY > 24); const onScroll = () => setScrolled(window.scrollY > 24);
onScroll(); onScroll();
@ -143,22 +116,29 @@ export default function SiteShell({
if (!menuOpen) return; if (!menuOpen) return;
const previousOverflow = document.body.style.overflow; const previousOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden"; document.body.style.overflow = "hidden";
menuPanelRef.current?.querySelector<HTMLButtonElement>("button")?.focus();
const trapFocus = (event: KeyboardEvent) => {
if (event.key !== "Tab") return;
const items = Array.from(navRef.current?.querySelectorAll<HTMLElement>('a[href], button:not(:disabled)') || [])
.filter((element) => element.getClientRects().length > 0 && getComputedStyle(element).visibility !== "hidden");
const first = items[0], last = items[items.length - 1];
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
};
const media = matchMedia("(min-width: 901px)");
const closeOnDesktop = () => { if (media.matches) setMenuOpen(false); };
document.addEventListener("keydown", trapFocus);
media.addEventListener("change", closeOnDesktop);
return () => { return () => {
document.body.style.overflow = previousOverflow; document.body.style.overflow = previousOverflow;
document.removeEventListener("keydown", trapFocus);
media.removeEventListener("change", closeOnDesktop);
}; };
}, [menuOpen]); }, [menuOpen]);
const toggleTheme = () => { const toggleTheme = () => {
const next = theme === "dark" ? "light" : "dark"; const next = theme === "dark" ? "light" : "dark";
try { setTheme(next);
localStorage.setItem("nomadro-theme", next);
} catch {
/* private mode */
}
document.documentElement.setAttribute("data-theme", next);
document.documentElement.classList.toggle("light", next === "light");
document.documentElement.classList.toggle("dark", next === "dark");
window.dispatchEvent(new Event("nomadro-theme-changed"));
}; };
const closeMenus = () => { const closeMenus = () => {
@ -196,7 +176,7 @@ export default function SiteShell({
<div className="nav-container"> <div className="nav-container">
<SocialBrandLogo onClick={closeMenus} /> <SocialBrandLogo onClick={closeMenus} />
<div id={menuId} className={`nav-links${menuOpen ? " open" : ""}`}> <div ref={menuPanelRef} id={menuId} className={`nav-links${menuOpen ? " open" : ""}`}>
{GROUPS.map((g) => ( {GROUPS.map((g) => (
<div <div
key={g.id} key={g.id}
@ -258,10 +238,10 @@ export default function SiteShell({
type="button" type="button"
className="nav-icon-btn" className="nav-icon-btn"
onClick={toggleTheme} onClick={toggleTheme}
aria-label="切换明暗" aria-label={theme === "dark" ? "切换日间模式" : "切换夜间模式"}
suppressHydrationWarning suppressHydrationWarning
> >
{theme === "dark" ? <Moon size={17} /> : <Sun size={17} />} {theme === "dark" ? <Sun size={17} /> : <Moon size={17} />}
</button> </button>
<Link <Link
href={socialPath("/chat")} href={socialPath("/chat")}

View File

@ -2,6 +2,7 @@
import Link from "next/link"; import Link from "next/link";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { useEffect, useRef } from "react";
import { import {
CircleUserRound, CircleUserRound,
Compass, Compass,
@ -21,8 +22,25 @@ const LINKS = [
export function SocialMobileDock() { export function SocialMobileDock() {
const pathname = usePathname(); const pathname = usePathname();
const dock = useRef<HTMLElement>(null);
useEffect(() => {
const viewport = window.visualViewport;
if (!viewport) return;
const syncKeyboard = () => {
const editing = document.activeElement?.matches("input, textarea, select");
if (dock.current) dock.current.dataset.keyboardOpen = String(Boolean(editing && innerHeight - viewport.height > 120));
};
viewport.addEventListener("resize", syncKeyboard);
document.addEventListener("focusin", syncKeyboard);
document.addEventListener("focusout", syncKeyboard);
return () => {
viewport.removeEventListener("resize", syncKeyboard);
document.removeEventListener("focusin", syncKeyboard);
document.removeEventListener("focusout", syncKeyboard);
};
}, []);
return ( return (
<nav className="social-mobile-dock" aria-label="快捷导航"> <nav ref={dock} className="social-mobile-dock" aria-label="快捷导航">
{LINKS.map((item) => ( {LINKS.map((item) => (
<Link <Link
key={item.href} key={item.href}

View File

@ -2,6 +2,7 @@
import Link from "next/link"; import Link from "next/link";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { useEffect, useRef } from "react";
import { socialPath } from "@social/lib/socialPath"; import { socialPath } from "@social/lib/socialPath";
const RAIL = [ const RAIL = [
@ -18,9 +19,15 @@ const RAIL = [
export default function SocialQuickRail() { export default function SocialQuickRail() {
const pathname = usePathname(); const pathname = usePathname();
const track = useRef<HTMLDivElement>(null);
useEffect(() => {
const container = track.current;
const active = container?.querySelector<HTMLElement>('[aria-current="page"]');
if (container && active) container.scrollLeft = Math.max(0, active.offsetLeft - container.offsetLeft - (container.clientWidth - active.clientWidth) / 2);
}, [pathname]);
return ( return (
<nav className="social-quick-rail" aria-label="社区快捷入口"> <nav className="social-quick-rail" aria-label="社区快捷入口">
<div className="social-quick-rail-track"> <div ref={track} className="social-quick-rail-track">
{RAIL.map((item) => { {RAIL.map((item) => {
const href = socialPath(item.href); const href = socialPath(item.href);
const active = const active =

View File

@ -1,6 +1,6 @@
"use client"; "use client";
import { useEffect, useRef, useState, type ReactNode } from "react"; import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { Check, Copy, Search, X } from "lucide-react"; import { Check, Copy, Search, X } from "lucide-react";
import { useLocalState } from "@social/lib/useLocalState"; import { useLocalState } from "@social/lib/useLocalState";
import { useSocialConfig } from "./SocialExperience"; import { useSocialConfig } from "./SocialExperience";
@ -110,10 +110,12 @@ export function SearchField({
placeholder: string; placeholder: string;
label?: string; label?: string;
}) { }) {
const inputRef = useRef<HTMLInputElement>(null);
return ( return (
<label className="social-search"> <label className="social-search">
<Search size={17} /> <Search size={17} />
<input <input
ref={inputRef}
type="search" type="search"
aria-label={label} aria-label={label}
placeholder={placeholder} placeholder={placeholder}
@ -124,7 +126,7 @@ export function SearchField({
<button <button
type="button" type="button"
aria-label="清空搜索" aria-label="清空搜索"
onClick={() => onChange("")} onClick={() => { onChange(""); inputRef.current?.focus(); }}
> >
<X size={14} /> <X size={14} />
</button> </button>
@ -133,6 +135,20 @@ export function SearchField({
); );
} }
export function ResultSummary({ count, unit = "项结果", filtered, onReset }: {
count: number;
unit?: string;
filtered: boolean;
onReset: () => void;
}) {
return (
<div className="social-result-summary">
<p role="status" aria-live="polite" aria-atomic="true">{count} {unit}</p>
{filtered && <button type="button" className="social-save" onClick={onReset}><X size={14} />重置筛选</button>}
</div>
);
}
export function BookmarkButton({ export function BookmarkButton({
id, id,
collection = "saved-items", collection = "saved-items",
@ -151,7 +167,7 @@ export function BookmarkButton({
aria-pressed={selected} aria-pressed={selected}
onClick={() => onClick={() =>
setItems((current) => setItems((current) =>
selected ? current.filter((item) => item !== id) : [...current, id], current.includes(id) ? current.filter((item) => item !== id) : [...current, id],
) )
} }
title="收藏保存在当前设备" title="收藏保存在当前设备"
@ -230,6 +246,8 @@ export function SocialDialog({
children: ReactNode; children: ReactNode;
}) { }) {
const ref = useRef<HTMLDialogElement>(null); const ref = useRef<HTMLDialogElement>(null);
const titleId = useId();
const backdropPress = useRef(false);
useEffect(() => { useEffect(() => {
const dialog = ref.current; const dialog = ref.current;
const opener = document.activeElement as HTMLElement; const opener = document.activeElement as HTMLElement;
@ -246,17 +264,19 @@ export function SocialDialog({
<dialog <dialog
ref={ref} ref={ref}
className="social-dialog" className="social-dialog"
aria-labelledby={titleId}
onPointerDown={(event) => { backdropPress.current = event.target === ref.current; }}
onCancel={(event) => { onCancel={(event) => {
event.preventDefault(); event.preventDefault();
onClose(); onClose();
}} }}
onClick={(event) => { onClick={(event) => {
if (event.target === ref.current) onClose(); if (backdropPress.current && event.target === ref.current) onClose();
}} }}
> >
<div className="social-dialog-sheet"> <div className="social-dialog-sheet">
<header> <header>
<h2>{title}</h2> <h2 id={titleId}>{title}</h2>
<button type="button" aria-label="关闭" onClick={onClose}> <button type="button" aria-label="关闭" onClick={onClose}>
<X size={18} /> <X size={18} />
</button> </button>

View File

@ -4,9 +4,20 @@ import type { SocialMeetup } from "./types";
export function eventDate(event: SocialMeetup): Date { export function eventDate(event: SocialMeetup): Date {
const [year, month, day] = event.date.split("-").map(Number); const [year, month, day] = event.date.split("-").map(Number);
const [hour, minute] = event.time.split(":").map(Number); const [hour, minute] = event.time.split(":").map(Number);
const calendarDay = new Date(Date.UTC(year, month - 1, day));
if (
!/^\d{4}-\d{2}-\d{2}$/.test(event.date) ||
!/^\d{2}:\d{2}$/.test(event.time) ||
hour > 23 || minute > 59 ||
calendarDay.getUTCFullYear() !== year ||
calendarDay.getUTCMonth() !== month - 1 ||
calendarDay.getUTCDate() !== day
) return new Date(NaN);
const target = Date.UTC(year, month - 1, day, hour, minute); const target = Date.UTC(year, month - 1, day, hour, minute);
let instant = target; let instant = target;
const formatter = new Intl.DateTimeFormat("en-CA", { let formatter: Intl.DateTimeFormat;
try {
formatter = new Intl.DateTimeFormat("en-CA", {
timeZone: event.timeZone || "Asia/Shanghai", timeZone: event.timeZone || "Asia/Shanghai",
year: "numeric", year: "numeric",
month: "2-digit", month: "2-digit",
@ -16,6 +27,9 @@ export function eventDate(event: SocialMeetup): Date {
second: "2-digit", second: "2-digit",
hourCycle: "h23", hourCycle: "h23",
}); });
} catch {
return new Date(NaN);
}
for (let i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
const parts = Object.fromEntries( const parts = Object.fromEntries(
formatter formatter
@ -44,6 +58,8 @@ function escapeIcs(value: string) {
.replace(/;/g, "\\;"); .replace(/;/g, "\\;");
} }
export function saveEventCalendar(event: SocialMeetup) { export function saveEventCalendar(event: SocialMeetup) {
const start = eventDate(event);
if (!Number.isFinite(start.getTime())) return;
const stamp = (date: Date) => const stamp = (date: Date) =>
date date
.toISOString() .toISOString()
@ -58,7 +74,7 @@ export function saveEventCalendar(event: SocialMeetup) {
"BEGIN:VEVENT", "BEGIN:VEVENT",
`UID:${event.id}@nomadro.social`, `UID:${event.id}@nomadro.social`,
`DTSTAMP:${stamp(new Date())}`, `DTSTAMP:${stamp(new Date())}`,
`DTSTART:${stamp(eventDate(event))}`, `DTSTART:${stamp(start)}`,
`SUMMARY:${escapeIcs(event.title)}`, `SUMMARY:${escapeIcs(event.title)}`,
`DESCRIPTION:${escapeIcs(`nomadro 活动预览。活动时区:${event.timeZone || "Asia/Shanghai"}。具体安排请在活动频道确认。\n${url}`)}`, `DESCRIPTION:${escapeIcs(`nomadro 活动预览。活动时区:${event.timeZone || "Asia/Shanghai"}。具体安排请在活动频道确认。\n${url}`)}`,
`URL:${url}`, `URL:${url}`,

View File

@ -70,11 +70,19 @@ export function useDiscoveryRoster(): SocialRosterMember[] {
() => loadJson<boolean>(ROSTER_PUBLISH_KEY, false), () => loadJson<boolean>(ROSTER_PUBLISH_KEY, false),
() => false, () => false,
); );
const profile = useSyncExternalStore( // getSnapshot must be referentially stable: JSON.parse creates a new object
// on every read once a local profile exists, causing a React render loop.
const profileSnapshot = useSyncExternalStore(
subscribeSocialStorage, subscribeSocialStorage,
() => loadJson<SocialRosterProfile>("roster", EMPTY), () => JSON.stringify(loadJson<SocialRosterProfile>("roster", EMPTY)),
() => EMPTY, () => JSON.stringify(EMPTY),
); );
const profile = useMemo(() => {
const raw = JSON.parse(profileSnapshot) as Partial<SocialRosterProfile> | null;
return Object.fromEntries(Object.entries(EMPTY).map(([key, fallback]) => [
key, typeof raw?.[key as keyof SocialRosterProfile] === "string" ? raw[key as keyof SocialRosterProfile] : fallback,
])) as SocialRosterProfile;
}, [profileSnapshot]);
return useMemo(() => { return useMemo(() => {
const self = published ? profileToMember(profile) : null; const self = published ? profileToMember(profile) : null;
if (!self) return MOCK_ROSTER; if (!self) return MOCK_ROSTER;

View File

@ -1,14 +1,19 @@
"use client"; "use client";
const PREFIX = "nomadro-social:"; const PREFIX = "nomadro-social:";
const memory = new Map<string, string>();
export function loadJson<T>(key: string, fallback: T): T { export function loadJson<T>(key: string, fallback: T): T {
if (typeof window === "undefined") return fallback; if (typeof window === "undefined") return fallback;
try { try {
const raw = window.localStorage.getItem(PREFIX + key); const raw = memory.get(key) ?? window.localStorage.getItem(PREFIX + key);
if (!raw) return fallback; if (!raw) return fallback;
return JSON.parse(raw) as T; return JSON.parse(raw) as T;
} catch { } catch {
const raw = memory.get(key);
if (raw) {
try { return JSON.parse(raw) as T; } catch { /* invalid cached value */ }
}
return fallback; return fallback;
} }
} }
@ -17,8 +22,10 @@ export function saveJson<T>(key: string, value: T): void {
if (typeof window === "undefined") return; if (typeof window === "undefined") return;
try { try {
window.localStorage.setItem(PREFIX + key, JSON.stringify(value)); window.localStorage.setItem(PREFIX + key, JSON.stringify(value));
memory.delete(key);
} catch { } catch {
/* quota / private mode */ // Keep forms usable for this session when storage is blocked or full.
memory.set(key, JSON.stringify(value));
} }
} }

View File

@ -7,6 +7,7 @@ export function useRevealMotion(rootSelector: string, deps: unknown[] = []) {
useEffect(() => { useEffect(() => {
const root = document.querySelector(rootSelector); const root = document.querySelector(rootSelector);
if (!root) return; if (!root) return;
const media = matchMedia("(prefers-reduced-motion: reduce)");
const observer = new IntersectionObserver( const observer = new IntersectionObserver(
(entries) => (entries) =>
entries.forEach((entry) => { entries.forEach((entry) => {
@ -19,12 +20,19 @@ export function useRevealMotion(rootSelector: string, deps: unknown[] = []) {
const scan = () => { const scan = () => {
root root
.querySelectorAll(".reveal:not(.visible)") .querySelectorAll(".reveal:not(.visible)")
.forEach((el) => observer.observe(el)); .forEach((el) => {
if (media.matches) el.classList.add("visible");
else observer.observe(el);
});
}; };
scan(); scan();
const t = window.setTimeout(scan, 350); // Searches, remote catalogs and empty states mount after the initial render.
const mutations = new MutationObserver(scan);
mutations.observe(root, { childList: true, subtree: true });
media.addEventListener("change", scan);
return () => { return () => {
window.clearTimeout(t); mutations.disconnect();
media.removeEventListener("change", scan);
observer.disconnect(); observer.disconnect();
}; };
// eslint-disable-next-line react-hooks/exhaustive-deps -- caller owns deps // eslint-disable-next-line react-hooks/exhaustive-deps -- caller owns deps

View File

@ -0,0 +1,39 @@
"use client";
import { useMemo, useSyncExternalStore } from "react";
import { loadJson, saveJson } from "./storage";
const KEY = "social-roster-likes";
const CHANGE = "social-roster-likes-changed";
function readLikes(): Record<string, boolean> {
const value = loadJson<unknown>(KEY, {});
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
return Object.fromEntries(Object.entries(value).filter(([, liked]) => liked === true));
}
function subscribe(callback: () => void) {
window.addEventListener("storage", callback);
window.addEventListener(CHANGE, callback);
return () => {
window.removeEventListener("storage", callback);
window.removeEventListener(CHANGE, callback);
};
}
const snapshot = () => JSON.stringify(readLikes());
const serverSnapshot = () => "{}";
export function setRosterLike(id: string, liked: boolean) {
const next = readLikes();
if (liked) next[id] = true;
else delete next[id];
saveJson(KEY, next);
window.dispatchEvent(new Event(CHANGE));
}
/** One local follow list shared by discovery, profiles, homepage and swiping. */
export function useRosterLikes() {
const value = useSyncExternalStore(subscribe, snapshot, serverSnapshot);
return useMemo(() => JSON.parse(value) as Record<string, boolean>, [value]);
}