refactor: remove LocaleSwitcher component and update locale handling

- Removed LocaleSwitcher from NavUser, SiteHeader, and WorkbenchHeader components.
- Updated tests to reflect the removal of LocaleSwitcher.
- Changed default locale from "en-US" to "zh-CN" in i18n configuration.
- Refactored locale resolution logic to read configured locale without relying on browser language detection.
- Updated AgentDesk SDK to support language configuration from public API.
- Cleaned up unused auth options fetching in the auth API.
This commit is contained in:
mlogclub
2026-06-26 14:46:01 +08:00
parent 12d188fc7e
commit f827a7471c
32 changed files with 215 additions and 268 deletions
-4
View File
@@ -1,4 +1,3 @@
import { LocaleSwitcher } from "@/components/locale-switcher"
import { LoginForm } from "@/components/login-form"
import { Suspense } from "react"
@@ -6,9 +5,6 @@ export default function LoginPage() {
return (
<div className="flex min-h-svh flex-col items-center justify-center bg-muted p-6 md:p-10">
<div className="w-full max-w-sm md:max-w-4xl">
<div className="mb-4 flex justify-end">
<LocaleSwitcher />
</div>
<Suspense fallback={<div className="min-h-96" />}>
<LoginForm />
</Suspense>
+1 -3
View File
@@ -3,7 +3,6 @@
import Image from "next/image"
import Link from "next/link"
import { LocaleSwitcher } from "@/components/locale-switcher"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { useAppLocale, useI18n } from "@/i18n/provider"
import enUSMessages from "@/messages/en-US.json"
@@ -39,7 +38,7 @@ export function LegalDocumentPage({ type }: { type: LegalPageType }) {
return (
<main className="min-h-svh bg-muted px-6 py-8 md:px-10">
<div className="mx-auto flex w-full max-w-4xl flex-col gap-6">
<header className="flex items-center justify-between gap-4">
<header className="flex items-center gap-4">
<div className="flex items-center gap-2 font-medium">
<Image
src="/images/logo.svg"
@@ -51,7 +50,6 @@ export function LegalDocumentPage({ type }: { type: LegalPageType }) {
/>
<span>{t("app.brand")}</span>
</div>
<LocaleSwitcher />
</header>
<Card className="bg-card/95">
-42
View File
@@ -1,42 +0,0 @@
"use client"
import { LanguagesIcon } from "lucide-react"
import { useAppLocale, useI18n } from "@/i18n/provider"
import { SUPPORTED_LOCALES, type AppLocale } from "@/i18n/config"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
export function LocaleSwitcher() {
const t = useI18n()
const { locale, setLocale } = useAppLocale()
return (
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant="outline" size="sm" />}
aria-label={t("common.language")}
>
<LanguagesIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40 min-w-40">
<DropdownMenuRadioGroup
value={locale}
onValueChange={(value) => setLocale(value as AppLocale)}
>
{SUPPORTED_LOCALES.map((option) => (
<DropdownMenuRadioItem key={option} value={option}>
{t(`locale.${option}`)}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
)
}
+15 -14
View File
@@ -7,7 +7,8 @@ import { startTransition, useEffect, useState } from "react"
import { toast } from "sonner"
import { useAuth } from "@/components/auth-provider"
import { fetchAuthOptions, loginWithPassword, type AuthOptions } from "@/lib/api/auth"
import { loginWithPassword } from "@/lib/api/auth"
import { fetchPublicConfig, type PublicConfig } from "@/lib/api/config"
import { useI18n } from "@/i18n/provider"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
@@ -40,15 +41,15 @@ export function LoginForm({
const { session } = useAuth()
const [isPending, setIsPending] = useState(false)
const [isWxWorkEnv, setIsWxWorkEnv] = useState(false)
const [authOptions, setAuthOptions] = useState<AuthOptions | null>(null)
const [authOptionsError, setAuthOptionsError] = useState<string | null>(null)
const [publicConfig, setPublicConfig] = useState<PublicConfig | null>(null)
const [publicConfigError, setPublicConfigError] = useState<string | null>(null)
const nextPath = searchParams.get("next")
const wxworkError = searchParams.get("wxworkError")
const oidcError = searchParams.get("oidcError")
const redirectPath =
nextPath && nextPath.startsWith("/") ? nextPath : "/dashboard"
const enabledProviderCount =
Number(authOptions?.wxworkEnabled) + Number(authOptions?.oidcEnabled)
Number(publicConfig?.wxworkEnabled) + Number(publicConfig?.oidcEnabled)
useEffect(() => {
if (session) {
@@ -75,17 +76,17 @@ export function LoginForm({
useEffect(() => {
let cancelled = false
void fetchAuthOptions()
void fetchPublicConfig()
.then((options) => {
if (!cancelled) {
setAuthOptions(options)
setAuthOptionsError(null)
setPublicConfig(options)
setPublicConfigError(null)
}
})
.catch((error) => {
if (!cancelled) {
setAuthOptions(null)
setAuthOptionsError(error instanceof Error ? error.message : "")
setPublicConfig(null)
setPublicConfigError(error instanceof Error ? error.message : "")
}
})
@@ -115,7 +116,7 @@ export function LoginForm({
}
}
if (authOptionsError) {
if (publicConfigError) {
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card className="overflow-hidden p-0">
@@ -124,7 +125,7 @@ export function LoginForm({
<div className="space-y-1">
<h1 className="text-lg font-semibold">{t("auth.optionsLoadFailed")}</h1>
<p className="text-sm text-muted-foreground">
{authOptionsError || t("api.requestFailed")}
{publicConfigError || t("api.requestFailed")}
</p>
</div>
</CardContent>
@@ -133,7 +134,7 @@ export function LoginForm({
)
}
if (!authOptions) {
if (!publicConfig) {
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card className="overflow-hidden p-0">
@@ -206,7 +207,7 @@ export function LoginForm({
enabledProviderCount === 1 ? "grid-cols-1" : "grid-cols-2"
)}
>
{authOptions.wxworkEnabled ? (
{publicConfig.wxworkEnabled ? (
<Button
type="button"
variant="outline"
@@ -228,7 +229,7 @@ export function LoginForm({
<span>{t("auth.wxworkSignIn")}</span>
</Button>
) : null}
{authOptions.oidcEnabled ? (
{publicConfig.oidcEnabled ? (
<Button
type="button"
variant="outline"
-2
View File
@@ -6,7 +6,6 @@ import { useState } from "react"
import { useAuth } from "@/components/auth-provider"
import { useI18n } from "@/i18n/provider"
import { ChangePasswordDialog } from "@/components/change-password-dialog"
import { LocaleSwitcher } from "@/components/locale-switcher"
import { useNotifications } from "@/components/notification-provider"
import { PaletteToggle } from "@/components/palette-toggle"
import { ThemeToggle } from "@/components/theme-toggle"
@@ -104,7 +103,6 @@ export function NavUser({
{t("nav.preferences")}
</DropdownMenuLabel>
<div className="flex items-center gap-2 px-2 pb-2">
<LocaleSwitcher />
<PaletteToggle />
<ThemeToggle />
</div>
+3 -3
View File
@@ -5,10 +5,10 @@ import { describe, it } from "node:test";
const source = await readFile(new URL("./site-header.tsx", import.meta.url), "utf8");
describe("site header preferences", () => {
it("renders locale, palette, and theme controls in the dashboard header", () => {
assert.match(source, /import \{ LocaleSwitcher \} from "@\/components\/locale-switcher"/);
it("renders palette and theme controls without a locale switcher", () => {
assert.doesNotMatch(source, /LocaleSwitcher/);
assert.match(source, /import \{ PaletteToggle \} from "@\/components\/palette-toggle"/);
assert.match(source, /import \{ ThemeToggle \} from "@\/components\/theme-toggle"/);
assert.match(source, /<LocaleSwitcher \/>[\s\S]*<PaletteToggle \/>[\s\S]*<ThemeToggle \/>/);
assert.match(source, /<PaletteToggle \/>[\s\S]*<ThemeToggle \/>/);
});
});
-2
View File
@@ -3,7 +3,6 @@
import { useEffect, useRef } from "react"
import { usePathname } from "next/navigation"
import { LocaleSwitcher } from "@/components/locale-switcher"
import { PaletteToggle } from "@/components/palette-toggle"
import { RealtimeConnectionStatus } from "@/components/realtime-connection-status"
import { ThemeToggle } from "@/components/theme-toggle"
@@ -78,7 +77,6 @@ export function SiteHeader() {
</div>
</div>
<div className="flex shrink-0 items-center justify-end gap-2">
<LocaleSwitcher />
<PaletteToggle />
<ThemeToggle />
</div>
-2
View File
@@ -5,7 +5,6 @@ import { useRouter } from "next/navigation"
import { useState } from "react"
import { ChangePasswordDialog } from "@/components/change-password-dialog"
import { LocaleSwitcher } from "@/components/locale-switcher"
import { PaletteToggle } from "@/components/palette-toggle"
import { RealtimeConnectionStatus } from "@/components/realtime-connection-status"
import { ThemeToggle } from "@/components/theme-toggle"
@@ -36,7 +35,6 @@ export function WorkbenchHeader() {
<div className="hidden sm:block">
<RealtimeConnectionStatus status={realtimeStatus} compact />
</div>
<LocaleSwitcher />
<PaletteToggle />
<ThemeToggle />
<WorkbenchUserMenu />
+7 -22
View File
@@ -25,7 +25,7 @@ async function loadConfig() {
test("normalizes supported locale aliases", async () => {
const { DEFAULT_LOCALE, normalizeLocale } = await loadConfig()
assert.equal(DEFAULT_LOCALE, "en-US")
assert.equal(DEFAULT_LOCALE, "zh-CN")
assert.equal(normalizeLocale("zh-CN"), "zh-CN")
assert.equal(normalizeLocale("zh_CN"), "zh-CN")
assert.equal(normalizeLocale("zh"), "zh-CN")
@@ -35,26 +35,11 @@ test("normalizes supported locale aliases", async () => {
assert.equal(normalizeLocale("fr-FR"), DEFAULT_LOCALE)
})
test("resolves browser locale from stored value before navigator languages", async () => {
const { resolveBrowserLocale } = await loadConfig()
test("reads the configured locale without browser language detection", async () => {
const { configureLocale, readStoredLocale } = await loadConfig()
assert.equal(
resolveBrowserLocale({
storedLocale: "en-US",
navigatorLanguages: ["zh-CN"],
}),
"en-US"
)
})
test("falls back through navigator languages", async () => {
const { resolveBrowserLocale } = await loadConfig()
assert.equal(
resolveBrowserLocale({
storedLocale: "",
navigatorLanguages: ["fr-FR", "en"],
}),
"en-US"
)
assert.equal(readStoredLocale(), "zh-CN")
configureLocale("en-US")
assert.equal(readStoredLocale(), "en-US")
})
+6 -34
View File
@@ -1,8 +1,7 @@
export const SUPPORTED_LOCALES = ["zh-CN", "en-US"] as const
export type AppLocale = (typeof SUPPORTED_LOCALES)[number]
export const DEFAULT_LOCALE: AppLocale = "en-US"
export const LOCALE_STORAGE_KEY = "cs_ai_agent_locale"
export const DEFAULT_LOCALE: AppLocale = "zh-CN"
const LOCALE_ALIASES: Record<string, AppLocale> = {
zh: "zh-CN",
@@ -37,40 +36,13 @@ export function isSupportedLocale(
return SUPPORTED_LOCALES.includes(value as AppLocale)
}
export function resolveBrowserLocale({
storedLocale,
navigatorLanguages,
}: {
storedLocale?: string | null
navigatorLanguages?: readonly string[] | null
}): AppLocale {
if (isSupportedLocale(storedLocale)) {
return storedLocale
}
for (const locale of navigatorLanguages ?? []) {
const normalized = normalizeSupportedLocale(locale)
if (normalized) {
return normalized
}
}
return DEFAULT_LOCALE
}
let configuredLocale: AppLocale = DEFAULT_LOCALE
export function readStoredLocale(): AppLocale {
if (typeof window === "undefined") {
return DEFAULT_LOCALE
}
return resolveBrowserLocale({
storedLocale: window.localStorage.getItem(LOCALE_STORAGE_KEY),
navigatorLanguages: window.navigator.languages,
})
return configuredLocale
}
export function writeStoredLocale(locale: AppLocale) {
if (typeof window === "undefined") {
return
}
window.localStorage.setItem(LOCALE_STORAGE_KEY, locale)
export function configureLocale(locale: string | null | undefined): AppLocale {
configuredLocale = normalizeLocale(locale)
return configuredLocale
}
+21 -13
View File
@@ -12,10 +12,10 @@ import {
import {
DEFAULT_LOCALE,
type AppLocale,
readStoredLocale,
writeStoredLocale,
configureLocale,
} from "@/i18n/config"
import { translateMessage } from "@/i18n/messages"
import { fetchPublicConfig } from "@/lib/api/config"
type LocaleContextValue = {
locale: AppLocale
@@ -34,11 +34,24 @@ export function AppI18nProvider({ children }: { children: ReactNode }) {
const [isLocaleReady, setIsLocaleReady] = useState(false)
useEffect(() => {
const storedLocale = readStoredLocale()
setLocaleState(storedLocale)
document.documentElement.lang = storedLocale
document.title = translateMessage(storedLocale, "app.metadataTitle")
setIsLocaleReady(true)
let cancelled = false
fetchPublicConfig()
.then((config) => configureLocale(config.language))
.catch(() => configureLocale(DEFAULT_LOCALE))
.then((configuredLocale) => {
if (cancelled) {
return
}
setLocaleState(configuredLocale)
document.documentElement.lang = configuredLocale
document.title = translateMessage(configuredLocale, "app.metadataTitle")
setIsLocaleReady(true)
})
return () => {
cancelled = true
}
}, [])
useEffect(() => {
@@ -49,12 +62,7 @@ export function AppI18nProvider({ children }: { children: ReactNode }) {
() => ({
locale,
t: (key, values) => translateMessage(locale, key, values),
setLocale: (nextLocale) => {
setLocaleState(nextLocale)
writeStoredLocale(nextLocale)
document.documentElement.lang = nextLocale
document.title = translateMessage(nextLocale, "app.metadataTitle")
},
setLocale: () => {},
}),
[locale]
)
-11
View File
@@ -6,17 +6,6 @@ export type LoginRequest = {
password: string
}
export type AuthOptions = {
wxworkEnabled: boolean
oidcEnabled: boolean
}
export async function fetchAuthOptions() {
return request<AuthOptions>("/api/auth/options", {
skipAuth: true,
})
}
export async function loginWithPassword(payload: LoginRequest) {
const data = await request<AuthSession>("/api/auth/login", {
method: "POST",
-4
View File
@@ -1,5 +1,4 @@
import { expireSession, readSession } from "@/lib/auth"
import { readStoredLocale } from "@/i18n/config"
import { translateCurrentMessage } from "@/i18n/messages"
const API_BASE_URL =
@@ -50,9 +49,6 @@ function buildRequestHeaders(headers: HeadersInit | undefined, skipAuth?: boolea
) {
authHeaders.set("Content-Type", "application/json")
}
const locale = readStoredLocale()
authHeaders.set("Accept-Language", locale)
authHeaders.set("X-Locale", locale)
return authHeaders
}
+17 -9
View File
@@ -50,14 +50,21 @@ async function loadSdk(config) {
const sandbox = {
URL,
console,
fetch: async () => ({
json: async () => ({
success: true,
data: {
title: "\u5728\u7ebf\u5ba2\u670d",
themeColor: "#2563eb",
},
}),
fetch: async (url) => ({
json: async () =>
String(url).endsWith("/api/config")
? {
success: true,
data: {
language: "en-US",
},
}
: {
success: true,
data: {
themeColor: "#2563eb",
},
},
}),
document: {
body,
@@ -95,7 +102,7 @@ async function loadSdk(config) {
return sandbox
}
async function flushPromises(count = 5) {
async function flushPromises(count = 10) {
for (let i = 0; i < count; i += 1) {
await Promise.resolve()
}
@@ -133,6 +140,7 @@ test("launcher click creates chat iframe with a freshly resolved userToken", asy
)
assert.ok(launcher)
assert.equal(launcher.children.at(-1)?.textContent, "Support")
launcher.click()
await flushPromises()
+52 -24
View File
@@ -7,6 +7,7 @@ import type {
type NormalizedAgentDeskConfig = AgentDeskConfig & {
baseUrl: string
channelId: string
language: string
position: "left" | "right"
themeColor: string
width: string
@@ -38,22 +39,23 @@ type WidgetConfigResponse = {
>>
}
function getWidgetLocale() {
try {
const stored = window.localStorage?.getItem("cs_ai_agent_locale")
const language = stored || document.documentElement.lang || window.navigator?.language || ""
return language.toLowerCase().startsWith("zh") ? "zh-CN" : "en-US"
} catch {
return "en-US"
type PublicConfigResponse = {
success?: boolean
data?: {
language?: string
}
}
function getDefaultWidgetTitle() {
return getWidgetLocale() === "en-US" ? "Support" : "\u5728\u7ebf\u5ba2\u670d"
function normalizeWidgetLanguage(language: string | undefined) {
return String(language || "").toLowerCase().startsWith("en") ? "en-US" : "zh-CN"
}
function getLauncherText() {
return getWidgetLocale() === "en-US" ? "Support" : "\u5ba2\u670d"
function getDefaultWidgetTitle(config?: NormalizedAgentDeskConfig | null) {
return normalizeWidgetLanguage(config?.language) === "en-US" ? "Support" : "\u5728\u7ebf\u5ba2\u670d"
}
function getLauncherText(config?: NormalizedAgentDeskConfig | null) {
return normalizeWidgetLanguage(config?.language) === "en-US" ? "Support" : "\u5ba2\u670d"
}
type FrameMessage =
@@ -65,8 +67,9 @@ type FrameMessage =
(function () {
const DEFAULT_CONFIG: Pick<
NormalizedAgentDeskConfig,
"position" | "themeColor" | "width"
"language" | "position" | "themeColor" | "width"
> = {
language: "zh-CN",
position: "right",
themeColor: "#0f6cbd",
width: "380px",
@@ -103,6 +106,7 @@ type FrameMessage =
delete merged.apiBaseUrl
}
merged.channelId = String(merged.channelId || "")
merged.language = normalizeWidgetLanguage(String(merged.language || "zh-CN"))
if (merged.externalId) {
merged.externalId = String(merged.externalId)
}
@@ -209,6 +213,28 @@ type FrameMessage =
.catch(() => config)
}
function fetchPublicConfig(config: NormalizedAgentDeskConfig) {
const baseUrl = String(config.apiBaseUrl || config.baseUrl || "").replace(/\/$/, "")
if (!baseUrl || typeof fetch !== "function") {
return Promise.resolve(config)
}
return fetch(`${baseUrl}/api/config`, {
method: "GET",
cache: "no-store",
})
.then((response) => response.json() as Promise<PublicConfigResponse>)
.then((payload) => {
if (!payload || payload.success === false) {
return config
}
return normalizeConfig({
...config,
language: payload.data?.language || config.language,
})
})
.catch(() => config)
}
function clearFrameTimers() {
if (state.frameHideTimer) {
window.clearTimeout(state.frameHideTimer)
@@ -369,7 +395,7 @@ type FrameMessage =
state.frame = document.createElement("iframe")
state.frame.dataset.agentDeskWidget = "frame"
state.frame.title = state.config.title || getDefaultWidgetTitle()
state.frame.title = state.config.title || getDefaultWidgetTitle(state.config)
state.frame.src = state.frameUrl.toString()
applyFrameLayout()
state.frame.style.display = "block"
@@ -435,7 +461,7 @@ type FrameMessage =
const text = document.createElement("span")
button.type = "button"
button.dataset.agentDeskWidget = "launcher"
button.setAttribute("aria-label", config.title || getDefaultWidgetTitle())
button.setAttribute("aria-label", config.title || getDefaultWidgetTitle(config))
icon.setAttribute("viewBox", "0 0 24 24")
icon.setAttribute("fill", "none")
icon.setAttribute("stroke", "currentColor")
@@ -451,7 +477,7 @@ type FrameMessage =
path.setAttribute("d", pathData)
icon.appendChild(path)
})
text.textContent = getLauncherText()
text.textContent = getLauncherText(config)
text.style.display = "block"
button.style.position = "fixed"
button.style.bottom = "24px"
@@ -504,15 +530,17 @@ type FrameMessage =
}
state.configLoading = true
fetchWidgetConfig(state.config).then((nextConfig) => {
state.configLoading = false
state.config = normalizeConfig(nextConfig)
if (state.button?.parentNode) {
state.button.parentNode.removeChild(state.button)
state.button = null
}
createLauncher()
})
fetchPublicConfig(state.config)
.then((nextConfig) => fetchWidgetConfig(nextConfig))
.then((nextConfig) => {
state.configLoading = false
state.config = normalizeConfig(nextConfig)
if (state.button?.parentNode) {
state.button.parentNode.removeChild(state.button)
state.button = null
}
createLauncher()
})
}
function destroy() {
+1
View File
@@ -11,6 +11,7 @@ export type AgentDeskConfig = {
getUserToken?: () => string | Promise<string>
title?: string
subtitle?: string
language?: string
position?: "left" | "right"
themeColor?: string
width?: string
File diff suppressed because one or more lines are too long