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
7 changes: 7 additions & 0 deletions .roo/skills/roo-translation/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,13 @@ This guidance file is loaded at runtime and should be consulted for the latest b
- All user interface strings should be internationalized
- Always use the `Trans` component with named components for text with embedded components

### User-Facing Text (ESLint Enforcement)

- Avoid literal user-facing text in `src/**/*.tsx`: JSX text, attributes such as `aria-label`, `alt`, `title`, `placeholder` and `label`, `StandardTooltip` `content`, and fallbacks such as `{t("x") || "Text"}`. ESLint enforces this via `@roo-code/config-eslint/i18n-literal-strings`.
- Add a key to every locale under `src/i18n/locales/` and render it with `t` from `useAppTranslation`.
- URLs, ARNs, host names, paths and JSON examples are exempt by shape. For another string that must stay as is, such as a brand name or a CSS unit, add `eslint-disable-next-line` with the rule name and a one-line reason.
- Name a key that only screen readers use with an `AriaLabel` suffix, and give a decorative image `alt=""`.

### Trans Component Example

Translation string:
Expand Down
119 changes: 119 additions & 0 deletions packages/config-eslint/i18n-literal-strings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// Flags user-facing text written as literals in JSX, so labels go through translation keys instead.
// JSX text is checked by eslint-plugin-i18next's no-literal-string. Its jsx-text-only mode never looks at
// attributes or at expressions in element children, so the selectors below cover literals rendered from
// the attributes people see or hear and from children such as {t("x") || "Fallback"}.
import pluginI18next from "eslint-plugin-i18next"

const message =
"Translate user-facing text: use a key via t from useAppTranslation instead of a literal. For a brand name, URL or unit that must stay as is, add an eslint-disable-next-line comment with the reason."

// Attributes rendered as visible or announced text on any element. Everything else (className, href,
// data-*, ...) is skipped. ariaLabel is the prop that ToggleSwitch and Slider forward to aria-label.
export const userFacingAttributes = [
"alt",
"aria-description",
"aria-label",
"aria-placeholder",
"aria-roledescription",
"aria-valuetext",
"ariaLabel",
"label",
"placeholder",
"title",
]

// Props that render text only on specific components; on other elements the same name holds data.
export const userFacingComponentProps = {
StandardTooltip: ["content"],
}

// Technical values that read the same in every language: URLs, AWS ARNs, host names, paths, JSON and
// CSS length units such as the "px" after a font size.
export const technicalLiteralPatterns = [
/^(px|r?em)$/,
/^(•\s*)?https?:\/\/\S*$/,
/^arn:aws:\S+$/,
/^[a-z0-9-]+(\.[a-z0-9-]+)+(\/\S*)?$/,
/^[\w.~-]*(\/[\w.~-]+)+\/?$/,
/^\{[\s\S]*\}$/,
]

// esquery regexes end at the first "/", so slashes are written as \x2F.
const toSelectorRegex = (pattern) => `/${pattern.source.replaceAll("\\/", "\\x2F").replaceAll("/", "\\x2F")}/`

const anyOf = (names) => `/^(${names.join("|")})$/`
const componentAttributes = Object.entries(userFacingComponentProps).map(
([component, props]) => `JSXOpeningElement[name.name="${component}"] > JSXAttribute[name.name=${anyOf(props)}]`,
)
const attribute = `:matches(JSXAttribute[name.name=${anyOf(userFacingAttributes)}], ${componentAttributes.join(", ")})`
// Element children, except <style> (CSS) and anything in a <Trans> subtree (fallback text the translation
// replaces), so <Trans><div>{t("x") || "Fallback"}</div></Trans> is skipped too.
const insideTrans = `JSXElement[openingElement.name.name="Trans"] *`
const children = `:matches(JSXElement:not([openingElement.name.name=/^(style|Trans)$/]), JSXFragment):not(${insideTrans})`
// A word of two or more letters; punctuation, numbers and symbols such as "•", "✓" or "%" stay allowed.
const wordy = "/[A-Za-z]{2,}/"
const notTechnical = technicalLiteralPatterns.map((pattern) => `:not([value=${toSelectorRegex(pattern)}])`).join("")
// Template literals store their text in `value.raw`, so the technical-value exclusion needs its own
// attribute path. This lets a template literal holding an API URL in a placeholder pass, matching the
// quoted-attribute behavior.
const notTechnicalRaw = technicalLiteralPatterns
.map((pattern) => `:not([value.raw=${toSelectorRegex(pattern)}])`)
.join("")
// The attribute's value itself or a branch of a ternary / logical fallback, never a call argument such as a
// t() key or a comparison operand: those are not what the attribute renders.
const valueBranch = ":matches(ConditionalExpression, LogicalExpression)"
const valuePositions = [
`${attribute} > Literal`,
...[attribute, children].flatMap((owner) => [
`${owner} > JSXExpressionContainer > Literal`,
`${owner} > JSXExpressionContainer > ${valueBranch} > Literal`,
`${owner} > JSXExpressionContainer > ${valueBranch} > ${valueBranch} > Literal`,
]),
]
const templatePositions = [attribute, children].flatMap((owner) => [
`${owner} > JSXExpressionContainer > TemplateLiteral > TemplateElement`,
`${owner} > JSXExpressionContainer > ${valueBranch} > TemplateLiteral > TemplateElement`,
])

export const i18nLiteralSelectors = [
{
// <img alt="Logo" />, title={ok ? "Saved" : t("x")}, label={name || "Unknown"}, <p>{t("x") || "Fallback"}</p>
selector: valuePositions.map((position) => `${position}[value=${wordy}]${notTechnical}`).join(", "),
message,
},
{
// aria-label={`Open ${path}`}, <p>{`${count} hidden lines`}</p>: the template's static text is untranslated.
selector: templatePositions.map((position) => `${position}[value.raw=${wordy}]${notTechnicalRaw}`).join(", "),
message,
},
]

// The plugin's counterpart of `wordy`: text with at most one letter in a row ("⚠️", "(v", "→").
const noWord = /^(?:\p{L}(?!\p{L})|[^\p{L}])*$/u

/**
* The JSX-text half: eslint-plugin-i18next's no-literal-string in jsx-text-only mode.
* Add `i18nLiteralSelectors` to the same files' no-restricted-syntax list for attributes and children.
*
* @param {{ files: string[], ignores?: string[] }} options
* @returns {import("eslint").Linter.Config}
*/
export function createI18nLiteralStringConfig({ files, ignores = [] }) {
return {
files,
ignores,
plugins: { i18next: pluginI18next },
rules: {
// Text inside <Trans> is the fallback the translation replaces, so the plugin skips it by default.
"i18next/no-literal-string": [
"error",
{
mode: "jsx-text-only",
// Replaces the plugin's defaults: the same word test as the selectors, HTML entities, technical values.
words: { exclude: [noWord, "(&#?[a-zA-Z0-9]+;|\\s)+", ...technicalLiteralPatterns] },
message,
},
],
},
}
}
126 changes: 126 additions & 0 deletions packages/config-eslint/i18n-literal-strings.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { fileURLToPath, URL } from "node:url"

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

import { createI18nLiteralStringConfig, i18nLiteralSelectors } from "./i18n-literal-strings.js"

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

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

describe("i18n literal strings: JSX text", () => {
for (const code of ["<p>Sign out</p>", "<>Add Todo</>", "<span>{n}ms</span>"]) {
it(`flags: ${code}`, () => {
assert.equal(lint(code).length, 1)
})
}

for (const code of [
'<p>{t("chat:signOut")}</p>',
"<p>{count} • {total}</p>",
"<span>⚠️ {error}</span>",
"<span>✓</span>",
"<span>v{version}</span>",
"<span>{seconds}s</span>",
"<span>{fontSize}px</span>",
"<p>&nbsp;</p>",
'<Trans i18nKey="mcp:description"><a href="#">Learn More</a></Trans>',
"<li>arn:aws:bedrock:us-west-2:123456789012:provisioned-model/my-model</li>",
"<div>• https://gateway.my-company.com/route/app/bedrock</div>",
"<a>openrouter.ai/keys</a>",
]) {
it(`allows: ${code}`, () => {
assert.deepEqual(lint(code), [])
})
}
})

describe("i18n literal strings: user-facing attributes and children expressions", () => {
for (const code of [
'<img alt="Logo" />',
'<input placeholder="Search" />',
'<button aria-label={"Close"} />',
'<ToggleSwitch ariaLabel="Toggle server" />',
'<button title={saved ? "Saved" : t("chat:save")} />',
'<Item label={name || "Unknown"} />',
"<button aria-label={`Open ${path}`} />",
'<StandardTooltip content="Copy as markdown"><button /></StandardTooltip>',
'<input placeholder="Default: https://openrouter.ai/api/v1" />',
'<p>{t("x") || "Fallback text"}</p>',
'<code>{item.mimeType || "Unknown"}</code>',
"<p>{`${count} hidden lines`}</p>",
]) {
it(`flags: ${code}`, () => {
assert.equal(lint(code).length, 1)
})
}

for (const code of [
'<img alt="" />',
'<div className="flex gap-2" data-testid="row" />',
'<a href="https://example.com/docs" />',
'<Markdown content="# Heading" />',
'<input placeholder={t("common:ui.search_placeholder")} />',
'<button title={t(open ? "chat:collapse" : "chat:expand")} />',
'<button aria-label={mode === "edit" ? t("chat:edit") : t("chat:view")} />',
'<input placeholder="%" />',
'<input placeholder="https://api.openai.com/v1" />',
'<input placeholder="api.moonshot.ai" />',
'<input placeholder={branch || "worktree/feature-name"} />',
'<input placeholder={dir || "/path/to/worktree"} />',
`<textarea placeholder={'{\\n "metadata": {}\\n}'} />`,
"<style>{`@keyframes fadeIn { from { opacity: 0; } }`}</style>",
'<p>{" "}</p>',
// A template literal holding an API URL in a placeholder is technical text, matching the
// quoted-attribute behavior.
"<input placeholder={`https://api.openai.com/v1`} />",
// Fallback expressions owned by a nested element inside <Trans> are the translation's fallback.
'<Trans i18nKey="mcp:description"><div>{t("x") || "Fallback"}</div></Trans>',
'<Trans i18nKey="mcp:description"><p><>{t("x") || "Fallback"}</></p></Trans>',
]) {
it(`allows: ${code}`, () => {
assert.deepEqual(lint(code), [])
})
}
})

// Resolve the webview's real config so the __mocks__ exclusion is proven for both rules, with a
// component file as the control that the same code is still flagged there.
describe("i18n literal strings in the webview ESLint config", () => {
const webviewRoot = fileURLToPath(new URL("../../webview-ui/", import.meta.url))
const eslint = new ESLint({ cwd: webviewRoot })
const lintAs = async (code, filename) => {
const { rules } = await eslint.calculateConfigForFile(filename)
const resolved = [
{
...createI18nLiteralStringConfig({ files: ["**/*.tsx"] }),
languageOptions,
rules: {
"i18next/no-literal-string": rules["i18next/no-literal-string"] ?? "off",
"no-restricted-syntax": rules["no-restricted-syntax"] ?? "off",
},
},
]
return linter
.verify(code, resolved, { filename: "example.tsx" })
.map((message) => message.ruleId)
.sort()
}

for (const [filename, expected] of [
["src/components/common/__mocks__/Example.tsx", []],
["src/components/common/Example.tsx", ["i18next/no-literal-string", "no-restricted-syntax"]],
]) {
it(`reports ${expected.length ? "both rules" : "nothing"} for ${filename}`, async () => {
assert.deepEqual(await lintAs('<p title="Close">Sign out</p>', filename), expected)
})
}
})
4 changes: 3 additions & 1 deletion packages/config-eslint/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"./provider-identifiers": "./provider-identifiers.js",
"./api-provider-hygiene": "./api-provider-hygiene.js",
"./i18n-keys": "./i18n-keys.js",
"./i18n-language-switch": "./i18n-language-switch.js"
"./i18n-language-switch": "./i18n-language-switch.js",
"./i18n-literal-strings": "./i18n-literal-strings.js"
},
"scripts": {
"lint": "eslint . --max-warnings=0",
Expand All @@ -20,6 +21,7 @@
"@next/eslint-plugin-next": "15.5.28",
"eslint": "9.39.5",
"eslint-config-prettier": "10.1.8",
"eslint-plugin-i18next": "6.1.5",
"eslint-plugin-react": "7.37.5",
"eslint-plugin-react-hooks": "5.2.0",
"eslint-plugin-turbo": "catalog:",
Expand Down
17 changes: 17 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion webview-ui/eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ 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, getI18nDotKeySelectors } from "@roo-code/config-eslint/i18n-keys"
import { createI18nLiteralStringConfig, i18nLiteralSelectors } from "@roo-code/config-eslint/i18n-literal-strings"
import { providerIdentifiers, retiredProviderIdentifiers } from "@roo-code/types/provider-identifiers"

const i18nDotKeyConfig = createI18nDotKeyConfig(`${import.meta.dirname}/src/i18n/locales/en`)
Expand All @@ -11,6 +12,10 @@ export default [
{ ignores: ["playwright/.cache/**"] },
...reactConfig,
createProviderIdentifierConfig({ providerIdentifiers, retiredProviderIdentifiers }),
createI18nLiteralStringConfig({
files: ["src/**/*.tsx"],
ignores: ["src/**/__tests__/**", "src/**/__mocks__/**", "src/**/*.spec.tsx", "src/**/*.test.tsx"],
}),
i18nDotKeyConfig,
{
rules: {
Expand Down Expand Up @@ -97,14 +102,17 @@ export default [
},
{
// The block above replaces no-restricted-syntax for the same files, so repeat the i18n dot-key
// selectors. Keep the dot-key config's ignores so test files stay out of that check.
// selectors. Keep the dot-key config's ignores so test files stay out of that check and out of the
// literal-string selectors, and add __mocks__, which the literal-string plugin config also skips.
...i18nDotKeyConfig,
files: ["src/**/*.{ts,tsx}"],
ignores: [...i18nDotKeyConfig.ignores, "src/**/__mocks__/**"],
rules: {
"no-restricted-syntax": [
"error",
...i18nLanguageSwitchSelectors,
...getI18nDotKeySelectors(i18nDotKeyConfig),
...i18nLiteralSelectors,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
],
},
},
Expand Down
14 changes: 9 additions & 5 deletions webview-ui/playwright/gallery/stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -367,10 +367,12 @@ export const stories: Record<string, Story> = {
return <TelemetryBannerFixture />
},
"theme-aware-controls": async () => {
const [{ SelectDropdown }, { default: UpdateTodoListToolBlock }] = await Promise.all([
import("@/components/ui/select-dropdown"),
import("@/components/chat/UpdateTodoListToolBlock"),
])
const [{ SelectDropdown }, { default: UpdateTodoListToolBlock }, { EnglishChatTranslations }] =
await Promise.all([
import("@/components/ui/select-dropdown"),
import("@/components/chat/UpdateTodoListToolBlock"),
import("@/components/chat/__tests__/UpdateTodoListToolBlock.visual.fixture"),
])
type Todo = NonNullable<React.ComponentProps<typeof UpdateTodoListToolBlock>["todos"]>[number]

function ThemeAwareControlsStory() {
Expand All @@ -381,7 +383,9 @@ export const stories: Record<string, Story> = {
return (
<div className="flex flex-col gap-4 w-96">
<SelectDropdown value={value} options={[{ value: "code", label: "Code" }]} onChange={setValue} />
<UpdateTodoListToolBlock todos={todos} onChange={setTodos} />
<EnglishChatTranslations>
<UpdateTodoListToolBlock todos={todos} onChange={setTodos} />
</EnglishChatTranslations>
</div>
)
}
Expand Down
Loading
Loading