feat: 添加国际化支持,优化语言切换器和登录界面,增强用户体验
Some checks failed
lotteryfront CI / build (push) Has been cancelled

This commit is contained in:
2026-06-29 15:27:37 +08:00
parent 1a43e81fb4
commit ebc6f4d349
8 changed files with 181 additions and 100 deletions

View File

@@ -0,0 +1,25 @@
"use client";
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import { syncPreferredLanguage } from "@/i18n";
const I18nHydrationContext = createContext(false);
/** hydration 完成前保持 DEFAULT_LANGUAGE与 SSR 一致;完成后再同步用户偏好语言。 */
export function I18nHydrationProvider({ children }: { children: ReactNode }) {
const [hydrated, setHydrated] = useState(false);
useEffect(() => {
syncPreferredLanguage();
setHydrated(true);
}, []);
return (
<I18nHydrationContext.Provider value={hydrated}>{children}</I18nHydrationContext.Provider>
);
}
export function useI18nHydrated(): boolean {
return useContext(I18nHydrationContext);
}

View File

@@ -6,8 +6,15 @@ import { ChevronDown, Globe } from "lucide-react";
import { useMemo, useState, type ReactNode } from "react"; import { useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useI18nHydrated } from "@/components/i18n-hydration-provider";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { normalizeLanguage, SUPPORTED_LANGUAGES, type AppLanguage } from "@/i18n"; import zhCommon from "@/i18n/locales/zh/common.json";
import {
DEFAULT_LANGUAGE,
normalizeLanguage,
SUPPORTED_LANGUAGES,
type AppLanguage,
} from "@/i18n";
import { playerViewportPopoverMaxClass } from "@/lib/player-viewport"; import { playerViewportPopoverMaxClass } from "@/lib/player-viewport";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -33,6 +40,7 @@ export function LanguageSwitcher({
const { i18n, t } = useTranslation("common"); const { i18n, t } = useTranslation("common");
const active = normalizeLanguage(i18n.language) as AppLanguage; const active = normalizeLanguage(i18n.language) as AppLanguage;
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const mounted = useI18nHydrated();
const options = useMemo( const options = useMemo(
() => () =>
@@ -49,9 +57,14 @@ export function LanguageSwitcher({
setIsOpen(false); setIsOpen(false);
} }
const currentLabel = useFullLabel const displayLang = mounted ? active : DEFAULT_LANGUAGE;
? (options.find((o) => o.code === active)?.label ?? active.toUpperCase()) const currentLabel = mounted
: (options.find((o) => o.code === active)?.short ?? active.toUpperCase()); ? useFullLabel
? (options.find((o) => o.code === displayLang)?.label ?? displayLang.toUpperCase())
: (options.find((o) => o.code === displayLang)?.short ?? displayLang.toUpperCase())
: useFullLabel
? zhCommon.language[displayLang]
: zhCommon.languageShort[displayLang];
const currentFlag = options.find((o) => o.code === active)?.flag ?? ""; const currentFlag = options.find((o) => o.code === active)?.flag ?? "";
const variantStyles = { const variantStyles = {
@@ -105,7 +118,9 @@ export function LanguageSwitcher({
> >
<Globe className="size-4" aria-hidden /> <Globe className="size-4" aria-hidden />
{showFlag && currentFlag ? <span className="text-base">{currentFlag}</span> : null} {showFlag && currentFlag ? <span className="text-base">{currentFlag}</span> : null}
{showLabel ? <span>{currentLabel}</span> : null} {showLabel ? (
<span suppressHydrationWarning>{currentLabel}</span>
) : null}
<ChevronDown <ChevronDown
className={cn("size-4 transition-transform duration-200", isOpen && "rotate-180")} className={cn("size-4 transition-transform duration-200", isOpen && "rotate-180")}
aria-hidden aria-hidden

View File

@@ -1,7 +1,8 @@
"use client"; "use client";
import { useEffect, type ReactNode } from "react"; import type { ReactNode } from "react";
import { I18nHydrationProvider } from "@/components/i18n-hydration-provider";
import { Toaster } from "@/components/ui/sonner"; import { Toaster } from "@/components/ui/sonner";
import { ErrorProvider } from "@/components/error-provider"; import { ErrorProvider } from "@/components/error-provider";
import { IframeBridge } from "@/components/iframe-bridge"; import { IframeBridge } from "@/components/iframe-bridge";
@@ -9,19 +10,15 @@ import { PlayEffectiveWsListener } from "@/components/play-effective-ws-listener
import { PlayerBalanceWsListener } from "@/components/player-balance-ws-listener"; import { PlayerBalanceWsListener } from "@/components/player-balance-ws-listener";
import { TokenSilentRefresh } from "@/components/token-silent-refresh"; import { TokenSilentRefresh } from "@/components/token-silent-refresh";
import "@/i18n"; import "@/i18n";
import { syncPreferredLanguage } from "@/i18n";
type ProvidersProps = { type ProvidersProps = {
children: ReactNode; children: ReactNode;
}; };
export function Providers({ children }: ProvidersProps): ReactNode { export function Providers({ children }: ProvidersProps): ReactNode {
useEffect(() => {
syncPreferredLanguage();
}, []);
return ( return (
<> <>
<I18nHydrationProvider>
<ErrorProvider> <ErrorProvider>
{/* iframe 通信桥接 - 支持主站嵌入 */} {/* iframe 通信桥接 - 支持主站嵌入 */}
<IframeBridge> <IframeBridge>
@@ -32,6 +29,7 @@ export function Providers({ children }: ProvidersProps): ReactNode {
<TokenSilentRefresh /> <TokenSilentRefresh />
</IframeBridge> </IframeBridge>
</ErrorProvider> </ErrorProvider>
</I18nHydrationProvider>
<Toaster /> <Toaster />
</> </>
); );

View File

@@ -24,22 +24,19 @@ export function EntryHeroBanner({
return ( return (
<div <div
className={cn( className={cn(
"relative shrink-0 overflow-hidden", "relative w-full shrink-0 overflow-hidden lg:hidden",
"h-[36vh] min-h-[168px] max-h-[260px]",
"lg:hidden",
className, className,
)} )}
> >
<div className="pointer-events-none absolute inset-0"> <Image
<Image src={src}
src={src} alt={alt}
alt={alt} width={1228}
fill height={1108}
sizes="100vw" sizes="(max-width: 480px) 100vw, 480px"
className={cn("object-cover object-center", imageClassName)} className={cn("block h-auto w-full", imageClassName)}
priority priority
/> />
</div>
{children} {children}
</div> </div>
); );

View File

@@ -1,6 +1,7 @@
"use client"; "use client";
import type { TFunction } from "i18next"; import type { TFunction } from "i18next";
import Image from "next/image";
import { LanguageSwitcher } from "@/components/language-switcher"; import { LanguageSwitcher } from "@/components/language-switcher";
import { PlayerLoginForm } from "@/features/player/player-login-form"; import { PlayerLoginForm } from "@/features/player/player-login-form";
@@ -20,7 +21,7 @@ type PlayerLoginDesktopProps = {
onSubmit: (event: React.FormEvent) => void; onSubmit: (event: React.FormEvent) => void;
}; };
/** PC 端登录:左右分栏卡片,左侧插画占位。 */ /** PC 端登录:左右分栏卡片,小屏桌面下收紧高度与留白。 */
export function PlayerLoginDesktop({ export function PlayerLoginDesktop({
t, t,
username, username,
@@ -36,7 +37,10 @@ export function PlayerLoginDesktop({
onSubmit, onSubmit,
}: PlayerLoginDesktopProps) { }: PlayerLoginDesktopProps) {
return ( return (
<div className="relative hidden min-h-0 flex-1 overflow-y-auto bg-[#eceef2] lg:flex lg:items-center lg:justify-center lg:px-8 lg:py-10"> <div
className="relative hidden min-h-0 flex-1 overflow-y-auto bg-[#eceef2] lg:flex lg:items-center lg:justify-center lg:px-4 lg:py-4 xl:px-8 xl:py-10"
data-login-desktop-root
>
<div <div
className="pointer-events-none absolute inset-0 opacity-40" className="pointer-events-none absolute inset-0 opacity-40"
aria-hidden aria-hidden
@@ -46,14 +50,26 @@ export function PlayerLoginDesktop({
}} }}
/> />
<div className="relative z-10 flex w-full max-w-[1080px] min-h-[min(640px,88vh)] overflow-hidden rounded-[2rem] bg-white shadow-[0_24px_80px_rgba(15,23,42,0.12)]"> <div
{/* 左侧插画:图片待替换 */} className="relative z-10 flex min-h-[min(560px,calc(100dvh-2rem))] w-full max-w-[960px] overflow-hidden rounded-[1.5rem] bg-white shadow-[0_24px_80px_rgba(15,23,42,0.12)] xl:min-h-[min(640px,88vh)] xl:max-w-[1080px] xl:rounded-[2rem]"
data-login-desktop-card
>
{/* 左侧插画:暂用移动端同款 image1后续可替换 */}
<div <div
className="relative w-[min(46%,400px)] shrink-0 bg-gradient-to-br from-[#e11d1d] via-[#d41818] to-[#b91c1c]" className="relative w-[min(42%,340px)] shrink-0 overflow-hidden bg-[#f8fafc] xl:w-[min(46%,400px)]"
data-login-hero-slot data-login-hero-slot
/> >
<Image
src="/entry/image1.png"
alt=""
fill
sizes="(max-width: 1280px) 340px, 400px"
className="object-cover object-center"
priority
/>
</div>
<div className="flex min-w-0 flex-1 flex-col px-8 py-8 sm:px-10 sm:py-10"> <div className="flex min-w-0 flex-1 flex-col px-6 py-5 xl:px-10 xl:py-10">
<div className="flex justify-end"> <div className="flex justify-end">
<LanguageSwitcher <LanguageSwitcher
variant="pill" variant="pill"
@@ -63,14 +79,7 @@ export function PlayerLoginDesktop({
/> />
</div> </div>
<div className="mx-auto flex w-full max-w-[24rem] flex-1 flex-col justify-center"> <div className="mx-auto flex w-full max-w-[23rem] flex-1 flex-col justify-center xl:max-w-[24rem]">
<h1 className="text-[1.75rem] font-bold tracking-tight text-gray-900">
{t("login.title")}
</h1>
<p className="mt-2 text-sm leading-relaxed text-gray-500">
{t("login.hint")}
</p>
<PlayerLoginForm <PlayerLoginForm
variant="desktop" variant="desktop"
t={t} t={t}

View File

@@ -43,51 +43,47 @@ export function PlayerLoginForm({
const [showPassword, setShowPassword] = useState(false); const [showPassword, setShowPassword] = useState(false);
const isDesktop = variant === "desktop"; const isDesktop = variant === "desktop";
const inputClass = cn( const inputClass =
isDesktop && "h-10 rounded-xl border-gray-200 bg-white shadow-none", "h-10 rounded-xl border-gray-200 bg-white text-base shadow-none";
);
const captchaButtonClass = cn( const captchaButtonClass = cn(
"flex shrink-0 cursor-pointer items-center justify-center overflow-hidden border border-input bg-muted/40 transition-colors hover:bg-muted/60 disabled:pointer-events-none disabled:opacity-50", "flex h-10 min-w-[8.5rem] shrink-0 cursor-pointer items-center justify-center overflow-hidden rounded-xl border border-gray-200 bg-[#f4fbf6] transition-colors hover:bg-[#eaf7ee] disabled:pointer-events-none disabled:opacity-50",
isDesktop
? "h-10 min-w-[8.5rem] rounded-xl border-gray-200 bg-[#f4fbf6]"
: "h-8 min-w-[7.5rem] rounded-lg px-2 text-sm",
); );
return ( return (
<form <form
className={cn("space-y-4", isDesktop ? "mt-8 space-y-5" : "mt-6")} className={cn("space-y-5", isDesktop ? "mt-5 xl:mt-8" : "mt-6")}
onSubmit={onSubmit} onSubmit={onSubmit}
> >
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label htmlFor="login-user">{t("login.username")}</Label> <Label htmlFor="login-user" className="text-gray-700">
{t("login.username")}
</Label>
<div className="relative"> <div className="relative">
{isDesktop ? ( <User
<User className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-gray-400"
className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-gray-400" aria-hidden
aria-hidden />
/>
) : null}
<Input <Input
id="login-user" id="login-user"
value={username} value={username}
onChange={(e) => onUsernameChange(e.target.value)} onChange={(e) => onUsernameChange(e.target.value)}
autoComplete="username" autoComplete="username"
disabled={loading} disabled={loading}
placeholder={isDesktop ? t("login.usernamePlaceholder") : undefined} placeholder={t("login.usernamePlaceholder")}
className={cn(inputClass, isDesktop && "pl-10")} className={cn(inputClass, "pl-10")}
/> />
</div> </div>
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label htmlFor="login-pass">{t("login.password")}</Label> <Label htmlFor="login-pass" className="text-gray-700">
{t("login.password")}
</Label>
<div className="relative"> <div className="relative">
{isDesktop ? ( <Lock
<Lock className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-gray-400"
className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-gray-400" aria-hidden
aria-hidden />
/>
) : null}
<Input <Input
id="login-pass" id="login-pass"
type={showPassword ? "text" : "password"} type={showPassword ? "text" : "password"}
@@ -95,36 +91,34 @@ export function PlayerLoginForm({
onChange={(e) => onPasswordChange(e.target.value)} onChange={(e) => onPasswordChange(e.target.value)}
autoComplete="current-password" autoComplete="current-password"
disabled={loading} disabled={loading}
placeholder={isDesktop ? t("login.passwordPlaceholder") : undefined} placeholder={t("login.passwordPlaceholder")}
className={cn(inputClass, isDesktop && "pr-10 pl-10")} className={cn(inputClass, "pr-10 pl-10")}
/> />
{isDesktop ? ( <button
<button type="button"
type="button" className="absolute top-1/2 right-3 -translate-y-1/2 text-gray-400 transition-colors hover:text-gray-600"
className="absolute top-1/2 right-3 -translate-y-1/2 text-gray-400 transition-colors hover:text-gray-600" onClick={() => setShowPassword((prev) => !prev)}
onClick={() => setShowPassword((prev) => !prev)} aria-label={showPassword ? t("login.hidePassword") : t("login.showPassword")}
aria-label={showPassword ? t("login.hidePassword") : t("login.showPassword")} >
> {showPassword ? (
{showPassword ? ( <EyeOff className="size-4" aria-hidden />
<EyeOff className="size-4" aria-hidden /> ) : (
) : ( <Eye className="size-4" aria-hidden />
<Eye className="size-4" aria-hidden /> )}
)} </button>
</button>
) : null}
</div> </div>
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label htmlFor="login-captcha">{t("login.captcha")}</Label> <Label htmlFor="login-captcha" className="text-gray-700">
{t("login.captcha")}
</Label>
<div className="flex items-stretch gap-3"> <div className="flex items-stretch gap-3">
<div className="relative min-w-0 flex-1"> <div className="relative min-w-0 flex-1">
{isDesktop ? ( <KeyRound
<KeyRound className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-gray-400"
className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-gray-400" aria-hidden
aria-hidden />
/>
) : null}
<Input <Input
id="login-captcha" id="login-captcha"
name="captcha" name="captcha"
@@ -134,7 +128,7 @@ export function PlayerLoginForm({
placeholder={t("login.captchaPlaceholder")} placeholder={t("login.captchaPlaceholder")}
maxLength={32} maxLength={32}
disabled={loading} disabled={loading}
className={cn(inputClass, isDesktop && "pl-10")} className={cn(inputClass, "pl-10")}
/> />
</div> </div>
<button <button
@@ -162,10 +156,7 @@ export function PlayerLoginForm({
<Button <Button
type="submit" type="submit"
className={cn( className="mt-1 h-11 w-full rounded-xl bg-red-600 text-base font-medium hover:bg-red-700"
"w-full bg-red-600 hover:bg-red-700",
isDesktop && "mt-2 h-11 rounded-xl text-base font-medium",
)}
disabled={loading} disabled={loading}
> >
{loading ? <Loader2 className="mr-2 size-4 animate-spin" /> : null} {loading ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}

View File

@@ -3,6 +3,8 @@
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useHydrationSafeEntryT } from "@/i18n/hydration-t";
import { toast } from "sonner"; import { toast } from "sonner";
import { getPlayerMe } from "@/api/player"; import { getPlayerMe } from "@/api/player";
@@ -30,7 +32,8 @@ function stripSearchParamFromBrowserUrl(name: string): void {
} }
export function PlayerLoginScreen(): React.ReactElement { export function PlayerLoginScreen(): React.ReactElement {
const { t } = useTranslation("entry"); const { t: tErrors } = useTranslation("entry");
const t = useHydrationSafeEntryT();
const tRef = useRef(t); const tRef = useRef(t);
useEffect(() => { useEffect(() => {
tRef.current = t; tRef.current = t;
@@ -87,9 +90,9 @@ export function PlayerLoginScreen(): React.ReactElement {
sessionExpiredHandled.current = true; sessionExpiredHandled.current = true;
clearBearerToken(); clearBearerToken();
toast.error(t("errors.sessionExpired")); toast.error(tErrors("errors.sessionExpired"));
stripSearchParamFromBrowserUrl("session"); stripSearchParamFromBrowserUrl("session");
}, [clearBearerToken, searchParams, t]); }, [clearBearerToken, searchParams, tErrors]);
async function handleSubmit(event: React.FormEvent): Promise<void> { async function handleSubmit(event: React.FormEvent): Promise<void> {
event.preventDefault(); event.preventDefault();
@@ -173,11 +176,8 @@ export function PlayerLoginScreen(): React.ReactElement {
</div> </div>
</EntryHeroBanner> </EntryHeroBanner>
<div className="mx-auto flex w-full max-w-md flex-1 flex-col px-4 py-8"> <div className="mx-auto flex w-full max-w-md flex-1 flex-col px-5 py-6">
<div className="w-full max-w-md"> <div className="w-full rounded-2xl bg-white px-1 py-2">
<h1 className="text-xl font-bold text-gray-900">{t("login.title")}</h1>
<p className="mt-2 text-sm text-muted-foreground">{t("login.hint")}</p>
<PlayerLoginForm variant="mobile" {...formProps} /> <PlayerLoginForm variant="mobile" {...formProps} />
</div> </div>
</div> </div>

46
src/i18n/hydration-t.ts Normal file
View File

@@ -0,0 +1,46 @@
"use client";
import type { TFunction } from "i18next";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useI18nHydrated } from "@/components/i18n-hydration-provider";
import { DEFAULT_LANGUAGE, type AppLanguage } from "@/i18n/language";
import enEntry from "@/i18n/locales/en/entry.json";
import neEntry from "@/i18n/locales/ne/entry.json";
import zhEntry from "@/i18n/locales/zh/entry.json";
const STATIC_ENTRY: Record<AppLanguage, typeof zhEntry> = {
zh: zhEntry,
en: enEntry,
ne: neEntry,
};
function getStaticValue(obj: Record<string, unknown>, key: string): string {
const parts = key.split(".");
let cur: unknown = obj;
for (const part of parts) {
if (cur == null || typeof cur !== "object") return key;
cur = (cur as Record<string, unknown>)[part];
}
return typeof cur === "string" ? cur : key;
}
function createStaticEntryT(): TFunction<"entry"> {
const fn = ((key: string) =>
getStaticValue(STATIC_ENTRY[DEFAULT_LANGUAGE] as Record<string, unknown>, key)) as TFunction<
"entry"
>;
return fn;
}
/** entry 命名空间hydration 前固定 DEFAULT_LANGUAGE 文案,避免 SSR/客户端首屏不一致。 */
export function useHydrationSafeEntryT(): TFunction<"entry"> {
const hydrated = useI18nHydrated();
const { t } = useTranslation("entry");
return useMemo(
() => (hydrated ? t : createStaticEntryT()),
[hydrated, t],
);
}