Skip to content

Commit c0cded8

Browse files
committed
fix(ui): make UI language change consistent (#2185)
1 parent bb6cbee commit c0cded8

113 files changed

Lines changed: 1742 additions & 749 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.roo/rules-translate/001-general-rules.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,10 @@
3030
# 4. WEBVIEW UI LOCALIZATION (webview-ui/src/)
3131

3232
- Located in webview-ui/src/i18n/locales/
33-
- Uses standard React i18next patterns with the useTranslation hook
33+
- Use `useAppTranslation` from `@src/i18n/TranslationContext`, not react-i18next's `useTranslation` (ESLint enforces this). It returns `{ t, language }`; switching languages belongs to the provider, so the i18next instance is not exposed:
34+
- Always write fully qualified keys (`t("chat:about")`)
35+
- Always pass that `t` to `Trans` (`<Trans t={t} i18nKey="..." />`); `Trans` does not follow language changes on its own (ESLint enforces this)
36+
- Never use the global `t` from `i18next` (`i18next.t`); memoized output would keep showing the previous language after a switch (ESLint enforces this). Pass `t` (and `language` for dates) to helpers instead, as `utils/format.ts` and `utils/validate.ts` do
3437
- All user interface strings should be internationalized
3538
- Always use the Trans component with named components for text with embedded components
3639

@@ -40,6 +43,7 @@
4043

4144
```
4245
<Trans
46+
t={t}
4347
i18nKey="welcome:telemetry.changeSettings"
4448
components={{
4549
settingsLink: <VSCodeLink href="#" onClick={handleOpenSettings} />

‎.roo/skills/roo-translation/SKILL.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,10 @@ This guidance file is loaded at runtime and should be consulted for the latest b
7070
## WebView UI Localization (webview-ui/src/)
7171

7272
- Located in `webview-ui/src/i18n/locales/`
73-
- Uses standard React i18next patterns with the `useTranslation` hook
73+
- Use `useAppTranslation` from `@src/i18n/TranslationContext`, not react-i18next's `useTranslation` (ESLint enforces this). It returns `{ t, language }`; switching languages belongs to the provider, so the i18next instance is not exposed:
74+
- Always write fully qualified keys (`t("chat:about")`)
75+
- Always pass that `t` to `Trans` (`<Trans t={t} i18nKey="..." />`); `Trans` does not follow language changes on its own (ESLint enforces this)
76+
- Never use the global `t` from `i18next` (`i18next.t`); memoized output would keep showing the previous language after a switch (ESLint enforces this). Pass `t` (and `language` for dates) to helpers instead, as `utils/format.ts` and `utils/validate.ts` do
7477
- All user interface strings should be internationalized
7578
- Always use the `Trans` component with named components for text with embedded components
7679

@@ -86,6 +89,7 @@ React component usage:
8689

8790
```tsx
8891
<Trans
92+
t={t}
8993
i18nKey="welcome:telemetry.changeSettings"
9094
components={{
9195
settingsLink: <VSCodeLink href="#" onClick={handleOpenSettings} />,
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Guards that keep translated output in step with a language switch. Built-in no-restricted-syntax only.
2+
// Translations must come from the component's `t` (webview-ui's `useAppTranslation`), which changes identity
3+
// on a language switch; the global instance's `t` gives React (and React Compiler caches) nothing to
4+
// invalidate on, so memoized output would keep the previous language.
5+
6+
// Selectors cannot follow bindings, so the instance is recognised by name: a default import or
7+
// `useTranslation().i18n` held as `i18n`/`i18next`. The aliasing selectors below keep it under those names.
8+
// Passing the instance as an argument and reading `.t` from the parameter is not caught.
9+
const i18nInstanceName = "/^(i18n|i18next)$/"
10+
const i18nInstance = `:matches([name=${i18nInstanceName}], MemberExpression[property.name=${i18nInstanceName}])`
11+
12+
// i18next itself and modules that re-export its instance as their default (webview-ui's i18n/setup).
13+
const i18nInstanceSource = "/^(i18next|(.*\\/)?i18n\\/setup|\\.\\.?\\/setup)$/"
14+
15+
const globalTMessage = "Use t from useAppTranslation so memoized output follows language changes."
16+
const aliasMessage =
17+
"Keep the i18next instance named i18n or i18next: the global-t check recognises it by name, so an alias hides i18n.t."
18+
19+
export const i18nLanguageSwitchSelectors = [
20+
{
21+
// Global t read off the instance: i18next.t(...), i18n?.t(...), i18next["t"], useTranslation().i18n.t.
22+
selector: `MemberExpression:matches([property.name='t'][computed=false], [property.value='t']):has(> ${i18nInstance}.object)`,
23+
message: globalTMessage,
24+
},
25+
{
26+
// Global t destructured from the instance: const { t } = i18next, const { t: translate } = i18n.
27+
// Other properties stay allowed: const { language } = i18next.
28+
selector: `VariableDeclarator:has(> ${i18nInstance}.init) > ObjectPattern > Property[key.name='t']`,
29+
message: globalTMessage,
30+
},
31+
{
32+
// Default import under another name: import lang from "i18next", import { default as lang } from "@/i18n/setup".
33+
// Named imports such as initReactI18next or `type TFunction` are other specifiers and are not matched.
34+
selector: `ImportDeclaration[source.value=${i18nInstanceSource}] > :matches(ImportDefaultSpecifier, ImportSpecifier[imported.name='default']):not([local.name=${i18nInstanceName}])`,
35+
message: aliasMessage,
36+
},
37+
{
38+
// Namespace import: import * as lang from "i18next" exposes the instance's t as lang.t whatever lang is called.
39+
selector: `ImportDeclaration[source.value=${i18nInstanceSource}] > ImportNamespaceSpecifier`,
40+
message: aliasMessage,
41+
},
42+
{
43+
// Re-export under another name: export { default as lang } from "i18next" lets importers alias it unseen.
44+
selector: `ExportNamedDeclaration[source.value=${i18nInstanceSource}] > ExportSpecifier[local.name='default']:not([exported.name=${i18nInstanceName}])`,
45+
message: aliasMessage,
46+
},
47+
{
48+
// Variable alias: const lang = i18next, const lang = useTranslation().i18n.
49+
// Keeping the name is fine (const i18n = useTranslation().i18n); calls such as i18next.createInstance() are not
50+
// the instance itself and are not matched.
51+
selector: `VariableDeclarator[id.type='Identifier']:not([id.name=${i18nInstanceName}]):has(> ${i18nInstance}.init)`,
52+
message: aliasMessage,
53+
},
54+
{
55+
// Assignment alias to an existing variable: lang = i18n.
56+
selector: `AssignmentExpression:not([left.name=${i18nInstanceName}]):has(> ${i18nInstance}.right)`,
57+
message: aliasMessage,
58+
},
59+
{
60+
// Destructuring rename, in declarations and parameters: const { i18n: lang } = useTranslation(),
61+
// ({ i18n: lang }) => ..., and a nested pattern such as const { i18n: { t } } = useTranslation().
62+
// The shorthand const { i18n } = useTranslation() keeps the name and is allowed.
63+
selector: `ObjectPattern > Property[key.name=${i18nInstanceName}]:not([value.name=${i18nInstanceName}])`,
64+
message: aliasMessage,
65+
},
66+
{
67+
// <Trans> without its own t={t}: it reads the global instance, so a memoized element keeps the old language.
68+
// Direct child only: <Trans components={{ b: <Foo t={1} /> }} /> is allowed.
69+
selector: "JSXOpeningElement[name.name='Trans']:not(:has(> JSXAttribute[name.name='t']))",
70+
message:
71+
"Pass t={t} from useAppTranslation: Trans does not subscribe to language changes, so a cached <Trans> keeps the previous language.",
72+
},
73+
]
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import assert from "node:assert/strict"
2+
import { describe, it } from "node:test"
3+
4+
import { Linter } from "eslint"
5+
import typescriptEslint from "typescript-eslint"
6+
7+
import { i18nLanguageSwitchSelectors } from "./i18n-language-switch.js"
8+
9+
const linter = new Linter({ configType: "flat" })
10+
const config = [
11+
{
12+
files: ["**/*.tsx"],
13+
languageOptions: { parser: typescriptEslint.parser, parserOptions: { ecmaFeatures: { jsx: true } } },
14+
rules: { "no-restricted-syntax": ["error", ...i18nLanguageSwitchSelectors] },
15+
},
16+
]
17+
18+
const lint = (code) => linter.verify(code, config, { filename: "example.tsx" }).map((message) => message.message)
19+
20+
describe("i18n language switch: global t", () => {
21+
for (const code of [
22+
'i18next.t("chat:about")',
23+
'import i18n from "i18next"\ni18n.t("chat:about")',
24+
'i18n?.t("chat:about")',
25+
'i18next["t"]("chat:about")',
26+
'useTranslation().i18n.t("chat:about")',
27+
"const { t } = i18next",
28+
"const { t: translate } = i18n",
29+
"const { t } = useTranslation().i18n",
30+
]) {
31+
it(`flags: ${code}`, () => {
32+
assert.equal(lint(code).length, 1)
33+
})
34+
}
35+
36+
for (const code of [
37+
'const { t } = useTranslation()\nt("chat:about")',
38+
'i18next.changeLanguage("es")',
39+
"i18n.language",
40+
"i18next[t]",
41+
"const { language } = i18n",
42+
'other.t("chat:about")',
43+
]) {
44+
it(`allows: ${code}`, () => {
45+
assert.deepEqual(lint(code), [])
46+
})
47+
}
48+
})
49+
50+
describe("i18n language switch: aliasing the instance", () => {
51+
for (const code of [
52+
'import lang from "i18next"',
53+
'import { default as lang } from "i18next"',
54+
'import * as lang from "i18next"',
55+
'import lang from "@src/i18n/setup"',
56+
'import lang from "@/i18n/setup"',
57+
'import lang from "../setup"',
58+
'export { default as lang } from "i18next"',
59+
"const lang = i18next",
60+
"const lang = useTranslation().i18n",
61+
"lang = i18n",
62+
"const { i18n: lang } = useTranslation()",
63+
"const { i18n: { t } } = useTranslation()",
64+
"function Foo({ i18n: lang }) {}",
65+
]) {
66+
it(`flags: ${code}`, () => {
67+
assert.equal(lint(code).length, 1)
68+
})
69+
}
70+
71+
for (const code of [
72+
'import i18next from "i18next"',
73+
'import i18n from "i18next"',
74+
'import i18next, { type TFunction } from "i18next"',
75+
'import { initReactI18next } from "react-i18next"',
76+
'import i18next from "@src/i18n/setup"',
77+
'import { default as i18next } from "i18next"',
78+
'import config from "./config"',
79+
"const i18n = useTranslation().i18n",
80+
"const { i18n } = useTranslation()",
81+
"const { language } = i18next",
82+
"const instance = i18next.createInstance()",
83+
"changeLanguage(i18next)",
84+
]) {
85+
it(`allows: ${code}`, () => {
86+
assert.deepEqual(lint(code), [])
87+
})
88+
}
89+
})
90+
91+
describe("i18n language switch: Trans", () => {
92+
for (const code of [
93+
'<Trans i18nKey="chat:about" />',
94+
"<Trans components={{ b: <Foo t={1} /> }} />",
95+
"<Trans {...props} />",
96+
]) {
97+
it(`flags a Trans without its own t: ${code}`, () => {
98+
assert.equal(lint(code).length, 1)
99+
})
100+
}
101+
102+
for (const code of [
103+
'<Trans t={t} i18nKey="chat:about" />',
104+
"<Trans t={t} components={{ b: <Foo t={1} /> }} />",
105+
'<Other i18nKey="chat:about" />',
106+
]) {
107+
it(`allows: ${code}`, () => {
108+
assert.deepEqual(lint(code), [])
109+
})
110+
}
111+
})

‎packages/config-eslint/package.json‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,12 @@
88
"./next-js": "./next.js",
99
"./provider-identifiers": "./provider-identifiers.js",
1010
"./api-provider-hygiene": "./api-provider-hygiene.js",
11-
"./i18n-keys": "./i18n-keys.js"
11+
"./i18n-keys": "./i18n-keys.js",
12+
"./i18n-language-switch": "./i18n-language-switch.js"
1213
},
1314
"scripts": {
1415
"lint": "eslint . --max-warnings=0",
15-
"test": "node --test provider-identifiers.test.js api-provider-hygiene.test.js i18n-keys.test.js"
16+
"test": "node --test *.test.js"
1617
},
1718
"devDependencies": {
1819
"@eslint/js": "9.39.5",

‎webview-ui/eslint.config.mjs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { reactConfig } from "@roo-code/config-eslint/react"
2+
import { i18nLanguageSwitchSelectors } from "@roo-code/config-eslint/i18n-language-switch"
23
import { createProviderIdentifierConfig } from "@roo-code/config-eslint/provider-identifiers"
34
import { createI18nDotKeyConfig } from "@roo-code/config-eslint/i18n-keys"
45
import { providerIdentifiers, retiredProviderIdentifiers } from "@roo-code/types/provider-identifiers"
@@ -75,6 +76,36 @@ export default [
7576
message:
7677
"axios was removed from the webview bundle in favour of global fetch. Use fetch() for network calls. The dependency is no longer declared in webview-ui/package.json, so an import here only resolves through the hoisted store and would fail at build time.",
7778
},
79+
{
80+
name: "i18next",
81+
importNames: ["t"],
82+
message: "Use t from useAppTranslation so memoized output follows language changes.",
83+
},
84+
{
85+
name: "react-i18next",
86+
importNames: ["useTranslation"],
87+
message:
88+
"Use useAppTranslation from @src/i18n/TranslationContext: it loads the selected language and exposes the active one for date formatting.",
89+
},
90+
],
91+
},
92+
],
93+
"no-restricted-syntax": ["error", ...i18nLanguageSwitchSelectors],
94+
},
95+
},
96+
{
97+
// The provider is the one place that reads react-i18next's useTranslation.
98+
files: ["src/i18n/TranslationContext.tsx"],
99+
rules: {
100+
"no-restricted-imports": [
101+
"error",
102+
{
103+
paths: [
104+
{
105+
name: "i18next",
106+
importNames: ["t"],
107+
message: "Use t from useAppTranslation so memoized output follows language changes.",
108+
},
78109
],
79110
},
80111
],
@@ -108,6 +139,17 @@ export default [
108139
message:
109140
"axios was removed from the webview bundle in favour of global fetch. Use fetch() for network calls. The dependency is no longer declared in webview-ui/package.json, so an import here only resolves through the hoisted store and would fail at build time.",
110141
},
142+
{
143+
name: "i18next",
144+
importNames: ["t"],
145+
message: "Use t from useAppTranslation so memoized output follows language changes.",
146+
},
147+
{
148+
name: "react-i18next",
149+
importNames: ["useTranslation"],
150+
message:
151+
"Use useAppTranslation from @src/i18n/TranslationContext: it loads the selected language and exposes the active one for date formatting.",
152+
},
111153
{
112154
name: "@tanstack/react-query",
113155
importNames: ["QueryClientProvider"],

‎webview-ui/playwright/AppProviders.tsx‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import { ExtensionStateContextProvider } from "@/context/ExtensionStateContext"
77
import TranslationProvider from "@/i18n/TranslationContext"
88
import i18next from "@/i18n/setup"
99
import { TooltipProvider } from "@/components/ui/tooltip"
10-
import { TranslationContext as PlaywrightTranslationContext } from "@src/i18n/TranslationContext"
1110

1211
type InitialState = NonNullable<React.ComponentProps<typeof ExtensionStateContextProvider>["initialState"]>
1312

@@ -41,14 +40,11 @@ export function AppProviders({ children, initialState }: AppProvidersProps) {
4140
<I18nextProvider i18n={i18next}>
4241
<ExtensionStateContextProvider initialState={{ ...defaultInitialState, ...initialState }}>
4342
<TranslationProvider>
44-
<PlaywrightTranslationContext.Provider
45-
value={{ t: (key, options) => i18next.t(key, options), i18n: i18next }}>
46-
<QueryClientProvider client={queryClient}>
47-
<TooltipProvider>
48-
<div data-testid="ct-app-shell">{children}</div>
49-
</TooltipProvider>
50-
</QueryClientProvider>
51-
</PlaywrightTranslationContext.Provider>
43+
<QueryClientProvider client={queryClient}>
44+
<TooltipProvider>
45+
<div data-testid="ct-app-shell">{children}</div>
46+
</TooltipProvider>
47+
</QueryClientProvider>
5248
</TranslationProvider>
5349
</ExtensionStateContextProvider>
5450
</I18nextProvider>

‎webview-ui/playwright/TranslationContext.ts‎

Lines changed: 0 additions & 13 deletions
This file was deleted.

‎webview-ui/playwright/vite.config.ts‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,6 @@ export default defineConfig({
4848
find: "@src/context/ExtensionStateContext",
4949
replacement: path.resolve(dirname, "ExtensionStateContext.tsx"),
5050
},
51-
{
52-
find: "@src/i18n/TranslationContext",
53-
replacement: path.resolve(dirname, "TranslationContext.ts"),
54-
},
5551
{ find: "@", replacement: path.resolve(webviewRoot, "src") },
5652
{ find: "@src", replacement: path.resolve(webviewRoot, "src") },
5753
{ find: "@roo", replacement: path.resolve(webviewRoot, "../src/shared") },

‎webview-ui/src/__tests__/FileChangesPanel.spec.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ vi.mock("@src/utils/vscode", () => ({
1414
}))
1515

1616
// Mock i18n to return readable header with count
17-
vi.mock("react-i18next", () => ({
18-
useTranslation: () => ({
17+
vi.mock("@src/i18n/TranslationContext", () => ({
18+
useAppTranslation: () => ({
1919
t: (key: string, opts?: { count?: number }) => {
2020
if (key === "chat:fileChangesInConversation.header" && opts?.count != null) {
2121
return `${opts.count} file(s) changed in this conversation`

0 commit comments

Comments
 (0)