Files
monkey-ai-web/src/components/auth/RegisterForm.jsx
T
zhanjunhao b3f4711d20 perf(build): 优化开发预热与首屏分包懒加载
减少应用启动时的静态依赖,增加首屏体积预算与懒加载边界校验。验证通过:875 项单测、UI 依赖审计、ESLint、Prettier、生产构建与首屏产物校验;Chrome 模拟回归通过。
2026-11-20 15:03:30 +08:00

1098 lines
36 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { ArrowRight as ActionArrowRight } from '@/components/common/icons/ActionIcons';
import React, {
useContext,
useEffect,
useRef,
useState,
useCallback,
useMemo,
lazy,
Suspense,
} from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
API,
getLogo,
showError,
showInfo,
showSuccess,
getSystemName,
finishLogin as runLoginFlow,
onDiscordOAuthClicked,
onGitHubOAuthClicked,
onLinuxDOOAuthClicked,
onOIDCClicked,
onWeChatOpenOAuthClicked,
} from '../../helpers';
import Turnstile from 'react-turnstile';
import { Button, Checkbox, Form, Icon, Modal } from '@/components/ui';
import { Text } from '@/components/ui';
import {
IconGithubLogo,
IconMail,
IconUser,
IconLock,
IconKey,
} from '@/components/ui/icons';
import OIDCIcon from '../common/logo/OIDCIcon';
import LinuxDoIcon from '../common/logo/LinuxDoIcon';
import WeChatIcon from '../common/logo/WeChatIcon';
import DiscordIcon from '../common/logo/DiscordIcon';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import { useTranslation } from 'react-i18next';
import AuthBackground from '../common/AuthBackground';
import GlassCard from './GlassCard';
import AuthCardHeader from './AuthCardHeader';
import AuthLoginTabs from './AuthLoginTabs';
import AuthDivider from './AuthDivider';
import { Shield, Smartphone, QrCode } from 'lucide-react';
import AgreementModal from './LazyAgreementModal';
import {
isMiniProgramWebView,
withMiniProgramLogins,
} from '../../helpers/miniProgram';
// 懒加载 Telegram 登录组件(345KB),只在需要时加载
const TelegramLogin = lazy(() => import('./TelegramLogin'));
// 检测是否在微信内浏览器中
const isWeChatBrowser = () => {
const ua = navigator.userAgent.toLowerCase();
return ua.indexOf('micromessenger') !== -1;
};
// 检测是否是移动设备
const isMobileDevice = () => {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent,
);
};
const RegisterForm = () => {
let navigate = useNavigate();
const { t } = useTranslation();
const [inputs, setInputs] = useState({
username: '',
password: '',
password2: '',
email: '',
verification_code: '',
wechat_verification_code: '',
});
const { username, password, password2 } = inputs;
const [, userDispatch] = useContext(UserContext);
const [turnstileEnabled, setTurnstileEnabled] = useState(false);
const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
const [turnstileToken, setTurnstileToken] = useState('');
const [showWeChatLoginModal, setShowWeChatLoginModal] = useState(false);
const [showEmailRegister, setShowEmailRegister] = useState(false);
const [wechatLoading, setWechatLoading] = useState(false);
const [wechatOpenLoading, setWechatOpenLoading] = useState(false);
const [githubLoading, setGithubLoading] = useState(false);
const [discordLoading, setDiscordLoading] = useState(false);
const [oidcLoading, setOidcLoading] = useState(false);
const [linuxdoLoading, setLinuxdoLoading] = useState(false);
const [emailRegisterLoading, setEmailRegisterLoading] = useState(false);
const [registerLoading, setRegisterLoading] = useState(false);
const [verificationCodeLoading, setVerificationCodeLoading] = useState(false);
const [otherRegisterOptionsLoading, setOtherRegisterOptionsLoading] =
useState(false);
const [wechatCodeSubmitLoading, setWechatCodeSubmitLoading] = useState(false);
const [disableButton, setDisableButton] = useState(false);
const [countdown, setCountdown] = useState(30);
const [agreedToTerms, setAgreedToTerms] = useState(false);
const [hasUserAgreement, setHasUserAgreement] = useState(false);
const [hasPrivacyPolicy, setHasPrivacyPolicy] = useState(false);
const [agreementModal, setAgreementModal] = useState({
visible: false,
type: null,
});
const openAgreement = useCallback((e, type) => {
if (e && (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1)) {
return;
}
if (e) e.preventDefault();
setAgreementModal({ visible: true, type });
}, []);
const closeAgreement = useCallback(() => {
setAgreementModal((prev) => ({ ...prev, visible: false }));
}, []);
const [githubButtonText, setGithubButtonText] = useState('使用 GitHub 继续');
const [githubButtonDisabled, setGithubButtonDisabled] = useState(false);
const [showWeChatOpenTipModal, setShowWeChatOpenTipModal] = useState(false);
const githubTimeoutRef = useRef(null);
// 注册表单 / 微信验证码弹窗的表单实例:用于在原逻辑执行前做前端校验
const registerFormApi = useRef(null);
const wechatFormApi = useRef(null);
// 获取验证码前先校验邮箱必填与格式,通过后走原发送逻辑
const sendVerificationCodeWithValidation = async () => {
try {
await registerFormApi.current?.validate(['email']);
} catch {
return;
}
await sendVerificationCode();
};
const submitWeChatCodeWithValidation = async () => {
try {
await wechatFormApi.current?.validate();
} catch {
return;
}
await onSubmitWeChatVerificationCode();
};
const logo = getLogo();
const systemName = getSystemName();
let affCode = new URLSearchParams(window.location.search).get('aff');
if (affCode) {
localStorage.setItem('aff', affCode);
}
// 使用 StatusContext 获取最新状态,而不是从 localStorage 读取
const [statusState] = useContext(StatusContext);
// WeyAi 小程序的 web-view 里只留站内能完成的注册方式(见 helpers/miniProgram.js)。
const status = useMemo(() => {
const raw = statusState?.status || {};
return isMiniProgramWebView() ? withMiniProgramLogins(raw) : raw;
}, [statusState?.status]);
const statusLoaded = statusState?.status !== undefined;
const [showEmailVerification, setShowEmailVerification] = useState(() => {
return status.email_verification ?? false;
});
useEffect(() => {
setShowEmailVerification(status.email_verification);
if (status.turnstile_check) {
setTurnstileEnabled(true);
setTurnstileSiteKey(status.turnstile_site_key);
}
// 从 status 获取用户协议和隐私政策的启用状态
setHasUserAgreement(status.user_agreement_enabled || false);
setHasPrivacyPolicy(status.privacy_policy_enabled || false);
}, [status]);
useEffect(() => {
let countdownInterval = null;
if (disableButton && countdown > 0) {
countdownInterval = setInterval(() => {
setCountdown(countdown - 1);
}, 1000);
} else if (countdown === 0) {
setDisableButton(false);
setCountdown(30);
}
return () => clearInterval(countdownInterval); // Clean up on unmount
}, [disableButton, countdown]);
useEffect(() => {
return () => {
if (githubTimeoutRef.current) {
clearTimeout(githubTimeoutRef.current);
}
};
}, []);
const finishLogin = (data) =>
runLoginFlow({ data, userDispatch, navigate, t });
const onWeChatLoginClicked = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setWechatLoading(true);
setShowWeChatLoginModal(true);
setWechatLoading(false);
};
// 微信开放平台扫码登录
const handleWeChatOpenClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
// 在移动端且不在微信内时,显示提示弹窗
if (isMobileDevice() && !isWeChatBrowser()) {
setShowWeChatOpenTipModal(true);
return;
}
setWechatOpenLoading(true);
try {
onWeChatOpenOAuthClicked(status.wechat_open_app_id);
} finally {
setTimeout(() => setWechatOpenLoading(false), 3000);
}
};
// 强制继续微信扫码登录(用于移动端用户确认后)
const handleForceWeChatOpenLogin = () => {
setShowWeChatOpenTipModal(false);
setWechatOpenLoading(true);
try {
onWeChatOpenOAuthClicked(status.wechat_open_app_id);
} finally {
setTimeout(() => setWechatOpenLoading(false), 3000);
}
};
const onSubmitWeChatVerificationCode = async () => {
if (turnstileEnabled && turnstileToken === '') {
showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setWechatCodeSubmitLoading(true);
try {
const res = await API.get(
`/api/oauth/wechat?code=${inputs.wechat_verification_code}`,
);
const { success, message, data } = res.data;
if (success) {
// Close before finishLogin so the user isn't tempted to re-submit a
// consumed wechat code if session verification fails.
setShowWeChatLoginModal(false);
await finishLogin(data);
} else {
showError(message);
}
} catch (error) {
showError(t('登录失败,请重试'));
} finally {
setWechatCodeSubmitLoading(false);
}
};
function handleChange(name, value) {
setInputs((inputs) => ({ ...inputs, [name]: value }));
}
async function handleSubmit(e) {
if (e) {
e.preventDefault();
}
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
if (password.length < 8) {
showInfo(t('密码长度不得小于 8 位!'));
return;
}
if (password !== password2) {
showInfo(t('两次输入的密码不一致'));
return;
}
if (username && password) {
if (turnstileEnabled && turnstileToken === '') {
showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setRegisterLoading(true);
try {
// 获取邀请码,优先使用 URL 参数,其次使用 localStorage
const finalAffCode = affCode || localStorage.getItem('aff');
// 创建请求数据,不直接修改 state
const requestData = {
...inputs,
aff_code: finalAffCode,
};
const res = await API.post(
`/api/user/register?turnstile=${turnstileToken}`,
requestData,
);
const { success, message } = res.data;
if (success) {
localStorage.setItem('new_user_gift_pending', inputs.username);
navigate('/login');
showSuccess(t('注册成功!'));
} else {
showError(message);
}
} catch (error) {
showError(t('注册失败,请重试'));
} finally {
setRegisterLoading(false);
}
}
}
const sendVerificationCode = async () => {
if (inputs.email === '') return;
if (turnstileEnabled && turnstileToken === '') {
showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setVerificationCodeLoading(true);
try {
const res = await API.get(
`/api/verification?email=${encodeURIComponent(inputs.email)}&turnstile=${turnstileToken}`,
);
const { success, message } = res.data;
if (success) {
showSuccess(t('验证码发送成功,请检查你的邮箱!'));
setDisableButton(true); // 发送成功后禁用按钮,开始倒计时
} else {
showError(message);
}
} catch (error) {
showError(t('发送验证码失败,请重试'));
} finally {
setVerificationCodeLoading(false);
}
};
const handleGitHubClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
if (githubButtonDisabled) {
return;
}
setGithubLoading(true);
setGithubButtonDisabled(true);
setGithubButtonText(t('正在跳转 GitHub...'));
if (githubTimeoutRef.current) {
clearTimeout(githubTimeoutRef.current);
}
githubTimeoutRef.current = setTimeout(() => {
setGithubLoading(false);
setGithubButtonText(t('请求超时,请刷新页面后重新发起 GitHub 登录'));
setGithubButtonDisabled(true);
}, 20000);
try {
onGitHubOAuthClicked(status.github_client_id);
} finally {
setTimeout(() => setGithubLoading(false), 3000);
}
};
const handleDiscordClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setDiscordLoading(true);
try {
onDiscordOAuthClicked(status.discord_client_id);
} finally {
setTimeout(() => setDiscordLoading(false), 3000);
}
};
const handleOIDCClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setOidcLoading(true);
try {
onOIDCClicked(status.oidc_authorization_endpoint, status.oidc_client_id);
} finally {
setTimeout(() => setOidcLoading(false), 3000);
}
};
const handleLinuxDOClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setLinuxdoLoading(true);
try {
onLinuxDOOAuthClicked(status.linuxdo_client_id);
} finally {
setTimeout(() => setLinuxdoLoading(false), 3000);
}
};
const handleEmailRegisterClick = () => {
setEmailRegisterLoading(true);
setShowEmailRegister(true);
setEmailRegisterLoading(false);
};
const handleOtherRegisterOptionsClick = () => {
setOtherRegisterOptionsLoading(true);
setShowEmailRegister(false);
setOtherRegisterOptionsLoading(false);
};
const onTelegramLoginClicked = async (response) => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
const fields = [
'id',
'first_name',
'last_name',
'username',
'photo_url',
'auth_date',
'hash',
'lang',
];
const params = {};
fields.forEach((field) => {
if (response[field]) {
params[field] = response[field];
}
});
try {
const res = await API.get(`/api/oauth/telegram/login`, { params });
const { success, message, data } = res.data;
if (success) {
await finishLogin(data);
} else {
showError(message);
}
} catch (error) {
showError(t('登录失败,请重试'));
}
};
// 第三方注册按钮:与登录页一致的 36px 描边按钮,无位移 / 扫光动效
const OAuthButton = ({
icon,
children,
onClick,
loading,
disabled,
iconColor,
}) => (
<Button
block
className='auth-oauth-button'
onClick={onClick}
loading={loading}
disabled={disabled}
icon={
<span
className='auth-oauth-icon'
style={iconColor ? { color: iconColor } : undefined}
>
{icon}
</span>
}
>
{children}
</Button>
);
const renderOAuthOptions = () => {
return (
<GlassCard>
<AuthCardHeader
logo={logo}
title={systemName}
subtitle={t('创建您的账户')}
/>
<div className='auth-option-list'>
{status.wechat_login && (
<OAuthButton
icon={<Icon svg={<WeChatIcon />} />}
iconColor='#07C160'
onClick={onWeChatLoginClicked}
loading={wechatLoading}
>
{t('使用 微信 继续')}
</OAuthButton>
)}
{status.wechat_open_oauth && (
<OAuthButton
icon={<Icon svg={<WeChatIcon />} />}
iconColor='#07C160'
onClick={handleWeChatOpenClick}
loading={wechatOpenLoading}
>
{t('使用 微信扫码 注册')}
</OAuthButton>
)}
{status.github_oauth && (
<OAuthButton
icon={<IconGithubLogo size='large' />}
onClick={handleGitHubClick}
loading={githubLoading}
disabled={githubButtonDisabled}
>
{t(githubButtonText)}
</OAuthButton>
)}
{status.discord_oauth && (
<OAuthButton
icon={<DiscordIcon />}
iconColor='#5865F2'
onClick={handleDiscordClick}
loading={discordLoading}
>
{t('使用 Discord 继续')}
</OAuthButton>
)}
{status.oidc_enabled && (
<OAuthButton
icon={<OIDCIcon />}
iconColor='#1877F2'
onClick={handleOIDCClick}
loading={oidcLoading}
>
{t('使用 OIDC 继续')}
</OAuthButton>
)}
{status.linuxdo_oauth && (
<OAuthButton
icon={<LinuxDoIcon style={{ width: '20px', height: '20px' }} />}
iconColor='#E95420'
onClick={handleLinuxDOClick}
loading={linuxdoLoading}
>
{t('使用 LinuxDO 继续')}
</OAuthButton>
)}
{status.telegram_oauth && (
<Suspense
fallback={
<div className='flex justify-center my-2 h-10 items-center text-gray-400 text-xs'>
{t('加载中...')}
</div>
}
>
<TelegramLogin
onAuth={onTelegramLoginClicked}
botName={status.telegram_bot_name}
/>
</Suspense>
)}
<AuthDivider>{t('或')}</AuthDivider>
{/* 用户名注册按钮 */}
<Button
theme='solid'
block
className='auth-login-submit'
icon={<IconMail />}
onClick={handleEmailRegisterClick}
disabled={emailRegisterLoading}
>
{t('使用 用户名 注册')}
</Button>
</div>
{(hasUserAgreement || hasPrivacyPolicy) && (
<div className='auth-login-agreement flex justify-center'>
<Checkbox
checked={agreedToTerms}
onChange={(e) => setAgreedToTerms(e.target.checked)}
>
<Text
size='small'
className='text-gray-500 dark:text-gray-400 text-xs'
>
{t('我已阅读并同意')}
{hasUserAgreement && (
<a
href='/user-agreement'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'agreement')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-1 font-medium transition-colors'
>
{t('用户协议')}
</a>
)}
{hasUserAgreement && hasPrivacyPolicy && t('和')}
{hasPrivacyPolicy && (
<a
href='/privacy-policy'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'privacy')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-1 font-medium transition-colors'
>
{t('隐私政策')}
</a>
)}
</Text>
</Checkbox>
</div>
)}
<div className='auth-login-register text-center'>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('已有账户?')}{' '}
<Link
to='/login'
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-semibold transition-colors'
>
{t('登录')}
</Link>
</Text>
</div>
{/* 安全提示 */}
<div className='auth-login-security'>
<Shield size={12} />
<span>{t('安全注册')}</span>
</div>
</GlassCard>
);
};
const renderEmailRegisterForm = () => {
return (
<GlassCard>
<AuthCardHeader
logo={logo}
title={systemName}
subtitle={t('创建您的账户')}
wrapperClassName='mb-4'
logoWrapperClassName='mb-2'
/>
{/* 前端校验通过后才调用原 handleSubmit;其内协议 / 长度 / 一致性判断原样保留 */}
<Form
className='auth-login-form'
getFormApi={(api) => (registerFormApi.current = api)}
onSubmit={() => handleSubmit()}
>
<Form.Input
field='username'
label={t('用户名')}
rules={[{ required: true, message: t('请输入用户名') }]}
placeholder={t('请输入用户名')}
name='username'
autoComplete='username'
onChange={(value) => handleChange('username', value)}
prefix={<IconUser size='small' />}
/>
{/* 密码输入框:长度 8-20 与占位提示、后端约束一致 */}
<Form.Input
field='password'
label={t('密码')}
rules={[
{ required: true, message: t('请输入密码') },
{ min: 8, max: 20, message: t('密码长度需为 8-20 位') },
]}
trigger='blur'
placeholder={t('输入密码,最短 8 位,最长 20 位')}
name='password'
mode='password'
autoComplete='new-password'
onChange={(value) => handleChange('password', value)}
prefix={<IconLock size='small' />}
/>
{/* 确认密码输入框 */}
<Form.Input
field='password2'
label={t('确认密码')}
required
validate={(value, values) => {
if (!value) return t('请输入确认密码');
if (value !== values.password) return t('两次输入的密码不一致');
return '';
}}
trigger='blur'
placeholder={t('确认密码')}
name='password2'
mode='password'
autoComplete='new-password'
onChange={(value) => handleChange('password2', value)}
prefix={<IconLock size='small' />}
/>
{showEmailVerification && (
<>
<Form.Input
field='email'
label={t('邮箱')}
rules={[
{ required: true, message: t('请输入邮箱') },
{
type: 'email',
transform: (v) => v?.trim(),
message: t('邮箱格式不正确'),
},
]}
trigger='blur'
placeholder={t('输入邮箱地址')}
name='email'
type='email'
autoComplete='email'
onChange={(value) => handleChange('email', value)}
prefix={<IconMail size='small' />}
suffix={
<Button
size='small'
onClick={sendVerificationCodeWithValidation}
loading={verificationCodeLoading}
disabled={disableButton || verificationCodeLoading}
className='!rounded-lg'
>
{disableButton
? `${t('重新发送')} (${countdown})`
: t('获取验证码')}
</Button>
}
/>
<Form.Input
field='verification_code'
label={t('验证码')}
rules={[{ required: true, message: t('请输入验证码') }]}
placeholder={t('输入验证码')}
name='verification_code'
onChange={(value) => handleChange('verification_code', value)}
prefix={<IconKey size='small' />}
/>
</>
)}
{(hasUserAgreement || hasPrivacyPolicy) && (
<div className='auth-login-agree-row flex items-center'>
<Checkbox
checked={agreedToTerms}
onChange={(e) => setAgreedToTerms(e.target.checked)}
>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('我已阅读并同意')}
{hasUserAgreement && (
<a
href='/user-agreement'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'agreement')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-0.5 font-medium transition-colors'
>
{t('用户协议')}
</a>
)}
{hasUserAgreement && hasPrivacyPolicy && t('和')}
{hasPrivacyPolicy && (
<a
href='/privacy-policy'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'privacy')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-0.5 font-medium transition-colors'
>
{t('隐私政策')}
</a>
)}
</Text>
</Checkbox>
</div>
)}
<div className='auth-login-actions'>
{/* 注册按钮:提交经表单校验后调用原 handleSubmit,禁用条件不变 */}
<Button
theme='solid'
htmlType='submit'
block
className='auth-login-submit'
loading={registerLoading}
disabled={
registerLoading ||
((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms)
}
>
<span className='font-semibold'>{t('注 册')}</span>
<ActionArrowRight size={16} />
</Button>
</div>
</Form>
{(status.github_oauth ||
status.discord_oauth ||
status.oidc_enabled ||
status.wechat_login ||
status.wechat_open_oauth ||
status.linuxdo_oauth ||
status.telegram_oauth) && (
<div>
<AuthDivider>{t('或')}</AuthDivider>
<Button
block
className='auth-oauth-button'
onClick={handleOtherRegisterOptionsClick}
disabled={otherRegisterOptionsLoading}
>
{t('其他注册选项')}
</Button>
</div>
)}
<div className='auth-login-register text-center'>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('已有账户?')}{' '}
<Link
to='/login'
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-semibold transition-colors'
>
{t('登录')}
</Link>
</Text>
</div>
{/* 安全提示 */}
<div className='auth-login-security'>
<Shield size={12} />
<span>{t('安全注册')}</span>
</div>
</GlassCard>
);
};
// 微信登录模态框
const renderWeChatLoginModal = () => {
const isMobileView = isMobileDevice();
const isInWeChat = isWeChatBrowser();
return (
<Modal
title={
<div className='flex items-center gap-2'>
<div className='w-8 h-8 bg-green-100 dark:bg-green-900/30 rounded-lg flex items-center justify-center'>
<Icon svg={<WeChatIcon />} style={{ color: '#07C160' }} />
</div>
<span>{t('微信扫码登录')}</span>
</div>
}
visible={showWeChatLoginModal}
maskClosable={true}
onOk={submitWeChatCodeWithValidation}
onCancel={() => setShowWeChatLoginModal(false)}
okText={t('登录')}
centered={true}
okButtonProps={{
loading: wechatCodeSubmitLoading,
}}
className='wechat-login-modal auth-login-modal'
>
{/* 移动端提示 */}
{isMobileView && !isInWeChat && (
<div className='mb-4 p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl'>
<div className='flex items-start gap-2'>
<Smartphone
size={18}
className='text-amber-600 dark:text-amber-400 mt-0.5 shrink-0'
/>
<div>
<p className='text-sm text-amber-800 dark:text-amber-200 font-medium'>
{t('移动端登录提示')}
</p>
<p className='text-xs text-amber-600 dark:text-amber-400 mt-1'>
{t(
'请长按保存下方二维码,在微信中扫一扫打开。或使用其他设备的微信扫描二维码。',
)}
</p>
</div>
</div>
</div>
)}
<div className='flex flex-col items-center'>
<div className='relative p-2 bg-white rounded-xl shadow-lg'>
<img
src={status.wechat_qrcode}
alt={t('微信二维码')}
className='rounded-lg'
/>
{/* 移动端可长按保存提示 */}
{isMobileView && (
<div className='absolute -bottom-2 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-gray-900/80 text-white text-[10px] rounded-full whitespace-nowrap'>
{t('长按保存')}
</div>
)}
</div>
</div>
<div className='text-center my-4 px-4'>
<div className='flex items-center justify-center gap-2 mb-2'>
<QrCode size={16} className='text-gray-400' />
<p className='text-gray-600 dark:text-gray-300 text-sm'>
{isMobileView
? t('使用其他设备微信扫码关注公众号')
: t('微信扫码关注公众号')}
</p>
</div>
<p className='text-gray-500 dark:text-gray-400 text-xs'>
{t('输入「验证码」获取验证码(三分钟内有效)')}
</p>
</div>
<Form getFormApi={(api) => (wechatFormApi.current = api)}>
<Form.Input
field='wechat_verification_code'
placeholder={t('请输入验证码')}
label={t('验证码')}
rules={[{ required: true, message: t('请输入验证码') }]}
value={inputs.wechat_verification_code}
onChange={(value) =>
handleChange('wechat_verification_code', value)
}
/>
</Form>
</Modal>
);
};
// 移动端微信扫码登录提示弹窗
const renderWeChatOpenTipModal = () => {
return (
<Modal
title={
<div className='flex items-center gap-2'>
<div className='w-8 h-8 bg-amber-100 dark:bg-amber-900/30 rounded-lg flex items-center justify-center'>
<Smartphone size={18} className='text-amber-600' />
</div>
<span>{t('移动端登录提示')}</span>
</div>
}
visible={showWeChatOpenTipModal}
maskClosable={true}
onCancel={() => setShowWeChatOpenTipModal(false)}
footer={null}
centered={true}
className='wechat-tip-modal'
>
<div className='space-y-4'>
{/* 提示信息 */}
<div className='p-4 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl'>
<p className='text-sm text-amber-800 dark:text-amber-200'>
{t('微信扫码登录功能在移动端体验不佳。建议您:')}
</p>
<ul className='mt-2 space-y-1.5 text-xs text-amber-700 dark:text-amber-300'>
<li className='flex items-start gap-2'>
<span className='w-4 h-4 bg-amber-200 dark:bg-amber-800 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0 mt-0.5'>
1
</span>
<span>{t('使用电脑浏览器打开本页面进行扫码登录')}</span>
</li>
<li className='flex items-start gap-2'>
<span className='w-4 h-4 bg-amber-200 dark:bg-amber-800 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0 mt-0.5'>
2
</span>
<span>{t('或使用用户名密码方式注册')}</span>
</li>
</ul>
</div>
{/* 操作按钮 */}
<div className='flex gap-3'>
<Button
block
onClick={() => {
setShowWeChatOpenTipModal(false);
setShowEmailRegister(true);
}}
className='!rounded-xl !h-10'
>
{t('使用用户名注册')}
</Button>
<Button
block
theme='solid'
type='warning'
onClick={handleForceWeChatOpenLogin}
className='!rounded-xl !h-10'
>
{t('仍然继续')}
</Button>
</div>
</div>
</Modal>
);
};
const renderSkeleton = () => {
return (
<GlassCard withCornerHalos={false} withAurora={false}>
<div className='flex flex-col items-center justify-center mb-5'>
<div className='w-14 h-14 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse mb-3' />
<div className='w-24 h-5 rounded bg-gray-200/60 dark:bg-white/10 animate-pulse mb-1' />
<div className='w-32 h-3 rounded bg-gray-100/80 dark:bg-white/5 animate-pulse' />
</div>
<div className='space-y-2'>
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
</div>
</GlassCard>
);
};
return (
<div
className='auth-login-page relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
// 抵扣 PageLayout 跑马灯占位高度,保证占位+容器恰为一屏,避免幽灵滚动
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
>
<AuthBackground />
<div className='w-full max-w-md z-10 flex flex-col items-center'>
{/* 企业开放自助注册时,注册页与登录页保持同样的「个人/企业」切换(自用模式下无注册入口,不展示) */}
{statusLoaded &&
!status.self_use_mode_enabled &&
status.org_self_register && (
<div className='w-full max-w-sm mb-4'>
<AuthLoginTabs mode='register' active='personal' />
</div>
)}
{!statusLoaded
? renderSkeleton()
: showEmailRegister ||
!(
status.github_oauth ||
status.discord_oauth ||
status.oidc_enabled ||
status.wechat_login ||
status.wechat_open_oauth ||
status.linuxdo_oauth ||
status.telegram_oauth
)
? renderEmailRegisterForm()
: renderOAuthOptions()}
{renderWeChatLoginModal()}
{renderWeChatOpenTipModal()}
{turnstileEnabled && (
<div className='flex justify-center mt-6'>
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => {
setTurnstileToken(token);
}}
/>
</div>
)}
</div>
<AgreementModal
visible={agreementModal.visible}
type={agreementModal.type}
onClose={closeAgreement}
/>
</div>
);
};
export default RegisterForm;