nomadro/src/modules/social/components/CommunityWelcome.tsx
Eric abdcafb1eb Ship Work access gate, pads/boards upgrades, and locale hydration fix on .com.
Gate /social/work behind join/login/profile; harden Work UX and LanguageSwitcher SSR; deploy portal, admin, and work API.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-08 00:14:39 +08:00

1315 lines
43 KiB
TypeScript

"use client";
import {
useEffect,
useRef,
useState,
useSyncExternalStore,
type FormEvent,
} from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import {
ArrowUpRight,
Camera,
Check,
Globe2,
Send,
} from "lucide-react";
import SiteShell from "./SiteShell";
import AvatarSelfieModal, {
type SelfieCapturePayload,
} from "./AvatarSelfieModal";
import { PageIntro } from "./SocialUI";
import { useSocialConfig } from "./SocialExperience";
import { socialApi } from "@social/lib/api";
import { isSocialAvatarFaceCheckEnabled } from "@social/lib/avatarFaceCheck";
import { getSocialLive } from "@social/lib/socialLive";
import { useCaptureCapability } from "@social/lib/useCaptureCapability";
import {
getLivenessState,
isFaceOk,
isLivenessVerified,
clearFaceOk,
getLivenessServerSnapshot,
getLivenessSnapshot,
markFaceOk,
markLivenessVerified,
subscribeLivenessState,
} from "@social/lib/livenessGate";
import {
JOIN_AVAILABILITY_OPTIONS,
JOIN_GENDER_OPTIONS,
JOIN_INTENT_OPTIONS,
JOIN_LIVENESS_RETURN,
JOIN_PROFILE_RETURN,
isJoinPaid,
clearJoinProfileDone,
isJoinProfileDone,
markJoinProfileDone,
type JoinProfileDraft,
} from "@social/lib/joinFlow";
import { archiveJoinLead } from "@social/lib/joinArchive";
import { flagOpenJoinModalSoon, openSocialJoinModal } from "@social/lib/joinModal";
import { setRosterPublished } from "@social/lib/discoveryRoster";
import { loadJson, saveJson } from "@social/lib/storage";
import { useLocalState } from "@social/lib/useLocalState";
import { socialPath } from "@social/lib/socialPath";
import { useSocialI18n } from "@social/lib/useSocialI18n";
import { socialTx } from "@social/lib/socialTx";
import type { SocialRosterProfile } from "@social/lib/types";
export function CommunityFeedback() {
const [draft, setDraft] = useLocalState<{
kind: "反馈" | "建议";
text: string;
contact: string;
}>("feedback-draft", { kind: "建议", text: "", contact: "" });
const [delivery, setDelivery] = useLocalState("feedback-delivery", "draft");
const [status, setStatus] = useState("");
const [busy, setBusy] = useState(false);
const lock = useRef(false);
const update = (key: keyof typeof draft, value: string) => {
setDraft((current) => ({ ...current, [key]: value }));
setDelivery("draft");
setStatus("");
};
const reset = () => {
setDraft({ kind: "建议", text: "", contact: "" });
setDelivery("draft");
setStatus("");
};
const submit = async (event: FormEvent) => {
event.preventDefault();
if (!draft.text.trim() || lock.current || delivery === "sent") return;
lock.current = true;
setBusy(true);
try {
await socialApi.postFeedback({
...draft,
text: draft.text.trim(),
contact: draft.contact.trim(),
});
setDelivery("sent");
setStatus(socialTx("已提交,感谢反馈。"));
} catch (e) {
// 草稿仍在本机表单里;不要再装成「没网」——多数是服务端挂了
setDelivery("local");
const msg = e instanceof Error ? e.message : "";
setStatus(
msg && msg.length < 120
? socialTx(`提交失败:${msg}。内容还在表单里,修好后点重试。`)
: socialTx("提交失败。内容还在表单里,请稍后点重试。"),
);
} finally {
lock.current = false;
setBusy(false);
}
};
return (
<SiteShell title={socialTx("说说想法")}>
<PageIntro title={socialTx("意见反馈")} accent="我们在听" />
<section className="social-panel social-feedback-panel reveal">
<div className="social-page-kicker">
<span />
{socialTx("说说你的想法")}
</div>
<h2 className="social-feedback-title">
{socialTx("哪里用得不顺手?告诉我们")}
</h2>
<p className="social-muted">
{socialTx("我们会看,但不保证马上回复。提交成功后会清空表单。")}
</p>
{delivery === "sent" ? (
<div className="social-join-success">
<p className="social-status" role="status">
{status || socialTx("已提交")}
</p>
<div className="social-actions">
<button
type="button"
className="social-btn primary"
onClick={reset}
>
{socialTx("再提一条")}
</button>
<Link className="social-btn" href={socialPath("/")}>
{socialTx("回社区首页")}
</Link>
</div>
</div>
) : (
<form className="social-form" onSubmit={(event) => void submit(event)}>
<fieldset disabled={busy} className="social-fieldset">
<div className="social-filters">
{(["建议", "反馈"] as const).map((kind) => (
<button
type="button"
key={kind}
className={draft.kind === kind ? "active" : ""}
aria-pressed={draft.kind === kind}
onClick={() => update("kind", kind)}
>
{socialTx(kind)}
</button>
))}
</div>
<label>
{socialTx("内容")}
<textarea
rows={6}
required
maxLength={3000}
value={draft.text}
onChange={(event) => update("text", event.target.value)}
placeholder={socialTx("具体页面 / 操作 / 期望…")}
/>
<small>{draft.text.length}/3000</small>
</label>
<label>
{socialTx("联系方式(选填)")}
<input
maxLength={120}
value={draft.contact}
onChange={(event) => update("contact", event.target.value)}
placeholder={socialTx("邮箱 / 微信")}
/>
</label>
</fieldset>
<button
type="submit"
className="social-btn primary"
disabled={busy || !draft.text.trim()}
>
<Send size={15} />
{busy
? socialTx("提交中…")
: delivery === "local"
? socialTx("重试")
: socialTx("提交")}
</button>
{status && (
<p
role="status"
className={`social-status${delivery === "local" ? " warn" : ""}`}
>
{status}
</p>
)}
</form>
)}
</section>
</SiteShell>
);
}
const EMPTY_JOIN_PROFILE: JoinProfileDraft = {
name: "",
avatar: "",
gender: "",
phone: "",
wechat: "",
city: "",
title: "",
skills: "",
education: "",
graduation: "",
relationship: "",
intents: [],
availability: "",
status: "online",
linktree: "",
bio: "",
};
type JoinStep = "pay" | "profile" | "liveness" | "done";
/** URL-only — must match SSR; localStorage flags applied after mount. */
function stepFromParam(param: string | null): JoinStep {
if (param === "profile") return "profile";
if (param === "liveness") return "liveness";
if (param === "done") return "done";
return "pay";
}
function resolveJoinStep(param: string | null): JoinStep {
// Unpaid users cannot skip into profile / liveness / done via URL.
if (!isJoinPaid()) {
if (param === "profile" || param === "liveness" || param === "done") {
return "pay";
}
}
// Explicit URL steps win only after paid (re-fill / QA).
if (param === "profile") return "profile";
if (param === "liveness") return isJoinProfileDone() ? "liveness" : "profile";
if (param === "done") {
if (isLivenessVerified() && isJoinProfileDone()) return "done";
if (isJoinProfileDone()) return "liveness";
return "profile";
}
if (isLivenessVerified() && isJoinProfileDone() && isJoinPaid()) return "done";
if (isJoinProfileDone() && isJoinPaid()) return "liveness";
if (isJoinPaid()) return "profile";
return "pay";
}
function JoinStepMark({ active }: { active: 2 | 3 | 4 }) {
const label =
active === 2
? socialTx("资料")
: active === 3
? socialTx("确认本人")
: socialTx("完成");
return (
<p className="social-join-stepmark" aria-label={socialTx("加入步骤")}>
<span>{String(active).padStart(2, "0")}</span>
<em>/</em>
04
<b>{label}</b>
</p>
);
}
function JoinProfileForm({ onDone }: { onDone: () => void }) {
const { locale } = useSocialI18n();
const config = useSocialConfig();
const faceCheckOn = isSocialAvatarFaceCheckEnabled(config);
const liveUx = getSocialLive(config);
const livenessOn = liveUx.livenessGate;
const capture = useCaptureCapability();
const nameRef = useRef<HTMLInputElement>(null);
const avatarInputRef = useRef<HTMLInputElement>(null);
const captureInputRef = useRef<HTMLInputElement>(null);
// Empty seed for SSR — hydrate from localStorage after mount (avoids mismatch).
const [draft, setDraft] = useState<JoinProfileDraft>(EMPTY_JOIN_PROFILE);
const [busy, setBusy] = useState(false);
const [avatarBusy, setAvatarBusy] = useState(false);
const [avatarErr, setAvatarErr] = useState("");
const [selfieOpen, setSelfieOpen] = useState(false);
const [faceOk, setFaceOk] = useState(false);
const [liveOk, setLiveOk] = useState(false);
const [err, setErr] = useState("");
const lock = useRef(false);
useEffect(() => {
const s = getLivenessState();
setFaceOk(s.faceOk);
setLiveOk(s.livenessStatus === "verified");
}, []);
/** Step 1: always prefer album / clear face photo */
const openPrimaryCapture = () => {
avatarInputRef.current?.click();
};
const avatarHint = (() => {
if (avatarBusy) return socialTx("上传中…");
if (!capture.ready) return socialTx("准备中…");
if (liveOk && (draft.avatar || "").trim()) {
return socialTx("头像和自拍都好了,可以去认识朋友");
}
if (liveOk) return socialTx("请上传一张头像");
// Face-copy only when admin switch is on — otherwise never mention 人脸/正面.
if (faceCheckOn && faceOk) {
return socialTx("照片看起来不错。再拍张自拍,确认是你本人");
}
if (faceCheckOn) {
return socialTx("请先上传一张清晰的正面照片,再拍张自拍确认本人");
}
return socialTx("上传一张头像就可以");
})();
useEffect(() => {
const saved = loadJson<Partial<JoinProfileDraft>>(
"join-profile",
EMPTY_JOIN_PROFILE,
);
const nickLs =
typeof window !== "undefined"
? localStorage.getItem("userName") || ""
: "";
const nick =
(nickLs && !nickLs.includes("@") ? nickLs : "") ||
loadJson<string>("nick", "") ||
saved.name ||
"";
const genderRaw =
typeof saved.gender === "string" ? saved.gender.trim() : "";
setDraft({
...EMPTY_JOIN_PROFILE,
...saved,
intents: Array.isArray(saved.intents) ? saved.intents : [],
availability:
typeof saved.availability === "string" ? saved.availability : "",
status:
typeof saved.status === "string" && saved.status
? saved.status
: "online",
// Only 男/女 — drop legacy nb / empty placeholders
gender: genderRaw === "m" || genderRaw === "f" ? genderRaw : "",
relationship: "",
name: typeof nick === "string" ? nick : "",
avatar:
typeof saved.avatar === "string" && !saved.avatar.startsWith("blob:")
? saved.avatar
: "",
});
nameRef.current?.focus();
}, []);
const update = <K extends keyof JoinProfileDraft>(
key: K,
value: JoinProfileDraft[K],
) => {
setDraft((current) => ({ ...current, [key]: value }));
setErr("");
};
const onAvatarPick = async (file: File | null) => {
if (!file || avatarBusy) return;
const mime = (file.type || "").toLowerCase();
const okMime =
!mime ||
mime.startsWith("image/") ||
/\.(jpe?g|png|webp|gif)$/i.test(file.name);
if (!okMime) {
setAvatarErr(socialTx("请选择图片文件"));
return;
}
if (file.size > 8 * 1024 * 1024) {
setAvatarErr(socialTx("头像不能超过 8MB"));
return;
}
setAvatarBusy(true);
setAvatarErr("");
setErr("");
// Instant local preview while uploading / face-checking
const localUrl = URL.createObjectURL(file);
setDraft((current) => ({ ...current, avatar: localUrl }));
try {
const uploaded = await socialApi.uploadAvatar(file, "avatar");
const url = (uploaded?.url || "").trim();
if (!url) throw new Error(socialTx("头像上传失败"));
setDraft((current) => {
const next = { ...current, avatar: url };
saveJson("join-profile", next);
const roster = loadJson<SocialRosterProfile>("roster", {
name: "",
title: "",
city: "",
phone: "",
linktree: "",
skills: "",
bio: "",
avatar: "",
});
saveJson("roster", { ...roster, avatar: url });
return next;
});
// faceOk is server-side only for display gates; never lecture the user unless switch on.
if (uploaded.faceOk) {
markFaceOk();
setFaceOk(true);
setAvatarErr("");
} else {
clearFaceOk();
setFaceOk(false);
if (faceCheckOn) {
setAvatarErr(socialTx("没看清脸,请上传一张清晰的正面照"));
} else {
setAvatarErr("");
}
}
requestAnimationFrame(() => URL.revokeObjectURL(localUrl));
if (
faceCheckOn &&
uploaded.faceOk &&
!isLivenessVerified() &&
capture.mode === "live-modal"
) {
setErr("");
}
} catch (e) {
setDraft((current) => ({ ...current, avatar: "" }));
URL.revokeObjectURL(localUrl);
const raw =
e instanceof Error ? e.message.slice(0, 160).trim() : "";
// Soft-upload never throws face errors; hard gate (switch on) may.
const facey =
/脸|人脸|正面|face|liveness|selfie/i.test(raw);
if (facey && !faceCheckOn) {
setAvatarErr(socialTx("头像上传失败"));
} else {
const msg =
raw && !/^upload failed|^no url|^上传失败 HTTP/i.test(raw)
? socialTx(raw)
: socialTx("头像上传失败");
setAvatarErr(msg || socialTx("头像上传失败"));
}
} finally {
setAvatarBusy(false);
}
};
const onSelfieChallenge = async (payload: SelfieCapturePayload) => {
// Live capture = liveness gate only — never replace album/selfie avatar
setAvatarBusy(true);
setAvatarErr("");
setErr("");
try {
const uploaded = await socialApi.uploadAvatarChallenge(
payload.front,
payload.turn,
payload.video,
payload.videoMime,
);
// Live audit ≠ album avatar / faceOk
markLivenessVerified({ videoUrl: uploaded.videoUrl || "" });
setLiveOk(true);
setAvatarErr("");
if (!(draft.avatar || "").trim()) {
setAvatarErr(
faceCheckOn
? socialTx("自拍已通过。请再选一张正面照片当头像。")
: socialTx("自拍已通过。请再上传一张头像。"),
);
}
} catch (e) {
const raw =
e instanceof Error ? e.message.slice(0, 160).trim() : "";
setAvatarErr(
raw ? socialTx(raw) || raw : socialTx("自拍没通过,请再试一次"),
);
throw e instanceof Error ? e : new Error(socialTx("自拍没通过,请再试一次"));
} finally {
setAvatarBusy(false);
}
};
const toggleIntent = (value: string) => {
setDraft((current) => {
const has = current.intents.includes(value);
return {
...current,
intents: has
? current.intents.filter((item) => item !== value)
: [...current.intents, value],
};
});
};
const submit = async (event: FormEvent) => {
event.preventDefault();
if (lock.current) return;
const name = draft.name.trim();
if (!name) {
setErr(socialTx("请填写怎么称呼你"));
nameRef.current?.focus();
return;
}
if (draft.gender !== "m" && draft.gender !== "f") {
setErr(socialTx("请选择性别"));
return;
}
if (!draft.intents.length) {
setErr(socialTx("请至少选一个「想认识 / 想做什么」"));
return;
}
const avatarUrl =
draft.avatar.startsWith("blob:") ? "" : draft.avatar.trim();
if (!avatarUrl) {
setErr(socialTx("请先上传头像"));
return;
}
if (faceCheckOn && !faceOk && !isFaceOk()) {
setErr(socialTx("请先上传一张清楚的正面头像"));
return;
}
if (draft.linktree.trim() && !/^https?:\/\//i.test(draft.linktree.trim())) {
setErr(socialTx("作品链接请以 https:// 或 http:// 开头。"));
return;
}
lock.current = true;
setBusy(true);
setErr("");
const intentLabels = draft.intents
.map(
(id) =>
JOIN_INTENT_OPTIONS.find((opt) => opt.value === id)?.[
locale === "en" ? "labelEn" : "labelZh"
] || id,
)
.filter(Boolean);
const availLabel =
JOIN_AVAILABILITY_OPTIONS.find((o) => o.value === draft.availability)?.[
locale === "en" ? "labelEn" : "labelZh"
] || draft.availability;
const lookingFor = intentLabels.join(" · ");
const avatar = avatarUrl;
const roster: SocialRosterProfile = {
name,
title: draft.title.trim(),
city: draft.city.trim(),
phone: draft.phone.trim(),
linktree: draft.linktree.trim(),
skills: draft.skills.trim(),
bio: draft.bio.trim(),
avatar,
intents: draft.intents.join(","),
availability: availLabel || draft.availability,
status: draft.status || "online",
lookingFor,
gender: draft.gender,
updatedAt: new Date().toISOString(),
};
try {
saveJson("roster", roster);
saveJson("nick", name);
saveJson("join-profile", draft);
setRosterPublished(true);
await socialApi.saveRoster({
name: roster.name,
title: roster.title,
city: roster.city,
phone: roster.phone,
linktree: roster.linktree,
skills: roster.skills,
bio: roster.bio,
avatar: roster.avatar || "",
gender: draft.gender,
relationship: draft.relationship,
education: draft.education,
graduation: draft.graduation.trim(),
wechat: draft.wechat.trim(),
intents: draft.intents.join(","),
availability: roster.availability || "",
status: roster.status || "online",
lookingFor,
discoverable: "1",
updatedAt: roster.updatedAt || "",
email:
(typeof localStorage !== "undefined"
? localStorage.getItem("userEmail") || ""
: "") || "",
});
} catch {
// Offline / API fail: keep local draft; still mark profile done so UX continues
}
markJoinProfileDone();
void archiveJoinLead("profile_done", {
name: roster.name,
city: roster.city,
avatar: roster.avatar || "",
intents: draft.intents,
});
lock.current = false;
setBusy(false);
onDone();
};
const summaryName = draft.name.trim() || socialTx("你的名字");
const summaryTitle = draft.title.trim() || socialTx("职业待写");
const summaryBio =
draft.bio.trim() || socialTx("自我介绍会出现在这里");
const summaryInitial = (draft.name.trim()[0] || "N").toUpperCase();
const summaryGender =
JOIN_GENDER_OPTIONS.find((opt) => opt.value === draft.gender)?.[
locale === "en" ? "labelEn" : "labelZh"
] || "";
const summaryIntents = draft.intents
.map(
(id) =>
JOIN_INTENT_OPTIONS.find((opt) => opt.value === id)?.[
locale === "en" ? "labelEn" : "labelZh"
] || id,
)
.slice(0, 6);
const filled = [
draft.name,
draft.avatar && !draft.avatar.startsWith("blob:") ? draft.avatar : "",
draft.title,
draft.bio,
draft.intents.length ? "1" : "",
].filter((v) => v.trim()).length;
return (
<section className="social-join-desk">
<aside className="social-join-desk-aside">
<JoinStepMark active={2} />
<header className="social-join-desk-intro">
<h1>{socialTx("完善资料,方便认识你")}</h1>
<p>
{socialTx(
"写得越完整,越容易碰到同频的人。头像请重新上传,不要用别人的照片。",
)}
</p>
</header>
<article className="social-join-live-card" aria-live="polite">
<div className="social-join-live-glow" aria-hidden />
<div className="social-join-live-pattern" aria-hidden>
<Globe2 size={150} strokeWidth={0.55} />
</div>
<div className="social-join-live-top">
<button
type="button"
className="social-join-live-mono"
data-empty={!draft.avatar && !draft.name.trim()}
data-busy={avatarBusy || undefined}
aria-label={socialTx("上传头像")}
onClick={() => avatarInputRef.current?.click()}
>
{draft.avatar ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={draft.avatar} alt="" />
) : (
summaryInitial
)}
<span className="social-join-live-cam" aria-hidden>
<Camera size={14} />
</span>
</button>
<div className="social-join-live-meter" aria-label={socialTx("名片完整度")}>
<span>
{socialTx("名片完整度")} {filled}/5
</span>
<i>
<b style={{ width: `${(filled / 5) * 100}%` }} />
</i>
</div>
</div>
<p className="social-join-live-kicker">{socialTx("实时预览")}</p>
<h2 className="social-join-live-name">{summaryName}</h2>
<p className="social-join-live-title">{summaryTitle}</p>
{summaryGender ? (
<div className="social-join-live-meta">
<span>{summaryGender}</span>
</div>
) : null}
{summaryIntents.length ? (
<div className="social-join-live-tags is-intent">
{summaryIntents.map((item) => (
<span key={item}>{item}</span>
))}
</div>
) : (
<p className="social-join-live-hint">
{socialTx("勾选你想在社区做的事,会出现在这里")}
</p>
)}
<p className="social-join-live-bio">{summaryBio}</p>
<footer>
<span>{socialTx("游民社区")}</span>
<span aria-hidden>✦</span>
</footer>
</article>
</aside>
<form
className="social-form social-join-desk-form"
onSubmit={(event) => void submit(event)}
aria-busy={busy}
>
<input
ref={avatarInputRef}
type="file"
accept="image/jpeg,image/png,image/webp,image/gif"
className="social-join-file-input"
tabIndex={-1}
onChange={(e) => {
const file = e.target.files?.[0] || null;
e.target.value = "";
void onAvatarPick(file);
}}
/>
{/* Mobile native camera — capture=user opens front camera sheet */}
<input
ref={captureInputRef}
type="file"
accept="image/*"
capture="user"
className="social-join-file-input"
tabIndex={-1}
onChange={(e) => {
const file = e.target.files?.[0] || null;
e.target.value = "";
void onAvatarPick(file);
}}
/>
<fieldset disabled={busy} className="social-fieldset social-join-fields">
<p className="social-join-section">{socialTx("基本信息")}</p>
<div
className="social-join-avatar-row social-join-span-2"
data-capture-mode={capture.mode}
data-capture-ready={capture.ready ? "true" : "false"}
data-device={capture.isMobile ? "mobile" : "pc"}
>
<button
type="button"
className={`social-join-avatar-btn${avatarErr ? " is-error" : ""}${avatarBusy ? " is-busy" : ""}`}
disabled={avatarBusy || !capture.ready}
aria-busy={avatarBusy}
aria-invalid={Boolean(avatarErr) || undefined}
onClick={openPrimaryCapture}
>
{draft.avatar ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={draft.avatar} alt="" />
) : (
<Camera size={22} />
)}
{avatarBusy ? (
<span className="social-join-avatar-spin" aria-hidden />
) : null}
</button>
<div>
<strong>{socialTx("头像")}</strong>
<p>{avatarHint}</p>
{avatarErr ? (
<p className="social-join-avatar-err" role="alert">
{avatarErr}
</p>
) : null}
{livenessOn && faceOk && !liveOk ? (
<div className="social-join-liveness-banner" role="status">
<p>
{socialTx(
"头像可以了。再拍张自拍确认本人,就能畅聊、约会。",
)}
</p>
<button
type="button"
className="social-join-avatar-action"
disabled={avatarBusy || capture.mode !== "live-modal"}
onClick={() => setSelfieOpen(true)}
>
{socialTx("开始自拍")}
</button>
</div>
) : null}
{liveOk ? (
<p className="social-join-liveness-ok" role="status">
{socialTx("自拍已通过")}
</p>
) : null}
<div className="social-join-avatar-actions">
<button
type="button"
className="social-join-avatar-action"
disabled={avatarBusy}
onClick={() => avatarInputRef.current?.click()}
>
{faceCheckOn
? socialTx("上传正面照片")
: socialTx("上传头像")}
</button>
{capture.isMobile ? (
<button
type="button"
className="social-join-avatar-action is-ghost"
disabled={avatarBusy}
onClick={() => captureInputRef.current?.click()}
>
{socialTx("手机拍照上传")}
</button>
) : null}
{livenessOn &&
faceOk &&
!liveOk &&
capture.mode === "live-modal" ? (
<button
type="button"
className="social-join-avatar-action is-ghost"
disabled={avatarBusy || !capture.ready}
onClick={() => setSelfieOpen(true)}
>
{socialTx("拍张自拍")}
</button>
) : null}
{draft.avatar && !draft.avatar.startsWith("blob:") ? (
<button
type="button"
className="social-join-avatar-clear"
onClick={() => {
setAvatarErr("");
update("avatar", "");
}}
>
{socialTx("移除头像")}
</button>
) : null}
</div>
</div>
</div>
<label className="social-join-span-2">
{socialTx("怎么称呼你")}
<input
ref={nameRef}
required
maxLength={40}
autoComplete="nickname"
placeholder={socialTx("一个让人记得住的名字")}
value={draft.name}
onChange={(e) => update("name", e.target.value)}
/>
</label>
<div
className="social-join-gender social-join-span-2"
role="group"
aria-label={socialTx("性别")}
>
<span className="social-join-gender-label">
{socialTx("性别")}
<span className="social-join-req">*</span>
</span>
<div className="social-join-gender-pills">
{JOIN_GENDER_OPTIONS.map((opt) => {
const on = draft.gender === opt.value;
return (
<button
key={opt.value}
type="button"
className={`social-join-gender-pill${on ? " is-on" : ""}`}
aria-pressed={on}
onClick={() => update("gender", opt.value)}
>
{locale === "en" ? opt.labelEn : opt.labelZh}
</button>
);
})}
</div>
</div>
<p className="social-join-section">{socialTx("工作与背景")}</p>
<label className="social-join-span-2">
{socialTx("你的职业或专业")}
<input
maxLength={80}
placeholder={socialTx("独立开发者 / 设计师 / 自由撰稿人…")}
value={draft.title}
onChange={(e) => update("title", e.target.value)}
/>
</label>
<p className="social-join-section">
{socialTx("你想在社区做什么")}
<span className="social-join-req">*</span>
</p>
<div
className="social-join-intent-grid social-join-span-2"
role="group"
aria-label={socialTx("你想在社区做什么")}
>
{JOIN_INTENT_OPTIONS.map((opt) => {
const on = draft.intents.includes(opt.value);
return (
<button
key={opt.value}
type="button"
className={`social-join-intent${on ? " is-on" : ""}`}
aria-pressed={on}
onClick={() => toggleIntent(opt.value)}
>
{locale === "en" ? opt.labelEn : opt.labelZh}
</button>
);
})}
</div>
<label className="full social-join-span-2">
{socialTx("自我介绍")}
<textarea
rows={4}
maxLength={600}
placeholder={socialTx("分享经历、兴趣或加入原因,越详细越好")}
value={draft.bio}
onChange={(e) => update("bio", e.target.value)}
/>
<small>{draft.bio.length}/600</small>
</label>
<p className="social-join-section">{socialTx("联系方式(选填)")}</p>
<label>
{socialTx("手机号")}
<input
type="tel"
inputMode="tel"
maxLength={20}
autoComplete="tel"
placeholder={socialTx("方便拉群联络")}
value={draft.phone}
onChange={(e) => update("phone", e.target.value)}
/>
</label>
<label>
{socialTx("微信号")}
<input
maxLength={40}
placeholder={socialTx("选填")}
value={draft.wechat}
onChange={(e) => update("wechat", e.target.value)}
/>
</label>
<label className="social-join-span-2">
{socialTx("作品 / 主页链接(选填)")}
<input
type="url"
maxLength={400}
placeholder="https://"
value={draft.linktree}
onChange={(e) => update("linktree", e.target.value)}
/>
</label>
</fieldset>
{err ? (
<p className="social-join-err" role="alert">
{err}
</p>
) : null}
<div className="social-join-desk-foot">
<button
type="submit"
className="social-btn coral social-join-desk-submit"
disabled={busy || !draft.name.trim()}
>
{busy ? socialTx("保存中…") : socialTx("提交资料,下一步自拍")}
<ArrowUpRight size={15} />
</button>
<p className="social-join-desk-hint">
{socialTx("先保存在这里,联网后会自动同步。")}
</p>
</div>
</form>
{capture.mode === "live-modal" ? (
<AvatarSelfieModal
open={selfieOpen}
onClose={() => setSelfieOpen(false)}
onCaptured={onSelfieChallenge}
/>
) : null}
</section>
);
}
function JoinLivenessForm({ onDone }: { onDone: () => void }) {
const capture = useCaptureCapability();
const [selfieOpen, setSelfieOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [err, setErr] = useState("");
const liveSnap = useSyncExternalStore(
subscribeLivenessState,
getLivenessSnapshot,
getLivenessServerSnapshot,
);
const liveOk =
(JSON.parse(liveSnap) as { livenessStatus?: string }).livenessStatus ===
"verified";
const onSelfieChallenge = async (payload: SelfieCapturePayload) => {
setBusy(true);
setErr("");
try {
const uploaded = await socialApi.uploadAvatarChallenge(
payload.front,
payload.turn,
payload.video,
payload.videoMime,
);
// Do not markFaceOk — album avatar is separate from live audit frames
markLivenessVerified({ videoUrl: uploaded.videoUrl || "" });
void archiveJoinLead("liveness_verified", {
videoUrl: uploaded.videoUrl || "",
frontUrl: uploaded.frontUrl || "",
turnUrl: uploaded.turnUrl || "",
avatarUrl: uploaded.avatarUrl || uploaded.url || "",
storage: uploaded.storage || "",
auditId: uploaded.auditId || "",
});
onDone();
} catch (e) {
const raw =
e instanceof Error ? e.message.slice(0, 160).trim() : "";
setErr(raw ? socialTx(raw) || raw : socialTx("自拍没通过,请再试一次"));
void archiveJoinLead("liveness_failed", { error: raw });
throw e instanceof Error ? e : new Error(socialTx("自拍没通过,请再试一次"));
} finally {
setBusy(false);
}
};
return (
<section className="social-join-desk">
<aside className="social-join-desk-aside">
<JoinStepMark active={3} />
<header className="social-join-desk-intro">
<h1>{socialTx("确认本人")}</h1>
<p>
{socialTx(
"拍张自拍,确认是你。做完就能畅聊、开视频、一起做事。",
)}
</p>
</header>
</aside>
<div className="social-join-desk-form">
{liveOk ? (
<p className="social-join-liveness-ok" role="status">
{socialTx("自拍已通过")}
</p>
) : (
<div className="social-join-liveness-banner" role="status">
<p>
{socialTx(
"请拍张自拍。拍完就能畅聊、开视频、一起做事。",
)}
</p>
<button
type="button"
className="social-join-avatar-action"
disabled={busy || capture.mode !== "live-modal"}
onClick={() => setSelfieOpen(true)}
>
{socialTx("开始自拍")}
</button>
</div>
)}
{err ? (
<p className="social-join-err" role="alert">
{err}
</p>
) : null}
<div className="social-join-desk-foot">
{liveOk ? (
<button
type="button"
className="social-btn coral social-join-desk-submit"
onClick={onDone}
>
{socialTx("进入社区")}
<ArrowUpRight size={15} />
</button>
) : (
<button
type="button"
className="social-btn social-join-desk-submit"
onClick={() => {
// 只记「稍后再自拍」,绝不能写成 join_done / 加入完成
void archiveJoinLead("liveness_skipped");
onDone();
}}
>
{socialTx("稍后再说")}
</button>
)}
</div>
</div>
{capture.mode === "live-modal" ? (
<AvatarSelfieModal
open={selfieOpen}
onClose={() => setSelfieOpen(false)}
onCaptured={onSelfieChallenge}
/>
) : null}
</section>
);
}
export function CommunityJoin() {
const searchParams = useSearchParams();
const router = useRouter();
const stepParam = searchParams.get("step");
const [step, setStep] = useState<JoinStep>(() => stepFromParam(stepParam));
useEffect(() => {
const next = resolveJoinStep(stepParam);
// Bare /join or pay step: no dedicated page — bounce home + open modal.
if (next === "pay") {
flagOpenJoinModalSoon();
router.replace(socialPath("/"));
return;
}
setStep(next);
if (next === "profile") {
void archiveJoinLead("profile_started");
}
// Never invent "paid" here — only /paid (or localhost skip) may markJoinPaid.
if (next === "profile") {
if (stepParam === "profile" && isJoinPaid()) {
// Explicit re-fill — clear done so form is writable
clearJoinProfileDone();
}
if (stepParam !== "profile") {
router.replace(JOIN_PROFILE_RETURN);
}
}
if (next === "liveness" && stepParam !== "liveness") {
router.replace(JOIN_LIVENESS_RETURN);
}
}, [stepParam, router]);
const goLiveness = () => {
setStep("liveness");
router.replace(JOIN_LIVENESS_RETURN);
};
const goDone = () => {
setStep("done");
// 只有真人核验通过才算「加入完成」;跳过自拍停在 liveness_skipped
if (isLivenessVerified()) {
void archiveJoinLead("join_done", { liveness: "verified" });
}
router.replace(`${socialPath("/join")}?step=done`);
};
const focusMode =
step === "profile" || step === "liveness" || step === "done";
const liveSnap = useSyncExternalStore(
subscribeLivenessState,
getLivenessSnapshot,
getLivenessServerSnapshot,
);
const liveOk =
(JSON.parse(liveSnap) as { livenessStatus?: string }).livenessStatus ===
"verified";
// Pay landing removed — redirect handles it; avoid flash of page UI.
if (step === "pay") {
return (
<div className="social-status" style={{ padding: "2rem" }}>
{socialTx("正在打开加入…")}
</div>
);
}
return (
<SiteShell title={socialTx("加入社区")} immersive={focusMode}>
{step === "profile" ? (
<JoinProfileForm onDone={goLiveness} />
) : null}
{step === "liveness" ? (
<JoinLivenessForm onDone={goDone} />
) : null}
{step === "done" ? (
<section className="social-join-desk social-join-desk--done">
<aside className="social-join-desk-aside">
<JoinStepMark active={4} />
<header className="social-join-desk-intro">
<h1>{socialTx("欢迎加入")}</h1>
<p>
{liveOk
? socialTx("自拍已通过,可以畅聊、一起做事了。")
: socialTx(
"资料已保存。拍张自拍后,就能畅聊、开视频、一起做事。",
)}
</p>
</header>
</aside>
<div className="social-join-desk-form social-join-done-panel">
<div className="social-actions">
{liveOk ? (
<Link className="social-btn coral" href={socialPath("/chat")}>
{socialTx("进群聊")}
<ArrowUpRight size={15} />
</Link>
) : (
<Link
className="social-btn coral"
href={JOIN_LIVENESS_RETURN}
>
{socialTx("去拍自拍")}
<ArrowUpRight size={15} />
</Link>
)}
<Link className="social-btn" href={socialPath("/roster")}>
{socialTx("完善介绍")}
<ArrowUpRight size={15} />
</Link>
</div>
</div>
</section>
) : null}
</SiteShell>
);
}
export function CommunityMembership() {
const config = useSocialConfig();
const rawMemFen = Number(config.copy.vipPriceFen);
const memFen =
Number.isFinite(rawMemFen) && rawMemFen >= 0 ? Math.round(rawMemFen) : 0;
const price = (memFen / 100).toLocaleString("zh-CN", {
maximumFractionDigits: 2,
});
const benefits = [
"更好地展示自己的介绍",
"更方便认识想见的人",
"视频见面与同城活动更新提醒",
"找搭子做事时优先沟通",
];
return (
<SiteShell title={socialTx("会员")}>
<PageIntro title={socialTx("会员")} accent={`¥${price}`} />
<section className="social-membership-banner reveal">
<div className="social-page-kicker">
<span />
{socialTx("会员通行证")}
</div>
<h2 className="social-feedback-title">{socialTx("游民会员")}</h2>
<p className="social-muted">
{socialTx("开通后能更方便参与社区。具体权益以支付页说明为准。")}
</p>
<ul className="social-benefit-list">
{benefits.map((item) => (
<li key={item}>
<Check size={15} />
{item}
</li>
))}
</ul>
<div className="social-actions">
{config.flags.payEnabled ? (
<Link className="social-btn coral" href="/vip">
{config.copy.vipCta || "开通会员"}
<ArrowUpRight size={15} />
</Link>
) : (
<span className="social-status">{socialTx("暂时还不能购买")}</span>
)}
<button
type="button"
className="social-btn"
onClick={() => openSocialJoinModal({ reason: "cta" })}
>
{socialTx("去加入社区")}
</button>
</div>
</section>
<div className="social-grid">
{[
{ title: "我的介绍", href: socialPath("/roster") },
{ title: "认识一下", href: socialPath("/date") },
{ title: "城市 / 咖啡馆", href: socialPath("/places") },
{ title: "大家聊天", href: socialPath("/chat") },
].map((item) => (
<Link
className="social-card social-membership-card"
href={item.href}
key={item.href}
>
<Check size={18} />
<h2>{item.title}</h2>
<span>
{socialTx("打开")} <ArrowUpRight size={14} />
</span>
</Link>
))}
</div>
</SiteShell>
);
}