Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .roo/rules-translate/001-general-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@
# 4. WEBVIEW UI LOCALIZATION (webview-ui/src/)

- Located in webview-ui/src/i18n/locales/
- Uses standard React i18next patterns with the useTranslation hook
- 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:
- Always write fully qualified keys (`t("chat:about")`)
- Always pass that `t` to `Trans` (`<Trans t={t} i18nKey="..." />`); `Trans` does not follow language changes on its own (ESLint enforces this)
- 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
- All user interface strings should be internationalized
- Always use the Trans component with named components for text with embedded components

Expand All @@ -40,6 +43,7 @@

```
<Trans
t={t}
i18nKey="welcome:telemetry.changeSettings"
components={{
settingsLink: <VSCodeLink href="#" onClick={handleOpenSettings} />
Expand Down
6 changes: 5 additions & 1 deletion .roo/skills/roo-translation/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@ This guidance file is loaded at runtime and should be consulted for the latest b
## WebView UI Localization (webview-ui/src/)

- Located in `webview-ui/src/i18n/locales/`
- Uses standard React i18next patterns with the `useTranslation` hook
- 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:
- Always write fully qualified keys (`t("chat:about")`)
- Always pass that `t` to `Trans` (`<Trans t={t} i18nKey="..." />`); `Trans` does not follow language changes on its own (ESLint enforces this)
- 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
- All user interface strings should be internationalized
- Always use the `Trans` component with named components for text with embedded components

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

```tsx
<Trans
t={t}
i18nKey="welcome:telemetry.changeSettings"
components={{
settingsLink: <VSCodeLink href="#" onClick={handleOpenSettings} />,
Expand Down
73 changes: 73 additions & 0 deletions packages/config-eslint/i18n-language-switch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Guards that keep translated output in step with a language switch. Built-in no-restricted-syntax only.
// Translations must come from the component's `t` (webview-ui's `useAppTranslation`), which changes identity
// on a language switch; the global instance's `t` gives React (and React Compiler caches) nothing to
// invalidate on, so memoized output would keep the previous language.

// Selectors cannot follow bindings, so the instance is recognised by name: a default import or
// `useTranslation().i18n` held as `i18n`/`i18next`. The aliasing selectors below keep it under those names.
// Passing the instance as an argument and reading `.t` from the parameter is not caught.
const i18nInstanceName = "/^(i18n|i18next)$/"
const i18nInstance = `:matches([name=${i18nInstanceName}], MemberExpression[property.name=${i18nInstanceName}])`

// i18next itself and modules that re-export its instance as their default (webview-ui's i18n/setup).
const i18nInstanceSource = "/^(i18next|(.*\\/)?i18n\\/setup|\\.\\.?\\/setup)$/"

const globalTMessage = "Use t from useAppTranslation so memoized output follows language changes."
const aliasMessage =
"Keep the i18next instance named i18n or i18next: the global-t check recognises it by name, so an alias hides i18n.t."

export const i18nLanguageSwitchSelectors = [
{
// Global t read off the instance: i18next.t(...), i18n?.t(...), i18next["t"], useTranslation().i18n.t.
selector: `MemberExpression:matches([property.name='t'][computed=false], [property.value='t']):has(> ${i18nInstance}.object)`,
message: globalTMessage,
},
{
// Global t destructured from the instance: const { t } = i18next, const { t: translate } = i18n.
// Other properties stay allowed: const { language } = i18next.
selector: `VariableDeclarator:has(> ${i18nInstance}.init) > ObjectPattern > Property[key.name='t']`,
message: globalTMessage,
},
{
// Default import under another name: import lang from "i18next", import { default as lang } from "@/i18n/setup".
// Named imports such as initReactI18next or `type TFunction` are other specifiers and are not matched.
selector: `ImportDeclaration[source.value=${i18nInstanceSource}] > :matches(ImportDefaultSpecifier, ImportSpecifier[imported.name='default']):not([local.name=${i18nInstanceName}])`,
message: aliasMessage,
},
{
// Namespace import: import * as lang from "i18next" exposes the instance's t as lang.t whatever lang is called.
selector: `ImportDeclaration[source.value=${i18nInstanceSource}] > ImportNamespaceSpecifier`,
message: aliasMessage,
},
{
// Re-export under another name: export { default as lang } from "i18next" lets importers alias it unseen.
selector: `ExportNamedDeclaration[source.value=${i18nInstanceSource}] > ExportSpecifier[local.name='default']:not([exported.name=${i18nInstanceName}])`,
message: aliasMessage,
},
{
// Variable alias: const lang = i18next, const lang = useTranslation().i18n.
// Keeping the name is fine (const i18n = useTranslation().i18n); calls such as i18next.createInstance() are not
// the instance itself and are not matched.
selector: `VariableDeclarator[id.type='Identifier']:not([id.name=${i18nInstanceName}]):has(> ${i18nInstance}.init)`,
message: aliasMessage,
},
{
// Assignment alias to an existing variable: lang = i18n.
selector: `AssignmentExpression:not([left.name=${i18nInstanceName}]):has(> ${i18nInstance}.right)`,
message: aliasMessage,
},
{
// Destructuring rename, in declarations and parameters: const { i18n: lang } = useTranslation(),
// ({ i18n: lang }) => ..., and a nested pattern such as const { i18n: { t } } = useTranslation().
// The shorthand const { i18n } = useTranslation() keeps the name and is allowed.
selector: `ObjectPattern > Property[key.name=${i18nInstanceName}]:not([value.name=${i18nInstanceName}])`,
message: aliasMessage,
},
{
// <Trans> without its own t={t}: it reads the global instance, so a memoized element keeps the old language.
// Direct child only: <Trans components={{ b: <Foo t={1} /> }} /> is allowed.
selector: "JSXOpeningElement[name.name='Trans']:not(:has(> JSXAttribute[name.name='t']))",
message:
"Pass t={t} from useAppTranslation: Trans does not subscribe to language changes, so a cached <Trans> keeps the previous language.",
},
]
111 changes: 111 additions & 0 deletions packages/config-eslint/i18n-language-switch.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"

import { Linter } from "eslint"
import typescriptEslint from "typescript-eslint"

import { i18nLanguageSwitchSelectors } from "./i18n-language-switch.js"

const linter = new Linter({ configType: "flat" })
const config = [
{
files: ["**/*.tsx"],
languageOptions: { parser: typescriptEslint.parser, parserOptions: { ecmaFeatures: { jsx: true } } },
rules: { "no-restricted-syntax": ["error", ...i18nLanguageSwitchSelectors] },
},
]

const lint = (code) => linter.verify(code, config, { filename: "example.tsx" }).map((message) => message.message)

describe("i18n language switch: global t", () => {
for (const code of [
'i18next.t("chat:about")',
'import i18n from "i18next"\ni18n.t("chat:about")',
'i18n?.t("chat:about")',
'i18next["t"]("chat:about")',
'useTranslation().i18n.t("chat:about")',
"const { t } = i18next",
"const { t: translate } = i18n",
"const { t } = useTranslation().i18n",
]) {
it(`flags: ${code}`, () => {
assert.equal(lint(code).length, 1)
})
}

for (const code of [
'const { t } = useTranslation()\nt("chat:about")',
'i18next.changeLanguage("es")',
"i18n.language",
"i18next[t]",
"const { language } = i18n",
'other.t("chat:about")',
]) {
it(`allows: ${code}`, () => {
assert.deepEqual(lint(code), [])
})
}
})

describe("i18n language switch: aliasing the instance", () => {
for (const code of [
'import lang from "i18next"',
'import { default as lang } from "i18next"',
'import * as lang from "i18next"',
'import lang from "@src/i18n/setup"',
'import lang from "@/i18n/setup"',
'import lang from "../setup"',
'export { default as lang } from "i18next"',
"const lang = i18next",
"const lang = useTranslation().i18n",
"lang = i18n",
"const { i18n: lang } = useTranslation()",
"const { i18n: { t } } = useTranslation()",
"function Foo({ i18n: lang }) {}",
]) {
it(`flags: ${code}`, () => {
assert.equal(lint(code).length, 1)
})
}

for (const code of [
'import i18next from "i18next"',
'import i18n from "i18next"',
'import i18next, { type TFunction } from "i18next"',
'import { initReactI18next } from "react-i18next"',
'import i18next from "@src/i18n/setup"',
'import { default as i18next } from "i18next"',
'import config from "./config"',
"const i18n = useTranslation().i18n",
"const { i18n } = useTranslation()",
"const { language } = i18next",
"const instance = i18next.createInstance()",
"changeLanguage(i18next)",
]) {
it(`allows: ${code}`, () => {
assert.deepEqual(lint(code), [])
})
}
})

describe("i18n language switch: Trans", () => {
for (const code of [
'<Trans i18nKey="chat:about" />',
"<Trans components={{ b: <Foo t={1} /> }} />",
"<Trans {...props} />",
]) {
it(`flags a Trans without its own t: ${code}`, () => {
assert.equal(lint(code).length, 1)
})
}

for (const code of [
'<Trans t={t} i18nKey="chat:about" />',
"<Trans t={t} components={{ b: <Foo t={1} /> }} />",
'<Other i18nKey="chat:about" />',
]) {
it(`allows: ${code}`, () => {
assert.deepEqual(lint(code), [])
})
}
})
5 changes: 3 additions & 2 deletions packages/config-eslint/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
"./next-js": "./next.js",
"./provider-identifiers": "./provider-identifiers.js",
"./api-provider-hygiene": "./api-provider-hygiene.js",
"./i18n-keys": "./i18n-keys.js"
"./i18n-keys": "./i18n-keys.js",
"./i18n-language-switch": "./i18n-language-switch.js"
},
"scripts": {
"lint": "eslint . --max-warnings=0",
"test": "node --test provider-identifiers.test.js api-provider-hygiene.test.js i18n-keys.test.js"
"test": "node --test *.test.js"
},
"devDependencies": {
"@eslint/js": "9.39.5",
Expand Down
42 changes: 42 additions & 0 deletions webview-ui/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { reactConfig } from "@roo-code/config-eslint/react"
import { i18nLanguageSwitchSelectors } from "@roo-code/config-eslint/i18n-language-switch"
import { createProviderIdentifierConfig } from "@roo-code/config-eslint/provider-identifiers"
import { createI18nDotKeyConfig } from "@roo-code/config-eslint/i18n-keys"
import { providerIdentifiers, retiredProviderIdentifiers } from "@roo-code/types/provider-identifiers"
Expand Down Expand Up @@ -75,6 +76,36 @@ export default [
message:
"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.",
},
{
name: "i18next",
importNames: ["t"],
message: "Use t from useAppTranslation so memoized output follows language changes.",
},
{
name: "react-i18next",
importNames: ["useTranslation"],
message:
"Use useAppTranslation from @src/i18n/TranslationContext: it loads the selected language and exposes the active one for date formatting.",
},
],
},
],
"no-restricted-syntax": ["error", ...i18nLanguageSwitchSelectors],
},
},
{
// The provider is the one place that reads react-i18next's useTranslation.
files: ["src/i18n/TranslationContext.tsx"],
rules: {
"no-restricted-imports": [
"error",
{
paths: [
{
name: "i18next",
importNames: ["t"],
message: "Use t from useAppTranslation so memoized output follows language changes.",
},
],
},
],
Expand Down Expand Up @@ -108,6 +139,17 @@ export default [
message:
"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.",
},
{
name: "i18next",
importNames: ["t"],
message: "Use t from useAppTranslation so memoized output follows language changes.",
},
{
name: "react-i18next",
importNames: ["useTranslation"],
message:
"Use useAppTranslation from @src/i18n/TranslationContext: it loads the selected language and exposes the active one for date formatting.",
},
{
name: "@tanstack/react-query",
importNames: ["QueryClientProvider"],
Expand Down
14 changes: 5 additions & 9 deletions webview-ui/playwright/AppProviders.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { ExtensionStateContextProvider } from "@/context/ExtensionStateContext"
import TranslationProvider from "@/i18n/TranslationContext"
import i18next from "@/i18n/setup"
import { TooltipProvider } from "@/components/ui/tooltip"
import { TranslationContext as PlaywrightTranslationContext } from "@src/i18n/TranslationContext"

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

Expand Down Expand Up @@ -41,14 +40,11 @@ export function AppProviders({ children, initialState }: AppProvidersProps) {
<I18nextProvider i18n={i18next}>
<ExtensionStateContextProvider initialState={{ ...defaultInitialState, ...initialState }}>
<TranslationProvider>
<PlaywrightTranslationContext.Provider
value={{ t: (key, options) => i18next.t(key, options), i18n: i18next }}>
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<div data-testid="ct-app-shell">{children}</div>
</TooltipProvider>
</QueryClientProvider>
</PlaywrightTranslationContext.Provider>
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<div data-testid="ct-app-shell">{children}</div>
</TooltipProvider>
</QueryClientProvider>
</TranslationProvider>
</ExtensionStateContextProvider>
</I18nextProvider>
Expand Down
13 changes: 0 additions & 13 deletions webview-ui/playwright/TranslationContext.ts

This file was deleted.

4 changes: 0 additions & 4 deletions webview-ui/playwright/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,6 @@ export default defineConfig({
find: "@src/context/ExtensionStateContext",
replacement: path.resolve(dirname, "ExtensionStateContext.tsx"),
},
{
find: "@src/i18n/TranslationContext",
replacement: path.resolve(dirname, "TranslationContext.ts"),
},
{ find: "@", replacement: path.resolve(webviewRoot, "src") },
{ find: "@src", replacement: path.resolve(webviewRoot, "src") },
{ find: "@roo", replacement: path.resolve(webviewRoot, "../src/shared") },
Expand Down
4 changes: 2 additions & 2 deletions webview-ui/src/__tests__/FileChangesPanel.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ vi.mock("@src/utils/vscode", () => ({
}))

// Mock i18n to return readable header with count
vi.mock("react-i18next", () => ({
useTranslation: () => ({
vi.mock("@src/i18n/TranslationContext", () => ({
useAppTranslation: () => ({
t: (key: string, opts?: { count?: number }) => {
if (key === "chat:fileChangesInConversation.header" && opts?.count != null) {
return `${opts.count} file(s) changed in this conversation`
Expand Down
2 changes: 1 addition & 1 deletion webview-ui/src/components/chat/Announcement.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ const Announcement = ({ hideAnnouncement }: AnnouncementProps) => {
</div>

<div className="mt-3 text-sm text-center text-vscode-descriptionForeground">
<Trans i18nKey="chat:announcement.support" components={{ githubLink: <GitHubLink /> }} />
<Trans t={t} i18nKey="chat:announcement.support" components={{ githubLink: <GitHubLink /> }} />
</div>
</div>
</DialogContent>
Expand Down
Loading
Loading