feat(frontend): add next-intl bilingual i18n for core paths

Wire next-intl without locale routes, add zh-CN/en catalogs, language
switcher, and migrate layout/auth/settings UI copy. Document i18n rules
in AGENTS.md and keep static export builds working.
This commit is contained in:
ryan
2026-07-24 16:25:41 +08:00
parent 9c1369186f
commit 1625cfb2fb
23 changed files with 1638 additions and 355 deletions
+28 -34
View File
@@ -1,6 +1,6 @@
'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';
@@ -19,6 +19,7 @@ import { OTPForm } from './otp-form';
import { AuthService } from '@/lib/services/auth';
import { ConfigService } from '@/lib/services/config';
import type { LoginRequest } from '@/lib/services/auth/types';
import { useTranslations } from 'next-intl';
import { safeRedirectTarget } from '@/lib/utils';
function persistRedirectTarget(
@@ -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>
)}
+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>
+36 -41
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,7 +111,7 @@ 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]);
@@ -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>