feat(frontend): 控制台 next-intl 中英双语

接入无 URL 前缀的 zh-CN/en,顶栏与外观设置可切换语言;选择写入 cookie 后刷新生效。
This commit is contained in:
ryan
2026-08-16 16:49:16 +08:00
parent 64fbaa7ef1
commit 5a8722ff07
219 changed files with 21437 additions and 5212 deletions
+14 -6
View File
@@ -9,6 +9,7 @@ import {
ShieldQuestion,
} from 'lucide-react';
import { getCapToken } from '@/lib/cap-solver';
import { useTranslations } from 'next-intl';
type CapStatus = 'idle' | 'solving' | 'solved' | 'error';
@@ -38,6 +39,7 @@ export function CapWidget({
const [status, setStatus] = useState<CapStatus>('idle');
const [errorMsg, setErrorMsg] = useState('');
const solving = useRef(false);
const t = useTranslations('auth.capWidget');
const solve = async () => {
if (solving.current) return;
@@ -76,7 +78,9 @@ export function CapWidget({
onClick={() => void solve()}
>
<ShieldQuestion className='size-4 shrink-0 text-muted-foreground' />
<span className='flex-1 text-muted-foreground'>点击开始人机验证</span>
<span className='flex-1 text-muted-foreground'>
{t('clickToStart')}
</span>
</button>
)}
@@ -84,14 +88,16 @@ export function CapWidget({
{status === 'idle' && autoStart && (
<>
<ShieldAlert className='size-4 shrink-0 text-muted-foreground' />
<span className='text-muted-foreground'>等待人机验证…</span>
<span className='text-muted-foreground'>
{t('waitingVerification')}
</span>
</>
)}
{status === 'solving' && (
<>
<Loader2 className='size-4 shrink-0 animate-spin text-primary' />
<span className='text-muted-foreground'>正在完成人机验证…</span>
<span className='text-muted-foreground'>{t('verifying')}</span>
</>
)}
@@ -99,7 +105,7 @@ export function CapWidget({
<>
<CheckCircle2 className='size-4 shrink-0 text-green-500' />
<span className='text-green-600 dark:text-green-400'>
人机验证通过
{t('verificationPassed')}
</span>
<ShieldCheck className='ml-auto size-4 shrink-0 text-green-500' />
</>
@@ -113,9 +119,11 @@ export function CapWidget({
>
<ShieldAlert className='size-4 shrink-0 text-destructive' />
<span className='flex-1 text-destructive'>
{errorMsg || '人机验证失败'}
{errorMsg || t('verificationFailed')}
</span>
<span className='text-xs text-muted-foreground underline'>
{t('retry')}
</span>
<span className='text-xs text-muted-foreground underline'>重试</span>
</button>
)}
</div>
+28 -34
View File
@@ -1,11 +1,12 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useSearchParams } from 'next/navigation';
import { EyeIcon, EyeOffIcon } from 'lucide-react';
import { toast } from 'sonner';
import Link from 'next/link';
import { useTranslations } from 'next-intl';
import { useAuth } from '@/components/providers/auth-provider';
import { Button } from '@/components/ui/button';
@@ -45,6 +46,7 @@ export function LoginForm({
}) {
const searchParams = useSearchParams();
const { setUser } = useAuth();
const t = useTranslations('auth.login');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
@@ -52,7 +54,7 @@ export function LoginForm({
const [showLoginCodeInput, setShowLoginCodeInput] = useState(false);
const [loginCooldown, setLoginCooldown] = useState(0);
const [errorMessage, setErrorMessage] = useState('');
const [loginCodeTip, setLoginCodeTip] = useState<React.ReactNode>(null);
const [loginCodeTip, setLoginCodeTip] = useState<ReactNode>(null);
useEffect(() => {
onOTPStateChange?.(showLoginCodeInput);
@@ -103,22 +105,16 @@ export function LoginForm({
},
onSuccess: (user) => {
setUser(user);
toast.success('登录成功');
toast.success(t('success'));
},
onError: (error: Error) => {
const errorMsg = error.message || '';
if (errorMsg.startsWith('need_email_code:')) {
const emailMasked = errorMsg.substring('need_email_code:'.length);
setLoginCodeTip(
<>
已向您的安全邮箱{' '}
<span className='font-medium text-foreground'>{emailMasked}</span>{' '}
发送了登录验证码。
</>,
);
setLoginCodeTip(t('codeTipMasked', { email: emailMasked }));
setShowLoginCodeInput(true);
setLoginCooldown(60);
toast.success('登录验证码已发送至您的邮箱,请注意查收');
toast.success(t('codeSent'));
if (capEnabled) {
capTokenRef.current = null;
setCapReady(false);
@@ -129,7 +125,7 @@ export function LoginForm({
if (errorMsg.startsWith('smtp_invalid:')) {
const tip = errorMsg.substring('smtp_invalid:'.length);
setLoginCodeTip('请输入您的登录验证码。');
setLoginCodeTip(t('codeTipGeneric'));
setShowLoginCodeInput(true);
setLoginCooldown(0);
toast.warning(tip);
@@ -141,7 +137,7 @@ export function LoginForm({
return;
}
setErrorMessage(errorMsg || '登录失败,请重试');
setErrorMessage(errorMsg || t('failed'));
if (capEnabled) {
capTokenRef.current = null;
setCapReady(false);
@@ -154,17 +150,13 @@ export function LoginForm({
setErrorMessage('');
const trimmedUsername = username.trim();
if (!trimmedUsername || !password) {
toast.error('邮箱/用户名或密码未填写完整', {
description: '请先输入邮箱/用户名和密码后再登录',
toast.error(t('incomplete'), {
description: t('incompleteDesc'),
});
return;
}
if (capEnabled && !capReady) {
toast.error(
capAutoSolve
? '人机验证尚未完成,请稍候…'
: '请先点击「开始验证」完成人机验证',
);
toast.error(capAutoSolve ? t('capPending') : t('capRequired'));
return;
}
loginMutation.mutate({
@@ -189,7 +181,7 @@ export function LoginForm({
const { authorize_url } = await AuthService.getAuthorizeUrl(sourceName);
window.location.href = authorize_url;
} catch (error) {
toast.error(error instanceof Error ? error.message : '第三方登录失败');
toast.error(error instanceof Error ? error.message : t('oauthFailed'));
}
};
@@ -250,21 +242,21 @@ export function LoginForm({
<div className='flex flex-col gap-6 [@media(max-height:700px)]:gap-4'>
<AuthHeading
siteName={publicConfigQuery.data?.site_name}
title='登录到您的账号'
description='欢迎回来,请输入您的账号信息继续。'
title={t('title')}
description={t('description')}
/>
<div className='flex flex-col gap-5 [@media(max-height:700px)]:gap-3'>
<FieldGroup className='gap-4 [@media(max-height:700px)]:gap-3'>
<Field className='gap-1.5'>
<FieldLabel htmlFor='username'>
邮箱或用户名 <span className='text-destructive'>*</span>
{t('username')} <span className='text-destructive'>*</span>
</FieldLabel>
<Input
id='username'
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder='输入邮箱或用户名'
placeholder={t('usernamePlaceholder')}
autoComplete='username'
className='h-10 text-sm [@media(max-height:700px)]:h-9'
onKeyDown={(e) => e.key === 'Enter' && handlePasswordLogin()}
@@ -272,7 +264,7 @@ export function LoginForm({
</Field>
<Field className='gap-1.5'>
<FieldLabel htmlFor='password'>
密码 <span className='text-destructive'>*</span>
{t('password')} <span className='text-destructive'>*</span>
</FieldLabel>
<div className='relative'>
<Input
@@ -280,7 +272,7 @@ export function LoginForm({
value={password}
onChange={(e) => setPassword(e.target.value)}
type={showPassword ? 'text' : 'password'}
placeholder='输入您的密码'
placeholder={t('passwordPlaceholder')}
autoComplete='current-password'
className='h-10 pr-11 text-sm [@media(max-height:700px)]:h-9'
onKeyDown={(e) => e.key === 'Enter' && handlePasswordLogin()}
@@ -289,7 +281,9 @@ export function LoginForm({
type='button'
variant='ghost'
size='icon-sm'
aria-label={showPassword ? '隐藏密码' : '显示密码'}
aria-label={
showPassword ? t('hidePassword') : t('showPassword')
}
className='absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground'
onClick={() => setShowPassword((visible) => !visible)}
>
@@ -325,10 +319,10 @@ export function LoginForm({
{loginMutation.isPending ? (
<>
<Spinner />
登录中...
{t('submitting')}
</>
) : (
'登录'
t('submit')
)}
</Button>
</div>
@@ -337,7 +331,7 @@ export function LoginForm({
<div className='flex flex-col gap-3'>
<div className='flex items-center gap-3'>
<Separator className='flex-1' />
<span className='text-xs text-muted-foreground'>或者使用</span>
<span className='text-xs text-muted-foreground'>{t('orUse')}</span>
<Separator className='flex-1' />
</div>
<div className='grid gap-2'>
@@ -349,7 +343,7 @@ export function LoginForm({
className='h-10 [@media(max-height:700px)]:h-9'
onClick={() => void handleOAuthLogin(source.name)}
>
{source.display_name || source.name} 登录
{t('oauthLogin', { name: source.display_name || source.name })}
</Button>
))}
</div>
@@ -358,12 +352,12 @@ export function LoginForm({
{registrationEnabled && (
<div className='text-center text-sm text-muted-foreground'>
还没有账号?{' '}
{t('noAccount')}{' '}
<Link
href='/register'
className='font-medium text-foreground underline underline-offset-4'
>
立即注册
{t('registerNow')}
</Link>
</div>
)}
+14 -12
View File
@@ -12,6 +12,7 @@ import { Check } from 'lucide-react';
import { AuthService } from '@/lib/services/auth';
import { useAuth } from '@/components/providers/auth-provider';
import { safeRedirectTarget } from '@/lib/utils';
import { useTranslations } from 'next-intl';
/**
* 登录页面组件
@@ -27,6 +28,7 @@ export function LoginPage() {
const router = useRouter();
const searchParams = useSearchParams();
const { user, loading, setUser } = useAuth();
const t = useTranslations('auth.login');
const [showOTP, setShowOTP] = useState(false);
/* 处理OAuth回调 */
@@ -87,9 +89,7 @@ export function LoginPage() {
try {
const result = await AuthService.handleCallback({ state, code });
if (result.status === 'need_bind') {
toast.info(
'您的第三方账号未绑定本地账号,系统已关闭注册。请登录已有本地账号进行绑定。',
);
toast.info(t('needBind'));
setIsProcessingCallback(false);
router.replace('/login');
return;
@@ -98,7 +98,9 @@ export function LoginPage() {
setUser(result.user);
}
setLoginSuccess(true);
toast.success(result.status === 'bound' ? '绑定成功' : '登录成功');
toast.success(
result.status === 'bound' ? t('bindSuccess') : t('success'),
);
setTimeout(() => {
if (!redirectedRef.current) {
@@ -109,7 +111,7 @@ export function LoginPage() {
} catch (error) {
console.error('OAuth callback error:', error);
toast.error(
error instanceof Error ? error.message : '登录失败,请重试',
error instanceof Error ? error.message : t('failed'),
);
setIsProcessingCallback(false);
router.replace('/login');
@@ -117,7 +119,7 @@ export function LoginPage() {
}
};
handleOAuthCallback();
}, [router, searchParams, setUser]);
}, [router, searchParams, setUser, t]);
return (
<AuthShell wide={showOTP}>
@@ -138,10 +140,10 @@ export function LoginPage() {
</div>
<div className='flex flex-col gap-2 text-center'>
<h3 className='font-semibold tracking-tight text-foreground'>
正在检查登录状态
{t('checkingSession')}
</h3>
<p className='text-xs text-muted-foreground'>
请稍候,我们正在确认当前会话...
{t('checkingSessionDesc')}
</p>
</div>
</div>
@@ -157,10 +159,10 @@ export function LoginPage() {
</motion.div>
<div className='flex flex-col gap-2 text-center'>
<h3 className='font-semibold tracking-tight text-foreground'>
登录成功
{t('success')}
</h3>
<p className='text-xs text-muted-foreground'>
正在跳转至控制台...
{t('redirecting')}
</p>
</div>
</div>
@@ -171,10 +173,10 @@ export function LoginPage() {
</div>
<div className='flex flex-col gap-2 text-center'>
<h3 className='font-semibold tracking-tight text-foreground'>
正在验证凭据
{t('verifyingCredentials')}
</h3>
<p className='text-xs text-muted-foreground'>
请稍候,我们正在为您建立安全会话...
{t('establishingSession')}
</p>
</div>
</div>
+11 -9
View File
@@ -1,6 +1,7 @@
'use client';
import * as React from 'react';
import { useTranslations } from 'next-intl';
import { RefreshCwIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -33,12 +34,11 @@ export function OTPForm({
onResend,
onSubmit,
}: OTPFormProps) {
const t = useTranslations('auth.otp');
return (
<div className='flex flex-col gap-6 [@media(max-height:700px)]:gap-4'>
<AuthHeading
title='验证您的登录'
description='输入发送到安全邮箱的 6 位验证码。'
/>
<AuthHeading title={t('title')} description={t('description')} />
{loginCodeTip ? (
<p className='text-sm leading-6 text-muted-foreground'>
{loginCodeTip}
@@ -51,7 +51,7 @@ export function OTPForm({
htmlFor='otp-verification'
className='text-sm font-medium'
>
验证码
{t('code')}
</FieldLabel>
<Button
variant='outline'
@@ -62,7 +62,9 @@ export function OTPForm({
className='h-8 text-xs'
>
<RefreshCwIcon className={cn(isPending && 'animate-spin')} />
{loginCooldown > 0 ? `${loginCooldown}秒后重发` : '重新发送'}
{loginCooldown > 0
? t('resendIn', { seconds: loginCooldown })
: t('resend')}
</Button>
</div>
<div className='flex justify-start'>
@@ -96,15 +98,15 @@ export function OTPForm({
onClick={onSubmit}
disabled={isPending || code.length < 6}
>
{isPending ? '验证中...' : '验证'}
{isPending ? t('submitting') : t('submit')}
</Button>
<div className='text-center text-sm text-muted-foreground'>
遇到登录问题?{' '}
{t('help')}{' '}
<a
href='#'
className='underline underline-offset-4 transition-colors hover:text-primary'
>
联系客服
{t('contactSupport')}
</a>
</div>
</div>
+37 -42
View File
@@ -4,6 +4,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useRouter, useSearchParams } from 'next/navigation';
import { toast } from 'sonner';
import { useTranslations } from 'next-intl';
import Link from 'next/link';
import { useAuth } from '@/components/providers/auth-provider';
@@ -36,6 +37,8 @@ export function RegisterForm() {
const router = useRouter();
const searchParams = useSearchParams();
const { setUser } = useAuth();
const t = useTranslations('auth.register');
const tCommon = useTranslations('common');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [nickname, setNickname] = useState('');
@@ -108,10 +111,10 @@ export function RegisterForm() {
// Redirect to login if registration is closed
useEffect(() => {
if (publicConfigQuery.isSuccess && !registrationEnabled) {
toast.error('系统注册功能已关闭');
toast.error(t('closed'));
router.replace('/login');
}
}, [publicConfigQuery.isSuccess, registrationEnabled, router]);
}, [publicConfigQuery.isSuccess, registrationEnabled, router, t]);
const registerMutation = useMutation({
mutationFn: (req: RegisterRequest) => {
@@ -129,10 +132,10 @@ export function RegisterForm() {
onSuccess: (user) => {
setUser(user);
router.replace(redirectTarget);
toast.success('注册并登录成功');
toast.success(t('success'));
},
onError: (error: Error) => {
setErrorMessage(error.message || '注册失败,请重试');
setErrorMessage(error.message || t('failed'));
if (capEnabled) {
capTokenRef.current = null;
setCapReady(false);
@@ -157,7 +160,7 @@ export function RegisterForm() {
},
onSuccess: () => {
setRegisterCooldown(60);
toast.success('验证码已发送至您的邮箱,请查收');
toast.success(t('codeSent'));
if (capEnabled) {
setCapScope('register');
capTokenRef.current = null;
@@ -166,7 +169,7 @@ export function RegisterForm() {
}
},
onError: (error: Error) => {
toast.error(error.message || '发送验证码失败,请重试');
toast.error(error.message || t('sendCodeFailed'));
if (capEnabled) {
capTokenRef.current = null;
setCapReady(false);
@@ -195,20 +198,16 @@ export function RegisterForm() {
const handleSendRegisterCode = () => {
const trimmedEmail = email.trim();
if (!trimmedEmail) {
toast.error('请先输入邮箱地址');
toast.error(t('emailRequired'));
return;
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(trimmedEmail)) {
toast.error('请输入有效的邮箱地址');
toast.error(t('emailInvalid'));
return;
}
if (capEnabled && capScope === 'send_email_code' && !capReady) {
toast.error(
capAutoSolve
? '人机验证尚未完成,请稍候…'
: '请先点击「开始验证」完成人机验证',
);
toast.error(capAutoSolve ? t('capPending') : t('capRequired'));
return;
}
sendRegisterCodeMutation.mutate(trimmedEmail);
@@ -217,33 +216,29 @@ export function RegisterForm() {
const handleRegister = () => {
setErrorMessage('');
if (!username.trim() || !password) {
toast.error('用户名和密码不能为空');
toast.error(t('usernamePasswordRequired'));
return;
}
if (password.length < 8) {
toast.error('密码长度不能少于 8 位');
toast.error(t('passwordTooShort'));
return;
}
const trimmedEmail = email.trim();
if (!trimmedEmail) {
toast.error('邮箱不能为空');
toast.error(t('emailEmpty'));
return;
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(trimmedEmail)) {
toast.error('请输入有效的邮箱地址');
toast.error(t('emailInvalid'));
return;
}
if (emailRegisterEnabled && !code.trim()) {
toast.error('验证码不能为空');
toast.error(t('codeRequired'));
return;
}
if (capEnabled && capScope === 'register' && !capReady) {
toast.error(
capAutoSolve
? '人机验证尚未完成,请稍候…'
: '请先点击「开始验证」完成人机验证',
);
toast.error(capAutoSolve ? t('capPending') : t('capRequired'));
return;
}
registerMutation.mutate({
@@ -271,21 +266,21 @@ export function RegisterForm() {
<div className='flex flex-col gap-6 [@media(max-height:700px)]:gap-4'>
<AuthHeading
siteName={publicConfigQuery.data?.site_name}
title='创建您的账号'
description='填写以下信息,开始使用平台服务。'
title={t('title')}
description={t('description')}
/>
<div className='flex flex-col gap-5 [@media(max-height:700px)]:gap-3'>
<FieldGroup className='gap-4 [@media(min-width:500px)]:grid [@media(min-width:500px)]:grid-cols-2 [@media(max-height:700px)]:gap-3'>
<Field className='gap-1.5'>
<FieldLabel htmlFor='username'>
用户名 <span className='text-destructive'>*</span>
{t('username')} <span className='text-destructive'>*</span>
</FieldLabel>
<Input
id='username'
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder='请输入用户名'
placeholder={t('usernamePlaceholder')}
autoComplete='username'
className='h-10 text-sm [@media(max-height:700px)]:h-9'
onKeyDown={(e) => e.key === 'Enter' && handleRegister()}
@@ -293,16 +288,16 @@ export function RegisterForm() {
</Field>
<Field className='gap-1.5'>
<FieldLabel htmlFor='nickname'>
昵称
{t('nickname')}
<span className='ml-1 text-xs font-normal text-muted-foreground'>
(可选)
{tCommon('optional')}
</span>
</FieldLabel>
<Input
id='nickname'
value={nickname}
onChange={(e) => setNickname(e.target.value)}
placeholder='请输入昵称'
placeholder={t('nicknamePlaceholder')}
autoComplete='nickname'
className='h-10 text-sm [@media(max-height:700px)]:h-9'
onKeyDown={(e) => e.key === 'Enter' && handleRegister()}
@@ -310,13 +305,13 @@ export function RegisterForm() {
</Field>
<Field className='gap-1.5'>
<FieldLabel htmlFor='email'>
电子邮箱 <span className='text-destructive'>*</span>
{t('email')} <span className='text-destructive'>*</span>
</FieldLabel>
<Input
id='email'
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder='请输入电子邮箱'
placeholder={t('emailPlaceholder')}
autoComplete='email'
className='h-10 text-sm [@media(max-height:700px)]:h-9'
onKeyDown={(e) => e.key === 'Enter' && handleRegister()}
@@ -324,14 +319,14 @@ export function RegisterForm() {
</Field>
<Field className='gap-1.5'>
<FieldLabel htmlFor='password'>
密码 <span className='text-destructive'>*</span>
{t('password')} <span className='text-destructive'>*</span>
</FieldLabel>
<Input
id='password'
value={password}
onChange={(e) => setPassword(e.target.value)}
type='password'
placeholder='请输入密码(至少 8 位)'
placeholder={t('passwordPlaceholder')}
autoComplete='new-password'
className='h-10 text-sm [@media(max-height:700px)]:h-9'
onKeyDown={(e) => e.key === 'Enter' && handleRegister()}
@@ -340,14 +335,14 @@ export function RegisterForm() {
{emailRegisterEnabled && (
<Field className='gap-1.5 [@media(min-width:500px)]:col-span-2'>
<FieldLabel htmlFor='code'>
邮箱验证码 <span className='text-destructive'>*</span>
{t('emailCode')} <span className='text-destructive'>*</span>
</FieldLabel>
<div className='flex gap-2'>
<Input
id='code'
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder='请输入 6 位邮箱验证码'
placeholder={t('emailCodePlaceholder')}
maxLength={6}
className='h-10 flex-1 text-sm [@media(max-height:700px)]:h-9'
onKeyDown={(e) => e.key === 'Enter' && handleRegister()}
@@ -360,8 +355,8 @@ export function RegisterForm() {
className='h-10 w-[120px] text-xs [@media(max-height:700px)]:h-9'
>
{registerCooldown > 0
? `${registerCooldown}秒后重发`
: '获取验证码'}
? t('resendIn', { seconds: registerCooldown })
: t('getCode')}
</Button>
</div>
</Field>
@@ -394,21 +389,21 @@ export function RegisterForm() {
{registerMutation.isPending ? (
<>
<Spinner />
注册中...
{t('submitting')}
</>
) : (
'创建账号'
t('submit')
)}
</Button>
</div>
<div className='text-center text-sm text-muted-foreground'>
已经有账号?{' '}
{t('hasAccount')}{' '}
<Link
href='/login'
className='font-medium text-foreground underline underline-offset-4'
>
返回登录
{t('backToLogin')}
</Link>
</div>
</div>
+3 -1
View File
@@ -5,6 +5,7 @@ import { Loader2 } from 'lucide-react';
import { ErrorPage } from '@/components/layout/error';
import { useUser } from '@/contexts/user-context';
import { useTranslations } from 'next-intl';
type RequireAuthProps = {
children: ReactNode;
@@ -49,6 +50,7 @@ type RequireAdminAuthProps = {
/** Guards admin routes after the shared shell has rendered. */
export function RequireAdminAuth({ children }: RequireAdminAuthProps) {
const { user, loading } = useUser();
const t = useTranslations('auth.requireAuth');
if (loading) {
return (
@@ -59,7 +61,7 @@ export function RequireAdminAuth({ children }: RequireAdminAuthProps) {
}
if (!user?.is_admin) {
return <ErrorPage title='访问被拒绝' message='您没有权限访问此页面' />;
return <ErrorPage title={t('accessDenied')} message={t('noPermission')} />;
}
return <>{children}</>;