's'
This commit is contained in:
@@ -1,9 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useState, useCallback, useEffect } from "react";
|
||||
import { Link, useLocale } from "@/i18n/navigation";
|
||||
import { useTranslation } from "@/i18n/navigation";
|
||||
import JoinModal from "./JoinModal";
|
||||
import {
|
||||
getRecommendedChannel,
|
||||
mustUseWxPay,
|
||||
redirectToPay,
|
||||
getDeviceFromEnv,
|
||||
} from "@/app/lib/payment";
|
||||
import type { PayChannel, PayEnv } from "@/app/lib/payment";
|
||||
|
||||
const MEDIA_NAMES_ZH = ["36氪", "少数派", "极客公园", "虎嗅", "创业邦", "澎湃新闻"];
|
||||
const MEDIA_NAMES_EN = ["36Kr", "sspai", "GeekPark", "Huxiu", "Cyzone", "The Paper"];
|
||||
@@ -30,15 +37,144 @@ const features = [
|
||||
{ icon: "💬", key: "feature5" as const },
|
||||
];
|
||||
|
||||
function isPrivateDevHost(hostname: string): boolean {
|
||||
if (!hostname) return false;
|
||||
if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1") {
|
||||
return true;
|
||||
}
|
||||
if (/^10\./.test(hostname) || /^192\.168\./.test(hostname)) {
|
||||
return true;
|
||||
}
|
||||
const match = hostname.match(/^172\.(\d{1,2})\./);
|
||||
if (!match) return false;
|
||||
const secondOctet = Number(match[1]);
|
||||
return secondOctet >= 16 && secondOctet <= 31;
|
||||
}
|
||||
|
||||
function buildPendingUserId(email: string): string {
|
||||
return (
|
||||
"pending_" +
|
||||
Array.from(new TextEncoder().encode(email))
|
||||
.map((b) => b.toString(16).padStart(2, "0"))
|
||||
.join("")
|
||||
);
|
||||
}
|
||||
|
||||
export default function HeroSection() {
|
||||
const { t: tHero } = useTranslation("hero");
|
||||
const locale = useLocale();
|
||||
const [email, setEmail] = useState("");
|
||||
const [joinModalOpen, setJoinModalOpen] = useState(false);
|
||||
const [joinModalVipOnly, setJoinModalVipOnly] = useState(false);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/auth/me", { credentials: "include" });
|
||||
const data = await res.json();
|
||||
setIsLoggedIn(!!data?.user);
|
||||
} catch {
|
||||
setIsLoggedIn(false);
|
||||
}
|
||||
};
|
||||
checkAuth();
|
||||
const onAuth = () => checkAuth();
|
||||
window.addEventListener("auth:updated", onAuth);
|
||||
return () => window.removeEventListener("auth:updated", onAuth);
|
||||
}, []);
|
||||
|
||||
const handleCheckAndProceed = useCallback(
|
||||
async (em: string) => {
|
||||
if (checking) return;
|
||||
const trimmed = em.trim();
|
||||
if (!trimmed) {
|
||||
setError(locale === "zh" ? "请输入邮箱" : "Please enter your email");
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
setChecking(true);
|
||||
try {
|
||||
const checkRes = await fetch("/api/meetup/check-user", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email: trimmed }),
|
||||
credentials: "include",
|
||||
});
|
||||
const checkData = await checkRes.json();
|
||||
if (!checkRes.ok || !checkData?.ok) {
|
||||
throw new Error(checkData?.error || checkData?.detail || (locale === "zh" ? "操作失败" : "Operation failed"));
|
||||
}
|
||||
if (checkData.exists) {
|
||||
if (checkData.vip) {
|
||||
setJoinModalOpen(true);
|
||||
setJoinModalVipOnly(true);
|
||||
return;
|
||||
}
|
||||
setJoinModalVipOnly(false);
|
||||
setJoinModalOpen(true);
|
||||
return;
|
||||
}
|
||||
// 新用户:支付成功后才创建,用 pending_hex(email) 作为 user_id
|
||||
const shouldPrecreateUser =
|
||||
typeof window !== "undefined" &&
|
||||
isPrivateDevHost(window.location.hostname);
|
||||
let user_id = buildPendingUserId(trimmed);
|
||||
if (shouldPrecreateUser) {
|
||||
const ensureRes = await fetch("/api/meetup/ensure-user", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email: trimmed }),
|
||||
credentials: "include",
|
||||
});
|
||||
const ensureData = await ensureRes.json();
|
||||
if (!ensureRes.ok || !ensureData?.ok || !ensureData?.user_id) {
|
||||
throw new Error(
|
||||
ensureData?.error ||
|
||||
ensureData?.detail ||
|
||||
(locale === "zh" ? "创建用户失败" : "Failed to create user")
|
||||
);
|
||||
}
|
||||
user_id = String(ensureData.user_id).trim();
|
||||
if (ensureData?.token && ensureData?.record) {
|
||||
await fetch("/api/auth/sync-session", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token: ensureData.token, record: ensureData.record }),
|
||||
credentials: "include",
|
||||
});
|
||||
}
|
||||
}
|
||||
const returnUrl =
|
||||
typeof window !== "undefined" ? `${window.location.origin}/${locale}/join/paid` : "/zh/join/paid";
|
||||
const env: PayEnv =
|
||||
typeof window !== "undefined"
|
||||
? navigator.userAgent.includes("MicroMessenger")
|
||||
? "wechat"
|
||||
: "pc"
|
||||
: "pc";
|
||||
const channel: PayChannel = mustUseWxPay(env) ? "wxpay" : getRecommendedChannel(env);
|
||||
redirectToPay({
|
||||
user_id,
|
||||
return_url: returnUrl,
|
||||
channel,
|
||||
device: getDeviceFromEnv(env),
|
||||
useJoinConfig: true,
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "操作失败");
|
||||
} finally {
|
||||
setChecking(false);
|
||||
}
|
||||
},
|
||||
[checking, locale]
|
||||
);
|
||||
|
||||
const handleJoinClick = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setJoinModalOpen(true);
|
||||
handleCheckAndProceed(email);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -146,29 +282,39 @@ export default function HeroSection() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleJoinClick} className="p-4 sm:p-5">
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder={tHero("emailPlaceholder")}
|
||||
className="w-full border border-gray-200 dark:border-gray-700 rounded-lg px-4 py-3 text-sm placeholder-gray-400 dark:placeholder-gray-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-[#ff4d4f]/20 focus:border-[#ff4d4f] transition-colors mb-3"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full bg-[#ff4d4f] hover:bg-[#ff3333] dark:hover:bg-[#ff5c5e] text-white py-3 rounded-lg text-sm font-semibold transition-colors active:scale-[0.98]"
|
||||
>
|
||||
{tHero("ctaJoin")}
|
||||
</button>
|
||||
<p className="text-xs text-gray-400 dark:text-gray-500 text-center mt-3">
|
||||
{locale === "zh" ? "新用户将自动注册,支付成功后需修改默认密码" : "New users auto-register; change default password after payment"}
|
||||
</p>
|
||||
</form>
|
||||
{!isLoggedIn ? (
|
||||
<form onSubmit={handleJoinClick} className="p-4 sm:p-5">
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => { setEmail(e.target.value); setError(null); }}
|
||||
placeholder={tHero("emailPlaceholder")}
|
||||
className="w-full border border-gray-200 dark:border-gray-700 rounded-lg px-4 py-3 text-sm placeholder-gray-400 dark:placeholder-gray-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-[#ff4d4f]/20 focus:border-[#ff4d4f] transition-colors mb-3"
|
||||
/>
|
||||
{error && (
|
||||
<p className="mb-3 text-sm text-red-600 dark:text-red-400">{error}</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={checking}
|
||||
className="w-full bg-[#ff4d4f] hover:bg-[#ff3333] dark:hover:bg-[#ff5c5e] text-white py-3 rounded-lg text-sm font-semibold transition-colors active:scale-[0.98] disabled:opacity-70"
|
||||
>
|
||||
{checking ? (locale === "zh" ? "处理中…" : "Processing…") : tHero("ctaJoin")}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="p-4 sm:p-5 text-center">
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
{locale === "zh" ? "您已登录,可前往社区参与互动" : "You are logged in"}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<JoinModal
|
||||
isOpen={joinModalOpen}
|
||||
onClose={() => setJoinModalOpen(false)}
|
||||
onClose={() => { setJoinModalOpen(false); setJoinModalVipOnly(false); }}
|
||||
initialEmail={email.trim()}
|
||||
vipOnly={joinModalVipOnly}
|
||||
/>
|
||||
|
||||
<div className="mt-4 flex flex-wrap gap-2 justify-center">
|
||||
|
||||
@@ -15,9 +15,11 @@ interface JoinModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
initialEmail?: string;
|
||||
/** 仅登录(已有 VIP 用户验证密码后直接登录,不跳转支付) */
|
||||
vipOnly?: boolean;
|
||||
}
|
||||
|
||||
export default function JoinModal({ isOpen, onClose, initialEmail = "" }: JoinModalProps) {
|
||||
export default function JoinModal({ isOpen, onClose, initialEmail = "", vipOnly = false }: JoinModalProps) {
|
||||
const locale = useLocale();
|
||||
const [email, setEmail] = useState(initialEmail);
|
||||
const [password, setPassword] = useState("");
|
||||
@@ -34,6 +36,7 @@ export default function JoinModal({ isOpen, onClose, initialEmail = "" }: JoinMo
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (loading) return;
|
||||
const em = email.trim();
|
||||
if (!em) {
|
||||
setError(locale === "zh" ? "请输入邮箱" : "Please enter your email");
|
||||
@@ -52,12 +55,21 @@ export default function JoinModal({ isOpen, onClose, initialEmail = "" }: JoinMo
|
||||
if (!res.ok || !data?.ok) {
|
||||
throw new Error(data?.error || (locale === "zh" ? "操作失败" : "Operation failed"));
|
||||
}
|
||||
const { pbSaveAuth } = await import("@/app/lib/pocketbase");
|
||||
pbSaveAuth(data.token, data.record);
|
||||
await fetch("/api/auth/sync-session", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token: data.token, record: data.record }),
|
||||
credentials: "include",
|
||||
});
|
||||
if (typeof window !== "undefined") {
|
||||
window.dispatchEvent(new CustomEvent("auth:updated"));
|
||||
}
|
||||
if (vipOnly) {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
const returnUrl = typeof window !== "undefined" ? `${window.location.origin}/${locale}/join/paid` : "/zh/join/paid";
|
||||
const env: PayEnv = typeof window !== "undefined" ? (navigator.userAgent.includes("MicroMessenger") ? "wechat" : "pc") : "pc";
|
||||
const channel: PayChannel = mustUseWxPay(env) ? "wxpay" : getRecommendedChannel(env);
|
||||
@@ -96,11 +108,8 @@ export default function JoinModal({ isOpen, onClose, initialEmail = "" }: JoinMo
|
||||
</button>
|
||||
|
||||
<h2 className="text-xl font-bold text-gray-800 dark:text-gray-100">
|
||||
{locale === "zh" ? "加入游牧中国" : "Join Nomad China"}
|
||||
{vipOnly ? (locale === "zh" ? "验证密码登录" : "Verify password to login") : (locale === "zh" ? "加入游牧中国" : "Join Nomad China")}
|
||||
</h2>
|
||||
<p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
|
||||
{locale === "zh" ? "新用户将自动注册,老用户请输入密码" : "New users auto-register; existing users enter password"}
|
||||
</p>
|
||||
|
||||
<form onSubmit={handleSubmit} className="mt-6 space-y-4">
|
||||
<div>
|
||||
@@ -118,13 +127,13 @@ export default function JoinModal({ isOpen, onClose, initialEmail = "" }: JoinMo
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
{locale === "zh" ? "密码(老用户必填)" : "Password (required for existing users)"}
|
||||
{locale === "zh" ? "密码" : "Password"}
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => { setPassword(e.target.value); setError(null); }}
|
||||
placeholder={locale === "zh" ? "新用户可留空" : "Leave empty for new users"}
|
||||
placeholder={locale === "zh" ? "请输入密码" : "Enter your password"}
|
||||
className="w-full rounded-lg border border-gray-200 px-4 py-2.5 text-gray-800 placeholder-gray-400 focus:border-[#ff4d4f] focus:outline-none focus:ring-1 focus:ring-[#ff4d4f] dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
@@ -136,13 +145,9 @@ export default function JoinModal({ isOpen, onClose, initialEmail = "" }: JoinMo
|
||||
disabled={loading}
|
||||
className="w-full rounded-lg bg-[#ff4d4f] py-3 font-semibold text-white transition-colors hover:bg-[#ff3333] disabled:opacity-70"
|
||||
>
|
||||
{loading ? (locale === "zh" ? "处理中…" : "Processing…") : (locale === "zh" ? "加入游牧中国 →" : "Join Nomad China →")}
|
||||
{loading ? (locale === "zh" ? "处理中…" : "Processing…") : vipOnly ? (locale === "zh" ? "登录" : "Login") : (locale === "zh" ? "加入游牧中国 →" : "Join Nomad China →")}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="text-xs text-gray-400 dark:text-gray-500 text-center mt-3">
|
||||
{locale === "zh" ? "新用户将自动注册,支付成功后需修改默认密码" : "New users auto-register; change default password after payment"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getNavLinks } from "@/config";
|
||||
import AuthModal from "./AuthModal";
|
||||
import ThemeToggle from "./ThemeToggle";
|
||||
import SiteMenu from "./SiteMenu";
|
||||
import UserAvatar from "./UserAvatar";
|
||||
|
||||
export default function NavbarComponent() {
|
||||
const { t } = useTranslation("common");
|
||||
@@ -18,33 +19,42 @@ export default function NavbarComponent() {
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [authOpen, setAuthOpen] = useState(false);
|
||||
const [userEmail, setUserEmail] = useState<string | null>(null);
|
||||
const [userVip, setUserVip] = useState(false);
|
||||
|
||||
const navLinks = getNavLinks();
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/auth/me", { credentials: "include" });
|
||||
const data = await res.json();
|
||||
if (!mounted) return;
|
||||
if (data?.user && data?.token) {
|
||||
const { pbSaveAuth } = await import("@/app/lib/pocketbase");
|
||||
pbSaveAuth(data.token, { id: data.user.id, email: data.user.email });
|
||||
setUserEmail(data.user.email);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
const fetchAuth = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/auth/me", { credentials: "include", cache: "no-store" });
|
||||
const data = await res.json();
|
||||
if (data?.user && data?.token) {
|
||||
const { pbSaveAuth } = await import("@/app/lib/pocketbase");
|
||||
pbSaveAuth(data.token, { id: data.user.id, email: data.user.email });
|
||||
setUserEmail(data.user.email);
|
||||
setUserVip(!!data.user.vip);
|
||||
return;
|
||||
}
|
||||
if (mounted) setUserEmail(getStoredUserEmail());
|
||||
})();
|
||||
return () => { mounted = false; };
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
setUserEmail(getStoredUserEmail());
|
||||
setUserVip(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAuth();
|
||||
}, [fetchAuth]);
|
||||
|
||||
useEffect(() => {
|
||||
const onAuthUpdated = () => fetchAuth();
|
||||
window.addEventListener("auth:updated", onAuthUpdated);
|
||||
return () => window.removeEventListener("auth:updated", onAuthUpdated);
|
||||
}, [fetchAuth]);
|
||||
|
||||
const handleLogout = useCallback(async () => {
|
||||
await pbLogout();
|
||||
setUserEmail(null);
|
||||
setUserVip(false);
|
||||
}, []);
|
||||
|
||||
const isActive = useCallback((href: string) => {
|
||||
@@ -114,12 +124,7 @@ export default function NavbarComponent() {
|
||||
<span className="hidden sm:block max-w-[120px] truncate text-sm text-gray-600 dark:text-gray-400">
|
||||
{userEmail}
|
||||
</span>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="rounded-full border border-gray-200 dark:border-gray-700 px-2 sm:px-4 py-2 text-xs sm:text-sm font-medium text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors whitespace-nowrap"
|
||||
>
|
||||
{t("logout")}
|
||||
</button>
|
||||
<UserAvatar email={userEmail} isVip={userVip} onLogout={() => { setUserEmail(null); setUserVip(false); }} />
|
||||
</div>
|
||||
) : null}
|
||||
<button
|
||||
@@ -182,10 +187,8 @@ export default function NavbarComponent() {
|
||||
</button>
|
||||
{userEmail ? (
|
||||
<div className="pt-2 border-t border-gray-100 dark:border-gray-800 flex items-center justify-between px-4 py-2.5 rounded-lg bg-gray-50 dark:bg-gray-800">
|
||||
<UserAvatar email={userEmail} isVip={userVip} onLogout={() => { handleLogout(); setMobileOpen(false); }} />
|
||||
<span className="truncate text-sm text-gray-600 dark:text-gray-400">{userEmail}</span>
|
||||
<button onClick={() => { handleLogout(); setMobileOpen(false); }} className="text-sm font-medium text-[#ff4d4f]">
|
||||
{t("logout")}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
66
app/components/UserAvatar.tsx
Normal file
66
app/components/UserAvatar.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useTranslation } from "@/i18n/navigation";
|
||||
import { pbLogout } from "@/app/lib/pocketbase";
|
||||
|
||||
function getAvatarLetter(email: string): string {
|
||||
const local = email.split("@")[0];
|
||||
if (!local) return "?";
|
||||
return local.slice(0, 1).toUpperCase();
|
||||
}
|
||||
|
||||
interface UserAvatarProps {
|
||||
email: string;
|
||||
isVip?: boolean;
|
||||
onLogout?: () => void;
|
||||
}
|
||||
|
||||
/** 圆形头像 + VIP 标识 + 点击展开退出按钮 */
|
||||
export default function UserAvatar({ email, isVip = false, onLogout }: UserAvatarProps) {
|
||||
const { t } = useTranslation("common");
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, []);
|
||||
|
||||
const handleLogout = async () => {
|
||||
await pbLogout();
|
||||
setOpen(false);
|
||||
onLogout?.();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative" ref={ref}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[#ff4d4f] text-sm font-semibold text-white shadow-sm ring-2 ring-white dark:ring-gray-900 hover:bg-[#ff7a45]"
|
||||
aria-label={t("logout")}
|
||||
>
|
||||
{getAvatarLetter(email)}
|
||||
</button>
|
||||
{isVip && (
|
||||
<span className="absolute -top-1 -right-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-amber-500 px-1 text-[10px] font-bold text-white shadow-sm">
|
||||
VIP
|
||||
</span>
|
||||
)}
|
||||
{open && (
|
||||
<div className="absolute right-0 top-full z-50 mt-2 min-w-[120px] rounded-lg border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-800">
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-700"
|
||||
>
|
||||
{t("logout")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user